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