iced-code-editor 0.7.0

A custom code editor widget for the Iced GUI framework with syntax highlighting, line numbers, and scrolling support.
Documentation
//! Code folding logic for the text editor.
//!
//! This module detects foldable regions (collapsible blocks) in the buffer and
//! computes which logical lines must be hidden when a block is collapsed.
//!
//! Detection is **indentation-based**: a line is a fold header when the next
//! non-blank line is more deeply indented. This is language-agnostic and matches
//! the fallback strategy used by editors such as VS Code. The collapsed state and
//! the on/off toggle live on [`super::CodeEditor`]; this module is pure logic so
//! it can be unit-tested in isolation.

mod ops;

use std::collections::HashSet;

use crate::buffer::TextBuffer;

use crate::canvas_editor::indent_width;

/// A region of the buffer that can be collapsed into a single header line.
///
/// `start_line` is the header line, which always stays visible. When the region
/// is collapsed, the lines `start_line + 1 ..= end_line` are hidden.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FoldRegion {
    /// Index of the header line (stays visible when collapsed).
    pub start_line: usize,
    /// Index of the last line belonging to the region (hidden when collapsed).
    pub end_line: usize,
}

impl FoldRegion {
    /// Creates a new fold region.
    ///
    /// # Arguments
    ///
    /// * `start_line` - Index of the header line
    /// * `end_line` - Index of the last line in the region
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::FoldRegion;
    ///
    /// // A `fn` header on line 0 whose body runs to line 2.
    /// let region = FoldRegion::new(0, 2);
    ///
    /// assert_eq!(region.start_line, 0);
    /// assert_eq!(region.end_line, 2);
    /// ```
    ///
    /// Collapsing this region hides lines 1 and 2; the header stays visible.
    pub fn new(start_line: usize, end_line: usize) -> Self {
        Self { start_line, end_line }
    }
}

/// When the gutter draws fold markers (the `▼`/`▶` chevrons).
///
/// # Example
///
/// ```
/// use iced_code_editor::{CodeEditor, FoldMarkers};
///
/// let mut editor = CodeEditor::new("fn main() {\n    body();\n}", "rs");
/// editor.set_fold_markers(FoldMarkers::OnGutterHover);
/// assert_eq!(editor.fold_markers(), FoldMarkers::OnGutterHover);
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum FoldMarkers {
    /// Always shown (the default).
    #[default]
    Always,
    /// Shown while the pointer is over the gutter, and always on collapsed
    /// lines so hidden content stays discoverable.
    OnGutterHover,
    /// Never shown and taking no gutter space. Blocks can still be folded
    /// with the keyboard shortcuts and the API.
    Never,
}

impl FoldMarkers {
    /// Whether a fold header shows its marker.
    ///
    /// # Arguments
    ///
    /// * `folded` - Whether the header's block is collapsed
    /// * `gutter_hovered` - Whether the pointer is over the gutter
    pub(crate) fn is_visible(self, folded: bool, gutter_hovered: bool) -> bool {
        match self {
            Self::Always => true,
            Self::OnGutterHover => folded || gutter_hovered,
            Self::Never => false,
        }
    }
}

/// Which side of the line numbers the fold-marker column sits on.
///
/// # Example
///
/// ```
/// use iced_code_editor::{CodeEditor, FoldMarkerPosition};
///
/// let mut editor = CodeEditor::new("fn main() {\n    body();\n}", "rs");
/// editor.set_fold_marker_position(FoldMarkerPosition::BeforeLineNumbers);
/// assert_eq!(
///     editor.fold_marker_position(),
///     FoldMarkerPosition::BeforeLineNumbers
/// );
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum FoldMarkerPosition {
    /// At the outer (left) edge of the gutter, before the line numbers.
    BeforeLineNumbers,
    /// Between the line numbers and the text (the default).
    #[default]
    AfterLineNumbers,
}

/// Detects all indentation-based foldable regions in the buffer.
///
/// A line `i` is a fold header when the next non-blank line is indented more
/// deeply than `i`. The region extends over every following line that is either
/// blank or more deeply indented than the header; trailing blank lines are
/// trimmed so a collapsed block does not swallow the gap before the next block.
///
/// Nested blocks each yield their own region, so they can be folded
/// independently.
///
/// # Arguments
///
/// * `buffer` - The text buffer to analyze
///
/// # Returns
///
/// Fold regions in ascending order of `start_line`. Only regions hiding at least
/// one line are returned.
pub fn compute_foldable_regions(buffer: &TextBuffer) -> Vec<FoldRegion> {
    let line_count = buffer.line_count();
    // Precompute indentation once. Blank lines remain transparent to folding.
    let indents: Vec<Option<usize>> =
        (0..line_count).map(|i| indent_width(buffer.line(i))).collect();

    let mut regions: Vec<FoldRegion> = Vec::new();
    // Stack entries are `(indent, region_index)`. A region is opened when the
    // next non-blank line is deeper, and closed by the first non-blank line at
    // the same or a shallower indentation. This keeps detection O(n), including
    // deeply nested or very large uniformly-indented files.
    let mut open_regions: Vec<(usize, usize)> = Vec::new();
    let mut non_blank = indents
        .iter()
        .enumerate()
        .filter_map(|(line, indent)| indent.map(|width| (line, width)))
        .peekable();

    let mut previous_non_blank = None;
    while let Some((line, indent)) = non_blank.next() {
        while open_regions
            .last()
            .is_some_and(|(header_indent, _)| *header_indent >= indent)
        {
            if let Some((_, region_index)) = open_regions.pop()
                && let Some(end_line) = previous_non_blank
                && let Some(region) = regions.get_mut(region_index)
            {
                region.end_line = end_line;
            }
        }

        if non_blank
            .peek()
            .is_some_and(|(_, next_indent)| *next_indent > indent)
        {
            let region_index = regions.len();
            regions.push(FoldRegion::new(line, line));
            open_regions.push((indent, region_index));
        }

        previous_non_blank = Some(line);
    }

    if let Some(end_line) = previous_non_blank {
        for (_, region_index) in open_regions {
            if let Some(region) = regions.get_mut(region_index) {
                region.end_line = end_line;
            }
        }
    }

    regions
}

/// Returns whether `line` is the header of a foldable region.
///
/// # Arguments
///
/// * `regions` - Pre-computed fold regions
/// * `line` - The logical line index to test
pub fn is_fold_header(regions: &[FoldRegion], line: usize) -> bool {
    regions.binary_search_by_key(&line, |region| region.start_line).is_ok()
}

/// Checks whether one logical line is a fold header without scanning the whole
/// buffer or building every fold region.
///
/// Rendering and hover hit-testing only need this local yes/no answer. Full
/// region discovery remains deferred until the user actually folds a block.
pub fn is_line_fold_header(buffer: &TextBuffer, line: usize) -> bool {
    let Some(header_indent) = indent_width(buffer.line(line)) else {
        return false;
    };

    (line.saturating_add(1)..buffer.line_count())
        .find_map(|next_line| indent_width(buffer.line(next_line)))
        .is_some_and(|next_indent| next_indent > header_indent)
}

/// Computes the set of logical lines hidden by the currently collapsed regions.
///
/// A region contributes its hidden lines (`start_line + 1 ..= end_line`) only
/// when its header is present in `collapsed`. Overlapping (nested) regions are
/// handled naturally because the result is a union.
///
/// # Arguments
///
/// * `regions` - Pre-computed fold regions
/// * `collapsed` - Header line indices that are currently collapsed
///
/// # Returns
///
/// The set of logical line indices that must not be rendered.
pub fn hidden_lines(
    regions: &[FoldRegion],
    collapsed: &HashSet<usize>,
) -> HashSet<usize> {
    let mut hidden = HashSet::new();
    for region in regions {
        if collapsed.contains(&region.start_line) {
            hidden.extend((region.start_line + 1)..=region.end_line);
        }
    }
    hidden
}

#[cfg(test)]
mod marker_tests {
    use super::*;

    #[test]
    fn test_fold_marker_visibility_by_mode() {
        for folded in [false, true] {
            for hovered in [false, true] {
                assert!(FoldMarkers::Always.is_visible(folded, hovered));
                assert!(!FoldMarkers::Never.is_visible(folded, hovered));
            }
        }
        let on_hover = FoldMarkers::OnGutterHover;
        assert!(!on_hover.is_visible(false, false));
        assert!(on_hover.is_visible(false, true));
        assert!(on_hover.is_visible(true, false), "collapsed stays visible");
        assert!(on_hover.is_visible(true, true));
    }

    #[test]
    fn test_fold_marker_defaults_keep_the_existing_gutter() {
        assert_eq!(FoldMarkers::default(), FoldMarkers::Always);
        assert_eq!(
            FoldMarkerPosition::default(),
            FoldMarkerPosition::AfterLineNumbers
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_no_regions_for_flat_text() {
        let buffer = TextBuffer::new("a\nb\nc");
        assert!(compute_foldable_regions(&buffer).is_empty());
    }

    #[test]
    fn test_simple_block() {
        // `fn main` header at line 0, body at lines 1-2, closing brace dedented.
        let buffer =
            TextBuffer::new("fn main() {\n    let x = 1;\n    let y = 2;\n}");
        let regions = compute_foldable_regions(&buffer);
        assert_eq!(regions, vec![FoldRegion::new(0, 2)]);
    }

    #[test]
    fn test_nested_blocks() {
        // Two nesting levels produce two independent regions.
        let buffer = TextBuffer::new(
            "outer:\n    inner:\n        deep\n        deeper\n    after_inner",
        );
        let regions = compute_foldable_regions(&buffer);
        assert_eq!(regions, vec![FoldRegion::new(0, 4), FoldRegion::new(1, 3)]);
    }

    #[test]
    fn test_blank_lines_inside_and_trailing() {
        // Blank line (idx 2) stays inside the block; trailing blank (idx 4)
        // before a dedented line is trimmed.
        let buffer =
            TextBuffer::new("def f():\n    a = 1\n\n    b = 2\n\ng = 3");
        let regions = compute_foldable_regions(&buffer);
        // Region covers lines 1..=3 (the blank at 2 is absorbed), but not the
        // trailing blank at line 4.
        assert_eq!(regions, vec![FoldRegion::new(0, 3)]);
    }

    #[test]
    fn test_hidden_lines_single_collapsed() {
        let regions = vec![FoldRegion::new(0, 2)];
        let collapsed: HashSet<usize> = [0].into_iter().collect();
        let hidden = hidden_lines(&regions, &collapsed);
        assert_eq!(hidden, [1, 2].into_iter().collect());
    }

    #[test]
    fn test_hidden_lines_nested_union() {
        let regions = vec![FoldRegion::new(0, 4), FoldRegion::new(1, 3)];
        // Only the inner region is collapsed.
        let collapsed: HashSet<usize> = [1].into_iter().collect();
        assert_eq!(
            hidden_lines(&regions, &collapsed),
            [2, 3].into_iter().collect()
        );

        // Both collapsed: union covers 1..=4.
        let collapsed: HashSet<usize> = [0, 1].into_iter().collect();
        assert_eq!(
            hidden_lines(&regions, &collapsed),
            [1, 2, 3, 4].into_iter().collect()
        );
    }

    #[test]
    fn test_hidden_lines_ignores_unknown_collapsed() {
        // A stale collapsed entry without a matching region contributes nothing.
        let regions = vec![FoldRegion::new(0, 2)];
        let collapsed: HashSet<usize> = [99].into_iter().collect();
        assert!(hidden_lines(&regions, &collapsed).is_empty());
    }

    #[test]
    fn test_is_fold_header() {
        let regions = vec![FoldRegion::new(0, 2), FoldRegion::new(5, 7)];
        assert!(is_fold_header(&regions, 0));
        assert!(is_fold_header(&regions, 5));
        assert!(!is_fold_header(&regions, 1));
        assert!(!is_fold_header(&regions, 3));
    }

    #[test]
    fn test_is_line_fold_header_skips_blank_lines() {
        let buffer = TextBuffer::new("header\n\n    body\nsibling");
        assert!(is_line_fold_header(&buffer, 0));
        assert!(!is_line_fold_header(&buffer, 1));
        assert!(!is_line_fold_header(&buffer, 2));
    }
}