curd-editor 0.5.0

A small terminal code editor with language-server support, folding and snippets
//! Code folding: finding `{ ... }` blocks and remembering which are collapsed.

use std::collections::BTreeMap;

#[cfg(test)]
mod tests;

/// Where every foldable block in a document starts and ends. Built in one
/// pass over the text and reused until the text changes.
pub struct Blocks {
    /// For each line: the last line of the block it opens, if it opens one.
    ends: Vec<Option<usize>>,
}

impl Blocks {
    /// Finds `{ ... }` blocks that span more than one line.
    ///
    /// This counts braces only: braces inside strings or comments are not
    /// treated specially.
    pub fn by_braces(lines: &[String]) -> Self {
        let mut ends = vec![None; lines.len()];
        // Lines of the `{` that are still waiting for their `}`.
        let mut open: Vec<usize> = Vec::new();
        for (y, line) in lines.iter().enumerate() {
            for c in line.chars() {
                match c {
                    '{' => open.push(y),
                    '}' => {
                        if let Some(start) = open.pop() {
                            // When a line opens several blocks, folding it
                            // collapses the outermost, which closes last.
                            if start < y {
                                ends[start] = Some(y);
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
        Self { ends }
    }

    /// Finds blocks by indentation, for languages like Python: a line opens
    /// a block when the lines after it are indented further.
    pub fn by_indent(lines: &[String]) -> Self {
        let mut ends = vec![None; lines.len()];
        // (line, indent) of lines whose block may still be growing.
        let mut open: Vec<(usize, usize)> = Vec::new();
        let mut last_text_line = 0;
        for (y, line) in lines.iter().enumerate() {
            if line.trim().is_empty() {
                continue;
            }
            let indent = line.chars().take_while(|c| c.is_whitespace()).count();
            while let Some(&(start, start_indent)) = open.last() {
                if start_indent < indent {
                    break;
                }
                open.pop();
                if last_text_line > start {
                    ends[start] = Some(last_text_line);
                }
            }
            open.push((y, indent));
            last_text_line = y;
        }
        for (start, _) in open {
            if last_text_line > start {
                ends[start] = Some(last_text_line);
            }
        }
        Self { ends }
    }

    /// The last line of the block that line `y` opens, if it opens one.
    pub fn end(&self, y: usize) -> Option<usize> {
        self.ends.get(y).copied().flatten()
    }

    /// The innermost block that starts above line `y` and contains it,
    /// as (first line, last line).
    pub fn enclosing(&self, y: usize) -> Option<(usize, usize)> {
        (0..y.min(self.ends.len()))
            .rev()
            .find_map(|start| match self.end(start) {
                Some(end) if end >= y => Some((start, end)),
                _ => None,
            })
    }

    /// Every block that is not inside another block.
    pub fn top_level(&self) -> Vec<(usize, usize)> {
        let mut blocks = Vec::new();
        let mut y = 0;
        while y < self.ends.len() {
            match self.end(y) {
                Some(end) => {
                    blocks.push((y, end));
                    y = end + 1;
                }
                None => y += 1,
            }
        }
        blocks
    }
}

/// The collapsed blocks. Each is stored as header line -> last hidden line;
/// the header stays visible and every line after it up to the end is hidden.
#[derive(Default)]
pub struct Folds {
    ranges: BTreeMap<usize, usize>,
}

impl Folds {
    /// Collapses lines `start + 1 ..= end` under the header line `start`.
    pub fn fold(&mut self, start: usize, end: usize) {
        if end > start {
            self.ranges.insert(start, end);
        }
    }

    /// Expands the fold whose header is line `y`. Returns false if there is none.
    pub fn unfold(&mut self, y: usize) -> bool {
        self.ranges.remove(&y).is_some()
    }

    /// Expands every fold.
    pub fn clear(&mut self) {
        self.ranges.clear();
    }

    pub fn is_empty(&self) -> bool {
        self.ranges.is_empty()
    }

    /// Expands every fold that hides line `y`.
    pub fn reveal(&mut self, y: usize) {
        self.ranges.retain(|start, end| !(*start < y && y <= *end));
    }

    /// The last hidden line of the fold whose header is `y`, if `y` is folded.
    pub fn end_of(&self, y: usize) -> Option<usize> {
        self.ranges.get(&y).copied()
    }

    /// The visible line standing in for `y`: `y` itself, or the header of the
    /// outermost fold hiding it.
    pub fn header_of(&self, y: usize) -> usize {
        self.ranges
            .iter()
            .find(|(start, end)| **start < y && y <= **end)
            .map_or(y, |(start, _)| *start)
    }

    /// The next visible line below `y` in a document of `len` lines.
    pub fn next_visible(&self, y: usize, len: usize) -> Option<usize> {
        let next = self.end_of(y).unwrap_or(y) + 1;
        (next < len).then_some(next)
    }

    /// The next visible line above `y`.
    pub fn prev_visible(&self, y: usize) -> Option<usize> {
        y.checked_sub(1).map(|above| self.header_of(above))
    }

    /// How many screen rows separate visible line `from` from visible line `to`
    /// (0 when they are the same line).
    pub fn rows_between(&self, from: usize, to: usize) -> usize {
        let mut rows = 0;
        let mut y = from;
        while y < to {
            y = self.end_of(y).unwrap_or(y) + 1;
            rows += 1;
        }
        rows
    }

    /// Keeps folds pointing at the right lines after `delta` lines were added
    /// (or removed, when negative) just below line `y`.
    pub fn shift_after(&mut self, y: usize, delta: isize) {
        let shift = |line: usize| (line as isize + delta) as usize;
        self.ranges = std::mem::take(&mut self.ranges)
            .into_iter()
            .map(|(start, end)| {
                if start > y {
                    (shift(start), shift(end))
                } else {
                    (start, end)
                }
            })
            .collect();
    }
}