Skip to main content

rustaco_view/
folding.rs

1//! Folded regions and the regions that can be folded.
2
3use std::ops::Range;
4
5use rustaco_core::Rope;
6
7use crate::HeightMap;
8
9/// A collapsed region: the lines after the header line down to the line holding `end` are
10/// hidden. Both ends are char offsets (the end of the header line and the end of the last
11/// hidden line), so the fold follows edits.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub(crate) struct Fold {
14    pub start: usize,
15    pub end: usize,
16}
17
18/// A fold marker in the gutter: the line heads a region that can be folded, or is folded.
19#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct FoldMarker {
21    pub line: usize,
22    pub y: f32,
23    pub height: f32,
24    pub folded: bool,
25}
26
27/// Lines hidden by folds, with what is needed to convert between document heights with
28/// and without them. The height map keeps every line's own height; hidden lines are taken
29/// out here, so folding never rewrites the map.
30#[derive(Clone, Debug, Default)]
31pub(crate) struct Hidden {
32    /// Sorted, disjoint runs of hidden lines.
33    pub ranges: Vec<Range<usize>>,
34    /// Shown y of the top of each run (where the run would start).
35    shown_top: Vec<f64>,
36    /// Height hidden by runs `0..=i`.
37    hidden_through: Vec<f64>,
38}
39
40impl Hidden {
41    /// Hidden runs as the union of `ranges`, measured against `heights`.
42    pub fn new(mut ranges: Vec<Range<usize>>, heights: &HeightMap) -> Self {
43        ranges.sort_by_key(|r| r.start);
44        let mut merged: Vec<Range<usize>> = Vec::new();
45        for r in ranges {
46            match merged.last_mut() {
47                Some(last) if r.start <= last.end => last.end = last.end.max(r.end),
48                _ => merged.push(r),
49            }
50        }
51        let mut hidden = Self { ranges: Vec::new(), shown_top: Vec::new(), hidden_through: Vec::new() };
52        hidden.ranges = merged;
53        hidden.measure(heights);
54        hidden
55    }
56
57    /// Recomputes the measurements after line heights changed.
58    pub fn measure(&mut self, heights: &HeightMap) {
59        let len = heights.len();
60        self.ranges.retain(|r| r.start < len);
61        for r in &mut self.ranges {
62            r.end = r.end.min(len);
63        }
64        self.shown_top.clear();
65        self.hidden_through.clear();
66        let mut acc = 0.0;
67        for r in &self.ranges {
68            let top = heights.top(r.start);
69            self.shown_top.push(top - acc);
70            acc += heights.top(r.end) - top;
71            self.hidden_through.push(acc);
72        }
73    }
74
75    /// The run holding `line`, as its index.
76    pub fn run_of(&self, line: usize) -> Option<usize> {
77        let i = self.ranges.partition_point(|r| r.end <= line);
78        self.ranges.get(i).filter(|r| r.start <= line).map(|_| i)
79    }
80
81    /// Shown y of the top of `line`; a hidden line sits where its run starts.
82    pub fn top(&self, heights: &HeightMap, line: usize) -> f64 {
83        let i = self.ranges.partition_point(|r| r.end <= line);
84        if self.ranges.get(i).is_some_and(|r| r.start <= line) {
85            return self.shown_top[i];
86        }
87        heights.top(line) - if i == 0 { 0.0 } else { self.hidden_through[i - 1] }
88    }
89
90    /// The shown line at shown height `y`.
91    pub fn line_at(&self, heights: &HeightMap, y: f64) -> usize {
92        // Runs that start at or above y lie wholly above it, since they take no space.
93        let i = self.shown_top.partition_point(|&t| t <= y);
94        let natural = y + if i == 0 { 0.0 } else { self.hidden_through[i - 1] };
95        heights.line_at(natural)
96    }
97
98    /// Total shown height.
99    pub fn total(&self, heights: &HeightMap) -> f64 {
100        heights.total() - self.hidden_through.last().copied().unwrap_or(0.0)
101    }
102}
103
104/// Moves foldable regions past an edit that replaced lines `a..=a + old` with `a..=a + new`.
105/// Regions headed inside the edit are dropped until the provider recomputes them.
106pub(crate) fn shift_foldable(foldable: &mut Vec<(usize, usize)>, a: usize, old: usize, new: usize) {
107    let shift = |l: usize| if l > a + old { l + new - old } else { l.min(a + new) };
108    foldable.retain_mut(|(s, e)| {
109        if *s > a && *s <= a + old {
110            return false;
111        }
112        *s = shift(*s);
113        *e = shift(*e);
114        *e > *s
115    });
116}
117
118/// Moves a range of touched lines past a later edit, as [`shift_foldable`] does.
119pub(crate) fn shift_lines(r: &mut Range<usize>, a: usize, old: usize, new: usize) {
120    let shift = |l: usize| if l > a + old { l + new - old } else { l.min(a + new) };
121    r.start = shift(r.start);
122    r.end = shift(r.end.saturating_sub(1)) + 1;
123}
124
125/// Foldable regions from indentation: a non-blank line followed by more deeply indented
126/// lines heads a region ending at the last of them (trailing blank lines excluded). Used
127/// when no syntax tree gives better ranges, and for languages like Python where indentation
128/// is the structure.
129pub fn indent_fold_ranges(rope: &Rope, tab: usize) -> Vec<(usize, usize)> {
130    let tab = tab.max(1);
131    let total = rope.len_lines();
132    let mut out = Vec::new();
133    // Open headers as (line, indent cells); closed when a line at or below their indent appears.
134    let mut open: Vec<(usize, usize)> = Vec::new();
135    let mut last_nonblank = 0;
136    for line in 0..total {
137        let Some(cells) = indent_cells(rope, line, tab) else { continue };
138        while let Some(&(h, ind)) = open.last() {
139            if cells > ind {
140                break;
141            }
142            open.pop();
143            if last_nonblank > h {
144                out.push((h, last_nonblank));
145            }
146        }
147        open.push((line, cells));
148        last_nonblank = line;
149    }
150    while let Some((h, _)) = open.pop() {
151        if last_nonblank > h {
152            out.push((h, last_nonblank));
153        }
154    }
155    out.sort_unstable();
156    out
157}
158
159fn indent_cells(rope: &Rope, line: usize, tab: usize) -> Option<usize> {
160    let mut cells = 0;
161    for c in rope.line(line).chars() {
162        match c {
163            ' ' => cells += 1,
164            '\t' => cells += tab - cells % tab,
165            '\n' | '\r' => return None,
166            _ => return Some(cells),
167        }
168    }
169    None
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    #[test]
177    fn hidden_runs_take_no_space() {
178        let heights = HeightMap::new(10, 20.0);
179        let hidden = Hidden::new(vec![3..5, 4..7], &heights);
180        assert_eq!(hidden.ranges, vec![3..7]);
181        assert_eq!(hidden.top(&heights, 2), 40.0);
182        assert_eq!(hidden.top(&heights, 5), 60.0);
183        assert_eq!(hidden.top(&heights, 7), 60.0);
184        assert_eq!(hidden.top(&heights, 8), 80.0);
185        assert_eq!(hidden.line_at(&heights, 59.0), 2);
186        assert_eq!(hidden.line_at(&heights, 60.0), 7);
187        assert_eq!(hidden.total(&heights), 120.0);
188    }
189
190    #[test]
191    fn indentation_gives_fold_ranges() {
192        let rope = Rope::from_str("a\n  b\n\n  c\n    d\ne\n  f\n");
193        assert_eq!(indent_fold_ranges(&rope, 4), vec![(0, 4), (3, 4), (5, 6)]);
194    }
195}