curd-editor 0.3.0

A tiny terminal code editor with line numbers, folding and snippets
//! Code folding: finding `{ ... }` blocks and remembering which are collapsed.

use std::collections::BTreeMap;

#[cfg(test)]
mod tests;

/// If line `start` opens a `{` block that closes on a later line, returns
/// the line holding the matching `}`.
///
/// This counts braces only: braces inside strings or comments are not
/// treated specially.
pub fn block_end(lines: &[String], start: usize) -> Option<usize> {
    let mut depth = 0usize;
    for c in lines.get(start)?.chars() {
        match c {
            '{' => depth += 1,
            // A `}` that closes an earlier block, as in `} else {`.
            '}' => depth = depth.saturating_sub(1),
            _ => {}
        }
    }
    if depth == 0 {
        return None;
    }
    for (y, line) in lines.iter().enumerate().skip(start + 1) {
        for c in line.chars() {
            match c {
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        return Some(y);
                    }
                }
                _ => {}
            }
        }
    }
    None
}

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

/// 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 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();
    }
}