1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//! 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();
}
}