Debian Codegraph @

helix-core/src/auto_pairs.rs

raw symbols SCIP
1 //! When typing the opening character of one of the possible pairs defined below,
2 //! this module provides the functionality to insert the paired closing character.
3
4 use crate::{graphemes, movement::Direction, Change, Deletion, Range, Rope, Tendril};
5 use std::collections::HashMap;
6
7 // Heavily based on https://github.com/codemirror/closebrackets/
8 pub const DEFAULT_PAIRS: &[(char, char)] = &[
9 ('(', ')'),
10 ('{', '}'),
11 ('[', ']'),
12 ('\'', '\''),
13 ('"', '"'),
14 ('`', '`'),
15 ];
16
17 /// The type that represents the collection of auto pairs,
18 /// keyed by both opener and closer.
19 #[derive(Debug, Clone)]
20 pub struct AutoPairs(HashMap<char, Pair>);
21
22 /// Represents the config for a particular pairing.
23 #[derive(Debug, Clone, Copy)]
24 pub struct Pair {
25 pub open: char,
26 pub close: char,
27 }
28
29 impl Pair {
30 /// true if open == close
31 pub fn same(&self) -> bool {
32 self.open == self.close
33 }
34
35 /// true if all of the pair's conditions hold for the given document and range
36 pub fn should_close(&self, doc: &Rope, range: &Range) -> bool {
37 let mut should_close = Self::next_is_not_alpha(doc, range);
38
39 if self.same() {
40 should_close &= Self::prev_is_not_alpha(doc, range);
41 }
42
43 should_close
44 }
45
46 pub fn next_is_not_alpha(doc: &Rope, range: &Range) -> bool {
47 let cursor = range.cursor(doc.slice(..));
48 let next_char = doc.get_char(cursor);
49 next_char.map(|c| !c.is_alphanumeric()).unwrap_or(true)
50 }
51
52 pub fn prev_is_not_alpha(doc: &Rope, range: &Range) -> bool {
53 let cursor = range.cursor(doc.slice(..));
54 let prev_char = prev_char(doc, cursor);
55 prev_char.map(|c| !c.is_alphanumeric()).unwrap_or(true)
56 }
57 }
58
59 impl From<&(char, char)> for Pair {
60 fn from(&(open, close): &(char, char)) -> Self {
61 Self { open, close }
62 }
63 }
64
65 impl From<(&char, &char)> for Pair {
66 fn from((open, close): (&char, &char)) -> Self {
67 Self {
68 open: *open,
69 close: *close,
70 }
71 }
72 }
73
74 impl AutoPairs {
75 /// Make a new AutoPairs set with the given pairs and default conditions.
76 pub fn new<'a, V, A>(pairs: V) -> Self
77 where
78 V: IntoIterator<Item = A> + 'a,
79 A: Into<Pair>,
80 {
81 let mut auto_pairs = HashMap::new();
82
83 for pair in pairs.into_iter() {
84 let auto_pair = pair.into();
85
86 auto_pairs.insert(auto_pair.open, auto_pair);
87
88 if auto_pair.open != auto_pair.close {
89 auto_pairs.insert(auto_pair.close, auto_pair);
90 }
91 }
92
93 Self(auto_pairs)
94 }
95
96 pub fn get(&self, ch: char) -> Option<&Pair> {
97 self.0.get(&ch)
98 }
99 }
100
101 impl Default for AutoPairs {
102 fn default() -> Self {
103 AutoPairs::new(DEFAULT_PAIRS.iter())
104 }
105 }
106
107 // [TODO]
108 // * delete implementation where it erases the whole bracket (|) -> |
109 // * change to multi character pairs to handle cases like placing the cursor in the
110 // middle of triple quotes, and more exotic pairs like Jinja's {% %}
111
112 #[must_use]
113 pub fn hook_insert(
114 doc: &Rope,
115 range: &Range,
116 ch: char,
117 pairs: &AutoPairs,
118 ) -> Option<(Change, Range)> {
119 log::trace!("autopairs hook range: {:#?}", range);
120
121 if let Some(pair) = pairs.get(ch) {
122 if pair.same() {
123 return handle_insert_same(doc, range, pair);
124 } else if pair.open == ch {
125 return handle_insert_open(doc, range, pair);
126 } else if pair.close == ch {
127 // && char_at pos == close
128 return handle_insert_close(doc, range, pair);
129 }
130 } else if ch.is_whitespace() {
131 return handle_insert_whitespace(doc, range, ch, pairs);
132 }
133
134 None
135 }
136
137 #[must_use]
138 pub fn hook_delete(doc: &Rope, range: &Range, pairs: &AutoPairs) -> Option<(Deletion, Range)> {
139 log::trace!("autopairs delete hook range: {:#?}", range);
140
141 let text = doc.slice(..);
142 let cursor = range.cursor(text);
143
144 let cur = doc.get_char(cursor)?;
145 let prev = prev_char(doc, cursor)?;
146
147 // check for whitespace surrounding a pair
148 if doc.len_chars() >= 4 && prev.is_whitespace() && cur.is_whitespace() {
149 let second_prev = doc.get_char(graphemes::nth_prev_grapheme_boundary(text, cursor, 2))?;
150 let second_next = doc.get_char(graphemes::next_grapheme_boundary(text, cursor))?;
151 log::debug!("second_prev: {}, second_next: {}", second_prev, second_next);
152
153 if let Some(pair) = pairs.get(second_prev) {
154 if pair.open == second_prev && pair.close == second_next {
155 return handle_delete(doc, range);
156 }
157 }
158 }
159
160 let pair = pairs.get(cur)?;
161
162 if pair.open != prev || pair.close != cur {
163 return None;
164 }
165
166 handle_delete(doc, range)
167 }
168
169 pub fn handle_delete(doc: &Rope, range: &Range) -> Option<(Deletion, Range)> {
170 let text = doc.slice(..);
171 let cursor = range.cursor(text);
172
173 let end_next = graphemes::next_grapheme_boundary(text, cursor);
174 let end_prev = graphemes::prev_grapheme_boundary(text, cursor);
175
176 let delete = (end_prev, end_next);
177 let size_delete = end_next - end_prev;
178 let next_head = graphemes::next_grapheme_boundary(text, range.head) - size_delete;
179
180 // if the range is a single grapheme cursor, we do not want to shrink the
181 // range, just move it, so we only subtract the size of the closing pair char
182 let next_anchor = match (range.direction(), range.is_single_grapheme(text)) {
183 // single grapheme forward needs to move, but only the width of the
184 // character under the cursor, which is the closer
185 (Direction::Forward, true) => range.anchor - (end_next - cursor),
186 (Direction::Backward, true) => range.anchor - (cursor - end_prev),
187
188 (Direction::Forward, false) => range.anchor,
189 (Direction::Backward, false) => range.anchor - size_delete,
190 };
191
192 let next_range = Range::new(next_anchor, next_head);
193
194 log::trace!(
195 "auto pair delete: {:?}, range: {:?}, next_range: {:?}, text len: {}",
196 delete,
197 range,
198 next_range,
199 text.len_chars()
200 );
201
202 Some((delete, next_range))
203 }
204
205 fn handle_insert_whitespace(
206 doc: &Rope,
207 range: &Range,
208 ch: char,
209 pairs: &AutoPairs,
210 ) -> Option<(Change, Range)> {
211 let text = doc.slice(..);
212 let cursor = range.cursor(text);
213 let cur = doc.get_char(cursor)?;
214 let prev = prev_char(doc, cursor)?;
215 let pair = pairs.get(cur)?;
216
217 if pair.open != prev || pair.close != cur {
218 return None;
219 }
220
221 let whitespace_pair = Pair {
222 open: ch,
223 close: ch,
224 };
225
226 handle_insert_same(doc, range, &whitespace_pair)
227 }
228
229 fn prev_char(doc: &Rope, pos: usize) -> Option<char> {
230 if pos == 0 {
231 return None;
232 }
233
234 doc.get_char(pos - 1)
235 }
236
237 /// calculate what the resulting range should be for an auto pair insertion
238 fn get_next_range(doc: &Rope, start_range: &Range, len_inserted: usize) -> Range {
239 // When the character under the cursor changes due to complete pair
240 // insertion, we must look backward a grapheme and then add the length
241 // of the insertion to put the resulting cursor in the right place, e.g.
242 //
243 // foo[\r\n] - anchor: 3, head: 5
244 // foo([)]\r\n - anchor: 4, head: 5
245 //
246 // foo[\r\n] - anchor: 3, head: 5
247 // foo'[\r\n] - anchor: 4, head: 6
248 //
249 // foo([)]\r\n - anchor: 4, head: 5
250 // foo()[\r\n] - anchor: 5, head: 7
251 //
252 // [foo]\r\n - anchor: 0, head: 3
253 // [foo(])\r\n - anchor: 0, head: 5
254
255 // inserting at the very end of the document after the last newline
256 if start_range.head == doc.len_chars() && start_range.anchor == doc.len_chars() {
257 return Range::new(start_range.anchor + 1, start_range.head + 1);
258 }
259
260 let doc_slice = doc.slice(..);
261 let single_grapheme = start_range.is_single_grapheme(doc_slice);
262
263 // just skip over graphemes
264 if len_inserted == 0 {
265 let end_anchor = if single_grapheme {
266 graphemes::next_grapheme_boundary(doc_slice, start_range.anchor)
267
268 // even for backward inserts with multiple grapheme selections,
269 // we want the anchor to stay where it is so that the relative
270 // selection does not change, e.g.:
271 //
272 // foo([) wor]d -> insert ) -> foo()[ wor]d
273 } else {
274 start_range.anchor
275 };
276
277 return Range::new(
278 end_anchor,
279 graphemes::next_grapheme_boundary(doc_slice, start_range.head),
280 );
281 }
282
283 // trivial case: only inserted a single-char opener, just move the selection
284 if len_inserted == 1 {
285 let end_anchor = if single_grapheme || start_range.direction() == Direction::Backward {
286 start_range.anchor + 1
287 } else {
288 start_range.anchor
289 };
290
291 return Range::new(end_anchor, start_range.head + 1);
292 }
293
294 // If the head = 0, then we must be in insert mode with a backward
295 // cursor, which implies the head will just move
296 let end_head = if start_range.head == 0 || start_range.direction() == Direction::Backward {
297 start_range.head + 1
298 } else {
299 // We must have a forward cursor, which means we must move to the
300 // other end of the grapheme to get to where the new characters
301 // are inserted, then move the head to where it should be
302 let prev_bound = graphemes::prev_grapheme_boundary(doc_slice, start_range.head);
303 log::trace!("prev_bound: {}, len_inserted: {}", prev_bound, len_inserted);
304
305 prev_bound + len_inserted
306 };
307
308 let end_anchor = match (start_range.len(), start_range.direction()) {
309 // if we have a zero width cursor, it shifts to the same number
310 (0, _) => end_head,
311
312 // If we are inserting for a regular one-width cursor, the anchor
313 // moves with the head. This is the fast path for ASCII.
314 (1, Direction::Forward) => end_head - 1,
315 (1, Direction::Backward) => end_head + 1,
316
317 (_, Direction::Forward) => {
318 if single_grapheme {
319 graphemes::prev_grapheme_boundary(doc.slice(..), start_range.head) + 1
320
321 // if we are appending, the anchor stays where it is; only offset
322 // for multiple range insertions
323 } else {
324 start_range.anchor
325 }
326 }
327
328 (_, Direction::Backward) => {
329 if single_grapheme {
330 // if we're backward, then the head is at the first char
331 // of the typed char, so we need to add the length of
332 // the closing char
333 graphemes::prev_grapheme_boundary(doc.slice(..), start_range.anchor) + len_inserted
334 } else {
335 // when we are inserting in front of a selection, we need to move
336 // the anchor over by however many characters were inserted overall
337 start_range.anchor + len_inserted
338 }
339 }
340 };
341
342 Range::new(end_anchor, end_head)
343 }
344
345 fn handle_insert_open(doc: &Rope, range: &Range, pair: &Pair) -> Option<(Change, Range)> {
346 let cursor = range.cursor(doc.slice(..));
347 let next_char = doc.get_char(cursor);
348 let len_inserted;
349
350 // Since auto pairs are currently limited to single chars, we're either
351 // inserting exactly one or two chars. When arbitrary length pairs are
352 // added, these will need to be changed.
353 let change = match next_char {
354 Some(_) if !pair.should_close(doc, range) => {
355 return None;
356 }
357 _ => {
358 // insert open & close
359 let pair_str = Tendril::from_iter([pair.open, pair.close]);
360 len_inserted = 2;
361 (cursor, cursor, Some(pair_str))
362 }
363 };
364
365 let next_range = get_next_range(doc, range, len_inserted);
366 let result = (change, next_range);
367
368 log::debug!("auto pair change: {:#?}", &result);
369
370 Some(result)
371 }
372
373 fn handle_insert_close(doc: &Rope, range: &Range, pair: &Pair) -> Option<(Change, Range)> {
374 let cursor = range.cursor(doc.slice(..));
375 let next_char = doc.get_char(cursor);
376
377 let change = if next_char == Some(pair.close) {
378 // return transaction that moves past close
379 (cursor, cursor, None) // no-op
380 } else {
381 return None;
382 };
383
384 let next_range = get_next_range(doc, range, 0);
385 let result = (change, next_range);
386
387 log::debug!("auto pair change: {:#?}", &result);
388
389 Some(result)
390 }
391
392 /// handle cases where open and close is the same, or in triples ("""docstring""")
393 fn handle_insert_same(doc: &Rope, range: &Range, pair: &Pair) -> Option<(Change, Range)> {
394 let cursor = range.cursor(doc.slice(..));
395 let mut len_inserted = 0;
396 let next_char = doc.get_char(cursor);
397
398 let change = if next_char == Some(pair.open) {
399 // return transaction that moves past close
400 (cursor, cursor, None) // no-op
401 } else {
402 if !pair.should_close(doc, range) {
403 return None;
404 }
405
406 let pair_str = Tendril::from_iter([pair.open, pair.close]);
407 len_inserted = 2;
408 (cursor, cursor, Some(pair_str))
409 };
410
411 let next_range = get_next_range(doc, range, len_inserted);
412 let result = (change, next_range);
413
414 log::debug!("auto pair change: {:#?}", &result);
415
416 Some(result)
417 }