@@ -1,3 +1,5 @@
1+use smallvec::SmallVec;
1use crate::{Range, Rope, Selection, Tendril};
3use crate::{Range, Rope, Selection, Tendril};
2use std::borrow::Cow;
4use std::borrow::Cow;
@@ -466,6 +468,33 @@ impl Transaction {
471+ /// Generate a transaction from a set of potentially overlapping changes. The `change_ranges`
472+ /// iterator yield the range (of removed text) in the old document for each edit. If any change
473+ /// overlaps with a range overlaps with a previous range then that range is ignored.
475+ /// The `process_change` callback is called for each edit that is not ignored (in the order
476+ /// yielded by `changes`) and should return the new text that the associated range will be
479+ /// To make this function more flexible the iterator can yield additional data for each change
480+ /// that is passed to `process_change`
481+ pub fn change_ignore_overlapping<T>(
483+ change_ranges: impl Iterator<Item = (usize, usize, T)>,
484+ mut process_change: impl FnMut(usize, usize, T) -> Option<Tendril>,
487+ let changes = change_ranges.filter_map(|(from, to, data)| {
491+ let tendril = process_change(from, to, data);
493+ Some((from, to, tendril))
495+ Self::change(doc, changes)
469 /// Generate a transaction from a set of changes.
498 /// Generate a transaction from a set of changes.
470 pub fn change<I>(doc: &Rope, changes: I) -> Self
499 pub fn change<I>(doc: &Rope, changes: I) -> Self
@@ -513,6 +542,44 @@ impl Transaction {
513 Self::change(doc, selection.iter().map(f))
542 Self::change(doc, selection.iter().map(f))
545+ pub fn change_by_selection_ignore_overlapping(
547+ selection: &Selection,
548+ mut change_range: impl FnMut(&Range) -> (usize, usize),
549+ mut create_tendril: impl FnMut(usize, usize) -> Option<Tendril>,
550+ ) -> (Transaction, Selection) {
551+ let mut last_selection_idx = None;
552+ let mut new_primary_idx = None;
553+ let mut ranges: SmallVec<[Range; 1]> = SmallVec::new();
554+ let process_change = |change_start, change_end, (idx, range): (usize, &Range)| {
555+ // update the primary idx
556+ if idx == selection.primary_index() {
557+ new_primary_idx = Some(idx);
558+ } else if new_primary_idx.is_none() {
559+ if idx > selection.primary_index() {
560+ new_primary_idx = last_selection_idx;
562+ last_selection_idx = Some(idx);
565+ ranges.push(*range);
566+ create_tendril(change_start, change_end)
568+ let transaction = Self::change_ignore_overlapping(
570+ selection.iter().enumerate().map(|range| {
571+ let (change_start, change_end) = change_range(range.1);
572+ (change_start, change_end, range)
579+ Selection::new(ranges, new_primary_idx.unwrap_or(0)),
516 /// Insert text at each selection head.
583 /// Insert text at each selection head.
517 pub fn insert(doc: &Rope, selection: &Selection, text: Tendril) -> Self {
584 pub fn insert(doc: &Rope, selection: &Selection, text: Tendril) -> Self {
518 Self::change_by_selection(doc, selection, |range| {
585 Self::change_by_selection(doc, selection, |range| {