Debian Codegraph @

helix-core/src/snippets/active.rs

raw symbols SCIP
1 use std::ops::{Index, IndexMut};
2
3 use foldhash::HashSet;
4 use helix_stdx::range::{is_exact_subset, is_subset};
5 use helix_stdx::Range;
6 use ropey::Rope;
7
8 use crate::movement::Direction;
9 use crate::snippets::render::{RenderedSnippet, Tabstop};
10 use crate::snippets::TabstopIdx;
11 use crate::{Assoc, ChangeSet, Selection, Transaction};
12
13 pub struct ActiveSnippet {
14 ranges: Vec<Range>,
15 active_tabstops: HashSet<TabstopIdx>,
16 current_tabstop: TabstopIdx,
17 tabstops: Vec<Tabstop>,
18 }
19
20 impl Index<TabstopIdx> for ActiveSnippet {
21 type Output = Tabstop;
22 fn index(&self, index: TabstopIdx) -> &Tabstop {
23 &self.tabstops[index.0]
24 }
25 }
26
27 impl IndexMut<TabstopIdx> for ActiveSnippet {
28 fn index_mut(&mut self, index: TabstopIdx) -> &mut Tabstop {
29 &mut self.tabstops[index.0]
30 }
31 }
32
33 impl ActiveSnippet {
34 pub fn new(snippet: RenderedSnippet) -> Option<Self> {
35 let snippet = Self {
36 ranges: snippet.ranges,
37 tabstops: snippet.tabstops,
38 active_tabstops: HashSet::default(),
39 current_tabstop: TabstopIdx(0),
40 };
41 (snippet.tabstops.len() != 1).then_some(snippet)
42 }
43
44 pub fn is_valid(&self, new_selection: &Selection) -> bool {
45 is_subset::<false>(self.ranges.iter().copied(), new_selection.range_bounds())
46 }
47
48 pub fn tabstops(&self) -> impl Iterator<Item = &Tabstop> {
49 self.tabstops.iter()
50 }
51
52 pub fn delete_placeholder(&self, doc: &Rope) -> Transaction {
53 Transaction::delete(
54 doc,
55 self[self.current_tabstop]
56 .ranges
57 .iter()
58 .map(|range| (range.start, range.end)),
59 )
60 }
61
62 /// maps the active snippets through a `ChangeSet` updating all tabstop ranges
63 pub fn map(&mut self, changes: &ChangeSet) -> bool {
64 let positions_to_map = self.ranges.iter_mut().flat_map(|range| {
65 [
66 (&mut range.start, Assoc::After),
67 (&mut range.end, Assoc::After),
68 ]
69 });
70 changes.update_positions(positions_to_map);
71
72 for (i, tabstop) in self.tabstops.iter_mut().enumerate() {
73 if self.active_tabstops.contains(&TabstopIdx(i)) {
74 let positions_to_map = tabstop.ranges.iter_mut().flat_map(|range| {
75 [
76 (&mut range.start, Assoc::After),
77 (&mut range.end, Assoc::After),
78 ]
79 });
80 changes.update_positions(positions_to_map);
81 } else {
82 let positions_to_map = tabstop.ranges.iter_mut().flat_map(|range| {
83 let end_assoc = if range.start == range.end {
84 Assoc::After
85 } else {
86 Assoc::Before
87 };
88 [
89 (&mut range.start, Assoc::After),
90 (&mut range.end, end_assoc),
91 ]
92 });
93 changes.update_positions(positions_to_map);
94 }
95 let mut snippet_ranges = self.ranges.iter();
96 let mut snippet_range = snippet_ranges.next().unwrap();
97 let mut tabstop_i = 0;
98 let mut prev = Range { start: 0, end: 0 };
99 let num_ranges = tabstop.ranges.len() / self.ranges.len();
100 tabstop.ranges.retain_mut(|range| {
101 if tabstop_i == num_ranges {
102 snippet_range = snippet_ranges.next().unwrap();
103 tabstop_i = 0;
104 }
105 tabstop_i += 1;
106 let retain = snippet_range.start <= snippet_range.end;
107 if retain {
108 // guaranteed by assoc
109 debug_assert!(prev.start <= range.start);
110 debug_assert!(
111 range.start <= range.end,
112 "Changes: {changes:?} | Range: {range:?} | Tabstop_i: {tabstop_i:?} | Snippet_range: {snippet_range:?} | Prev: {prev:?}"
113 );
114 if prev.end > range.start {
115 // not really sure what to do in this case. It shouldn't
116 // really occur in practice, the below just ensures
117 // our invariants hold
118 range.start = prev.end;
119 range.end = range.end.max(range.start)
120 }
121 prev = *range;
122 }
123 retain
124 });
125 }
126 self.ranges.iter().all(|range| range.end <= range.start)
127 }
128
129 pub fn next_tabstop(&mut self, current_selection: &Selection) -> (Selection, bool) {
130 let primary_idx = self.primary_idx(current_selection);
131 while self.current_tabstop.0 + 1 < self.tabstops.len() {
132 self.current_tabstop.0 += 1;
133 if self.activate_tabstop() {
134 let selection = self.tabstop_selection(primary_idx, Direction::Forward);
135 return (selection, self.current_tabstop.0 + 1 == self.tabstops.len());
136 }
137 }
138
139 (
140 self.tabstop_selection(primary_idx, Direction::Forward),
141 true,
142 )
143 }
144
145 pub fn prev_tabstop(&mut self, current_selection: &Selection) -> Option<Selection> {
146 let primary_idx = self.primary_idx(current_selection);
147 while self.current_tabstop.0 != 0 {
148 self.current_tabstop.0 -= 1;
149 if self.activate_tabstop() {
150 return Some(self.tabstop_selection(primary_idx, Direction::Forward));
151 }
152 }
153 None
154 }
155 /// Computes the primary index adjusted for the number of cursors in the current tabstop.
156 /// We allow for the selection range to 1 over the end to avoid issues with tabstops
157 /// at the very end of snippets.
158 fn primary_idx(&self, current_selection: &Selection) -> usize {
159 let primary: Range = current_selection.primary().into();
160 let res = self
161 .ranges
162 .iter()
163 .position(|&range| range.start <= primary.start && primary.end <= range.end + 1);
164 res.unwrap_or_else(|| {
165 unreachable!(
166 "active snippet must be valid {current_selection:?} {:?}",
167 self.ranges
168 )
169 })
170 }
171
172 fn activate_tabstop(&mut self) -> bool {
173 // We can activate a tabstop if are not at the final one
174 if self.current_tabstop.0 == self.tabstops.len() - 1 {
175 return false;
176 }
177 self.active_tabstops.clear();
178 self.active_tabstops.insert(self.current_tabstop);
179 let mut parent = self[self.current_tabstop].parent;
180 while let Some(tabstop) = parent {
181 self.active_tabstops.insert(tabstop);
182 parent = self[tabstop].parent;
183 }
184 true
185 // TODO: if the user removes the selection(s) in one snippet (but
186 // there are still other cursors in other snippets) and jumps to the
187 // next tabstop the selection in that tabstop is restored (at the
188 // next tabstop). This could be annoying since its not possible to
189 // remove a snippet cursor until the snippet is complete. On the other
190 // hand it may be useful since the user may just have meant to edit
191 // a subselection (like with s) of the tabstops and so the selection
192 // removal was just temporary. Potentially this could have some sort of
193 // separate keymap
194 }
195
196 pub fn tabstop_selection(&self, primary_idx: usize, direction: Direction) -> Selection {
197 let tabstop = &self[self.current_tabstop];
198 tabstop.selection(direction, primary_idx, self.ranges.len())
199 }
200
201 pub fn insert_subsnippet(mut self, snippet: RenderedSnippet) -> Option<Self> {
202 if !snippet.ranges.len().is_multiple_of(self.ranges.len())
203 || !is_exact_subset(self.ranges.iter().copied(), snippet.ranges.iter().copied())
204 {
205 log::warn!("number of subsnippets did not match, discarding outer snippet");
206 return ActiveSnippet::new(snippet);
207 }
208 let mut cnt = 0;
209 let parent = self[self.current_tabstop].parent;
210 let tabstops = snippet.tabstops.into_iter().map(|mut tabstop| {
211 cnt += 1;
212 if let Some(parent) = &mut tabstop.parent {
213 parent.0 += self.current_tabstop.0;
214 } else {
215 tabstop.parent = parent;
216 }
217 tabstop
218 });
219 self.tabstops
220 .splice(self.current_tabstop.0..=self.current_tabstop.0, tabstops);
221 self.activate_tabstop();
222 Some(self)
223 }
224 }
225
226 #[cfg(test)]
227 mod tests {
228 use std::iter::{self};
229
230 use ropey::Rope;
231
232 use crate::snippets::{ActiveSnippet, Snippet, SnippetRenderCtx};
233 use crate::{Selection, Transaction};
234
235 #[test]
236 fn fully_remove() {
237 let snippet = Snippet::parse("foo(${1:bar})$0").unwrap();
238 let mut doc = Rope::from("bar.\n");
239 let (transaction, _, snippet) = snippet.render(
240 &doc,
241 &Selection::point(4),
242 |_| (4, 4),
243 &mut SnippetRenderCtx::test_ctx(),
244 );
245 assert!(transaction.apply(&mut doc));
246 assert_eq!(doc, "bar.foo(bar)\n");
247 let mut snippet = ActiveSnippet::new(snippet).unwrap();
248 let edit = Transaction::change(&doc, iter::once((4, 12, None)));
249 assert!(edit.apply(&mut doc));
250 snippet.map(edit.changes());
251 assert!(!snippet.is_valid(&Selection::point(4)))
252 }
253
254 #[test]
255 fn tabstop_zero_with_placeholder() {
256 // The `$0` tabstop should not have placeholder text. When we receive a snippet like this
257 // (from older versions of clangd for example) we should discard the placeholder text.
258 let snippet = Snippet::parse("sizeof(${0:expression-or-type})").unwrap();
259 let mut doc = Rope::from("\n");
260 let (transaction, _, snippet) = snippet.render(
261 &doc,
262 &Selection::point(0),
263 |_| (0, 0),
264 &mut SnippetRenderCtx::test_ctx(),
265 );
266 assert!(transaction.apply(&mut doc));
267 assert_eq!(doc, "sizeof()\n");
268 assert!(ActiveSnippet::new(snippet).is_none());
269 }
270 }