@@ -342,31 +342,37 @@ impl Transaction {
342342 true
343343 }
344344
345− pub fn insert(state: &State, text: Tendril) -> Self {
345+ pub fn change_by_selection<F>(state: &State, f: F) -> Self
346+ where
347+ F: Fn(&SelectionRange) -> (usize, usize, Option<Tendril>),
348+ {
346349 let len = state.doc.len_chars();
347350 let ranges = state.selection.ranges();
348− let mut changes = Vec::with_capacity(2 * ranges.len() + 1);
349− let mut last = 0;
351+ let mut acc = Vec::with_capacity(2 * ranges.len() + 1);
352+
353+ let changes = ranges.iter().map(f);
354+
355+ // TODO: verify ranges are ordered and not overlapping.
350356
351− for range in state.selection.ranges() {
352− let cur = range.head;
353− changes.push(Change::Retain(cur));
354− changes.push(Change::Insert(text.clone()));
355− last = cur;
357+ let mut last = 0;
358+ for (from, to, tendril) in changes {
359+ // TODO: need to fill the in-between ranges too
360+ // Retain from last "to" to current "from"
361+ acc.push(Change::Retain(from - last));
362+ match tendril {
363+ Some(text) => acc.push(Change::Insert(text)),
364+ None => acc.push(Change::Delete(to - from)),
365+ }
366+ last = to;
356367 }
357− changes.push(Change::Retain(len - last));
368+ acc.push(Change::Retain(len - last));
358369
359− Self::from(ChangeSet { changes, len })
370+ Self::from(ChangeSet { changes: acc, len })
360371 }
361372
362− pub fn change_selection<F>(selection: Selection, f: F) -> Self
363− where
364− F: Fn(SelectionRange) -> ChangeSet,
365− {
366− selection.ranges().iter().map(|range| true);
367− // TODO: most idiomatic would be to return a
368− // Change { from: x, to: y, insert: "str" }
369− unimplemented!()
373+ /// Insert text at each selection head.
374+ pub fn insert(state: &State, text: Tendril) -> Self {
375+ Self::change_by_selection(state, |range| (range.head, range.head, Some(text.clone())))
370376 }
371377}
372378