Skip to main content

iced_code_editor/canvas_editor/features/folding/
mod.rs

1//! Code folding logic for the text editor.
2//!
3//! This module detects foldable regions (collapsible blocks) in the buffer and
4//! computes which logical lines must be hidden when a block is collapsed.
5//!
6//! Detection is **indentation-based**: a line is a fold header when the next
7//! non-blank line is more deeply indented. This is language-agnostic and matches
8//! the fallback strategy used by editors such as VS Code. The collapsed state and
9//! the on/off toggle live on [`super::CodeEditor`]; this module is pure logic so
10//! it can be unit-tested in isolation.
11
12mod ops;
13
14use std::collections::HashSet;
15
16use crate::buffer::TextBuffer;
17
18use crate::canvas_editor::indent_width;
19
20/// A region of the buffer that can be collapsed into a single header line.
21///
22/// `start_line` is the header line, which always stays visible. When the region
23/// is collapsed, the lines `start_line + 1 ..= end_line` are hidden.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct FoldRegion {
26    /// Index of the header line (stays visible when collapsed).
27    pub start_line: usize,
28    /// Index of the last line belonging to the region (hidden when collapsed).
29    pub end_line: usize,
30}
31
32impl FoldRegion {
33    /// Creates a new fold region.
34    ///
35    /// # Arguments
36    ///
37    /// * `start_line` - Index of the header line
38    /// * `end_line` - Index of the last line in the region
39    pub fn new(start_line: usize, end_line: usize) -> Self {
40        Self {
41            start_line,
42            end_line,
43        }
44    }
45}
46
47/// Detects all indentation-based foldable regions in the buffer.
48///
49/// A line `i` is a fold header when the next non-blank line is indented more
50/// deeply than `i`. The region extends over every following line that is either
51/// blank or more deeply indented than the header; trailing blank lines are
52/// trimmed so a collapsed block does not swallow the gap before the next block.
53///
54/// Nested blocks each yield their own region, so they can be folded
55/// independently.
56///
57/// # Arguments
58///
59/// * `buffer` - The text buffer to analyze
60///
61/// # Returns
62///
63/// Fold regions in ascending order of `start_line`. Only regions hiding at least
64/// one line are returned.
65pub fn compute_foldable_regions(buffer: &TextBuffer) -> Vec<FoldRegion> {
66    let line_count = buffer.line_count();
67    // Precompute indentation once. Blank lines remain transparent to folding.
68    let indents: Vec<Option<usize>> =
69        (0..line_count).map(|i| indent_width(buffer.line(i))).collect();
70
71    let mut regions: Vec<FoldRegion> = Vec::new();
72    // Stack entries are `(indent, region_index)`. A region is opened when the
73    // next non-blank line is deeper, and closed by the first non-blank line at
74    // the same or a shallower indentation. This keeps detection O(n), including
75    // deeply nested or very large uniformly-indented files.
76    let mut open_regions: Vec<(usize, usize)> = Vec::new();
77    let mut non_blank = indents
78        .iter()
79        .enumerate()
80        .filter_map(|(line, indent)| indent.map(|width| (line, width)))
81        .peekable();
82
83    let mut previous_non_blank = None;
84    while let Some((line, indent)) = non_blank.next() {
85        while open_regions.last().is_some_and(|(header_indent, _)| *header_indent >= indent) {
86            if let Some((_, region_index)) = open_regions.pop()
87                && let Some(end_line) = previous_non_blank
88                && let Some(region) = regions.get_mut(region_index)
89            {
90                region.end_line = end_line;
91            }
92        }
93
94        if non_blank.peek().is_some_and(|(_, next_indent)| *next_indent > indent) {
95            let region_index = regions.len();
96            regions.push(FoldRegion::new(line, line));
97            open_regions.push((indent, region_index));
98        }
99
100        previous_non_blank = Some(line);
101    }
102
103    if let Some(end_line) = previous_non_blank {
104        for (_, region_index) in open_regions {
105            if let Some(region) = regions.get_mut(region_index) {
106                region.end_line = end_line;
107            }
108        }
109    }
110
111    regions
112}
113
114/// Returns whether `line` is the header of a foldable region.
115///
116/// # Arguments
117///
118/// * `regions` - Pre-computed fold regions
119/// * `line` - The logical line index to test
120pub fn is_fold_header(regions: &[FoldRegion], line: usize) -> bool {
121    regions.binary_search_by_key(&line, |region| region.start_line).is_ok()
122}
123
124/// Checks whether one logical line is a fold header without scanning the whole
125/// buffer or building every fold region.
126///
127/// Rendering and hover hit-testing only need this local yes/no answer. Full
128/// region discovery remains deferred until the user actually folds a block.
129pub fn is_line_fold_header(buffer: &TextBuffer, line: usize) -> bool {
130    let Some(header_indent) = indent_width(buffer.line(line)) else {
131        return false;
132    };
133
134    (line.saturating_add(1)..buffer.line_count())
135        .find_map(|next_line| indent_width(buffer.line(next_line)))
136        .is_some_and(|next_indent| next_indent > header_indent)
137}
138
139/// Computes the set of logical lines hidden by the currently collapsed regions.
140///
141/// A region contributes its hidden lines (`start_line + 1 ..= end_line`) only
142/// when its header is present in `collapsed`. Overlapping (nested) regions are
143/// handled naturally because the result is a union.
144///
145/// # Arguments
146///
147/// * `regions` - Pre-computed fold regions
148/// * `collapsed` - Header line indices that are currently collapsed
149///
150/// # Returns
151///
152/// The set of logical line indices that must not be rendered.
153pub fn hidden_lines(regions: &[FoldRegion], collapsed: &HashSet<usize>) -> HashSet<usize> {
154    let mut hidden = HashSet::new();
155    for region in regions {
156        if collapsed.contains(&region.start_line) {
157            hidden.extend((region.start_line + 1)..=region.end_line);
158        }
159    }
160    hidden
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn test_no_regions_for_flat_text() {
169        let buffer = TextBuffer::new("a\nb\nc");
170        assert!(compute_foldable_regions(&buffer).is_empty());
171    }
172
173    #[test]
174    fn test_simple_block() {
175        // `fn main` header at line 0, body at lines 1-2, closing brace dedented.
176        let buffer = TextBuffer::new("fn main() {\n    let x = 1;\n    let y = 2;\n}");
177        let regions = compute_foldable_regions(&buffer);
178        assert_eq!(regions, vec![FoldRegion::new(0, 2)]);
179    }
180
181    #[test]
182    fn test_nested_blocks() {
183        // Two nesting levels produce two independent regions.
184        let buffer =
185            TextBuffer::new("outer:\n    inner:\n        deep\n        deeper\n    after_inner");
186        let regions = compute_foldable_regions(&buffer);
187        assert_eq!(regions, vec![FoldRegion::new(0, 4), FoldRegion::new(1, 3)]);
188    }
189
190    #[test]
191    fn test_blank_lines_inside_and_trailing() {
192        // Blank line (idx 2) stays inside the block; trailing blank (idx 4)
193        // before a dedented line is trimmed.
194        let buffer = TextBuffer::new("def f():\n    a = 1\n\n    b = 2\n\ng = 3");
195        let regions = compute_foldable_regions(&buffer);
196        // Region covers lines 1..=3 (the blank at 2 is absorbed), but not the
197        // trailing blank at line 4.
198        assert_eq!(regions, vec![FoldRegion::new(0, 3)]);
199    }
200
201    #[test]
202    fn test_hidden_lines_single_collapsed() {
203        let regions = vec![FoldRegion::new(0, 2)];
204        let collapsed: HashSet<usize> = [0].into_iter().collect();
205        let hidden = hidden_lines(&regions, &collapsed);
206        assert_eq!(hidden, [1, 2].into_iter().collect());
207    }
208
209    #[test]
210    fn test_hidden_lines_nested_union() {
211        let regions = vec![FoldRegion::new(0, 4), FoldRegion::new(1, 3)];
212        // Only the inner region is collapsed.
213        let collapsed: HashSet<usize> = [1].into_iter().collect();
214        assert_eq!(
215            hidden_lines(&regions, &collapsed),
216            [2, 3].into_iter().collect()
217        );
218
219        // Both collapsed: union covers 1..=4.
220        let collapsed: HashSet<usize> = [0, 1].into_iter().collect();
221        assert_eq!(
222            hidden_lines(&regions, &collapsed),
223            [1, 2, 3, 4].into_iter().collect()
224        );
225    }
226
227    #[test]
228    fn test_hidden_lines_ignores_unknown_collapsed() {
229        // A stale collapsed entry without a matching region contributes nothing.
230        let regions = vec![FoldRegion::new(0, 2)];
231        let collapsed: HashSet<usize> = [99].into_iter().collect();
232        assert!(hidden_lines(&regions, &collapsed).is_empty());
233    }
234
235    #[test]
236    fn test_is_fold_header() {
237        let regions = vec![FoldRegion::new(0, 2), FoldRegion::new(5, 7)];
238        assert!(is_fold_header(&regions, 0));
239        assert!(is_fold_header(&regions, 5));
240        assert!(!is_fold_header(&regions, 1));
241        assert!(!is_fold_header(&regions, 3));
242    }
243
244    #[test]
245    fn test_is_line_fold_header_skips_blank_lines() {
246        let buffer = TextBuffer::new("header\n\n    body\nsibling");
247        assert!(is_line_fold_header(&buffer, 0));
248        assert!(!is_line_fold_header(&buffer, 1));
249        assert!(!is_line_fold_header(&buffer, 2));
250    }
251}