Debian Codegraph @

helix-core/src/transaction.rs

raw symbols SCIP
1 use ropey::RopeSlice;
2 use smallvec::SmallVec;
3
4 use crate::{chars::char_is_word, Range, Rope, Selection, Tendril};
5 use std::{borrow::Cow, iter::once};
6
7 /// (from, to, replacement)
8 pub type Change = (usize, usize, Option<Tendril>);
9 pub type Deletion = (usize, usize);
10
11 // TODO: pub(crate)
12 #[derive(Debug, Clone, PartialEq, Eq)]
13 pub enum Operation {
14 /// Move cursor by n characters.
15 Retain(usize),
16 /// Delete n characters.
17 Delete(usize),
18 /// Insert text at position.
19 Insert(Tendril),
20 }
21
22 impl Operation {
23 /// The number of characters affected by the operation.
24 pub fn len_chars(&self) -> usize {
25 match self {
26 Self::Retain(n) | Self::Delete(n) => *n,
27 Self::Insert(s) => s.chars().count(),
28 }
29 }
30 }
31
32 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
33 pub enum Assoc {
34 Before,
35 After,
36 /// Acts like `After` if a word character is inserted
37 /// after the position, otherwise acts like `Before`
38 AfterWord,
39 /// Acts like `Before` if a word character is inserted
40 /// before the position, otherwise acts like `After`
41 BeforeWord,
42 /// Acts like `Before` but if the position is within an exact replacement
43 /// (exact size) the offset to the start of the replacement is kept
44 BeforeSticky,
45 /// Acts like `After` but if the position is within an exact replacement
46 /// (exact size) the offset to the start of the replacement is kept
47 AfterSticky,
48 }
49
50 impl Assoc {
51 /// Whether to stick to gaps
52 fn stay_at_gaps(self) -> bool {
53 !matches!(self, Self::BeforeWord | Self::AfterWord)
54 }
55
56 fn insert_offset(self, s: &str) -> usize {
57 let chars = s.chars().count();
58 match self {
59 Assoc::After | Assoc::AfterSticky => chars,
60 Assoc::AfterWord => s.chars().take_while(|&c| char_is_word(c)).count(),
61 // return position before inserted text
62 Assoc::Before | Assoc::BeforeSticky => 0,
63 Assoc::BeforeWord => chars - s.chars().rev().take_while(|&c| char_is_word(c)).count(),
64 }
65 }
66
67 pub fn sticky(self) -> bool {
68 matches!(self, Assoc::BeforeSticky | Assoc::AfterSticky)
69 }
70 }
71
72 #[derive(Debug, Default, Clone, PartialEq, Eq)]
73 pub struct ChangeSet {
74 pub(crate) changes: Vec<Operation>,
75 /// The required document length. Will refuse to apply changes unless it matches.
76 len: usize,
77 len_after: usize,
78 }
79
80 impl ChangeSet {
81 pub fn with_capacity(capacity: usize) -> Self {
82 Self {
83 changes: Vec::with_capacity(capacity),
84 len: 0,
85 len_after: 0,
86 }
87 }
88
89 #[must_use]
90 pub fn new(doc: RopeSlice) -> Self {
91 let len = doc.len_chars();
92 Self {
93 changes: Vec::new(),
94 len,
95 len_after: len,
96 }
97 }
98
99 // TODO: from iter
100
101 #[doc(hidden)] // used by lsp to convert to LSP changes
102 pub fn changes(&self) -> &[Operation] {
103 &self.changes
104 }
105
106 // Changeset builder operations: delete/insert/retain
107 pub(crate) fn delete(&mut self, n: usize) {
108 use Operation::*;
109 if n == 0 {
110 return;
111 }
112
113 self.len += n;
114
115 if let Some(Delete(count)) = self.changes.last_mut() {
116 *count += n;
117 } else {
118 self.changes.push(Delete(n));
119 }
120 }
121
122 pub(crate) fn insert(&mut self, fragment: Tendril) {
123 use Operation::*;
124
125 if fragment.is_empty() {
126 return;
127 }
128
129 // Avoiding std::str::len() to account for UTF-8 characters.
130 self.len_after += fragment.chars().count();
131
132 let new_last = match self.changes.as_mut_slice() {
133 [.., Insert(prev)] | [.., Insert(prev), Delete(_)] => {
134 prev.push_str(&fragment);
135 return;
136 }
137 [.., last @ Delete(_)] => std::mem::replace(last, Insert(fragment)),
138 _ => Insert(fragment),
139 };
140
141 self.changes.push(new_last);
142 }
143
144 pub(crate) fn retain(&mut self, n: usize) {
145 use Operation::*;
146 if n == 0 {
147 return;
148 }
149
150 self.len += n;
151 self.len_after += n;
152
153 if let Some(Retain(count)) = self.changes.last_mut() {
154 *count += n;
155 } else {
156 self.changes.push(Retain(n));
157 }
158 }
159
160 /// Combine two changesets together.
161 /// In other words, If `this` goes `docA` → `docB` and `other` represents `docB` → `docC`, the
162 /// returned value will represent the change `docA` → `docC`.
163 pub fn compose(self, other: Self) -> Self {
164 assert!(self.len_after == other.len);
165
166 // composing fails in weird ways if one of the sets is empty
167 // a: [] len: 0 len_after: 1 | b: [Insert(Tendril<UTF8>(inline: "\n")), Retain(1)] len 1
168 if self.changes.is_empty() {
169 return other;
170 }
171 if other.changes.is_empty() {
172 return self;
173 }
174
175 let len = self.changes.len();
176
177 let mut changes_a = self.changes.into_iter();
178 let mut changes_b = other.changes.into_iter();
179
180 let mut head_a = changes_a.next();
181 let mut head_b = changes_b.next();
182
183 let mut changes = Self::with_capacity(len); // TODO: max(a, b), shrink_to_fit() afterwards
184
185 loop {
186 use std::cmp::Ordering;
187 use Operation::*;
188 match (head_a, head_b) {
189 // we are done
190 (None, None) => {
191 break;
192 }
193 // deletion in A
194 (Some(Delete(i)), b) => {
195 changes.delete(i);
196 head_a = changes_a.next();
197 head_b = b;
198 }
199 // insertion in B
200 (a, Some(Insert(current))) => {
201 changes.insert(current);
202 head_a = a;
203 head_b = changes_b.next();
204 }
205 (None, val) | (val, None) => unreachable!("({:?})", val),
206 (Some(Retain(i)), Some(Retain(j))) => match i.cmp(&j) {
207 Ordering::Less => {
208 changes.retain(i);
209 head_a = changes_a.next();
210 head_b = Some(Retain(j - i));
211 }
212 Ordering::Equal => {
213 changes.retain(i);
214 head_a = changes_a.next();
215 head_b = changes_b.next();
216 }
217 Ordering::Greater => {
218 changes.retain(j);
219 head_a = Some(Retain(i - j));
220 head_b = changes_b.next();
221 }
222 },
223 (Some(Insert(mut s)), Some(Delete(j))) => {
224 let len = s.chars().count();
225 match len.cmp(&j) {
226 Ordering::Less => {
227 head_a = changes_a.next();
228 head_b = Some(Delete(j - len));
229 }
230 Ordering::Equal => {
231 head_a = changes_a.next();
232 head_b = changes_b.next();
233 }
234 Ordering::Greater => {
235 // TODO: cover this with a test
236 // figure out the byte index of the truncated string end
237 let (pos, _) = s.char_indices().nth(j).unwrap();
238 s.replace_range(0..pos, "");
239 head_a = Some(Insert(s));
240 head_b = changes_b.next();
241 }
242 }
243 }
244 (Some(Insert(s)), Some(Retain(j))) => {
245 let len = s.chars().count();
246 match len.cmp(&j) {
247 Ordering::Less => {
248 changes.insert(s);
249 head_a = changes_a.next();
250 head_b = Some(Retain(j - len));
251 }
252 Ordering::Equal => {
253 changes.insert(s);
254 head_a = changes_a.next();
255 head_b = changes_b.next();
256 }
257 Ordering::Greater => {
258 // figure out the byte index of the truncated string end
259 let (pos, _) = s.char_indices().nth(j).unwrap();
260 let mut before = s;
261 let after = before.split_off(pos);
262
263 changes.insert(before);
264 head_a = Some(Insert(after));
265 head_b = changes_b.next();
266 }
267 }
268 }
269 (Some(Retain(i)), Some(Delete(j))) => match i.cmp(&j) {
270 Ordering::Less => {
271 changes.delete(i);
272 head_a = changes_a.next();
273 head_b = Some(Delete(j - i));
274 }
275 Ordering::Equal => {
276 changes.delete(j);
277 head_a = changes_a.next();
278 head_b = changes_b.next();
279 }
280 Ordering::Greater => {
281 changes.delete(j);
282 head_a = Some(Retain(i - j));
283 head_b = changes_b.next();
284 }
285 },
286 };
287 }
288
289 // starting len should still equal original starting len
290 debug_assert!(changes.len == self.len);
291
292 changes
293 }
294
295 /// Given another change set starting in the same document, maps this
296 /// change set over the other, producing a new change set that can be
297 /// applied to the document produced by applying `other`. When
298 /// `before` is `true`, order changes as if `this` comes before
299 /// `other`, otherwise (the default) treat `other` as coming first.
300 ///
301 /// Given two changes `A` and `B`, `A.compose(B.map(A))` and
302 /// `B.compose(A.map(B, true))` will produce the same document. This
303 /// provides a basic form of [operational
304 /// transformation](https://en.wikipedia.org/wiki/Operational_transformation),
305 /// and can be used for collaborative editing.
306 pub fn map(self, _other: Self) -> Self {
307 unimplemented!()
308 }
309
310 /// Returns a new changeset that reverts this one. Useful for `undo` implementation.
311 /// The document parameter expects the original document before this change was applied.
312 pub fn invert(&self, original_doc: &Rope) -> Self {
313 assert!(original_doc.len_chars() == self.len);
314
315 let mut changes = Self::with_capacity(self.changes.len());
316
317 let mut pos = 0;
318
319 for change in &self.changes {
320 use Operation::*;
321 match change {
322 Retain(n) => {
323 changes.retain(*n);
324 pos += n;
325 }
326 Delete(n) => {
327 let text = Cow::from(original_doc.slice(pos..pos + *n));
328 changes.insert(Tendril::from(text.as_ref()));
329 pos += n;
330 }
331 Insert(s) => {
332 let chars = s.chars().count();
333 changes.delete(chars);
334 }
335 }
336 }
337
338 changes
339 }
340
341 /// Returns true if applied successfully.
342 pub fn apply(&self, text: &mut Rope) -> bool {
343 if text.len_chars() != self.len {
344 return false;
345 }
346
347 let mut pos = 0;
348
349 for change in &self.changes {
350 use Operation::*;
351 match change {
352 Retain(n) => {
353 pos += n;
354 }
355 Delete(n) => {
356 text.remove(pos..pos + *n);
357 // pos += n;
358 }
359 Insert(s) => {
360 text.insert(pos, s);
361 pos += s.chars().count();
362 }
363 }
364 }
365 true
366 }
367
368 /// `true` when the set is empty.
369 #[inline]
370 pub fn is_empty(&self) -> bool {
371 self.changes.is_empty() || self.changes == [Operation::Retain(self.len)]
372 }
373
374 /// Map a (mostly) *sorted* list of positions through the changes.
375 ///
376 /// This is equivalent to updating each position with `map_pos`:
377 ///
378 /// ``` no-compile
379 /// for (pos, assoc) in positions {
380 /// *pos = changes.map_pos(*pos, assoc);
381 /// }
382 /// ```
383 /// However this function is significantly faster for sorted lists running
384 /// in `O(N+M)` instead of `O(NM)`. This function also handles unsorted/
385 /// partially sorted lists. However, in that case worst case complexity is
386 /// again `O(MN)`. For lists that are often/mostly sorted (like the end of diagnostic ranges)
387 /// performance is usally close to `O(N + M)`
388 pub fn update_positions<'a>(&self, positions: impl Iterator<Item = (&'a mut usize, Assoc)>) {
389 use Operation::*;
390
391 let mut positions = positions.peekable();
392
393 let mut old_pos = 0;
394 let mut new_pos = 0;
395 let mut iter = self.changes.iter().enumerate().peekable();
396
397 'outer: loop {
398 macro_rules! map {
399 ($map: expr, $i: expr) => {
400 loop {
401 let Some((pos, assoc)) = positions.peek_mut() else {
402 return;
403 };
404 if **pos < old_pos {
405 // Positions are not sorted, revert to the last Operation that
406 // contains this position and continue iterating from there.
407 // We can unwrap here since `pos` can not be negative
408 // (unsigned integer) and iterating backwards to the start
409 // should always move us back to the start
410 for (i, change) in self.changes[..$i].iter().enumerate().rev() {
411 match change {
412 Retain(i) => {
413 old_pos -= i;
414 new_pos -= i;
415 }
416 Delete(i) => {
417 old_pos -= i;
418 }
419 Insert(ins) => {
420 new_pos -= ins.chars().count();
421 }
422 }
423 if old_pos <= **pos {
424 iter = self.changes[i..].iter().enumerate().peekable();
425 }
426 }
427 debug_assert!(old_pos <= **pos, "Reverse Iter across changeset works");
428 continue 'outer;
429 }
430 #[allow(clippy::redundant_closure_call)]
431 let Some(new_pos) = $map(**pos, *assoc) else {
432 break;
433 };
434 **pos = new_pos;
435 positions.next();
436 }
437 };
438 }
439
440 let Some((i, change)) = iter.next() else {
441 map!(
442 |pos, _| (old_pos == pos).then_some(new_pos),
443 self.changes.len()
444 );
445 break;
446 };
447
448 let len = match change {
449 Delete(i) | Retain(i) => *i,
450 Insert(_) => 0,
451 };
452 let mut old_end = old_pos + len;
453
454 match change {
455 Retain(_) => {
456 map!(
457 |pos, _| (old_end > pos).then_some(new_pos + (pos - old_pos)),
458 i
459 );
460 new_pos += len;
461 }
462 Delete(_) => {
463 // in range
464 map!(|pos, _| (old_end > pos).then_some(new_pos), i);
465 }
466 Insert(s) => {
467 // a subsequent delete means a replace, consume it
468 if let Some((_, Delete(len))) = iter.peek() {
469 iter.next();
470
471 old_end = old_pos + len;
472 // in range of replaced text
473 map!(
474 |pos, assoc: Assoc| (old_end > pos).then(|| {
475 // at point or tracking before
476 if pos == old_pos && assoc.stay_at_gaps() {
477 new_pos
478 } else {
479 let ins = assoc.insert_offset(s);
480 // if the deleted and inserted text have the exact same size
481 // keep the relative offset into the new text
482 if *len == ins && assoc.sticky() {
483 new_pos + (pos - old_pos)
484 } else {
485 new_pos + assoc.insert_offset(s)
486 }
487 }
488 }),
489 i
490 );
491 } else {
492 // at insert point
493 map!(
494 |pos, assoc: Assoc| (old_pos == pos).then(|| {
495 // return position before inserted text
496 new_pos + assoc.insert_offset(s)
497 }),
498 i
499 );
500 }
501
502 new_pos += s.chars().count();
503 }
504 }
505 old_pos = old_end;
506 }
507 let out_of_bounds: Vec<_> = positions.collect();
508
509 panic!("Positions {out_of_bounds:?} are out of range for changeset len {old_pos}!",)
510 }
511
512 /// Map a position through the changes.
513 ///
514 /// `assoc` indicates which side to associate the position with. `Before` will keep the
515 /// position close to the character before, and will place it before insertions over that
516 /// range, or at that point. `After` will move it forward, placing it at the end of such
517 /// insertions.
518 pub fn map_pos(&self, mut pos: usize, assoc: Assoc) -> usize {
519 self.update_positions(once((&mut pos, assoc)));
520 pos
521 }
522
523 pub fn changes_iter(&self) -> ChangeIterator<'_> {
524 ChangeIterator::new(self)
525 }
526
527 pub fn from_change(doc: &Rope, change: Change) -> Self {
528 Self::from_changes(doc, std::iter::once(change))
529 }
530
531 /// Generate a ChangeSet from a set of changes.
532 pub fn from_changes<I>(doc: &Rope, changes: I) -> Self
533 where
534 I: Iterator<Item = Change>,
535 {
536 let len = doc.len_chars();
537
538 let (lower, upper) = changes.size_hint();
539 let size = upper.unwrap_or(lower);
540 let mut changeset = ChangeSet::with_capacity(2 * size + 1); // rough estimate
541
542 let mut last = 0;
543 for (from, to, tendril) in changes {
544 // Verify ranges are ordered and not overlapping
545 debug_assert!(last <= from);
546 // Verify ranges are correct
547 debug_assert!(
548 from <= to,
549 "Edit end must end before it starts (should {from} <= {to})"
550 );
551
552 // Retain from last "to" to current "from"
553 changeset.retain(from - last);
554 let span = to - from;
555 match tendril {
556 Some(text) => {
557 changeset.insert(text);
558 changeset.delete(span);
559 }
560 None => changeset.delete(span),
561 }
562 last = to;
563 }
564
565 changeset.retain(len - last);
566
567 changeset
568 }
569 }
570
571 /// Transaction represents a single undoable unit of changes. Several changes can be grouped into
572 /// a single transaction.
573 #[derive(Debug, Default, Clone, PartialEq, Eq)]
574 pub struct Transaction {
575 changes: ChangeSet,
576 selection: Option<Selection>,
577 }
578
579 impl Transaction {
580 /// Create a new, empty transaction.
581 pub fn new(doc: &Rope) -> Self {
582 Self {
583 changes: ChangeSet::new(doc.slice(..)),
584 selection: None,
585 }
586 }
587
588 /// Changes made to the buffer.
589 pub fn changes(&self) -> &ChangeSet {
590 &self.changes
591 }
592
593 /// When set, explicitly updates the selection.
594 pub fn selection(&self) -> Option<&Selection> {
595 self.selection.as_ref()
596 }
597
598 /// Returns true if applied successfully.
599 pub fn apply(&self, doc: &mut Rope) -> bool {
600 if self.changes.is_empty() {
601 return true;
602 }
603
604 // apply changes to the document
605 self.changes.apply(doc)
606 }
607
608 /// Generate a transaction that reverts this one.
609 pub fn invert(&self, original: &Rope) -> Self {
610 let changes = self.changes.invert(original);
611
612 Self {
613 changes,
614 selection: None,
615 }
616 }
617
618 pub fn compose(mut self, other: Self) -> Self {
619 self.changes = self.changes.compose(other.changes);
620 // Other selection takes precedence
621 self.selection = other.selection;
622 self
623 }
624
625 pub fn with_selection(mut self, selection: Selection) -> Self {
626 self.selection = Some(selection);
627 self
628 }
629
630 /// Generate a transaction from a set of potentially overlapping changes. The `change_ranges`
631 /// iterator yield the range (of removed text) in the old document for each edit. If any change
632 /// overlaps with a range overlaps with a previous range then that range is ignored.
633 ///
634 /// The `process_change` callback is called for each edit that is not ignored (in the order
635 /// yielded by `changes`) and should return the new text that the associated range will be
636 /// replaced with.
637 ///
638 /// To make this function more flexible the iterator can yield additional data for each change
639 /// that is passed to `process_change`
640 pub fn change_ignore_overlapping<T>(
641 doc: &Rope,
642 change_ranges: impl Iterator<Item = (usize, usize, T)>,
643 mut process_change: impl FnMut(usize, usize, T) -> Option<Tendril>,
644 ) -> Self {
645 let mut last = 0;
646 let changes = change_ranges.filter_map(|(from, to, data)| {
647 if from < last {
648 return None;
649 }
650 let tendril = process_change(from, to, data);
651 last = to;
652 Some((from, to, tendril))
653 });
654 Self::change(doc, changes)
655 }
656
657 /// Generate a transaction from a set of changes.
658 pub fn change<I>(doc: &Rope, changes: I) -> Self
659 where
660 I: Iterator<Item = Change>,
661 {
662 Self::from(ChangeSet::from_changes(doc, changes))
663 }
664
665 /// Generate a transaction from a set of potentially overlapping deletions
666 /// by merging overlapping deletions together.
667 pub fn delete<I>(doc: &Rope, deletions: I) -> Self
668 where
669 I: Iterator<Item = Deletion>,
670 {
671 let len = doc.len_chars();
672
673 let (lower, upper) = deletions.size_hint();
674 let size = upper.unwrap_or(lower);
675 let mut changeset = ChangeSet::with_capacity(2 * size + 1); // rough estimate
676
677 let mut last = 0;
678 for (mut from, to) in deletions {
679 if last > to {
680 continue;
681 }
682 if last > from {
683 from = last
684 }
685 debug_assert!(
686 from <= to,
687 "Edit end must end before it starts (should {from} <= {to})"
688 );
689 // Retain from last "to" to current "from"
690 changeset.retain(from - last);
691 changeset.delete(to - from);
692 last = to;
693 }
694
695 changeset.retain(len - last);
696
697 Self::from(changeset)
698 }
699
700 pub fn insert_at_eof(mut self, text: Tendril) -> Transaction {
701 self.changes.insert(text);
702 self
703 }
704
705 /// Generate a transaction with a change per selection range.
706 pub fn change_by_selection<F>(doc: &Rope, selection: &Selection, f: F) -> Self
707 where
708 F: FnMut(&Range) -> Change,
709 {
710 Self::change(doc, selection.iter().map(f))
711 }
712
713 pub fn change_by_selection_ignore_overlapping(
714 doc: &Rope,
715 selection: &Selection,
716 mut change_range: impl FnMut(&Range) -> (usize, usize),
717 mut create_tendril: impl FnMut(usize, usize) -> Option<Tendril>,
718 ) -> (Transaction, Selection) {
719 let mut last_selection_idx = None;
720 let mut new_primary_idx = None;
721 let mut ranges: SmallVec<[Range; 1]> = SmallVec::new();
722 let process_change = |change_start, change_end, (idx, range): (usize, &Range)| {
723 // update the primary idx
724 if idx == selection.primary_index() {
725 new_primary_idx = Some(idx);
726 } else if new_primary_idx.is_none() {
727 if idx > selection.primary_index() {
728 new_primary_idx = last_selection_idx;
729 } else {
730 last_selection_idx = Some(idx);
731 }
732 }
733 ranges.push(*range);
734 create_tendril(change_start, change_end)
735 };
736 let transaction = Self::change_ignore_overlapping(
737 doc,
738 selection.iter().enumerate().map(|range| {
739 let (change_start, change_end) = change_range(range.1);
740 (change_start, change_end, range)
741 }),
742 process_change,
743 );
744
745 (
746 transaction,
747 Selection::new(ranges, new_primary_idx.unwrap_or(0)),
748 )
749 }
750
751 /// Generate a transaction with a change per selection range, which
752 /// generates a new selection as well. Each range is operated upon by
753 /// the given function and can optionally produce a new range. If none
754 /// is returned by the function, that range is mapped through the change
755 /// as usual.
756 pub fn change_by_and_with_selection<F>(doc: &Rope, selection: &Selection, mut f: F) -> Self
757 where
758 F: FnMut(&Range) -> (Change, Option<Range>),
759 {
760 let mut end_ranges = SmallVec::with_capacity(selection.len());
761 let mut offset = 0;
762
763 let transaction = Transaction::change_by_selection(doc, selection, |start_range| {
764 let ((from, to, replacement), end_range) = f(start_range);
765 let mut change_size = to as isize - from as isize;
766
767 if let Some(ref text) = replacement {
768 change_size = text.chars().count() as isize - change_size;
769 } else {
770 change_size = -change_size;
771 }
772
773 let new_range = if let Some(end_range) = end_range {
774 end_range
775 } else {
776 let changeset = ChangeSet::from_change(doc, (from, to, replacement.clone()));
777 start_range.map(&changeset)
778 };
779
780 let offset_range = Range::new(
781 (new_range.anchor as isize + offset) as usize,
782 (new_range.head as isize + offset) as usize,
783 );
784
785 end_ranges.push(offset_range);
786 offset += change_size;
787
788 log::trace!(
789 "from: {}, to: {}, replacement: {:?}, offset: {}",
790 from,
791 to,
792 replacement,
793 offset
794 );
795
796 (from, to, replacement)
797 });
798
799 transaction.with_selection(Selection::new(end_ranges, selection.primary_index()))
800 }
801
802 /// Generate a transaction with a deletion per selection range.
803 /// Compared to using `change_by_selection` directly these ranges may overlap.
804 /// In that case they are merged.
805 pub fn delete_by_selection<F>(doc: &Rope, selection: &Selection, f: F) -> Self
806 where
807 F: FnMut(&Range) -> Deletion,
808 {
809 Self::delete(doc, selection.iter().map(f))
810 }
811
812 /// Generate a transaction with a delete per selection range, which
813 /// generates a new selection as well. Each range is operated upon by
814 /// the given function and can optionally produce a new range. If none
815 /// is returned by the function, that range is mapped through the change
816 /// as usual.
817 ///
818 /// Compared to using `change_by_and_with_selection` directly these ranges
819 /// may overlap. In that case they are merged.
820 pub fn delete_by_and_with_selection<F>(doc: &Rope, selection: &Selection, mut f: F) -> Self
821 where
822 F: FnMut(&Range) -> (Deletion, Option<Range>),
823 {
824 let mut end_ranges = SmallVec::with_capacity(selection.len());
825 let mut offset = 0;
826 let mut last = 0;
827
828 let transaction = Transaction::delete_by_selection(doc, selection, |start_range| {
829 let ((from, to), end_range) = f(start_range);
830
831 // must account for possibly overlapping deletes
832 let change_size = if last > from { to - last } else { to - from };
833
834 let new_range = if let Some(end_range) = end_range {
835 end_range
836 } else {
837 let changeset = ChangeSet::from_change(doc, (from, to, None));
838 start_range.map(&changeset)
839 };
840
841 let offset_range = Range::new(
842 new_range.anchor.saturating_sub(offset),
843 new_range.head.saturating_sub(offset),
844 );
845
846 log::trace!(
847 "delete from: {}, to: {}, offset: {}, new_range: {:?}, offset_range: {:?}",
848 from,
849 to,
850 offset,
851 new_range,
852 offset_range
853 );
854
855 end_ranges.push(offset_range);
856 offset += change_size;
857 last = to;
858
859 (from, to)
860 });
861
862 transaction.with_selection(Selection::new(end_ranges, selection.primary_index()))
863 }
864
865 /// Insert text at each selection head.
866 pub fn insert(doc: &Rope, selection: &Selection, text: Tendril) -> Self {
867 Self::change_by_selection(doc, selection, |range| {
868 (range.head, range.head, Some(text.clone()))
869 })
870 }
871
872 pub fn changes_iter(&self) -> ChangeIterator<'_> {
873 self.changes.changes_iter()
874 }
875 }
876
877 impl From<ChangeSet> for Transaction {
878 fn from(changes: ChangeSet) -> Self {
879 Self {
880 changes,
881 selection: None,
882 }
883 }
884 }
885
886 pub struct ChangeIterator<'a> {
887 iter: std::iter::Peekable<std::slice::Iter<'a, Operation>>,
888 pos: usize,
889 }
890
891 impl<'a> ChangeIterator<'a> {
892 fn new(changeset: &'a ChangeSet) -> Self {
893 let iter = changeset.changes.iter().peekable();
894 Self { iter, pos: 0 }
895 }
896 }
897
898 impl Iterator for ChangeIterator<'_> {
899 type Item = Change;
900
901 fn next(&mut self) -> Option<Self::Item> {
902 use Operation::*;
903
904 loop {
905 match self.iter.next()? {
906 Retain(len) => {
907 self.pos += len;
908 }
909 Delete(len) => {
910 let start = self.pos;
911 self.pos += len;
912 return Some((start, self.pos, None));
913 }
914 Insert(s) => {
915 let start = self.pos;
916 // a subsequent delete means a replace, consume it
917 if let Some(Delete(len)) = self.iter.peek() {
918 self.iter.next();
919
920 self.pos += len;
921 return Some((start, self.pos, Some(s.clone())));
922 } else {
923 return Some((start, start, Some(s.clone())));
924 }
925 }
926 }
927 }
928 }
929 }
930
931 #[cfg(test)]
932 mod test {
933 use super::*;
934 use crate::history::State;
935
936 #[test]
937 fn composition() {
938 use Operation::*;
939
940 let a = ChangeSet {
941 changes: vec![
942 Retain(5),
943 Insert(" test!".into()),
944 Retain(1),
945 Delete(2),
946 Insert("abc".into()),
947 ],
948 len: 8,
949 len_after: 15,
950 };
951
952 let b = ChangeSet {
953 changes: vec![Delete(10), Insert("世orld".into()), Retain(5)],
954 len: 15,
955 len_after: 10,
956 };
957
958 let mut text = Rope::from("hello xz");
959
960 // should probably return cloned text
961 let composed = a.compose(b);
962 assert_eq!(composed.len, 8);
963 assert!(composed.apply(&mut text));
964 assert_eq!(text, "世orld! abc");
965 }
966
967 #[test]
968 fn invert() {
969 use Operation::*;
970
971 let changes = ChangeSet {
972 changes: vec![Retain(4), Insert("test".into()), Delete(5), Retain(3)],
973 len: 12,
974 len_after: 11,
975 };
976
977 let doc = Rope::from("世界3 hello xz");
978 let revert = changes.invert(&doc);
979
980 let mut doc2 = doc.clone();
981 changes.apply(&mut doc2);
982
983 // a revert is different
984 assert_ne!(changes, revert);
985 assert_ne!(doc, doc2);
986
987 // but inverting a revert will give us the original
988 assert_eq!(changes, revert.invert(&doc2));
989
990 // applying a revert gives us back the original
991 revert.apply(&mut doc2);
992 assert_eq!(doc, doc2);
993 }
994
995 #[test]
996 fn map_pos() {
997 use Operation::*;
998
999 // maps inserts
1000 let cs = ChangeSet {
1001 changes: vec![Retain(4), Insert("!!".into()), Retain(4)],
1002 len: 8,
1003 len_after: 10,
1004 };
1005
1006 assert_eq!(cs.map_pos(0, Assoc::Before), 0); // before insert region
1007 assert_eq!(cs.map_pos(4, Assoc::Before), 4); // at insert, track before
1008 assert_eq!(cs.map_pos(4, Assoc::After), 6); // at insert, track after
1009 assert_eq!(cs.map_pos(5, Assoc::Before), 7); // after insert region
1010
1011 // maps deletes
1012 let cs = ChangeSet {
1013 changes: vec![Retain(4), Delete(4), Retain(4)],
1014 len: 12,
1015 len_after: 8,
1016 };
1017 assert_eq!(cs.map_pos(0, Assoc::Before), 0); // at start
1018 assert_eq!(cs.map_pos(4, Assoc::Before), 4); // before a delete
1019 assert_eq!(cs.map_pos(5, Assoc::Before), 4); // inside a delete
1020 assert_eq!(cs.map_pos(5, Assoc::After), 4); // inside a delete
1021
1022 // TODO: delete tracking
1023
1024 // stays inbetween replacements
1025 let cs = ChangeSet {
1026 changes: vec![
1027 Insert("ab".into()),
1028 Delete(2),
1029 Insert("cd".into()),
1030 Delete(2),
1031 ],
1032 len: 4,
1033 len_after: 4,
1034 };
1035 assert_eq!(cs.map_pos(2, Assoc::Before), 2);
1036 assert_eq!(cs.map_pos(2, Assoc::After), 2);
1037 // unsorted selection
1038 let cs = ChangeSet {
1039 changes: vec![
1040 Insert("ab".into()),
1041 Delete(2),
1042 Insert("cd".into()),
1043 Delete(2),
1044 ],
1045 len: 4,
1046 len_after: 4,
1047 };
1048 let mut positions = [4, 2];
1049 cs.update_positions(positions.iter_mut().map(|pos| (pos, Assoc::After)));
1050 assert_eq!(positions, [4, 2]);
1051 // stays at word boundary
1052 let cs = ChangeSet {
1053 changes: vec![
1054 Retain(2), // <space><space>
1055 Insert(" ab".into()),
1056 Retain(2), // cd
1057 Insert("de ".into()),
1058 ],
1059 len: 4,
1060 len_after: 10,
1061 };
1062 assert_eq!(cs.map_pos(2, Assoc::BeforeWord), 3);
1063 assert_eq!(cs.map_pos(4, Assoc::AfterWord), 9);
1064 let cs = ChangeSet {
1065 changes: vec![
1066 Retain(1), // <space>
1067 Insert(" b".into()),
1068 Delete(1), // c
1069 Retain(1), // d
1070 Insert("e ".into()),
1071 Delete(1), // <space>
1072 ],
1073 len: 5,
1074 len_after: 7,
1075 };
1076 assert_eq!(cs.map_pos(1, Assoc::BeforeWord), 2);
1077 assert_eq!(cs.map_pos(3, Assoc::AfterWord), 5);
1078 let cs = ChangeSet {
1079 changes: vec![
1080 Retain(1), // <space>
1081 Insert("a".into()),
1082 Delete(2), // <space>b
1083 Retain(1), // d
1084 Insert("e".into()),
1085 Delete(1), // f
1086 Retain(1), // <space>
1087 ],
1088 len: 5,
1089 len_after: 7,
1090 };
1091 assert_eq!(cs.map_pos(2, Assoc::BeforeWord), 1);
1092 assert_eq!(cs.map_pos(4, Assoc::AfterWord), 4);
1093 }
1094
1095 #[test]
1096 fn transaction_change() {
1097 let mut doc = Rope::from("hello world!\ntest 123");
1098 let transaction = Transaction::change(
1099 &doc,
1100 // (1, 1, None) is a useless 0-width delete that gets factored out
1101 vec![(1, 1, None), (6, 11, Some("void".into())), (12, 17, None)].into_iter(),
1102 );
1103 transaction.apply(&mut doc);
1104 assert_eq!(doc, Rope::from_str("hello void! 123"));
1105 }
1106
1107 #[test]
1108 fn changes_iter() {
1109 let doc = Rope::from("hello world!\ntest 123");
1110 let changes = vec![(6, 11, Some("void".into())), (12, 17, None)];
1111 let transaction = Transaction::change(&doc, changes.clone().into_iter());
1112 assert_eq!(transaction.changes_iter().collect::<Vec<_>>(), changes);
1113 }
1114
1115 #[test]
1116 fn optimized_composition() {
1117 let mut state = State {
1118 doc: "".into(),
1119 selection: Selection::point(0),
1120 };
1121 let t1 = Transaction::insert(&state.doc, &state.selection, Tendril::from("h"));
1122 t1.apply(&mut state.doc);
1123 state.selection = state.selection.clone().map(t1.changes());
1124 let t2 = Transaction::insert(&state.doc, &state.selection, Tendril::from("e"));
1125 t2.apply(&mut state.doc);
1126 state.selection = state.selection.clone().map(t2.changes());
1127 let t3 = Transaction::insert(&state.doc, &state.selection, Tendril::from("l"));
1128 t3.apply(&mut state.doc);
1129 state.selection = state.selection.clone().map(t3.changes());
1130 let t4 = Transaction::insert(&state.doc, &state.selection, Tendril::from("l"));
1131 t4.apply(&mut state.doc);
1132 state.selection = state.selection.clone().map(t4.changes());
1133 let t5 = Transaction::insert(&state.doc, &state.selection, Tendril::from("o"));
1134 t5.apply(&mut state.doc);
1135 state.selection = state.selection.clone().map(t5.changes());
1136
1137 assert_eq!(state.doc, Rope::from_str("hello"));
1138
1139 // changesets as follows:
1140 // h
1141 // retain 1, e
1142 // retain 2, l
1143
1144 let changes = t1
1145 .changes
1146 .compose(t2.changes)
1147 .compose(t3.changes)
1148 .compose(t4.changes)
1149 .compose(t5.changes);
1150
1151 use Operation::*;
1152 assert_eq!(changes.changes, &[Insert("hello".into())]);
1153 // instead of insert h, insert e, insert l, insert l, insert o
1154 }
1155
1156 #[test]
1157 fn combine_with_empty() {
1158 let empty = Rope::from("");
1159 let a = ChangeSet::new(empty.slice(..));
1160
1161 let mut b = ChangeSet::new(empty.slice(..));
1162 b.insert("a".into());
1163
1164 let changes = a.compose(b);
1165
1166 use Operation::*;
1167 assert_eq!(changes.changes, &[Insert("a".into())]);
1168 }
1169
1170 #[test]
1171 fn combine_with_utf8() {
1172 const TEST_CASE: &str = "Hello, これはヘリックスエディターです!";
1173
1174 let empty = Rope::from("");
1175 let a = ChangeSet::new(empty.slice(..));
1176
1177 let mut b = ChangeSet::new(empty.slice(..));
1178 b.insert(TEST_CASE.into());
1179
1180 let changes = a.compose(b);
1181
1182 use Operation::*;
1183 assert_eq!(changes.changes, &[Insert(TEST_CASE.into())]);
1184 assert_eq!(changes.len_after, TEST_CASE.chars().count());
1185 }
1186 }