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    ///
40    /// # Example
41    ///
42    /// ```
43    /// use iced_code_editor::FoldRegion;
44    ///
45    /// // A `fn` header on line 0 whose body runs to line 2.
46    /// let region = FoldRegion::new(0, 2);
47    ///
48    /// assert_eq!(region.start_line, 0);
49    /// assert_eq!(region.end_line, 2);
50    /// ```
51    ///
52    /// Collapsing this region hides lines 1 and 2; the header stays visible.
53    pub fn new(start_line: usize, end_line: usize) -> Self {
54        Self { start_line, end_line }
55    }
56}
57
58/// When the gutter draws fold markers (the `▼`/`▶` chevrons).
59///
60/// # Example
61///
62/// ```
63/// use iced_code_editor::{CodeEditor, FoldMarkers};
64///
65/// let mut editor = CodeEditor::new("fn main() {\n    body();\n}", "rs");
66/// editor.set_fold_markers(FoldMarkers::OnGutterHover);
67/// assert_eq!(editor.fold_markers(), FoldMarkers::OnGutterHover);
68/// ```
69#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
70pub enum FoldMarkers {
71    /// Always shown (the default).
72    #[default]
73    Always,
74    /// Shown while the pointer is over the gutter, and always on collapsed
75    /// lines so hidden content stays discoverable.
76    OnGutterHover,
77    /// Never shown and taking no gutter space. Blocks can still be folded
78    /// with the keyboard shortcuts and the API.
79    Never,
80}
81
82impl FoldMarkers {
83    /// Whether a fold header shows its marker.
84    ///
85    /// # Arguments
86    ///
87    /// * `folded` - Whether the header's block is collapsed
88    /// * `gutter_hovered` - Whether the pointer is over the gutter
89    pub(crate) fn is_visible(self, folded: bool, gutter_hovered: bool) -> bool {
90        match self {
91            Self::Always => true,
92            Self::OnGutterHover => folded || gutter_hovered,
93            Self::Never => false,
94        }
95    }
96}
97
98/// Which side of the line numbers the fold-marker column sits on.
99///
100/// # Example
101///
102/// ```
103/// use iced_code_editor::{CodeEditor, FoldMarkerPosition};
104///
105/// let mut editor = CodeEditor::new("fn main() {\n    body();\n}", "rs");
106/// editor.set_fold_marker_position(FoldMarkerPosition::BeforeLineNumbers);
107/// assert_eq!(
108///     editor.fold_marker_position(),
109///     FoldMarkerPosition::BeforeLineNumbers
110/// );
111/// ```
112#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
113pub enum FoldMarkerPosition {
114    /// At the outer (left) edge of the gutter, before the line numbers.
115    BeforeLineNumbers,
116    /// Between the line numbers and the text (the default).
117    #[default]
118    AfterLineNumbers,
119}
120
121/// Detects all indentation-based foldable regions in the buffer.
122///
123/// A line `i` is a fold header when the next non-blank line is indented more
124/// deeply than `i`. The region extends over every following line that is either
125/// blank or more deeply indented than the header; trailing blank lines are
126/// trimmed so a collapsed block does not swallow the gap before the next block.
127///
128/// Nested blocks each yield their own region, so they can be folded
129/// independently.
130///
131/// # Arguments
132///
133/// * `buffer` - The text buffer to analyze
134///
135/// # Returns
136///
137/// Fold regions in ascending order of `start_line`. Only regions hiding at least
138/// one line are returned.
139pub fn compute_foldable_regions(buffer: &TextBuffer) -> Vec<FoldRegion> {
140    let line_count = buffer.line_count();
141    // Precompute indentation once. Blank lines remain transparent to folding.
142    let indents: Vec<Option<usize>> =
143        (0..line_count).map(|i| indent_width(buffer.line(i))).collect();
144
145    let mut regions: Vec<FoldRegion> = Vec::new();
146    // Stack entries are `(indent, region_index)`. A region is opened when the
147    // next non-blank line is deeper, and closed by the first non-blank line at
148    // the same or a shallower indentation. This keeps detection O(n), including
149    // deeply nested or very large uniformly-indented files.
150    let mut open_regions: Vec<(usize, usize)> = Vec::new();
151    let mut non_blank = indents
152        .iter()
153        .enumerate()
154        .filter_map(|(line, indent)| indent.map(|width| (line, width)))
155        .peekable();
156
157    let mut previous_non_blank = None;
158    while let Some((line, indent)) = non_blank.next() {
159        while open_regions
160            .last()
161            .is_some_and(|(header_indent, _)| *header_indent >= indent)
162        {
163            if let Some((_, region_index)) = open_regions.pop()
164                && let Some(end_line) = previous_non_blank
165                && let Some(region) = regions.get_mut(region_index)
166            {
167                region.end_line = end_line;
168            }
169        }
170
171        if non_blank
172            .peek()
173            .is_some_and(|(_, next_indent)| *next_indent > indent)
174        {
175            let region_index = regions.len();
176            regions.push(FoldRegion::new(line, line));
177            open_regions.push((indent, region_index));
178        }
179
180        previous_non_blank = Some(line);
181    }
182
183    if let Some(end_line) = previous_non_blank {
184        for (_, region_index) in open_regions {
185            if let Some(region) = regions.get_mut(region_index) {
186                region.end_line = end_line;
187            }
188        }
189    }
190
191    regions
192}
193
194/// Returns whether `line` is the header of a foldable region.
195///
196/// # Arguments
197///
198/// * `regions` - Pre-computed fold regions
199/// * `line` - The logical line index to test
200pub fn is_fold_header(regions: &[FoldRegion], line: usize) -> bool {
201    regions.binary_search_by_key(&line, |region| region.start_line).is_ok()
202}
203
204/// Checks whether one logical line is a fold header without scanning the whole
205/// buffer or building every fold region.
206///
207/// Rendering and hover hit-testing only need this local yes/no answer. Full
208/// region discovery remains deferred until the user actually folds a block.
209pub fn is_line_fold_header(buffer: &TextBuffer, line: usize) -> bool {
210    let Some(header_indent) = indent_width(buffer.line(line)) else {
211        return false;
212    };
213
214    (line.saturating_add(1)..buffer.line_count())
215        .find_map(|next_line| indent_width(buffer.line(next_line)))
216        .is_some_and(|next_indent| next_indent > header_indent)
217}
218
219/// Computes the set of logical lines hidden by the currently collapsed regions.
220///
221/// A region contributes its hidden lines (`start_line + 1 ..= end_line`) only
222/// when its header is present in `collapsed`. Overlapping (nested) regions are
223/// handled naturally because the result is a union.
224///
225/// # Arguments
226///
227/// * `regions` - Pre-computed fold regions
228/// * `collapsed` - Header line indices that are currently collapsed
229///
230/// # Returns
231///
232/// The set of logical line indices that must not be rendered.
233pub fn hidden_lines(
234    regions: &[FoldRegion],
235    collapsed: &HashSet<usize>,
236) -> HashSet<usize> {
237    let mut hidden = HashSet::new();
238    for region in regions {
239        if collapsed.contains(&region.start_line) {
240            hidden.extend((region.start_line + 1)..=region.end_line);
241        }
242    }
243    hidden
244}
245
246#[cfg(test)]
247mod marker_tests {
248    use super::*;
249
250    #[test]
251    fn test_fold_marker_visibility_by_mode() {
252        for folded in [false, true] {
253            for hovered in [false, true] {
254                assert!(FoldMarkers::Always.is_visible(folded, hovered));
255                assert!(!FoldMarkers::Never.is_visible(folded, hovered));
256            }
257        }
258        let on_hover = FoldMarkers::OnGutterHover;
259        assert!(!on_hover.is_visible(false, false));
260        assert!(on_hover.is_visible(false, true));
261        assert!(on_hover.is_visible(true, false), "collapsed stays visible");
262        assert!(on_hover.is_visible(true, true));
263    }
264
265    #[test]
266    fn test_fold_marker_defaults_keep_the_existing_gutter() {
267        assert_eq!(FoldMarkers::default(), FoldMarkers::Always);
268        assert_eq!(
269            FoldMarkerPosition::default(),
270            FoldMarkerPosition::AfterLineNumbers
271        );
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    #[test]
280    fn test_no_regions_for_flat_text() {
281        let buffer = TextBuffer::new("a\nb\nc");
282        assert!(compute_foldable_regions(&buffer).is_empty());
283    }
284
285    #[test]
286    fn test_simple_block() {
287        // `fn main` header at line 0, body at lines 1-2, closing brace dedented.
288        let buffer =
289            TextBuffer::new("fn main() {\n    let x = 1;\n    let y = 2;\n}");
290        let regions = compute_foldable_regions(&buffer);
291        assert_eq!(regions, vec![FoldRegion::new(0, 2)]);
292    }
293
294    #[test]
295    fn test_nested_blocks() {
296        // Two nesting levels produce two independent regions.
297        let buffer = TextBuffer::new(
298            "outer:\n    inner:\n        deep\n        deeper\n    after_inner",
299        );
300        let regions = compute_foldable_regions(&buffer);
301        assert_eq!(regions, vec![FoldRegion::new(0, 4), FoldRegion::new(1, 3)]);
302    }
303
304    #[test]
305    fn test_blank_lines_inside_and_trailing() {
306        // Blank line (idx 2) stays inside the block; trailing blank (idx 4)
307        // before a dedented line is trimmed.
308        let buffer =
309            TextBuffer::new("def f():\n    a = 1\n\n    b = 2\n\ng = 3");
310        let regions = compute_foldable_regions(&buffer);
311        // Region covers lines 1..=3 (the blank at 2 is absorbed), but not the
312        // trailing blank at line 4.
313        assert_eq!(regions, vec![FoldRegion::new(0, 3)]);
314    }
315
316    #[test]
317    fn test_hidden_lines_single_collapsed() {
318        let regions = vec![FoldRegion::new(0, 2)];
319        let collapsed: HashSet<usize> = [0].into_iter().collect();
320        let hidden = hidden_lines(&regions, &collapsed);
321        assert_eq!(hidden, [1, 2].into_iter().collect());
322    }
323
324    #[test]
325    fn test_hidden_lines_nested_union() {
326        let regions = vec![FoldRegion::new(0, 4), FoldRegion::new(1, 3)];
327        // Only the inner region is collapsed.
328        let collapsed: HashSet<usize> = [1].into_iter().collect();
329        assert_eq!(
330            hidden_lines(&regions, &collapsed),
331            [2, 3].into_iter().collect()
332        );
333
334        // Both collapsed: union covers 1..=4.
335        let collapsed: HashSet<usize> = [0, 1].into_iter().collect();
336        assert_eq!(
337            hidden_lines(&regions, &collapsed),
338            [1, 2, 3, 4].into_iter().collect()
339        );
340    }
341
342    #[test]
343    fn test_hidden_lines_ignores_unknown_collapsed() {
344        // A stale collapsed entry without a matching region contributes nothing.
345        let regions = vec![FoldRegion::new(0, 2)];
346        let collapsed: HashSet<usize> = [99].into_iter().collect();
347        assert!(hidden_lines(&regions, &collapsed).is_empty());
348    }
349
350    #[test]
351    fn test_is_fold_header() {
352        let regions = vec![FoldRegion::new(0, 2), FoldRegion::new(5, 7)];
353        assert!(is_fold_header(&regions, 0));
354        assert!(is_fold_header(&regions, 5));
355        assert!(!is_fold_header(&regions, 1));
356        assert!(!is_fold_header(&regions, 3));
357    }
358
359    #[test]
360    fn test_is_line_fold_header_skips_blank_lines() {
361        let buffer = TextBuffer::new("header\n\n    body\nsibling");
362        assert!(is_line_fold_header(&buffer, 0));
363        assert!(!is_line_fold_header(&buffer, 1));
364        assert!(!is_line_fold_header(&buffer, 2));
365    }
366}