Skip to main content

continuity_text/
edit.rs

1//! Atomic edit operations.
2//!
3//! Every mutation, every undo entry, and every persisted edit row reduces to
4//! one of these three variants. Higher-level commands (move-line-up,
5//! duplicate-selection, etc.) decompose into a sequence of `EditOp`s grouped
6//! by an `UndoGroupId`.
7
8use crate::{Position, Range};
9
10/// A single, atomic edit on a buffer.
11///
12/// All positions and ranges are raw source-rope UTF-8 byte coordinates.
13/// Display-map adjusted coordinates must be converted before constructing
14/// an edit.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum EditOp {
17    /// Insert `text` at position `at`.
18    Insert {
19        /// Where to insert.
20        at: Position,
21        /// What to insert.
22        text: String,
23    },
24    /// Delete the bytes covered by `range`.
25    Delete {
26        /// The range to delete.
27        range: Range,
28    },
29    /// Replace the bytes covered by `range` with `text`.
30    Replace {
31        /// The range to replace.
32        range: Range,
33        /// The replacement text.
34        text: String,
35    },
36}
37
38impl EditOp {
39    /// Convenience constructor for [`EditOp::Insert`].
40    pub fn insert(at: Position, text: impl Into<String>) -> Self {
41        Self::Insert {
42            at,
43            text: text.into(),
44        }
45    }
46
47    /// Convenience constructor for [`EditOp::Delete`].
48    #[must_use]
49    pub fn delete(range: Range) -> Self {
50        Self::Delete { range }
51    }
52
53    /// Convenience constructor for [`EditOp::Replace`].
54    pub fn replace(range: Range, text: impl Into<String>) -> Self {
55        Self::Replace {
56            range,
57            text: text.into(),
58        }
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn insert_constructor() {
68        let e = EditOp::insert(Position::ZERO, "hi");
69        assert!(matches!(e, EditOp::Insert { ref text, .. } if text == "hi"));
70    }
71
72    #[test]
73    fn delete_constructor() {
74        let e = EditOp::delete(Range::empty(Position::ZERO));
75        assert!(matches!(e, EditOp::Delete { .. }));
76    }
77
78    #[test]
79    fn replace_constructor() {
80        let e = EditOp::replace(Range::empty(Position::ZERO), "x");
81        assert!(matches!(e, EditOp::Replace { ref text, .. } if text == "x"));
82    }
83}