1#![allow(clippy::single_range_in_vec_init)]
13
14use std::collections::HashMap;
15use std::ops::Range;
16
17use crate::decorations::{DecorationId, Stickiness};
18use crate::editor::Editor;
19use crate::history::EditKind;
20use crate::selection::{Selection, Selections};
21
22#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct Snippet {
25 pub text: String,
26 pub stops: Vec<TabStop>,
28}
29
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct TabStop {
32 pub index: u32,
33 pub ranges: Vec<Range<usize>>,
34 pub choices: Option<Vec<String>>,
36}
37
38#[derive(Clone, Debug)]
40enum Node {
41 Text(String),
42 Stop { index: u32, children: Vec<Node>, choices: Option<Vec<String>> },
43}
44
45impl Snippet {
46 pub fn parse(source: &str, variable: &dyn Fn(&str) -> Option<String>) -> Snippet {
49 let chars: Vec<char> = source.chars().collect();
50 let mut p = Parser { chars: &chars, pos: 0, variable, next_auto: 1000 };
51 let nodes = p.parse_until(&[]);
52 let mut defaults: HashMap<u32, String> = HashMap::new();
54 collect_defaults(&nodes, &mut defaults);
55 let mut out = Render { text: String::new(), len: 0, stops: Vec::new() };
56 out.render(&nodes, &defaults);
57 let mut stops: Vec<TabStop> = Vec::new();
58 let mut order: Vec<(u32, Range<usize>, Option<Vec<String>>)> = out.stops;
59 order.sort_by_key(|s| (s.0 == 0, s.0, s.1.start));
60 for (index, range, choices) in order {
61 match stops.last_mut() {
62 Some(last) if last.index == index => {
63 last.ranges.push(range);
64 if last.choices.is_none() {
65 last.choices = choices;
66 }
67 }
68 _ => stops.push(TabStop { index, ranges: vec![range], choices }),
69 }
70 }
71 if !stops.iter().any(|s| s.index == 0) {
72 let end = out.len;
73 stops.push(TabStop { index: 0, ranges: vec![end..end], choices: None });
74 }
75 Snippet { text: out.text, stops }
76 }
77
78 pub fn indented(&self, indent: &str, unit: &str) -> Snippet {
81 let mut text = String::new();
82 let mut map: Vec<usize> = Vec::with_capacity(self.text.chars().count() + 1);
84 let mut at_line_start = false;
85 let mut new_len = 0;
86 for c in self.text.chars() {
87 if at_line_start && c != '\n' {
88 text.push_str(indent);
89 new_len += indent.chars().count();
90 at_line_start = false;
91 }
92 map.push(new_len);
93 if c == '\t' && unit != "\t" {
94 text.push_str(unit);
95 new_len += unit.chars().count();
96 } else {
97 text.push(c);
98 new_len += 1;
99 }
100 if c == '\n' {
101 at_line_start = true;
102 }
103 }
104 map.push(new_len);
105 let stops = self
106 .stops
107 .iter()
108 .map(|s| TabStop {
109 index: s.index,
110 ranges: s.ranges.iter().map(|r| map[r.start]..map[r.end]).collect(),
111 choices: s.choices.clone(),
112 })
113 .collect();
114 Snippet { text, stops }
115 }
116}
117
118fn plain_text(nodes: &[Node]) -> String {
119 nodes
120 .iter()
121 .map(|n| match n {
122 Node::Text(t) => t.clone(),
123 Node::Stop { children, .. } => plain_text(children),
124 })
125 .collect()
126}
127
128fn collect_defaults(nodes: &[Node], out: &mut HashMap<u32, String>) {
129 for n in nodes {
130 if let Node::Stop { index, children, choices } = n {
131 let text = match choices {
132 Some(c) => c.first().cloned().unwrap_or_default(),
133 None => plain_text(children),
134 };
135 if !text.is_empty() {
136 out.entry(*index).or_insert(text);
137 }
138 collect_defaults(children, out);
139 }
140 }
141}
142
143struct Render {
144 text: String,
145 len: usize,
146 stops: Vec<(u32, Range<usize>, Option<Vec<String>>)>,
147}
148
149impl Render {
150 fn push(&mut self, s: &str) {
151 self.text.push_str(s);
152 self.len += s.chars().count();
153 }
154
155 fn render(&mut self, nodes: &[Node], defaults: &HashMap<u32, String>) {
156 for n in nodes {
157 match n {
158 Node::Text(t) => self.push(t),
159 Node::Stop { index, children, choices } => {
160 let from = self.len;
161 if let Some(c) = choices {
162 self.push(c.first().map_or("", String::as_str));
163 } else if children.is_empty() {
164 if let Some(d) = defaults.get(index) {
165 self.push(d);
166 }
167 } else {
168 self.render(children, defaults);
169 }
170 self.stops.push((*index, from..self.len, choices.clone()));
171 }
172 }
173 }
174 }
175}
176
177struct Parser<'a> {
178 chars: &'a [char],
179 pos: usize,
180 variable: &'a dyn Fn(&str) -> Option<String>,
181 next_auto: u32,
183}
184
185impl Parser<'_> {
186 fn peek(&self) -> Option<char> {
187 self.chars.get(self.pos).copied()
188 }
189
190 fn parse_until(&mut self, stop: &[char]) -> Vec<Node> {
192 let mut nodes = Vec::new();
193 let mut text = String::new();
194 while let Some(c) = self.peek() {
195 if stop.contains(&c) {
196 break;
197 }
198 match c {
199 '\\' => {
200 let next = self.chars.get(self.pos + 1).copied();
201 if matches!(next, Some('$' | '}' | '\\')) || next.is_some_and(|n| stop.contains(&n)) {
202 text.push(next.expect("checked"));
203 self.pos += 2;
204 } else {
205 text.push('\\');
206 self.pos += 1;
207 }
208 }
209 '$' => match self.element() {
210 Some(node) => {
211 if !text.is_empty() {
212 nodes.push(Node::Text(std::mem::take(&mut text)));
213 }
214 nodes.extend(node);
215 }
216 None => {
217 text.push('$');
218 self.pos += 1;
219 }
220 },
221 _ => {
222 text.push(c);
223 self.pos += 1;
224 }
225 }
226 }
227 if !text.is_empty() {
228 nodes.push(Node::Text(text));
229 }
230 nodes
231 }
232
233 fn number(&mut self) -> Option<u32> {
234 let start = self.pos;
235 while self.peek().is_some_and(|c| c.is_ascii_digit()) {
236 self.pos += 1;
237 }
238 if self.pos == start {
239 return None;
240 }
241 self.chars[start..self.pos].iter().collect::<String>().parse().ok()
242 }
243
244 fn name(&mut self) -> Option<String> {
245 let start = self.pos;
246 if !self.peek().is_some_and(|c| c == '_' || c.is_ascii_alphabetic()) {
247 return None;
248 }
249 while self.peek().is_some_and(|c| c == '_' || c.is_ascii_alphanumeric()) {
250 self.pos += 1;
251 }
252 Some(self.chars[start..self.pos].iter().collect())
253 }
254
255 fn close(&mut self) {
256 if self.peek() == Some('}') {
257 self.pos += 1;
258 }
259 }
260
261 fn element(&mut self) -> Option<Vec<Node>> {
264 let start = self.pos;
265 self.pos += 1; let stop = |index| Node::Stop { index, children: Vec::new(), choices: None };
267 if let Some(index) = self.number() {
268 return Some(vec![stop(index)]);
269 }
270 if let Some(name) = self.name() {
271 return Some(self.variable_value(&name, None));
272 }
273 if self.peek() != Some('{') {
274 self.pos = start;
275 return None;
276 }
277 self.pos += 1;
278 if let Some(index) = self.number() {
279 match self.peek() {
280 Some('}') => {
281 self.pos += 1;
282 return Some(vec![stop(index)]);
283 }
284 Some(':') => {
285 self.pos += 1;
286 let children = self.parse_until(&['}']);
287 self.close();
288 return Some(vec![Node::Stop { index, children, choices: None }]);
289 }
290 Some('|') => {
291 self.pos += 1;
292 let mut options = Vec::new();
293 let mut current = String::new();
294 while let Some(c) = self.peek() {
295 self.pos += 1;
296 match c {
297 '\\' if matches!(self.peek(), Some(',' | '|' | '\\')) => {
298 current.push(self.peek().expect("checked"));
299 self.pos += 1;
300 }
301 ',' => options.push(std::mem::take(&mut current)),
302 '|' => break,
303 _ => current.push(c),
304 }
305 }
306 options.push(current);
307 self.close();
308 return Some(vec![Node::Stop { index, children: Vec::new(), choices: Some(options) }]);
309 }
310 Some('/') => {
311 self.skip_to_close();
313 return Some(vec![stop(index)]);
314 }
315 _ => {
316 self.pos = start;
317 return None;
318 }
319 }
320 }
321 if let Some(name) = self.name() {
322 match self.peek() {
323 Some('}') => {
324 self.pos += 1;
325 return Some(self.variable_value(&name, None));
326 }
327 Some(':') => {
328 self.pos += 1;
329 let default = self.parse_until(&['}']);
330 self.close();
331 return Some(self.variable_value(&name, Some(default)));
332 }
333 Some('/') => {
334 self.skip_to_close();
335 return Some(self.variable_value(&name, None));
336 }
337 _ => {}
338 }
339 }
340 self.pos = start;
341 None
342 }
343
344 fn skip_to_close(&mut self) {
345 let mut depth = 0;
346 while let Some(c) = self.peek() {
347 self.pos += 1;
348 match c {
349 '\\' => self.pos += 1,
350 '{' => depth += 1,
351 '}' if depth == 0 => return,
352 '}' => depth -= 1,
353 _ => {}
354 }
355 }
356 }
357
358 fn variable_value(&mut self, name: &str, default: Option<Vec<Node>>) -> Vec<Node> {
359 if let Some(value) = (self.variable)(name) {
360 return vec![Node::Text(value)];
361 }
362 match default {
363 Some(nodes) => nodes,
364 None => {
365 let index = self.next_auto;
367 self.next_auto += 1;
368 vec![Node::Stop { index, children: vec![Node::Text(name.to_owned())], choices: None }]
369 }
370 }
371 }
372}
373
374#[derive(Clone, Debug)]
376pub struct SnippetSession {
377 stops: Vec<(Vec<DecorationId>, Option<Vec<String>>)>,
379 current: usize,
380 owner: u32,
381}
382
383pub const SNIPPET_STOP: u32 = 3;
385
386pub const SNIPPET_OWNER: u32 = 1 << 18;
388
389impl SnippetSession {
390 pub fn choices(&self) -> Option<&[String]> {
392 self.stops.get(self.current).and_then(|s| s.1.as_deref())
393 }
394
395 pub fn owner(&self) -> u32 {
396 self.owner
397 }
398}
399
400impl Editor<'_> {
401 pub fn insert_snippet(&mut self, snippet: &Snippet) {
404 self.end_snippet();
405 let o = self.model.options;
406 let unit = if o.insert_spaces { " ".repeat(o.tab_size) } else { "\t".to_owned() };
407 let rope = &self.model.rope;
408 let copies: Vec<(usize, Snippet)> = self
410 .cursors
411 .selections
412 .iter()
413 .map(|s| {
414 let line = rope.char_to_line(s.start());
415 let indent: String = rope.line(line).chars().take_while(|c| *c == ' ' || *c == '\t').collect();
416 (s.start(), snippet.indented(&indent, &unit))
417 })
418 .collect();
419 let texts: Vec<String> = copies.iter().map(|(_, s)| s.text.clone()).collect();
420 let before: Vec<Selection> = self.cursors.selections.iter().cloned().collect();
421 self.replace_each(EditKind::Other, |_, i, _| texts[i].clone());
422 let mut shift = 0isize;
424 let mut starts = Vec::with_capacity(copies.len());
425 for (i, s) in before.iter().enumerate() {
426 starts.push(s.start().wrapping_add_signed(shift));
427 shift += copies[i].1.text.chars().count() as isize - s.len() as isize;
428 }
429 let owner = SNIPPET_OWNER + self.cursors.id().0;
430 let mut stops = Vec::new();
431 for stop in &snippet.stops {
432 let ranges: Vec<Range<usize>> = copies
433 .iter()
434 .zip(&starts)
435 .flat_map(|((_, copy), &start)| {
436 let s = copy.stops.iter().find(|t| t.index == stop.index).expect("same stops in every copy");
437 s.ranges.iter().map(move |r| start + r.start..start + r.end).collect::<Vec<_>>()
438 })
439 .collect();
440 stops.push((ranges, stop.choices.clone()));
441 }
442 let all: Vec<(Range<usize>, u32)> =
444 stops.iter().flat_map(|(ranges, _)| ranges.iter().map(|r| (r.clone(), SNIPPET_STOP))).collect();
445 let ids = self.model.decorations.set_each(owner, Stickiness::AlwaysGrows, all);
446 let mut it = ids.into_iter();
447 let stops =
448 stops.into_iter().map(|(ranges, choices)| (it.by_ref().take(ranges.len()).collect(), choices)).collect();
449 self.cursors.snippet = Some(SnippetSession { stops, current: 0, owner });
450 self.select_stop(0);
451 self.model.history.break_group();
452 }
453
454 fn select_stop(&mut self, i: usize) {
456 let Some(session) = self.cursors.snippet.as_mut() else { return };
457 session.current = i;
458 let ranges: Vec<Range<usize>> = session.stops[i]
459 .0
460 .iter()
461 .filter_map(|id| self.model.decorations.get(*id).map(|d| d.range.clone()))
462 .collect();
463 let last = i + 1 == session.stops.len();
464 if ranges.is_empty() {
465 return;
466 }
467 let sels: Vec<Selection> = ranges.iter().map(|r| Selection::new(r.start, r.end)).collect();
468 self.set_selections(Selections::new(sels, 0));
469 if last {
470 self.end_snippet();
471 }
472 }
473
474 pub fn next_snippet_stop(&mut self) -> bool {
476 let Some(session) = self.cursors.snippet.as_ref() else { return false };
477 let next = (session.current + 1).min(session.stops.len() - 1);
478 self.select_stop(next);
479 true
480 }
481
482 pub fn prev_snippet_stop(&mut self) -> bool {
484 let Some(session) = self.cursors.snippet.as_ref() else { return false };
485 let prev = session.current.saturating_sub(1);
486 self.select_stop(prev);
487 true
488 }
489
490 pub fn end_snippet(&mut self) {
492 if let Some(session) = self.cursors.snippet.take() {
493 self.model.decorations.clear(session.owner);
494 }
495 }
496
497 pub fn check_snippet(&mut self) {
499 let Some(session) = self.cursors.snippet.as_ref() else { return };
500 let head = self.cursors.selections.primary().head;
501 let inside =
502 session.stops.iter().flat_map(|s| s.0.iter()).any(|id| {
503 self.model.decorations.get(*id).is_some_and(|d| d.range.start <= head && head <= d.range.end)
504 });
505 if !inside {
506 self.end_snippet();
507 }
508 }
509
510 pub fn snippet(&self) -> Option<&SnippetSession> {
512 self.cursors.snippet.as_ref()
513 }
514}
515
516#[cfg(test)]
517mod tests {
518 use super::*;
519
520 fn parse(s: &str) -> Snippet {
521 Snippet::parse(s, &|name| (name == "TM_FILENAME").then(|| "main.rs".to_owned()))
522 }
523
524 #[test]
525 fn stops_placeholders_and_final_position() {
526 let s = parse("fn ${1:name}($2) {\n\t$0\n}");
527 assert_eq!(s.text, "fn name() {\n\t\n}");
528 assert_eq!(
529 s.stops.iter().map(|t| (t.index, t.ranges.clone())).collect::<Vec<_>>(),
530 vec![(1, vec![3..7]), (2, vec![8..8]), (0, vec![13..13]),]
531 );
532 }
533
534 #[test]
535 fn nested_placeholders_choices_variables_and_escapes() {
536 let s = parse("${1:outer ${2:inner}} ${3|a,b\\,c|} $TM_FILENAME ${NOPE} \\$1 ${UNSET:dflt}");
537 assert_eq!(s.text, "outer inner a main.rs NOPE $1 dflt");
538 let stop = |i: u32| s.stops.iter().find(|t| t.index == i).unwrap();
539 assert_eq!(stop(1).ranges, vec![0..11]);
540 assert_eq!(stop(2).ranges, vec![6..11]);
541 assert_eq!(stop(3).choices.as_deref(), Some(&["a".to_owned(), "b,c".to_owned()][..]));
542 assert!(
543 s.stops.iter().any(|t| t.index >= 1000 && t.ranges == vec![22..26]),
544 "unknown variable is a placeholder"
545 );
546 assert_eq!(s.stops.last().unwrap().index, 0);
547 }
548
549 #[test]
550 fn mirrors_share_an_index_and_the_default() {
551 let s = parse("${1:x} = $1;");
552 assert_eq!(s.text, "x = x;");
553 assert_eq!(s.stops[0].ranges, vec![0..1, 4..5]);
554 }
555
556 #[test]
557 fn indentation_follows_the_line() {
558 let s = parse("if {\n\t$1\n}").indented(" ", " ");
559 assert_eq!(s.text, "if {\n \n }");
560 assert_eq!(s.stops[0].ranges, vec![11..11]);
561 }
562}