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