Skip to main content

editor_core/
delta.rs

1//! Structured text change deltas.
2//!
3//! `editor-core` historically exposed state changes as a coarse event
4//! ([`crate::StateChangeType::DocumentModified`]) plus a best-effort affected region.
5//! For a full-featured editor, incremental consumers (LSP sync, incremental parsing, indexing,
6//! match highlighting, etc.) typically need **structured edits** without diffing old/new text.
7//!
8//! This module defines a small, UI-agnostic delta format expressed in **character offsets**
9//! (Unicode scalar values).
10
11/// A single text edit expressed in character offsets.
12///
13/// Semantics:
14/// - `start` is a character offset in the document **at the time this edit is applied**.
15/// - The deleted range is defined by the length (in `char`s) of `deleted_text`.
16/// - Edits inside a [`TextDelta`] must be applied **in order** to transform the "before" document
17///   into the "after" document.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct TextDeltaEdit {
20    /// Start character offset of the edit.
21    pub start: usize,
22    /// Exact deleted text (may be empty).
23    pub deleted_text: String,
24    /// Exact inserted text (may be empty).
25    pub inserted_text: String,
26}
27
28impl TextDeltaEdit {
29    /// Length of `deleted_text` in characters.
30    pub fn deleted_len(&self) -> usize {
31        self.deleted_text.chars().count()
32    }
33
34    /// Length of `inserted_text` in characters.
35    pub fn inserted_len(&self) -> usize {
36        self.inserted_text.chars().count()
37    }
38
39    /// Exclusive end character offset in the pre-edit document.
40    pub fn end(&self) -> usize {
41        self.start.saturating_add(self.deleted_len())
42    }
43}
44
45/// A structured description of a document text change.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct TextDelta {
48    /// Character count before applying `edits`.
49    pub before_char_count: usize,
50    /// Character count after applying `edits`.
51    pub after_char_count: usize,
52    /// Ordered list of edits that transforms the "before" document into the "after" document.
53    pub edits: Vec<TextDeltaEdit>,
54    /// If known, the undo group id associated with this change.
55    pub undo_group_id: Option<usize>,
56}
57
58impl TextDelta {
59    /// Returns `true` if this delta contains no edits.
60    pub fn is_empty(&self) -> bool {
61        self.edits.is_empty()
62    }
63
64    /// Merge two consecutive deltas into a single equivalent delta.
65    ///
66    /// `first` transforms document `B0 -> B1` and `second` transforms `B1 -> B2` (i.e. `second`
67    /// was produced against the document state that results from applying `first`). The returned
68    /// delta transforms `B0 -> B2`.
69    ///
70    /// Because a [`TextDelta`]'s edits are defined to be applied **in order**, each using the
71    /// offset valid *at the time that edit is applied*, the merge is simply the concatenation of
72    /// the two edit lists: applying `first`'s edits reaches `B1`, then applying `second`'s edits
73    /// (already expressed against `B1`) reaches `B2`. No coordinate remapping is required.
74    ///
75    /// This is used to coalesce buffer deltas that accumulate between consumptions, so a consumer
76    /// that only reads the latest stored delta still observes every intervening edit.
77    pub fn merge(first: &TextDelta, second: &TextDelta) -> TextDelta {
78        debug_assert_eq!(
79            first.after_char_count, second.before_char_count,
80            "merged deltas must be consecutive: first.after must equal second.before"
81        );
82
83        // Concatenating empty lists still yields a valid delta; handle the fast paths cheaply.
84        if first.is_empty() {
85            return second.clone();
86        }
87        if second.is_empty() {
88            return first.clone();
89        }
90
91        let mut edits = Vec::with_capacity(first.edits.len() + second.edits.len());
92        edits.extend(first.edits.iter().cloned());
93        edits.extend(second.edits.iter().cloned());
94
95        TextDelta {
96            before_char_count: first.before_char_count,
97            after_char_count: second.after_char_count,
98            edits,
99            // The merged delta spans two changes; only keep a group id if both agree on one.
100            undo_group_id: match (first.undo_group_id, second.undo_group_id) {
101                (Some(a), Some(b)) if a == b => Some(a),
102                _ => None,
103            },
104        }
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    /// Apply a delta's edits, in order, to a string using char offsets (the delta contract).
113    fn apply(text: &str, delta: &TextDelta) -> String {
114        let mut chars: Vec<char> = text.chars().collect();
115        assert_eq!(chars.len(), delta.before_char_count, "before_char_count");
116        for edit in &delta.edits {
117            let start = edit.start;
118            let end = edit.end();
119            assert!(end <= chars.len(), "edit out of range");
120            let inserted: Vec<char> = edit.inserted_text.chars().collect();
121            chars.splice(start..end, inserted);
122        }
123        assert_eq!(chars.len(), delta.after_char_count, "after_char_count");
124        chars.into_iter().collect()
125    }
126
127    fn edit(start: usize, deleted: &str, inserted: &str) -> TextDeltaEdit {
128        TextDeltaEdit {
129            start,
130            deleted_text: deleted.to_string(),
131            inserted_text: inserted.to_string(),
132        }
133    }
134
135    #[test]
136    fn merge_of_two_inserts_replays_both() {
137        // B0 "abc" --insert ">>" at 0--> B1 ">>abc" --insert "!" at 5--> B2 ">>abc!"
138        let d1 = TextDelta {
139            before_char_count: 3,
140            after_char_count: 5,
141            edits: vec![edit(0, "", ">>")],
142            undo_group_id: Some(1),
143        };
144        let d2 = TextDelta {
145            before_char_count: 5,
146            after_char_count: 6,
147            edits: vec![edit(5, "", "!")],
148            undo_group_id: Some(2),
149        };
150
151        let merged = TextDelta::merge(&d1, &d2);
152        assert_eq!(merged.before_char_count, 3);
153        assert_eq!(merged.after_char_count, 6);
154        // Applying the merged delta to B0 must equal applying d1 then d2.
155        let via_merged = apply("abc", &merged);
156        let via_steps = apply(&apply("abc", &d1), &d2);
157        assert_eq!(via_merged, ">>abc!");
158        assert_eq!(via_merged, via_steps);
159        // Differing group ids collapse to None.
160        assert_eq!(merged.undo_group_id, None);
161    }
162
163    #[test]
164    fn merge_with_deletions_replays_both() {
165        // B0 "hello world" --del [0,6)--> B1 "world" --replace [0,5) with "there"--> B2 "there"
166        let d1 = TextDelta {
167            before_char_count: 11,
168            after_char_count: 5,
169            edits: vec![edit(0, "hello ", "")],
170            undo_group_id: None,
171        };
172        let d2 = TextDelta {
173            before_char_count: 5,
174            after_char_count: 5,
175            edits: vec![edit(0, "world", "there")],
176            undo_group_id: None,
177        };
178        let merged = TextDelta::merge(&d1, &d2);
179        assert_eq!(apply("hello world", &merged), "there");
180        assert_eq!(
181            apply("hello world", &merged),
182            apply(&apply("hello world", &d1), &d2)
183        );
184    }
185
186    #[test]
187    fn merge_preserves_shared_group_id() {
188        let d1 = TextDelta {
189            before_char_count: 0,
190            after_char_count: 1,
191            edits: vec![edit(0, "", "a")],
192            undo_group_id: Some(7),
193        };
194        let d2 = TextDelta {
195            before_char_count: 1,
196            after_char_count: 2,
197            edits: vec![edit(1, "", "b")],
198            undo_group_id: Some(7),
199        };
200        assert_eq!(TextDelta::merge(&d1, &d2).undo_group_id, Some(7));
201    }
202
203    #[test]
204    fn merge_with_empty_delta_is_identity() {
205        let empty = TextDelta {
206            before_char_count: 3,
207            after_char_count: 3,
208            edits: Vec::new(),
209            undo_group_id: None,
210        };
211        let d = TextDelta {
212            before_char_count: 3,
213            after_char_count: 4,
214            edits: vec![edit(3, "", "!")],
215            undo_group_id: Some(1),
216        };
217        // empty ∘ d == d
218        assert_eq!(TextDelta::merge(&empty, &d), d);
219        // d ∘ empty' == d, where empty' matches d's after state
220        let empty_after = TextDelta {
221            before_char_count: 4,
222            after_char_count: 4,
223            edits: Vec::new(),
224            undo_group_id: None,
225        };
226        assert_eq!(TextDelta::merge(&d, &empty_after), d);
227    }
228
229    #[test]
230    fn merge_multi_edit_deltas_replays_in_order() {
231        // Two multi-edit deltas; verify the merged edits reproduce sequential application.
232        let d1 = TextDelta {
233            before_char_count: 5,
234            after_char_count: 7,
235            // "abcde": insert "X" at 5, then (already-applied-order) insert "Y" at 0 uses
236            // post-first-edit coordinates per the in-order contract.
237            edits: vec![edit(5, "", "X"), edit(0, "", "Y")],
238            undo_group_id: None,
239        };
240        let b1 = apply("abcde", &d1); // "YabcdeX"
241        let d2 = TextDelta {
242            before_char_count: 7,
243            after_char_count: 6,
244            edits: vec![edit(0, "Y", "")],
245            undo_group_id: None,
246        };
247        let merged = TextDelta::merge(&d1, &d2);
248        assert_eq!(apply("abcde", &merged), apply(&b1, &d2));
249        assert_eq!(apply("abcde", &merged), "abcdeX");
250    }
251}