Skip to main content

continuity_engine/
edit_indent_subtree.rs

1//! Indent-subtree range computation.
2//!
3//! The "indent subtree" of a line `n` is the half-open line range
4//! `[n, end)` covering `n` plus every following line whose leading
5//! indent is **deeper than** `n`'s. Blank lines are absorbed: they
6//! belong to the subtree only when followed by a line still indented
7//! deeper than `n`. The first line with indent `<= n` ends the
8//! subtree.
9//!
10//! Two consumers (this module ships the analysis side; the planner
11//! `SelectionEdit::MoveIndentSubtreeUp/Down` wiring is queued for a
12//! follow-up):
13//! - §H3 folding: the foldable region geometry.
14//! - §H3a `MoveIndentSubtreeUp/Down`: swap the subtree with its
15//!   nearest equal-or-shallower sibling.
16//!
17//! The `Buffer` ↔ `EditOp` glue lives upstream of this module so the
18//! analysis stays pure-function over `&Rope`.
19
20use ropey::Rope;
21
22/// Half-open source-line range `[start_line, end_line)`.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct IndentRange {
25    /// First line (inclusive).
26    pub start_line: u32,
27    /// Last-line-exclusive end.
28    pub end_line: u32,
29}
30
31impl IndentRange {
32    /// `true` when this range spans only a single line.
33    #[must_use]
34    pub(crate) fn is_single_line(&self) -> bool {
35        self.end_line.saturating_sub(self.start_line) <= 1
36    }
37}
38
39/// Leading-indent column of `line` (tabs counted as 4 columns).
40/// Blank lines return `u32::MAX` so they never terminate a subtree.
41#[must_use]
42pub fn line_indent(rope: &Rope, line: u32) -> u32 {
43    let total = rope.len_lines();
44    if (line as usize) >= total {
45        return 0;
46    }
47    let start = rope.line_to_byte(line as usize);
48    let end = if (line as usize) + 1 < total {
49        rope.line_to_byte((line as usize) + 1)
50    } else {
51        rope.len_bytes()
52    };
53    let slice = rope.byte_slice(start..end);
54    let mut indent = 0u32;
55    let mut any_non_ws = false;
56    for ch in slice.chars() {
57        match ch {
58            ' ' => indent += 1,
59            '\t' => indent += 4,
60            '\r' | '\n' => break,
61            _ => {
62                any_non_ws = true;
63                break;
64            }
65        }
66    }
67    if any_non_ws {
68        indent
69    } else {
70        u32::MAX
71    }
72}
73
74/// Compute the indent subtree of `line`. Returns `None` when `line`
75/// is past the buffer's last source line.
76///
77/// The subtree includes `line` itself plus every following line whose
78/// indent is strictly deeper than `line`'s. Blank lines are absorbed.
79#[must_use]
80pub fn indent_subtree(rope: &Rope, line: u32) -> Option<IndentRange> {
81    let total = u32::try_from(rope.len_lines()).ok()?;
82    if total == 0 || line >= total {
83        return None;
84    }
85    let base = line_indent(rope, line);
86    if base == u32::MAX {
87        return Some(IndentRange {
88            start_line: line,
89            end_line: line + 1,
90        });
91    }
92    let mut end = line + 1;
93    while end < total {
94        let i = line_indent(rope, end);
95        if i == u32::MAX {
96            // Blank line — peek forward. If the next non-blank line
97            // is still deeper than base, absorb; else stop.
98            let mut peek = end + 1;
99            while peek < total && line_indent(rope, peek) == u32::MAX {
100                peek += 1;
101            }
102            if peek < total && line_indent(rope, peek) > base {
103                end = peek + 1;
104                continue;
105            }
106            break;
107        }
108        if i <= base {
109            break;
110        }
111        end += 1;
112    }
113    Some(IndentRange {
114        start_line: line,
115        end_line: end,
116    })
117}
118
119/// Find the previous sibling of the subtree starting at `line`. A
120/// sibling is the closest preceding line with indent equal to or
121/// shallower than `line`'s. Returns the `IndentRange` of that
122/// sibling, or `None` if no sibling exists at or above this depth.
123#[must_use]
124pub fn previous_sibling_subtree(rope: &Rope, line: u32) -> Option<IndentRange> {
125    if line == 0 {
126        return None;
127    }
128    let base = line_indent(rope, line);
129    if base == u32::MAX {
130        return None;
131    }
132    let mut probe = line;
133    while probe > 0 {
134        probe -= 1;
135        let i = line_indent(rope, probe);
136        if i == u32::MAX {
137            continue;
138        }
139        if i <= base {
140            return indent_subtree(rope, probe);
141        }
142    }
143    None
144}
145
146/// Find the next sibling of the subtree starting at `line`. Returns
147/// `None` when the subtree is the last one at its depth.
148#[must_use]
149pub fn next_sibling_subtree(rope: &Rope, line: u32) -> Option<IndentRange> {
150    let me = indent_subtree(rope, line)?;
151    let total = u32::try_from(rope.len_lines()).ok()?;
152    let base = line_indent(rope, line);
153    if base == u32::MAX {
154        return None;
155    }
156    let mut probe = me.end_line;
157    while probe < total {
158        let i = line_indent(rope, probe);
159        if i == u32::MAX {
160            probe += 1;
161            continue;
162        }
163        if i <= base {
164            return indent_subtree(rope, probe);
165        }
166        probe += 1;
167    }
168    None
169}
170
171/// Enumerate every top-level (column-0) indent subtree in the buffer.
172/// Useful for §H3 `view.fold_all`.
173#[must_use]
174pub fn all_top_level_subtrees(rope: &Rope) -> Vec<IndentRange> {
175    let total = match u32::try_from(rope.len_lines()) {
176        Ok(n) => n,
177        Err(_) => return Vec::new(),
178    };
179    let mut out = Vec::new();
180    let mut i = 0u32;
181    while i < total {
182        let indent = line_indent(rope, i);
183        if indent != 0 {
184            i += 1;
185            continue;
186        }
187        if let Some(r) = indent_subtree(rope, i) {
188            if !r.is_single_line() {
189                out.push(r);
190            }
191            i = r.end_line.max(i + 1);
192        } else {
193            i += 1;
194        }
195    }
196    out
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use ropey::Rope;
203
204    fn r(s: &str) -> Rope {
205        Rope::from_str(s)
206    }
207
208    #[test]
209    fn line_indent_counts_spaces_and_tabs() {
210        let rope = r("    hello\n\tworld\nnone\n");
211        assert_eq!(line_indent(&rope, 0), 4);
212        assert_eq!(line_indent(&rope, 1), 4);
213        assert_eq!(line_indent(&rope, 2), 0);
214    }
215
216    #[test]
217    fn line_indent_blank_lines_return_max() {
218        let rope = r("foo\n\n   \nbar\n");
219        assert_eq!(line_indent(&rope, 0), 0);
220        assert_eq!(line_indent(&rope, 1), u32::MAX);
221        assert_eq!(line_indent(&rope, 2), u32::MAX);
222        assert_eq!(line_indent(&rope, 3), 0);
223    }
224
225    #[test]
226    fn indent_subtree_single_line_when_no_deeper_lines() {
227        let rope = r("alpha\nbeta\ngamma\n");
228        let r = indent_subtree(&rope, 1).unwrap();
229        assert_eq!(r.start_line, 1);
230        assert_eq!(r.end_line, 2);
231        assert!(r.is_single_line());
232    }
233
234    #[test]
235    fn indent_subtree_absorbs_deeper_descendants() {
236        let rope = r("parent\n  child a\n  child b\n    grandchild\n  child c\nsibling\n");
237        let r = indent_subtree(&rope, 0).unwrap();
238        assert_eq!(r.start_line, 0);
239        assert_eq!(r.end_line, 5);
240    }
241
242    #[test]
243    fn indent_subtree_terminates_on_shallower_or_equal_indent() {
244        // line 0 indent 4, line 1 deeper (8), line 2 shallower (2).
245        // Subtree of line 0 must include line 1 and stop at line 2.
246        let rope = r("    a\n        deeper\n  shallower\n    d\n");
247        let r = indent_subtree(&rope, 0).unwrap();
248        assert_eq!(r.end_line, 2);
249    }
250
251    #[test]
252    fn indent_subtree_absorbs_blank_lines_inside_subtree() {
253        let rope = r("parent\n  child\n\n  child2\nsibling\n");
254        let r = indent_subtree(&rope, 0).unwrap();
255        assert_eq!(r.end_line, 4);
256    }
257
258    #[test]
259    fn indent_subtree_past_eof_returns_none() {
260        let rope = r("only\n");
261        assert!(indent_subtree(&rope, 5).is_none());
262    }
263
264    #[test]
265    fn next_sibling_finds_following_equal_depth_line() {
266        let rope = r("first\n  child\nsecond\n  child2\nthird\n");
267        let s = next_sibling_subtree(&rope, 0).unwrap();
268        assert_eq!(s.start_line, 2);
269    }
270
271    #[test]
272    fn previous_sibling_finds_prior_equal_depth_line() {
273        let rope = r("first\n  child\nsecond\n  child2\nthird\n");
274        let s = previous_sibling_subtree(&rope, 2).unwrap();
275        assert_eq!(s.start_line, 0);
276    }
277
278    #[test]
279    fn previous_sibling_returns_none_at_top() {
280        let rope = r("first\n  child\nsecond\n");
281        assert!(previous_sibling_subtree(&rope, 0).is_none());
282    }
283
284    #[test]
285    fn next_sibling_returns_none_at_bottom() {
286        let rope = r("first\nsecond\nlast\n");
287        assert!(next_sibling_subtree(&rope, 2).is_none());
288    }
289
290    #[test]
291    fn all_top_level_subtrees_returns_each_block() {
292        let rope = r("alpha\n  a1\n  a2\nbeta\n  b1\ngamma\n");
293        let subs = all_top_level_subtrees(&rope);
294        assert_eq!(subs.len(), 2);
295        assert_eq!(subs[0].start_line, 0);
296        assert_eq!(subs[0].end_line, 3);
297        assert_eq!(subs[1].start_line, 3);
298        assert_eq!(subs[1].end_line, 5);
299    }
300}