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