Skip to main content

cimview/
text.rs

1//! Places in a document's text and edits to it, as an editor counts them: lines from 0, and
2//! columns in UTF-16 code units, as LSP and JavaScript strings do. They serialize as LSP's do
3//! (`{ "line", "character" }`, `{ "start", "end" }`, `{ "range", "newText" }`).
4
5use serde::{Deserialize, Serialize};
6
7#[derive(
8    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
9)]
10pub struct Position {
11    pub line: u32,
12    pub character: u32,
13}
14
15impl Position {
16    pub fn new(line: u32, character: u32) -> Self {
17        Self { line, character }
18    }
19}
20
21#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
22pub struct Range {
23    pub start: Position,
24    pub end: Position,
25}
26
27impl Range {
28    pub fn new(start: Position, end: Position) -> Self {
29        Self { start, end }
30    }
31}
32
33/// Whether `pos` is in `r`, its ends included.
34pub fn contains(r: Range, pos: Position) -> bool {
35    r.start <= pos && pos <= r.end
36}
37
38/// `range` of a document replaced by `new_text`.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "camelCase")]
41pub struct TextEdit {
42    pub range: Range,
43    pub new_text: String,
44}
45
46impl TextEdit {
47    pub fn new(range: Range, new_text: String) -> Self {
48        Self { range, new_text }
49    }
50}
51
52/// Byte offsets ↔ positions.
53pub struct LineIndex {
54    starts: Vec<usize>,
55}
56
57impl LineIndex {
58    pub fn new(text: &str) -> Self {
59        let mut starts = vec![0];
60        starts.extend(
61            text.bytes()
62                .enumerate()
63                .filter(|(_, b)| *b == b'\n')
64                .map(|(i, _)| i + 1),
65        );
66        Self { starts }
67    }
68
69    pub fn position(&self, text: &str, offset: usize) -> Position {
70        let line = self.starts.partition_point(|s| *s <= offset) - 1;
71        let start = self.starts[line];
72        let character = text
73            .get(start..offset)
74            .map_or(0, |s| s.encode_utf16().count());
75        Position {
76            line: line as u32,
77            character: character as u32,
78        }
79    }
80
81    pub fn range(&self, text: &str, start: usize, end: usize) -> Range {
82        Range {
83            start: self.position(text, start),
84            end: self.position(text, end),
85        }
86    }
87
88    pub fn offset(&self, text: &str, pos: Position) -> usize {
89        let Some(&start) = self.starts.get(pos.line as usize) else {
90            return text.len();
91        };
92        let end = self
93            .starts
94            .get(pos.line as usize + 1)
95            .copied()
96            .unwrap_or(text.len());
97        let mut units = 0u32;
98        for (i, c) in text[start..end].char_indices() {
99            if units >= pos.character {
100                return start + i;
101            }
102            units += c.len_utf16() as u32;
103        }
104        end
105    }
106}
107
108/// `text` with `edits` applied, each placed in `text` as it was: they must not overlap.
109pub fn apply(text: &str, edits: &[TextEdit]) -> String {
110    apply_indexed(text, &LineIndex::new(text), edits)
111}
112
113/// [`apply`], with the lines of `text` already counted. In one pass: the text is copied once
114/// however many the edits, which matters for a file of 80 MB.
115pub fn apply_indexed(text: &str, lines: &LineIndex, edits: &[TextEdit]) -> String {
116    let mut spans: Vec<(usize, usize, &str)> = edits
117        .iter()
118        .map(|e| {
119            (
120                lines.offset(text, e.range.start),
121                lines.offset(text, e.range.end),
122                e.new_text.as_str(),
123            )
124        })
125        .collect();
126    // Stable: inserts at one place keep their order.
127    spans.sort_by_key(|s| s.0);
128    let added: usize = spans.iter().map(|s| s.2.len()).sum();
129    let mut out = String::with_capacity(text.len() + added);
130    let (mut at, mut i) = (0, 0);
131    while i < spans.len() {
132        let start = spans[i].0;
133        let mut j = i;
134        while j < spans.len() && spans[j].0 == start {
135            j += 1;
136        }
137        // A replacement among inserts at one place takes its span.
138        let end = spans[i..j].iter().map(|s| s.1).max().unwrap_or(start);
139        out.push_str(&text[at.min(start)..start]);
140        spans[i..j].iter().for_each(|s| out.push_str(s.2));
141        at = at.max(end);
142        i = j;
143    }
144    out.push_str(&text[at.min(text.len())..]);
145    out
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn utf16_positions_round_trip() {
154        let text = "a\n€x𝄞y\n";
155        let lines = LineIndex::new(text);
156        let y = text.find('y').unwrap();
157        assert_eq!(lines.position(text, y), Position::new(1, 4));
158        assert_eq!(lines.offset(text, Position::new(1, 4)), y);
159    }
160
161    #[test]
162    fn edits_apply_from_the_end_and_inserts_at_one_place_keep_their_order() {
163        let text = "ab\ncd\n";
164        let at = |l, c| Position::new(l, c);
165        let edits = [
166            TextEdit::new(Range::new(at(0, 1), at(0, 2)), "B".into()),
167            TextEdit::new(Range::new(at(1, 0), at(1, 0)), "1".into()),
168            TextEdit::new(Range::new(at(1, 0), at(1, 0)), "2".into()),
169        ];
170        assert_eq!(apply(text, &edits), "aB\n12cd\n");
171    }
172
173    #[test]
174    fn positions_serialize_as_lsp_does() {
175        let edit = TextEdit::new(
176            Range::new(Position::new(1, 2), Position::new(3, 4)),
177            "x".into(),
178        );
179        assert_eq!(
180            serde_json::to_value(&edit).unwrap(),
181            serde_json::json!({ "range": { "start": { "line": 1, "character": 2 }, "end": { "line": 3, "character": 4 } }, "newText": "x" })
182        );
183    }
184}