WIP
This commit is contained in:
@@ -0,0 +1,698 @@
|
||||
use super::{
|
||||
buffer, Anchor, AnchorRangeExt, Buffer, DisplayPoint, Edit, Point, TextSummary, ToOffset,
|
||||
};
|
||||
use crate::{
|
||||
app::{AppContext, ModelHandle},
|
||||
sum_tree::{self, Cursor, SumTree},
|
||||
util::find_insertion_index,
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
use std::{
|
||||
cmp::{self, Ordering},
|
||||
iter::Take,
|
||||
ops::Range,
|
||||
};
|
||||
use sum_tree::{Dimension, SeekBias};
|
||||
|
||||
pub struct FoldMap {
|
||||
buffer: ModelHandle<Buffer>,
|
||||
transforms: SumTree<Transform>,
|
||||
folds: Vec<Range<Anchor>>,
|
||||
}
|
||||
|
||||
impl FoldMap {
|
||||
pub fn new(buffer: ModelHandle<Buffer>, app: &AppContext) -> Self {
|
||||
let text_summary = buffer.as_ref(app).text_summary();
|
||||
Self {
|
||||
buffer,
|
||||
folds: Vec::new(),
|
||||
transforms: SumTree::from_item(Transform {
|
||||
summary: TransformSummary {
|
||||
buffer: text_summary.clone(),
|
||||
display: text_summary,
|
||||
},
|
||||
display_text: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn buffer_rows(&self, start_row: u32) -> Result<BufferRows> {
|
||||
if start_row > self.transforms.summary().display.lines.row {
|
||||
return Err(anyhow!("invalid display row {}", start_row));
|
||||
}
|
||||
|
||||
let display_point = Point::new(start_row, 0);
|
||||
let mut cursor = self.transforms.cursor();
|
||||
cursor.seek(&DisplayPoint(display_point), SeekBias::Left);
|
||||
|
||||
Ok(BufferRows {
|
||||
display_point,
|
||||
cursor,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.transforms.summary().display.chars
|
||||
}
|
||||
|
||||
pub fn line_len(&self, row: u32, ctx: &AppContext) -> Result<u32> {
|
||||
let line_start = self.to_display_offset(DisplayPoint::new(row, 0), ctx)?.0;
|
||||
let line_end = if row >= self.max_point().row() {
|
||||
self.len()
|
||||
} else {
|
||||
self.to_display_offset(DisplayPoint::new(row + 1, 0), ctx)?
|
||||
.0
|
||||
- 1
|
||||
};
|
||||
|
||||
Ok((line_end - line_start) as u32)
|
||||
}
|
||||
|
||||
pub fn chars_at<'a>(&'a self, point: DisplayPoint, app: &'a AppContext) -> Result<Chars<'a>> {
|
||||
let offset = self.to_display_offset(point, app)?;
|
||||
let mut cursor = self.transforms.cursor();
|
||||
cursor.seek(&offset, SeekBias::Right);
|
||||
let buffer = self.buffer.as_ref(app);
|
||||
Ok(Chars {
|
||||
cursor,
|
||||
offset: offset.0,
|
||||
buffer,
|
||||
buffer_chars: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn max_point(&self) -> DisplayPoint {
|
||||
DisplayPoint(self.transforms.summary().display.lines)
|
||||
}
|
||||
|
||||
pub fn rightmost_point(&self) -> DisplayPoint {
|
||||
DisplayPoint(self.transforms.summary().display.rightmost_point)
|
||||
}
|
||||
|
||||
pub fn fold<T: ToOffset>(
|
||||
&mut self,
|
||||
ranges: impl IntoIterator<Item = Range<T>>,
|
||||
app: &AppContext,
|
||||
) -> Result<()> {
|
||||
let mut edits = Vec::new();
|
||||
let buffer = self.buffer.as_ref(app);
|
||||
for range in ranges.into_iter() {
|
||||
let start = range.start.to_offset(buffer)?;
|
||||
let end = range.end.to_offset(buffer)?;
|
||||
edits.push(Edit {
|
||||
old_range: start..end,
|
||||
new_range: start..end,
|
||||
});
|
||||
|
||||
let fold = buffer.anchor_after(start)?..buffer.anchor_before(end)?;
|
||||
let ix = find_insertion_index(&self.folds, |probe| probe.cmp(&fold, buffer))?;
|
||||
self.folds.insert(ix, fold);
|
||||
}
|
||||
edits.sort_unstable_by(|a, b| {
|
||||
a.old_range
|
||||
.start
|
||||
.cmp(&b.old_range.start)
|
||||
.then_with(|| b.old_range.end.cmp(&a.old_range.end))
|
||||
});
|
||||
|
||||
self.apply_edits(&edits, app)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn unfold<T: ToOffset>(
|
||||
&mut self,
|
||||
ranges: impl IntoIterator<Item = Range<T>>,
|
||||
app: &AppContext,
|
||||
) -> Result<()> {
|
||||
let buffer = self.buffer.as_ref(app);
|
||||
|
||||
let mut edits = Vec::new();
|
||||
for range in ranges.into_iter() {
|
||||
let start = buffer.anchor_before(range.start.to_offset(buffer)?)?;
|
||||
let end = buffer.anchor_after(range.end.to_offset(buffer)?)?;
|
||||
|
||||
// Remove intersecting folds and add their ranges to edits that are passed to apply_edits
|
||||
self.folds.retain(|fold| {
|
||||
if fold.start.cmp(&end, buffer).unwrap() > Ordering::Equal
|
||||
|| fold.end.cmp(&start, buffer).unwrap() < Ordering::Equal
|
||||
{
|
||||
true
|
||||
} else {
|
||||
let offset_range =
|
||||
fold.start.to_offset(buffer).unwrap()..fold.end.to_offset(buffer).unwrap();
|
||||
edits.push(Edit {
|
||||
old_range: offset_range.clone(),
|
||||
new_range: offset_range,
|
||||
});
|
||||
false
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
self.apply_edits(&edits, app)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_line_folded(&self, display_row: u32) -> bool {
|
||||
let mut cursor = self.transforms.cursor::<DisplayPoint, DisplayPoint>();
|
||||
cursor.seek(&DisplayPoint::new(display_row, 0), SeekBias::Right);
|
||||
while let Some(transform) = cursor.item() {
|
||||
if transform.display_text.is_some() {
|
||||
return true;
|
||||
}
|
||||
if cursor.end().row() == display_row {
|
||||
cursor.next()
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn to_display_offset(
|
||||
&self,
|
||||
point: DisplayPoint,
|
||||
app: &AppContext,
|
||||
) -> Result<DisplayOffset> {
|
||||
let mut cursor = self.transforms.cursor::<DisplayPoint, TransformSummary>();
|
||||
cursor.seek(&point, SeekBias::Right);
|
||||
let overshoot = point.0 - cursor.start().display.lines;
|
||||
let mut offset = cursor.start().display.chars;
|
||||
if !overshoot.is_zero() {
|
||||
let transform = cursor
|
||||
.item()
|
||||
.ok_or_else(|| anyhow!("display point {:?} is out of range", point))?;
|
||||
assert!(transform.display_text.is_none());
|
||||
let end_buffer_offset =
|
||||
(cursor.start().buffer.lines + overshoot).to_offset(self.buffer.as_ref(app))?;
|
||||
offset += end_buffer_offset - cursor.start().buffer.chars;
|
||||
}
|
||||
Ok(DisplayOffset(offset))
|
||||
}
|
||||
|
||||
pub fn to_buffer_point(&self, display_point: DisplayPoint) -> Point {
|
||||
let mut cursor = self.transforms.cursor::<DisplayPoint, TransformSummary>();
|
||||
cursor.seek(&display_point, SeekBias::Right);
|
||||
let overshoot = display_point.0 - cursor.start().display.lines;
|
||||
cursor.start().buffer.lines + overshoot
|
||||
}
|
||||
|
||||
pub fn to_display_point(&self, point: Point) -> DisplayPoint {
|
||||
let mut cursor = self.transforms.cursor::<Point, TransformSummary>();
|
||||
cursor.seek(&point, SeekBias::Right);
|
||||
let overshoot = point - cursor.start().buffer.lines;
|
||||
DisplayPoint(cmp::min(
|
||||
cursor.start().display.lines + overshoot,
|
||||
cursor.end().display.lines,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn apply_edits(&mut self, edits: &[Edit], app: &AppContext) -> Result<()> {
|
||||
let buffer = self.buffer.as_ref(app);
|
||||
let mut edits = edits.iter().cloned().peekable();
|
||||
|
||||
let mut new_transforms = SumTree::new();
|
||||
let mut cursor = self.transforms.cursor::<usize, usize>();
|
||||
cursor.seek(&0, SeekBias::Right);
|
||||
|
||||
while let Some(mut edit) = edits.next() {
|
||||
new_transforms.push_tree(cursor.slice(&edit.old_range.start, SeekBias::Left));
|
||||
edit.new_range.start -= edit.old_range.start - cursor.start();
|
||||
edit.old_range.start = *cursor.start();
|
||||
|
||||
cursor.seek(&edit.old_range.end, SeekBias::Right);
|
||||
cursor.next();
|
||||
|
||||
let mut delta = edit.delta();
|
||||
loop {
|
||||
edit.old_range.end = *cursor.start();
|
||||
|
||||
if let Some(next_edit) = edits.peek() {
|
||||
if next_edit.old_range.start > edit.old_range.end {
|
||||
break;
|
||||
}
|
||||
|
||||
let next_edit = edits.next().unwrap();
|
||||
delta += next_edit.delta();
|
||||
|
||||
if next_edit.old_range.end > edit.old_range.end {
|
||||
edit.old_range.end = next_edit.old_range.end;
|
||||
cursor.seek(&edit.old_range.end, SeekBias::Right);
|
||||
cursor.next();
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
edit.new_range.end =
|
||||
((edit.new_range.start + edit.old_extent()) as isize + delta) as usize;
|
||||
|
||||
let anchor = buffer.anchor_before(edit.new_range.start)?;
|
||||
let folds_start =
|
||||
find_insertion_index(&self.folds, |probe| probe.start.cmp(&anchor, buffer))?;
|
||||
let mut folds = self.folds[folds_start..]
|
||||
.iter()
|
||||
.map(|fold| {
|
||||
fold.start.to_offset(buffer).unwrap()..fold.end.to_offset(buffer).unwrap()
|
||||
})
|
||||
.peekable();
|
||||
|
||||
while folds
|
||||
.peek()
|
||||
.map_or(false, |fold| fold.start < edit.new_range.end)
|
||||
{
|
||||
let mut fold = folds.next().unwrap();
|
||||
let sum = new_transforms.summary();
|
||||
|
||||
assert!(fold.start >= sum.buffer.chars);
|
||||
|
||||
while folds
|
||||
.peek()
|
||||
.map_or(false, |next_fold| next_fold.start <= fold.end)
|
||||
{
|
||||
let next_fold = folds.next().unwrap();
|
||||
if next_fold.end > fold.end {
|
||||
fold.end = next_fold.end;
|
||||
}
|
||||
}
|
||||
|
||||
if fold.start > sum.buffer.chars {
|
||||
let text_summary = buffer.text_summary_for_range(sum.buffer.chars..fold.start);
|
||||
new_transforms.push(Transform {
|
||||
summary: TransformSummary {
|
||||
display: text_summary.clone(),
|
||||
buffer: text_summary,
|
||||
},
|
||||
display_text: None,
|
||||
});
|
||||
}
|
||||
|
||||
if fold.end > fold.start {
|
||||
new_transforms.push(Transform {
|
||||
summary: TransformSummary {
|
||||
display: TextSummary {
|
||||
chars: 1,
|
||||
bytes: '…'.len_utf8(),
|
||||
lines: Point::new(0, 1),
|
||||
first_line_len: 1,
|
||||
rightmost_point: Point::new(0, 1),
|
||||
},
|
||||
buffer: buffer.text_summary_for_range(fold.start..fold.end),
|
||||
},
|
||||
display_text: Some('…'),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let sum = new_transforms.summary();
|
||||
if sum.buffer.chars < edit.new_range.end {
|
||||
let text_summary =
|
||||
buffer.text_summary_for_range(sum.buffer.chars..edit.new_range.end);
|
||||
new_transforms.push(Transform {
|
||||
summary: TransformSummary {
|
||||
display: text_summary.clone(),
|
||||
buffer: text_summary,
|
||||
},
|
||||
display_text: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
new_transforms.push_tree(cursor.suffix());
|
||||
|
||||
drop(cursor);
|
||||
self.transforms = new_transforms;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
struct Transform {
|
||||
summary: TransformSummary,
|
||||
display_text: Option<char>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
struct TransformSummary {
|
||||
display: TextSummary,
|
||||
buffer: TextSummary,
|
||||
}
|
||||
|
||||
impl sum_tree::Item for Transform {
|
||||
type Summary = TransformSummary;
|
||||
|
||||
fn summary(&self) -> Self::Summary {
|
||||
self.summary.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> std::ops::AddAssign<&'a Self> for TransformSummary {
|
||||
fn add_assign(&mut self, other: &'a Self) {
|
||||
self.buffer += &other.buffer;
|
||||
self.display += &other.display;
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Dimension<'a, TransformSummary> for TransformSummary {
|
||||
fn add_summary(&mut self, summary: &'a TransformSummary) {
|
||||
*self += summary;
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BufferRows<'a> {
|
||||
cursor: Cursor<'a, Transform, DisplayPoint, TransformSummary>,
|
||||
display_point: Point,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for BufferRows<'a> {
|
||||
type Item = u32;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
while self.display_point > self.cursor.end().display.lines {
|
||||
self.cursor.next();
|
||||
if self.cursor.item().is_none() {
|
||||
// TODO: Return a bool from next?
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if self.cursor.item().is_some() {
|
||||
let overshoot = self.display_point - self.cursor.start().display.lines;
|
||||
let buffer_point = self.cursor.start().buffer.lines + overshoot;
|
||||
self.display_point.row += 1;
|
||||
Some(buffer_point.row)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Chars<'a> {
|
||||
cursor: Cursor<'a, Transform, DisplayOffset, TransformSummary>,
|
||||
offset: usize,
|
||||
buffer: &'a Buffer,
|
||||
buffer_chars: Option<Take<buffer::Chars<'a>>>,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Chars<'a> {
|
||||
type Item = char;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if let Some(c) = self.buffer_chars.as_mut().and_then(|chars| chars.next()) {
|
||||
self.offset += 1;
|
||||
return Some(c);
|
||||
}
|
||||
|
||||
if self.offset == self.cursor.end().display.chars {
|
||||
self.cursor.next();
|
||||
}
|
||||
|
||||
self.cursor.item().and_then(|transform| {
|
||||
if let Some(c) = transform.display_text {
|
||||
self.offset += 1;
|
||||
Some(c)
|
||||
} else {
|
||||
let overshoot = self.offset - self.cursor.start().display.chars;
|
||||
let buffer_start = self.cursor.start().buffer.chars + overshoot;
|
||||
let char_count = self.cursor.end().buffer.chars - buffer_start;
|
||||
self.buffer_chars =
|
||||
Some(self.buffer.chars_at(buffer_start).unwrap().take(char_count));
|
||||
self.next()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Dimension<'a, TransformSummary> for DisplayPoint {
|
||||
fn add_summary(&mut self, summary: &'a TransformSummary) {
|
||||
self.0 += &summary.display.lines;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
|
||||
pub struct DisplayOffset(usize);
|
||||
|
||||
impl<'a> Dimension<'a, TransformSummary> for DisplayOffset {
|
||||
fn add_summary(&mut self, summary: &'a TransformSummary) {
|
||||
self.0 += &summary.display.chars;
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Dimension<'a, TransformSummary> for Point {
|
||||
fn add_summary(&mut self, summary: &'a TransformSummary) {
|
||||
*self += &summary.buffer.lines;
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Dimension<'a, TransformSummary> for usize {
|
||||
fn add_summary(&mut self, summary: &'a TransformSummary) {
|
||||
*self += &summary.buffer.chars;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::App;
|
||||
use crate::test_utils::sample_text;
|
||||
|
||||
#[test]
|
||||
fn test_basic_folds() -> Result<()> {
|
||||
let mut app = App::new()?;
|
||||
let buffer = app.add_model(|_| Buffer::new(0, sample_text(5, 6)));
|
||||
let mut map = app.read(|app| FoldMap::new(buffer.clone(), app));
|
||||
|
||||
app.read(|app| {
|
||||
map.fold(
|
||||
vec![
|
||||
Point::new(0, 2)..Point::new(2, 2),
|
||||
Point::new(2, 4)..Point::new(4, 1),
|
||||
],
|
||||
app,
|
||||
)?;
|
||||
assert_eq!(map.text(app), "aa…cc…eeeee");
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})?;
|
||||
|
||||
let edits = buffer.update(&mut app, |buffer, ctx| {
|
||||
let start_version = buffer.version.clone();
|
||||
buffer.edit(
|
||||
vec![
|
||||
Point::new(0, 0)..Point::new(0, 1),
|
||||
Point::new(2, 3)..Point::new(2, 3),
|
||||
],
|
||||
"123",
|
||||
Some(ctx),
|
||||
)?;
|
||||
Ok::<_, anyhow::Error>(buffer.edits_since(start_version).collect::<Vec<_>>())
|
||||
})?;
|
||||
|
||||
app.read(|app| {
|
||||
map.apply_edits(&edits, app)?;
|
||||
assert_eq!(map.text(app), "123a…c123c…eeeee");
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})?;
|
||||
|
||||
let edits = buffer.update(&mut app, |buffer, ctx| {
|
||||
let start_version = buffer.version.clone();
|
||||
buffer.edit(Some(Point::new(2, 6)..Point::new(4, 3)), "456", Some(ctx))?;
|
||||
Ok::<_, anyhow::Error>(buffer.edits_since(start_version).collect::<Vec<_>>())
|
||||
})?;
|
||||
|
||||
app.read(|app| {
|
||||
map.apply_edits(&edits, app)?;
|
||||
assert_eq!(map.text(app), "123a…c123456eee");
|
||||
|
||||
map.unfold(Some(Point::new(0, 4)..Point::new(0, 4)), app)?;
|
||||
assert_eq!(map.text(app), "123aaaaa\nbbbbbb\nccc123456eee");
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_overlapping_folds() -> Result<()> {
|
||||
let mut app = App::new()?;
|
||||
let buffer = app.add_model(|_| Buffer::new(0, sample_text(5, 6)));
|
||||
app.read(|app| {
|
||||
let mut map = FoldMap::new(buffer.clone(), app);
|
||||
map.fold(
|
||||
vec![
|
||||
Point::new(0, 2)..Point::new(2, 2),
|
||||
Point::new(0, 4)..Point::new(1, 0),
|
||||
Point::new(1, 2)..Point::new(3, 2),
|
||||
Point::new(3, 1)..Point::new(4, 1),
|
||||
],
|
||||
app,
|
||||
)?;
|
||||
assert_eq!(map.text(app), "aa…eeeee");
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merging_folds_via_edit() -> Result<()> {
|
||||
let mut app = App::new()?;
|
||||
let buffer = app.add_model(|_| Buffer::new(0, sample_text(5, 6)));
|
||||
let mut map = app.read(|app| FoldMap::new(buffer.clone(), app));
|
||||
|
||||
app.read(|app| {
|
||||
map.fold(
|
||||
vec![
|
||||
Point::new(0, 2)..Point::new(2, 2),
|
||||
Point::new(3, 1)..Point::new(4, 1),
|
||||
],
|
||||
app,
|
||||
)?;
|
||||
assert_eq!(map.text(app), "aa…cccc\nd…eeeee");
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})?;
|
||||
|
||||
let edits = buffer.update(&mut app, |buffer, ctx| {
|
||||
let start_version = buffer.version.clone();
|
||||
buffer.edit(Some(Point::new(2, 2)..Point::new(3, 1)), "", Some(ctx))?;
|
||||
Ok::<_, anyhow::Error>(buffer.edits_since(start_version).collect::<Vec<_>>())
|
||||
})?;
|
||||
|
||||
app.read(|app| {
|
||||
map.apply_edits(&edits, app)?;
|
||||
assert_eq!(map.text(app), "aa…eeeee");
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_random_folds() -> Result<()> {
|
||||
use crate::buffer::ToPoint;
|
||||
use crate::util::RandomCharIter;
|
||||
use rand::prelude::*;
|
||||
|
||||
for seed in 0..100 {
|
||||
println!("{:?}", seed);
|
||||
let mut rng = StdRng::seed_from_u64(seed);
|
||||
|
||||
let mut app = App::new()?;
|
||||
let buffer = app.add_model(|_| {
|
||||
let len = rng.gen_range(0, 10);
|
||||
let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
|
||||
Buffer::new(0, text)
|
||||
});
|
||||
let mut map = app.read(|app| FoldMap::new(buffer.clone(), app));
|
||||
|
||||
app.read(|app| {
|
||||
let buffer = buffer.as_ref(app);
|
||||
|
||||
let fold_count = rng.gen_range(0, 10);
|
||||
let mut fold_ranges: Vec<Range<usize>> = Vec::new();
|
||||
for _ in 0..fold_count {
|
||||
let end = rng.gen_range(0, buffer.len() + 1);
|
||||
let start = rng.gen_range(0, end + 1);
|
||||
fold_ranges.push(start..end);
|
||||
}
|
||||
|
||||
map.fold(fold_ranges, app)?;
|
||||
|
||||
let mut expected_text = buffer.text();
|
||||
for fold_range in map.merged_fold_ranges(app).into_iter().rev() {
|
||||
expected_text.replace_range(fold_range.start..fold_range.end, "…");
|
||||
}
|
||||
|
||||
assert_eq!(map.text(app), expected_text);
|
||||
|
||||
for fold_range in map.merged_fold_ranges(app) {
|
||||
let display_point =
|
||||
map.to_display_point(fold_range.start.to_point(buffer).unwrap());
|
||||
assert!(map.is_line_folded(display_point.row()));
|
||||
}
|
||||
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})?;
|
||||
|
||||
let edits = buffer.update(&mut app, |buffer, ctx| {
|
||||
let start_version = buffer.version.clone();
|
||||
let edit_count = rng.gen_range(1, 10);
|
||||
buffer.randomly_edit(&mut rng, edit_count, Some(ctx));
|
||||
Ok::<_, anyhow::Error>(buffer.edits_since(start_version).collect::<Vec<_>>())
|
||||
})?;
|
||||
|
||||
app.read(|app| {
|
||||
map.apply_edits(&edits, app)?;
|
||||
|
||||
let buffer = map.buffer.as_ref(app);
|
||||
let mut expected_text = buffer.text();
|
||||
for fold_range in map.merged_fold_ranges(app).into_iter().rev() {
|
||||
expected_text.replace_range(fold_range.start..fold_range.end, "…");
|
||||
}
|
||||
assert_eq!(map.text(app), expected_text);
|
||||
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_buffer_rows() -> Result<()> {
|
||||
let mut app = App::new()?;
|
||||
let text = sample_text(6, 6) + "\n";
|
||||
let buffer = app.add_model(|_| Buffer::new(0, text));
|
||||
|
||||
app.read(|app| {
|
||||
let mut map = FoldMap::new(buffer.clone(), app);
|
||||
|
||||
map.fold(
|
||||
vec![
|
||||
Point::new(0, 2)..Point::new(2, 2),
|
||||
Point::new(3, 1)..Point::new(4, 1),
|
||||
],
|
||||
app,
|
||||
)?;
|
||||
|
||||
assert_eq!(map.text(app), "aa…cccc\nd…eeeee\nffffff\n");
|
||||
assert_eq!(map.buffer_rows(0)?.collect::<Vec<_>>(), vec![0, 3, 5, 6]);
|
||||
assert_eq!(map.buffer_rows(3)?.collect::<Vec<_>>(), vec![6]);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
impl FoldMap {
|
||||
fn text(&self, app: &AppContext) -> String {
|
||||
self.chars_at(DisplayPoint(Point::zero()), app)
|
||||
.unwrap()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn merged_fold_ranges(&self, app: &AppContext) -> Vec<Range<usize>> {
|
||||
let buffer = self.buffer.as_ref(app);
|
||||
let mut fold_ranges = self
|
||||
.folds
|
||||
.iter()
|
||||
.map(|fold| {
|
||||
fold.start.to_offset(buffer).unwrap()..fold.end.to_offset(buffer).unwrap()
|
||||
})
|
||||
.peekable();
|
||||
|
||||
let mut merged_ranges = Vec::new();
|
||||
while let Some(mut fold_range) = fold_ranges.next() {
|
||||
while let Some(next_range) = fold_ranges.peek() {
|
||||
if fold_range.end >= next_range.start {
|
||||
if next_range.end > fold_range.end {
|
||||
fold_range.end = next_range.end;
|
||||
}
|
||||
fold_ranges.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if fold_range.end > fold_range.start {
|
||||
merged_ranges.push(fold_range);
|
||||
}
|
||||
}
|
||||
merged_ranges
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
mod fold_map;
|
||||
|
||||
use super::ToPoint;
|
||||
use super::{buffer, Anchor, AnchorRangeExt, Buffer, Edit, Point, TextSummary, ToOffset};
|
||||
use crate::app::{AppContext, Entity, ModelContext, ModelHandle};
|
||||
use anyhow::Result;
|
||||
pub use fold_map::BufferRows;
|
||||
use fold_map::FoldMap;
|
||||
use std::ops::Range;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub enum Bias {
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
pub struct DisplayMap {
|
||||
buffer: ModelHandle<Buffer>,
|
||||
fold_map: FoldMap,
|
||||
tab_size: usize,
|
||||
}
|
||||
|
||||
impl Entity for DisplayMap {
|
||||
type Event = ();
|
||||
}
|
||||
|
||||
impl DisplayMap {
|
||||
pub fn new(buffer: ModelHandle<Buffer>, tab_size: usize, ctx: &mut ModelContext<Self>) -> Self {
|
||||
ctx.subscribe(&buffer, Self::handle_buffer_event);
|
||||
|
||||
DisplayMap {
|
||||
buffer: buffer.clone(),
|
||||
fold_map: FoldMap::new(buffer, ctx.app()),
|
||||
tab_size,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fold<T: ToOffset>(
|
||||
&mut self,
|
||||
ranges: impl IntoIterator<Item = Range<T>>,
|
||||
ctx: &mut ModelContext<Self>,
|
||||
) -> Result<()> {
|
||||
self.fold_map.fold(ranges, ctx.app())?;
|
||||
ctx.notify();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn unfold<T: ToOffset>(
|
||||
&mut self,
|
||||
ranges: impl IntoIterator<Item = Range<T>>,
|
||||
ctx: &mut ModelContext<Self>,
|
||||
) -> Result<()> {
|
||||
self.fold_map.unfold(ranges, ctx.app())?;
|
||||
ctx.notify();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_line_folded(&self, display_row: u32) -> bool {
|
||||
self.fold_map.is_line_folded(display_row)
|
||||
}
|
||||
|
||||
pub fn text(&self, app: &AppContext) -> String {
|
||||
self.chars_at(DisplayPoint::zero(), app).unwrap().collect()
|
||||
}
|
||||
|
||||
pub fn line(&self, display_row: u32, app: &AppContext) -> Result<String> {
|
||||
let chars = self.chars_at(DisplayPoint::new(display_row, 0), app)?;
|
||||
Ok(chars.take_while(|c| *c != '\n').collect())
|
||||
}
|
||||
|
||||
pub fn chars_at<'a>(&'a self, point: DisplayPoint, app: &'a AppContext) -> Result<Chars<'a>> {
|
||||
let column = point.column() as usize;
|
||||
let (point, to_next_stop) = point.collapse_tabs(self, Bias::Left, app)?;
|
||||
let mut fold_chars = self.fold_map.chars_at(point, app)?;
|
||||
if to_next_stop > 0 {
|
||||
fold_chars.next();
|
||||
}
|
||||
|
||||
Ok(Chars {
|
||||
fold_chars,
|
||||
column,
|
||||
to_next_stop,
|
||||
tab_size: self.tab_size,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn buffer_rows(&self, start_row: u32) -> Result<BufferRows> {
|
||||
self.fold_map.buffer_rows(start_row)
|
||||
}
|
||||
|
||||
pub fn line_len(&self, row: u32, ctx: &AppContext) -> Result<u32> {
|
||||
DisplayPoint::new(row, self.fold_map.line_len(row, ctx)?)
|
||||
.expand_tabs(self, ctx)
|
||||
.map(|point| point.column())
|
||||
}
|
||||
|
||||
pub fn max_point(&self, app: &AppContext) -> DisplayPoint {
|
||||
self.fold_map.max_point().expand_tabs(self, app).unwrap()
|
||||
}
|
||||
|
||||
pub fn rightmost_point(&self) -> DisplayPoint {
|
||||
self.fold_map.rightmost_point()
|
||||
}
|
||||
|
||||
pub fn anchor_before(
|
||||
&self,
|
||||
point: DisplayPoint,
|
||||
bias: Bias,
|
||||
app: &AppContext,
|
||||
) -> Result<Anchor> {
|
||||
self.buffer
|
||||
.as_ref(app)
|
||||
.anchor_before(point.to_buffer_point(self, bias, app)?)
|
||||
}
|
||||
|
||||
pub fn anchor_after(
|
||||
&self,
|
||||
point: DisplayPoint,
|
||||
bias: Bias,
|
||||
app: &AppContext,
|
||||
) -> Result<Anchor> {
|
||||
self.buffer
|
||||
.as_ref(app)
|
||||
.anchor_after(point.to_buffer_point(self, bias, app)?)
|
||||
}
|
||||
|
||||
fn handle_buffer_event(&mut self, event: &buffer::Event, ctx: &mut ModelContext<Self>) {
|
||||
match event {
|
||||
buffer::Event::Edited(edits) => self.fold_map.apply_edits(edits, ctx.app()).unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
|
||||
pub struct DisplayPoint(Point);
|
||||
|
||||
impl DisplayPoint {
|
||||
pub fn new(row: u32, column: u32) -> Self {
|
||||
Self(Point::new(row, column))
|
||||
}
|
||||
|
||||
pub fn zero() -> Self {
|
||||
Self::new(0, 0)
|
||||
}
|
||||
|
||||
pub fn row(self) -> u32 {
|
||||
self.0.row
|
||||
}
|
||||
|
||||
pub fn column(self) -> u32 {
|
||||
self.0.column
|
||||
}
|
||||
|
||||
pub fn row_mut(&mut self) -> &mut u32 {
|
||||
&mut self.0.row
|
||||
}
|
||||
|
||||
pub fn column_mut(&mut self) -> &mut u32 {
|
||||
&mut self.0.column
|
||||
}
|
||||
|
||||
pub fn to_buffer_point(self, map: &DisplayMap, bias: Bias, app: &AppContext) -> Result<Point> {
|
||||
Ok(map
|
||||
.fold_map
|
||||
.to_buffer_point(self.collapse_tabs(map, bias, app)?.0))
|
||||
}
|
||||
|
||||
fn expand_tabs(mut self, map: &DisplayMap, app: &AppContext) -> Result<Self> {
|
||||
let chars = map
|
||||
.fold_map
|
||||
.chars_at(DisplayPoint(Point::new(self.row(), 0)), app)?;
|
||||
let expanded = expand_tabs(chars, self.column() as usize, map.tab_size);
|
||||
*self.column_mut() = expanded as u32;
|
||||
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn collapse_tabs(
|
||||
mut self,
|
||||
map: &DisplayMap,
|
||||
bias: Bias,
|
||||
app: &AppContext,
|
||||
) -> Result<(Self, usize)> {
|
||||
let chars = map
|
||||
.fold_map
|
||||
.chars_at(DisplayPoint(Point::new(self.0.row, 0)), app)?;
|
||||
let expanded = self.column() as usize;
|
||||
let (collapsed, to_next_stop) = collapse_tabs(chars, expanded, bias, map.tab_size);
|
||||
*self.column_mut() = collapsed as u32;
|
||||
|
||||
Ok((self, to_next_stop))
|
||||
}
|
||||
}
|
||||
|
||||
impl Point {
|
||||
pub fn to_display_point(self, map: &DisplayMap, app: &AppContext) -> Result<DisplayPoint> {
|
||||
let mut display_point = map.fold_map.to_display_point(self);
|
||||
let chars = map
|
||||
.fold_map
|
||||
.chars_at(DisplayPoint::new(display_point.row(), 0), app)?;
|
||||
*display_point.column_mut() =
|
||||
expand_tabs(chars, display_point.column() as usize, map.tab_size) as u32;
|
||||
Ok(display_point)
|
||||
}
|
||||
}
|
||||
|
||||
impl Anchor {
|
||||
pub fn to_display_point(&self, map: &DisplayMap, app: &AppContext) -> Result<DisplayPoint> {
|
||||
self.to_point(map.buffer.as_ref(app))?
|
||||
.to_display_point(map, app)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Chars<'a> {
|
||||
fold_chars: fold_map::Chars<'a>,
|
||||
column: usize,
|
||||
to_next_stop: usize,
|
||||
tab_size: usize,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Chars<'a> {
|
||||
type Item = char;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.to_next_stop > 0 {
|
||||
self.to_next_stop -= 1;
|
||||
self.column += 1;
|
||||
Some(' ')
|
||||
} else {
|
||||
self.fold_chars.next().map(|c| match c {
|
||||
'\t' => {
|
||||
self.to_next_stop = self.tab_size - self.column % self.tab_size - 1;
|
||||
self.column += 1;
|
||||
' '
|
||||
}
|
||||
'\n' => {
|
||||
self.column = 0;
|
||||
c
|
||||
}
|
||||
_ => {
|
||||
self.column += 1;
|
||||
c
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expand_tabs(chars: impl Iterator<Item = char>, column: usize, tab_size: usize) -> usize {
|
||||
let mut expanded = 0;
|
||||
for c in chars.take(column) {
|
||||
if c == '\t' {
|
||||
expanded += tab_size - expanded % tab_size;
|
||||
} else {
|
||||
expanded += 1;
|
||||
}
|
||||
}
|
||||
expanded
|
||||
}
|
||||
|
||||
pub fn collapse_tabs(
|
||||
mut chars: impl Iterator<Item = char>,
|
||||
column: usize,
|
||||
bias: Bias,
|
||||
tab_size: usize,
|
||||
) -> (usize, usize) {
|
||||
let mut expanded = 0;
|
||||
let mut collapsed = 0;
|
||||
while let Some(c) = chars.next() {
|
||||
if expanded == column {
|
||||
break;
|
||||
}
|
||||
|
||||
if c == '\t' {
|
||||
expanded += tab_size - (expanded % tab_size);
|
||||
if expanded > column {
|
||||
return match bias {
|
||||
Bias::Left => (collapsed, expanded - column),
|
||||
Bias::Right => (collapsed + 1, 0),
|
||||
};
|
||||
}
|
||||
collapsed += 1;
|
||||
} else {
|
||||
expanded += 1;
|
||||
collapsed += 1;
|
||||
}
|
||||
}
|
||||
(collapsed, 0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::App;
|
||||
use crate::test_utils::*;
|
||||
use anyhow::Error;
|
||||
|
||||
#[test]
|
||||
fn test_chars_at() -> Result<()> {
|
||||
let mut app = App::new()?;
|
||||
let text = sample_text(6, 6);
|
||||
let buffer = app.add_model(|_| Buffer::new(0, text));
|
||||
let map = app.add_model(|ctx| DisplayMap::new(buffer.clone(), 4, ctx));
|
||||
buffer.update(&mut app, |buffer, ctx| {
|
||||
buffer.edit(
|
||||
vec![
|
||||
Point::new(1, 0)..Point::new(1, 0),
|
||||
Point::new(1, 1)..Point::new(1, 1),
|
||||
Point::new(2, 1)..Point::new(2, 1),
|
||||
],
|
||||
"\t",
|
||||
Some(ctx),
|
||||
)
|
||||
})?;
|
||||
|
||||
map.read(&app, |map, ctx| {
|
||||
assert_eq!(
|
||||
map.chars_at(DisplayPoint::new(1, 0), ctx)?
|
||||
.take(10)
|
||||
.collect::<String>(),
|
||||
" b bb"
|
||||
);
|
||||
assert_eq!(
|
||||
map.chars_at(DisplayPoint::new(1, 2), ctx)?
|
||||
.take(10)
|
||||
.collect::<String>(),
|
||||
" b bbbb"
|
||||
);
|
||||
assert_eq!(
|
||||
map.chars_at(DisplayPoint::new(1, 6), ctx)?
|
||||
.take(13)
|
||||
.collect::<String>(),
|
||||
" bbbbb\nc c"
|
||||
);
|
||||
|
||||
Ok::<(), Error>(())
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_tabs() {
|
||||
assert_eq!(expand_tabs("\t".chars(), 0, 4), 0);
|
||||
assert_eq!(expand_tabs("\t".chars(), 1, 4), 4);
|
||||
assert_eq!(expand_tabs("\ta".chars(), 2, 4), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_collapse_tabs() {
|
||||
assert_eq!(collapse_tabs("\t".chars(), 0, Bias::Left, 4), (0, 0));
|
||||
assert_eq!(collapse_tabs("\t".chars(), 0, Bias::Right, 4), (0, 0));
|
||||
assert_eq!(collapse_tabs("\t".chars(), 1, Bias::Left, 4), (0, 3));
|
||||
assert_eq!(collapse_tabs("\t".chars(), 1, Bias::Right, 4), (1, 0));
|
||||
assert_eq!(collapse_tabs("\t".chars(), 2, Bias::Left, 4), (0, 2));
|
||||
assert_eq!(collapse_tabs("\t".chars(), 2, Bias::Right, 4), (1, 0));
|
||||
assert_eq!(collapse_tabs("\t".chars(), 3, Bias::Left, 4), (0, 1));
|
||||
assert_eq!(collapse_tabs("\t".chars(), 3, Bias::Right, 4), (1, 0));
|
||||
assert_eq!(collapse_tabs("\t".chars(), 4, Bias::Left, 4), (1, 0));
|
||||
assert_eq!(collapse_tabs("\t".chars(), 4, Bias::Right, 4), (1, 0));
|
||||
assert_eq!(collapse_tabs("\ta".chars(), 5, Bias::Left, 4), (2, 0));
|
||||
assert_eq!(collapse_tabs("\ta".chars(), 5, Bias::Right, 4), (2, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_max_point() -> Result<()> {
|
||||
let mut app = App::new()?;
|
||||
let buffer = app.add_model(|_| Buffer::new(0, "aaa\n\t\tbbb"));
|
||||
let map = app.add_model(|ctx| DisplayMap::new(buffer.clone(), 4, ctx));
|
||||
map.read(&app, |map, app| {
|
||||
assert_eq!(map.max_point(app), DisplayPoint::new(1, 11))
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user