iced_code_editor/canvas_editor/features/folding/ops.rs
1//! Fold/unfold operations on [`CodeEditor`](crate::canvas_editor::CodeEditor):
2//! toggling, folding, and unfolding regions, plus the cursor/cache upkeep
3//! that keeps folded state consistent with the buffer.
4
5use std::collections::HashSet;
6use std::rc::Rc;
7
8use crate::canvas_editor::CodeEditor;
9
10impl CodeEditor {
11 /// Returns whether the region whose header is `header_line` is collapsed.
12 ///
13 /// # Arguments
14 ///
15 /// * `header_line` - Logical line index of the region header
16 ///
17 /// # Returns
18 ///
19 /// `true` if that region is currently collapsed, `false` otherwise --
20 /// including when `header_line` is not a fold header at all.
21 ///
22 /// # Example
23 ///
24 /// ```
25 /// use iced_code_editor::CodeEditor;
26 ///
27 /// // A single block: the `fn` header on line 0 encloses lines 1 and 2.
28 /// let mut editor = CodeEditor::new(
29 /// "fn main() {\n let a = 1;\n let b = 2;\n}",
30 /// "rs",
31 /// );
32 ///
33 /// assert!(!editor.is_folded(0));
34 ///
35 /// editor.toggle_fold(0);
36 /// assert!(editor.is_folded(0));
37 /// ```
38 pub fn is_folded(&self, header_line: usize) -> bool {
39 self.collapsed_folds.contains(&header_line)
40 }
41
42 /// Toggles the collapsed state of the foldable region whose header is
43 /// `header_line`.
44 ///
45 /// The call is a no-op if `header_line` is not currently a fold header.
46 /// When collapsing, any cursor that would land on a hidden line is moved up
47 /// to the header line so the caret stays visible.
48 ///
49 /// # Arguments
50 ///
51 /// * `header_line` - Logical line index of the region header
52 ///
53 /// # Example
54 ///
55 /// ```
56 /// use iced_code_editor::CodeEditor;
57 ///
58 /// // A single block: the `fn` header on line 0 encloses lines 1 and 2.
59 /// let mut editor = CodeEditor::new(
60 /// "fn main() {\n let a = 1;\n let b = 2;\n}",
61 /// "rs",
62 /// );
63 ///
64 /// editor.toggle_fold(0);
65 /// assert!(editor.is_folded(0));
66 ///
67 /// editor.toggle_fold(0);
68 /// assert!(!editor.is_folded(0));
69 ///
70 /// // Line 1 sits inside the block but does not head it, so nothing moves.
71 /// editor.toggle_fold(1);
72 /// assert!(!editor.is_folded(0));
73 /// assert!(!editor.is_folded(1));
74 /// ```
75 pub fn toggle_fold(&mut self, header_line: usize) {
76 let regions = self.foldable_regions();
77 if !super::is_fold_header(®ions, header_line) {
78 return; // Not a fold header: nothing to toggle.
79 }
80
81 if self.collapsed_folds.contains(&header_line) {
82 self.collapsed_folds.remove(&header_line);
83 } else {
84 self.collapsed_folds.insert(header_line);
85 }
86 self.after_fold_change();
87 }
88
89 /// Toggles the collapsed state of the innermost foldable region containing
90 /// `line`.
91 ///
92 /// Folds the region if it is expanded, unfolds it if it is collapsed. Does
93 /// nothing if `line` is not inside any foldable region. This is the
94 /// cursor-driven primitive used by the keyboard shortcut and mirrors a click
95 /// on the fold chevron.
96 ///
97 /// # Arguments
98 ///
99 /// * `line` - A logical line inside (or heading) the region to toggle
100 ///
101 /// # Example
102 ///
103 /// ```
104 /// use iced_code_editor::CodeEditor;
105 ///
106 /// // A single block: the `fn` header on line 0 encloses lines 1 and 2.
107 /// let mut editor = CodeEditor::new(
108 /// "fn main() {\n let a = 1;\n let b = 2;\n}",
109 /// "rs",
110 /// );
111 ///
112 /// // Line 1 is inside the block, so the block's header collapses.
113 /// editor.toggle_fold_at(1);
114 /// assert!(editor.is_folded(0));
115 ///
116 /// editor.toggle_fold_at(1);
117 /// assert!(!editor.is_folded(0));
118 /// ```
119 pub fn toggle_fold_at(&mut self, line: usize) {
120 let regions = self.foldable_regions();
121 let header = regions
122 .iter()
123 .filter(|r| r.start_line <= line && line <= r.end_line)
124 .map(|r| r.start_line)
125 .max();
126 if let Some(header) = header {
127 if self.collapsed_folds.contains(&header) {
128 self.collapsed_folds.remove(&header);
129 } else {
130 self.collapsed_folds.insert(header);
131 }
132 self.after_fold_change();
133 }
134 }
135
136 /// Folds the innermost foldable region containing `line`.
137 ///
138 /// Does nothing if `line` is not inside any foldable region or the region
139 /// is already collapsed. This is the cursor-driven counterpart to
140 /// [`Self::toggle_fold`].
141 ///
142 /// # Arguments
143 ///
144 /// * `line` - A logical line inside (or heading) the region to fold
145 ///
146 /// # Example
147 ///
148 /// ```
149 /// use iced_code_editor::CodeEditor;
150 ///
151 /// // A single block: the `fn` header on line 0 encloses lines 1 and 2.
152 /// let mut editor = CodeEditor::new(
153 /// "fn main() {\n let a = 1;\n let b = 2;\n}",
154 /// "rs",
155 /// );
156 ///
157 /// editor.fold_at(2);
158 /// assert!(editor.is_folded(0));
159 ///
160 /// // Already collapsed: a second call is a no-op rather than a re-open.
161 /// editor.fold_at(2);
162 /// assert!(editor.is_folded(0));
163 /// ```
164 pub fn fold_at(&mut self, line: usize) {
165 let regions = self.foldable_regions();
166 // Innermost containing region: the one with the greatest start line.
167 let header = regions
168 .iter()
169 .filter(|r| r.start_line <= line && line <= r.end_line)
170 .map(|r| r.start_line)
171 .max();
172 if let Some(header) = header
173 && self.collapsed_folds.insert(header)
174 {
175 self.after_fold_change();
176 }
177 }
178
179 /// Unfolds the innermost collapsed region containing `line`.
180 ///
181 /// Does nothing if no collapsed region contains `line`.
182 ///
183 /// # Arguments
184 ///
185 /// * `line` - A logical line inside (or heading) the region to unfold
186 ///
187 /// # Example
188 ///
189 /// ```
190 /// use iced_code_editor::CodeEditor;
191 ///
192 /// // A single block: the `fn` header on line 0 encloses lines 1 and 2.
193 /// let mut editor = CodeEditor::new(
194 /// "fn main() {\n let a = 1;\n let b = 2;\n}",
195 /// "rs",
196 /// );
197 ///
198 /// editor.fold_at(1);
199 /// assert!(editor.is_folded(0));
200 ///
201 /// editor.unfold_at(1);
202 /// assert!(!editor.is_folded(0));
203 ///
204 /// // Nothing is collapsed any more, so unfolding again does nothing.
205 /// editor.unfold_at(1);
206 /// assert!(!editor.is_folded(0));
207 /// ```
208 pub fn unfold_at(&mut self, line: usize) {
209 let regions = self.foldable_regions();
210 let header = regions
211 .iter()
212 .filter(|r| {
213 r.start_line <= line
214 && line <= r.end_line
215 && self.collapsed_folds.contains(&r.start_line)
216 })
217 .map(|r| r.start_line)
218 .max();
219 if let Some(header) = header
220 && self.collapsed_folds.remove(&header)
221 {
222 self.after_fold_change();
223 }
224 }
225
226 /// Folds every foldable block in the buffer.
227 ///
228 /// Nested blocks are collapsed too, so the outermost header is the only
229 /// line each top-level block leaves on screen.
230 ///
231 /// # Example
232 ///
233 /// ```
234 /// use iced_code_editor::CodeEditor;
235 ///
236 /// // Two sibling blocks: headers on lines 0 and 3.
237 /// let mut editor = CodeEditor::new(
238 /// "fn a() {\n let x = 1;\n}\nfn b() {\n let y = 2;\n}",
239 /// "rs",
240 /// );
241 ///
242 /// editor.fold_all();
243 ///
244 /// assert!(editor.is_folded(0));
245 /// assert!(editor.is_folded(3));
246 /// ```
247 pub fn fold_all(&mut self) {
248 let regions = self.foldable_regions();
249 let mut changed = false;
250 for region in regions.iter() {
251 changed |= self.collapsed_folds.insert(region.start_line);
252 }
253 if changed {
254 self.after_fold_change();
255 }
256 }
257
258 /// Unfolds every collapsed block in the buffer.
259 ///
260 /// # Example
261 ///
262 /// ```
263 /// use iced_code_editor::CodeEditor;
264 ///
265 /// // Two sibling blocks: headers on lines 0 and 3.
266 /// let mut editor = CodeEditor::new(
267 /// "fn a() {\n let x = 1;\n}\nfn b() {\n let y = 2;\n}",
268 /// "rs",
269 /// );
270 ///
271 /// editor.fold_all();
272 /// assert!(editor.is_folded(0));
273 ///
274 /// editor.unfold_all();
275 ///
276 /// assert!(!editor.is_folded(0));
277 /// assert!(!editor.is_folded(3));
278 /// ```
279 pub fn unfold_all(&mut self) {
280 if !self.collapsed_folds.is_empty() {
281 self.collapsed_folds.clear();
282 self.after_fold_change();
283 }
284 }
285
286 /// Finalizes a change to the collapsed set: keeps every cursor on a visible
287 /// line and invalidates fold-dependent caches.
288 fn after_fold_change(&mut self) {
289 let hidden = self.hidden_lines_set();
290 self.move_cursors_out_of_hidden(&hidden);
291 self.bump_fold_revision();
292 }
293
294 /// Moves any cursor sitting on a hidden line up to the nearest visible line
295 /// above it (the header of the enclosing collapsed block).
296 fn move_cursors_out_of_hidden(&mut self, hidden: &HashSet<usize>) {
297 if hidden.is_empty() {
298 return;
299 }
300 for cursor in self.cursors.as_mut_slice() {
301 let mut line = cursor.position.0;
302 while line > 0 && hidden.contains(&line) {
303 line -= 1;
304 }
305 if line != cursor.position.0 {
306 cursor.position = (line, 0);
307 }
308 }
309 self.cursors.sort_and_merge();
310 }
311
312 /// Invalidates fold-dependent caches after a fold-state change.
313 pub(crate) fn bump_fold_revision(&mut self) {
314 self.fold_revision = self.fold_revision.wrapping_add(1);
315 self.content_cache.clear();
316 self.overlay_cache.clear();
317 }
318
319 /// Returns the indentation blocks of the current buffer, memoized by
320 /// `buffer_revision`.
321 ///
322 /// Independent of [`CodeEditor::folding_enabled`]: these are the blocks the
323 /// buffer *has*, not the ones the user may collapse. Sticky scroll reads
324 /// them to know which headers enclose a line
325 /// (see [`CodeEditor::sticky_headroom`]) without offering to fold anything,
326 /// so the two features share the computation and its cache but not the
327 /// toggle. Callers that act on *folding* want
328 /// [`Self::foldable_regions`] instead.
329 pub(crate) fn block_regions(&self) -> Rc<Vec<super::FoldRegion>> {
330 let mut cache = self.foldable_regions_cache.borrow_mut();
331 if let Some((revision, regions)) = cache.as_ref()
332 && *revision == self.buffer_revision
333 {
334 return regions.clone();
335 }
336
337 let regions = Rc::new(super::compute_foldable_regions(&self.buffer));
338 *cache = Some((self.buffer_revision, regions.clone()));
339 regions
340 }
341
342 /// Returns the foldable regions for the current buffer, memoized by
343 /// `buffer_revision`.
344 ///
345 /// Returns an empty list when folding is disabled — which is what makes
346 /// every folding operation a no-op without each of them testing the flag.
347 pub(crate) fn foldable_regions(&self) -> Rc<Vec<super::FoldRegion>> {
348 if !self.folding_enabled {
349 return Rc::new(Vec::new());
350 }
351
352 self.block_regions()
353 }
354
355 /// Returns the set of logical lines hidden by the currently collapsed folds.
356 ///
357 /// Empty when folding is disabled or nothing is collapsed.
358 pub(crate) fn hidden_lines_set(&self) -> HashSet<usize> {
359 if !self.folding_enabled || self.collapsed_folds.is_empty() {
360 return HashSet::new();
361 }
362 let regions = self.foldable_regions();
363 super::hidden_lines(®ions, &self.collapsed_folds)
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 /// Buffer with one outer block (lines 0..=4) and a nested inner block
372 /// (lines 2..=3), used by the folding tests.
373 fn folding_editor() -> CodeEditor {
374 CodeEditor::new(
375 "fn main() {\n let x = 1;\n if x > 0 {\n print();\n }\n}",
376 "rs",
377 )
378 }
379
380 #[test]
381 fn test_foldable_regions_detected() {
382 let editor = folding_editor();
383 let regions = editor.foldable_regions();
384 assert_eq!(
385 *regions,
386 vec![
387 super::super::FoldRegion::new(0, 4),
388 super::super::FoldRegion::new(2, 3)
389 ]
390 );
391 }
392
393 #[test]
394 fn test_toggle_fold_hides_and_shows_lines() {
395 let mut editor = folding_editor();
396 let width = editor.viewport_width;
397 let total = editor.visual_lines_cached(width).len();
398
399 editor.toggle_fold(0);
400 assert!(editor.is_folded(0));
401 // Outer block hides lines 1..=4: only lines 0 and 5 remain.
402 assert_eq!(editor.visual_lines_cached(width).len(), 2);
403
404 editor.toggle_fold(0);
405 assert!(!editor.is_folded(0));
406 assert_eq!(editor.visual_lines_cached(width).len(), total);
407 }
408
409 #[test]
410 fn test_toggle_fold_ignores_non_header() {
411 let mut editor = folding_editor();
412 editor.toggle_fold(3); // line 3 is not a header
413 assert!(!editor.is_folded(3));
414 assert!(editor.collapsed_folds.is_empty());
415 }
416
417 #[test]
418 fn test_fold_at_picks_innermost_region() {
419 let mut editor = folding_editor();
420 // Line 3 is inside both (0,4) and (2,3); the innermost (header 2) folds.
421 editor.fold_at(3);
422 assert!(editor.is_folded(2));
423 assert!(!editor.is_folded(0));
424 assert_eq!(editor.hidden_lines_set(), [3].into_iter().collect());
425 }
426
427 #[test]
428 fn test_unfold_at_expands_innermost_region() {
429 let mut editor = folding_editor();
430 editor.fold_at(3);
431 editor.unfold_at(2);
432 assert!(!editor.is_folded(2));
433 assert!(editor.hidden_lines_set().is_empty());
434 }
435
436 #[test]
437 fn test_toggle_fold_at_cursor_folds_then_unfolds() {
438 let mut editor = folding_editor();
439 // Line 3 is inside the innermost region (header 2).
440 editor.toggle_fold_at(3);
441 assert!(editor.is_folded(2));
442
443 // Toggling again on the same line expands it back.
444 editor.toggle_fold_at(2);
445 assert!(!editor.is_folded(2));
446 }
447
448 #[test]
449 fn test_toggle_fold_at_ignores_unfoldable_line() {
450 let mut editor = CodeEditor::new("a\nb\nc", "rs");
451 editor.toggle_fold_at(1);
452 assert!(editor.collapsed_folds.is_empty());
453 }
454
455 #[test]
456 fn test_fold_all_and_unfold_all() {
457 let mut editor = folding_editor();
458 editor.fold_all();
459 assert!(editor.is_folded(0));
460 assert!(editor.is_folded(2));
461 // Outer fold hides 1..=4, inner hides 3: union is 1..=4.
462 assert_eq!(
463 editor.hidden_lines_set(),
464 [1, 2, 3, 4].into_iter().collect()
465 );
466
467 editor.unfold_all();
468 assert!(editor.collapsed_folds.is_empty());
469 assert!(editor.hidden_lines_set().is_empty());
470 }
471
472 #[test]
473 fn test_fold_moves_cursor_out_of_hidden_lines() {
474 let mut editor = folding_editor();
475 editor.cursors.set_single((3, 2));
476 editor.fold_all();
477 // Line 3 is hidden; the cursor moves up to the nearest visible line (0).
478 assert_eq!(editor.cursors.primary_position(), (0, 0));
479 }
480
481 #[test]
482 fn test_disabled_folding_yields_no_regions() {
483 let mut editor = folding_editor();
484 editor.set_folding_enabled(false);
485 assert!(editor.foldable_regions().is_empty());
486 // Collapsed state is preserved but produces no hidden lines while off.
487 editor.collapsed_folds.insert(0);
488 assert!(editor.hidden_lines_set().is_empty());
489 }
490}