Debian Codegraph @

helix-core/src/snippets/parser.rs

raw symbols SCIP
1 /*!
2 A parser for LSP/VSCode style snippet syntax
3 See <https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#snippet_syntax>.
4
5 ``` text
6 any ::= tabstop | placeholder | choice | variable | text
7 tabstop ::= '$' int | '${' int '}'
8 placeholder ::= '${' int ':' any '}'
9 choice ::= '${' int '|' text (',' text)* '|}'
10 variable ::= '$' var | '${' var }'
11 | '${' var ':' any '}'
12 | '${' var '/' regex '/' (format | text)+ '/' options '}'
13 format ::= '$' int | '${' int '}'
14 | '${' int ':' '/upcase' | '/downcase' | '/capitalize' '}'
15 | '${' int ':+' if '}'
16 | '${' int ':?' if ':' else '}'
17 | '${' int ':-' else '}' | '${' int ':' else '}'
18 regex ::= Regular Expression value (ctor-string)
19 options ::= Regular Expression option (ctor-options)
20 var ::= [_a-zA-Z] [_a-zA-Z0-9]*
21 int ::= [0-9]+
22 text ::= .*
23 if ::= text
24 else ::= text
25 ```
26 */
27
28 use crate::Tendril;
29 use helix_parsec::*;
30
31 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
32 pub enum CaseChange {
33 Upcase,
34 Downcase,
35 Capitalize,
36 PascalCase,
37 CamelCase,
38 }
39
40 #[derive(Debug, PartialEq, Eq)]
41 pub enum FormatItem {
42 Text(Tendril),
43 Capture(usize),
44 CaseChange(usize, CaseChange),
45 Conditional(usize, Tendril, Tendril),
46 }
47
48 #[derive(Debug, PartialEq, Eq)]
49 pub struct Transform {
50 pub regex: Tendril,
51 pub replacement: Vec<FormatItem>,
52 pub options: Tendril,
53 }
54
55 #[derive(Debug, PartialEq, Eq)]
56 pub enum SnippetElement {
57 Tabstop {
58 tabstop: usize,
59 transform: Option<Transform>,
60 },
61 Placeholder {
62 tabstop: usize,
63 value: Vec<SnippetElement>,
64 },
65 Choice {
66 tabstop: usize,
67 choices: Vec<Tendril>,
68 },
69 Variable {
70 name: Tendril,
71 default: Option<Vec<SnippetElement>>,
72 transform: Option<Transform>,
73 },
74 Text(Tendril),
75 }
76
77 pub fn parse(s: &str) -> Result<Vec<SnippetElement>, &str> {
78 snippet().parse(s).and_then(|(remainder, snippet)| {
79 if remainder.is_empty() {
80 Ok(snippet)
81 } else {
82 Err(remainder)
83 }
84 })
85 }
86
87 fn var<'a>() -> impl Parser<'a, Output = &'a str> {
88 // var = [_a-zA-Z][_a-zA-Z0-9]*
89 move |input: &'a str| {
90 input
91 .char_indices()
92 .take_while(|(p, c)| {
93 *c == '_'
94 || if *p == 0 {
95 c.is_ascii_alphabetic()
96 } else {
97 c.is_ascii_alphanumeric()
98 }
99 })
100 .last()
101 .map(|(index, c)| {
102 let index = index + c.len_utf8();
103 (&input[index..], &input[0..index])
104 })
105 .ok_or(input)
106 }
107 }
108
109 const TEXT_ESCAPE_CHARS: &[char] = &['\\', '}', '$'];
110 const CHOICE_TEXT_ESCAPE_CHARS: &[char] = &['\\', '|', ','];
111
112 fn text<'a>(
113 escape_chars: &'static [char],
114 term_chars: &'static [char],
115 ) -> impl Parser<'a, Output = Tendril> {
116 move |input: &'a str| {
117 let mut chars = input.char_indices().peekable();
118 let mut res = Tendril::new();
119 while let Some((i, c)) = chars.next() {
120 match c {
121 '\\' => {
122 if let Some(&(_, c)) = chars.peek() {
123 if escape_chars.contains(&c) {
124 chars.next();
125 res.push(c);
126 continue;
127 }
128 }
129 res.push('\\');
130 }
131 c if term_chars.contains(&c) => return Ok((&input[i..], res)),
132 c => res.push(c),
133 }
134 }
135
136 Ok(("", res))
137 }
138 }
139
140 fn digit<'a>() -> impl Parser<'a, Output = usize> {
141 filter_map(take_while(|c| c.is_ascii_digit()), |s| s.parse().ok())
142 }
143
144 fn case_change<'a>() -> impl Parser<'a, Output = CaseChange> {
145 use CaseChange::*;
146
147 choice!(
148 map("upcase", |_| Upcase),
149 map("downcase", |_| Downcase),
150 map("capitalize", |_| Capitalize),
151 map("pascalcase", |_| PascalCase),
152 map("camelcase", |_| CamelCase),
153 )
154 }
155
156 fn format<'a>() -> impl Parser<'a, Output = FormatItem> {
157 use FormatItem::*;
158
159 choice!(
160 // '$' int
161 map(right("$", digit()), Capture),
162 // '${' int '}'
163 map(seq!("${", digit(), "}"), |seq| Capture(seq.1)),
164 // '${' int ':' '/upcase' | '/downcase' | '/capitalize' '}'
165 map(seq!("${", digit(), ":/", case_change(), "}"), |seq| {
166 CaseChange(seq.1, seq.3)
167 }),
168 // '${' int ':+' if '}'
169 map(
170 seq!("${", digit(), ":+", text(TEXT_ESCAPE_CHARS, &['}']), "}"),
171 |seq| { Conditional(seq.1, seq.3, Tendril::new()) }
172 ),
173 // '${' int ':?' if ':' else '}'
174 map(
175 seq!(
176 "${",
177 digit(),
178 ":?",
179 text(TEXT_ESCAPE_CHARS, &[':']),
180 ":",
181 text(TEXT_ESCAPE_CHARS, &['}']),
182 "}"
183 ),
184 |seq| { Conditional(seq.1, seq.3, seq.5) }
185 ),
186 // '${' int ':-' else '}' | '${' int ':' else '}'
187 map(
188 seq!(
189 "${",
190 digit(),
191 ":",
192 optional("-"),
193 text(TEXT_ESCAPE_CHARS, &['}']),
194 "}"
195 ),
196 |seq| { Conditional(seq.1, Tendril::new(), seq.4) }
197 ),
198 )
199 }
200
201 fn regex<'a>() -> impl Parser<'a, Output = Transform> {
202 map(
203 seq!(
204 "/",
205 // TODO parse as ECMAScript and convert to rust regex
206 text(&['/'], &['/']),
207 "/",
208 zero_or_more(choice!(
209 format(),
210 // text doesn't parse $, if format fails we just accept the $ as text
211 map("$", |_| FormatItem::Text("$".into())),
212 map(text(&['\\', '/'], &['/', '$']), FormatItem::Text),
213 )),
214 "/",
215 // vscode really doesn't allow escaping } here
216 // so it's impossible to write a regex escape containing a }
217 // we can consider deviating here and allowing the escape
218 text(&[], &['}']),
219 ),
220 |(_, value, _, replacement, _, options)| Transform {
221 regex: value,
222 replacement,
223 options,
224 },
225 )
226 }
227
228 fn tabstop<'a>() -> impl Parser<'a, Output = SnippetElement> {
229 map(
230 or(
231 map(right("$", digit()), |i| (i, None)),
232 map(
233 seq!("${", digit(), optional(regex()), "}"),
234 |(_, i, transform, _)| (i, transform),
235 ),
236 ),
237 |(tabstop, transform)| SnippetElement::Tabstop { tabstop, transform },
238 )
239 }
240
241 fn placeholder<'a>() -> impl Parser<'a, Output = SnippetElement> {
242 map(
243 seq!(
244 "${",
245 digit(),
246 ":",
247 // according to the grammar there is just a single anything here.
248 // However in the prose it is explained that placeholders can be nested.
249 // The example there contains both a placeholder text and a nested placeholder
250 // which indicates a list. Looking at the VSCode sourcecode, the placeholder
251 // is indeed parsed as zero_or_more so the grammar is simply incorrect here
252 zero_or_more(anything(TEXT_ESCAPE_CHARS, true)),
253 "}"
254 ),
255 |seq| SnippetElement::Placeholder {
256 tabstop: seq.1,
257 value: seq.3,
258 },
259 )
260 }
261
262 fn choice<'a>() -> impl Parser<'a, Output = SnippetElement> {
263 map(
264 seq!(
265 "${",
266 digit(),
267 "|",
268 sep(text(CHOICE_TEXT_ESCAPE_CHARS, &['|', ',']), ","),
269 "|}",
270 ),
271 |seq| SnippetElement::Choice {
272 tabstop: seq.1,
273 choices: seq.3,
274 },
275 )
276 }
277
278 fn variable<'a>() -> impl Parser<'a, Output = SnippetElement> {
279 choice!(
280 // $var
281 map(right("$", var()), |name| SnippetElement::Variable {
282 name: name.into(),
283 default: None,
284 transform: None,
285 }),
286 // ${var}
287 map(seq!("${", var(), "}",), |values| SnippetElement::Variable {
288 name: values.1.into(),
289 default: None,
290 transform: None,
291 }),
292 // ${var:default}
293 map(
294 seq!(
295 "${",
296 var(),
297 ":",
298 zero_or_more(anything(TEXT_ESCAPE_CHARS, true)),
299 "}",
300 ),
301 |values| SnippetElement::Variable {
302 name: values.1.into(),
303 default: Some(values.3),
304 transform: None,
305 }
306 ),
307 // ${var/value/format/options}
308 map(seq!("${", var(), regex(), "}"), |values| {
309 SnippetElement::Variable {
310 name: values.1.into(),
311 default: None,
312 transform: Some(values.2),
313 }
314 }),
315 )
316 }
317
318 fn anything<'a>(
319 escape_chars: &'static [char],
320 end_at_brace: bool,
321 ) -> impl Parser<'a, Output = SnippetElement> {
322 let term_chars: &[_] = if end_at_brace { &['$', '}'] } else { &['$'] };
323 move |input: &'a str| {
324 let parser = choice!(
325 tabstop(),
326 placeholder(),
327 choice(),
328 variable(),
329 map("$", |_| SnippetElement::Text("$".into())),
330 map(text(escape_chars, term_chars), SnippetElement::Text),
331 );
332 parser.parse(input)
333 }
334 }
335
336 fn snippet<'a>() -> impl Parser<'a, Output = Vec<SnippetElement>> {
337 one_or_more(anything(TEXT_ESCAPE_CHARS, false))
338 }
339
340 #[cfg(test)]
341 mod test {
342 use crate::snippets::{Snippet, SnippetRenderCtx};
343
344 use super::SnippetElement::*;
345 use super::*;
346
347 #[test]
348 fn empty_string_is_error() {
349 assert_eq!(Err(""), parse(""));
350 }
351
352 #[test]
353 fn parse_placeholders_in_function_call() {
354 assert_eq!(
355 Ok(vec![
356 Text("match(".into()),
357 Placeholder {
358 tabstop: 1,
359 value: vec![Text("Arg1".into())],
360 },
361 Text(")".into()),
362 ]),
363 parse("match(${1:Arg1})")
364 );
365 // The `$0` tabstop should not have placeholder text. The parser should handle this case
366 // normally and then the placeholder text should be discarded during elaboration.
367 assert_eq!(
368 Ok(vec![
369 Text("sizeof(".into()),
370 Placeholder {
371 tabstop: 0,
372 value: vec![Text("expression-or-type".into())],
373 },
374 Text(")".into()),
375 ]),
376 parse("sizeof(${0:expression-or-type})")
377 );
378 }
379
380 #[test]
381 fn unterminated_placeholder() {
382 assert_eq!(
383 Ok(vec![
384 Text("match(".into()),
385 Text("$".into()),
386 Text("{1:)".into())
387 ]),
388 parse("match(${1:)")
389 )
390 }
391
392 #[test]
393 fn parse_empty_placeholder() {
394 assert_eq!(
395 Ok(vec![
396 Text("match(".into()),
397 Placeholder {
398 tabstop: 1,
399 value: vec![],
400 },
401 Text(")".into()),
402 ]),
403 parse("match(${1:})")
404 )
405 }
406
407 #[test]
408 fn parse_placeholders_in_statement() {
409 assert_eq!(
410 Ok(vec![
411 Text("local ".into()),
412 Placeholder {
413 tabstop: 1,
414 value: vec![Text("var".into())],
415 },
416 Text(" = ".into()),
417 Placeholder {
418 tabstop: 1,
419 value: vec![Text("value".into())],
420 },
421 ]),
422 parse("local ${1:var} = ${1:value}")
423 )
424 }
425
426 #[test]
427 fn parse_tabstop_nested_in_placeholder() {
428 assert_eq!(
429 Ok(vec![Placeholder {
430 tabstop: 1,
431 value: vec![
432 Text("var, ".into()),
433 Tabstop {
434 tabstop: 2,
435 transform: None
436 }
437 ],
438 }]),
439 parse("${1:var, $2}")
440 )
441 }
442
443 #[test]
444 fn parse_placeholder_nested_in_placeholder() {
445 assert_eq!(
446 Ok({
447 vec![Placeholder {
448 tabstop: 1,
449 value: vec![
450 Text("foo ".into()),
451 Placeholder {
452 tabstop: 2,
453 value: vec![Text("bar".into())],
454 },
455 ],
456 }]
457 }),
458 parse("${1:foo ${2:bar}}")
459 )
460 }
461
462 #[test]
463 fn parse_all() {
464 assert_eq!(
465 Ok(vec![
466 Text("hello ".into()),
467 Tabstop {
468 tabstop: 1,
469 transform: None
470 },
471 Tabstop {
472 tabstop: 2,
473 transform: None
474 },
475 Text(" ".into()),
476 Choice {
477 tabstop: 1,
478 choices: vec!["one".into(), "two".into(), "three".into()],
479 },
480 Text(" ".into()),
481 Variable {
482 name: "name".into(),
483 default: Some(vec![Text("foo".into())]),
484 transform: None,
485 },
486 Text(" ".into()),
487 Variable {
488 name: "var".into(),
489 default: None,
490 transform: None,
491 },
492 Text(" ".into()),
493 Variable {
494 name: "TM".into(),
495 default: None,
496 transform: None,
497 },
498 ]),
499 parse("hello $1${2} ${1|one,two,three|} ${name:foo} $var $TM")
500 );
501 }
502
503 #[test]
504 fn regex_capture_replace() {
505 assert_eq!(
506 Ok({
507 vec![Variable {
508 name: "TM_FILENAME".into(),
509 default: None,
510 transform: Some(Transform {
511 regex: "(.*).+$".into(),
512 replacement: vec![FormatItem::Capture(1), FormatItem::Text("$".into())],
513 options: Tendril::new(),
514 }),
515 }]
516 }),
517 parse("${TM_FILENAME/(.*).+$/$1$/}")
518 );
519 }
520
521 #[test]
522 fn rust_macro() {
523 assert_eq!(
524 Ok({
525 vec![
526 Text("macro_rules! ".into()),
527 Tabstop {
528 tabstop: 1,
529 transform: None,
530 },
531 Text(" {\n (".into()),
532 Tabstop {
533 tabstop: 2,
534 transform: None,
535 },
536 Text(") => {\n ".into()),
537 Tabstop {
538 tabstop: 0,
539 transform: None,
540 },
541 Text("\n };\n}".into()),
542 ]
543 }),
544 parse("macro_rules! $1 {\n ($2) => {\n $0\n };\n}")
545 );
546 }
547
548 fn assert_text(snippet: &str, parsed_text: &str) {
549 let snippet = Snippet::parse(snippet).unwrap();
550 let mut rendered_snippet = snippet.prepare_render();
551 let rendered_text = snippet
552 .render_at(
553 &mut rendered_snippet,
554 "".into(),
555 false,
556 &mut SnippetRenderCtx::test_ctx(),
557 0,
558 )
559 .0;
560 assert_eq!(rendered_text, parsed_text)
561 }
562
563 #[test]
564 fn robust_parsing() {
565 assert_text("$", "$");
566 assert_text("\\\\$", "\\$");
567 assert_text("{", "{");
568 assert_text("\\}", "}");
569 assert_text("\\abc", "\\abc");
570 assert_text("foo${f:\\}}bar", "foo}bar");
571 assert_text("\\{", "\\{");
572 assert_text("I need \\\\\\$", "I need \\$");
573 assert_text("\\", "\\");
574 assert_text("\\{{", "\\{{");
575 assert_text("{{", "{{");
576 assert_text("{{dd", "{{dd");
577 assert_text("}}", "}}");
578 assert_text("ff}}", "ff}}");
579 assert_text("farboo", "farboo");
580 assert_text("far{{}}boo", "far{{}}boo");
581 assert_text("far{{123}}boo", "far{{123}}boo");
582 assert_text("far\\{{123}}boo", "far\\{{123}}boo");
583 assert_text("far{{id:bern}}boo", "far{{id:bern}}boo");
584 assert_text("far{{id:bern {{basel}}}}boo", "far{{id:bern {{basel}}}}boo");
585 assert_text(
586 "far{{id:bern {{id:basel}}}}boo",
587 "far{{id:bern {{id:basel}}}}boo",
588 );
589 assert_text(
590 "far{{id:bern {{id2:basel}}}}boo",
591 "far{{id:bern {{id2:basel}}}}boo",
592 );
593 assert_text("${}$\\a\\$\\}\\\\", "${}$\\a$}\\");
594 assert_text("farboo", "farboo");
595 assert_text("far{{}}boo", "far{{}}boo");
596 assert_text("far{{123}}boo", "far{{123}}boo");
597 assert_text("far\\{{123}}boo", "far\\{{123}}boo");
598 assert_text("far`123`boo", "far`123`boo");
599 assert_text("far\\`123\\`boo", "far\\`123\\`boo");
600 assert_text("\\$far-boo", "$far-boo");
601 }
602
603 fn assert_snippet(snippet: &str, expect: &[SnippetElement]) {
604 let elements = parse(snippet).unwrap();
605 assert_eq!(elements, expect.to_owned())
606 }
607
608 #[test]
609 fn parse_variable() {
610 use SnippetElement::*;
611 assert_snippet(
612 "$far-boo",
613 &[
614 Variable {
615 name: "far".into(),
616 default: None,
617 transform: None,
618 },
619 Text("-boo".into()),
620 ],
621 );
622 assert_snippet(
623 "far$farboo",
624 &[
625 Text("far".into()),
626 Variable {
627 name: "farboo".into(),
628 transform: None,
629 default: None,
630 },
631 ],
632 );
633 assert_snippet(
634 "far${farboo}",
635 &[
636 Text("far".into()),
637 Variable {
638 name: "farboo".into(),
639 transform: None,
640 default: None,
641 },
642 ],
643 );
644 assert_snippet(
645 "$123",
646 &[Tabstop {
647 tabstop: 123,
648 transform: None,
649 }],
650 );
651 assert_snippet(
652 "$farboo",
653 &[Variable {
654 name: "farboo".into(),
655 transform: None,
656 default: None,
657 }],
658 );
659 assert_snippet(
660 "$far12boo",
661 &[Variable {
662 name: "far12boo".into(),
663 transform: None,
664 default: None,
665 }],
666 );
667 assert_snippet(
668 "000_${far}_000",
669 &[
670 Text("000_".into()),
671 Variable {
672 name: "far".into(),
673 transform: None,
674 default: None,
675 },
676 Text("_000".into()),
677 ],
678 );
679 }
680
681 #[test]
682 fn parse_variable_transform() {
683 assert_snippet(
684 "${foo///}",
685 &[Variable {
686 name: "foo".into(),
687 transform: Some(Transform {
688 regex: Tendril::new(),
689 replacement: Vec::new(),
690 options: Tendril::new(),
691 }),
692 default: None,
693 }],
694 );
695 assert_snippet(
696 "${foo/regex/format/gmi}",
697 &[Variable {
698 name: "foo".into(),
699 transform: Some(Transform {
700 regex: "regex".into(),
701 replacement: vec![FormatItem::Text("format".into())],
702 options: "gmi".into(),
703 }),
704 default: None,
705 }],
706 );
707 assert_snippet(
708 "${foo/([A-Z][a-z])/format/}",
709 &[Variable {
710 name: "foo".into(),
711 transform: Some(Transform {
712 regex: "([A-Z][a-z])".into(),
713 replacement: vec![FormatItem::Text("format".into())],
714 options: Tendril::new(),
715 }),
716 default: None,
717 }],
718 );
719
720 // invalid regex TODO: reneable tests once we actually parse this regex flavor
721 // assert_text(
722 // "${foo/([A-Z][a-z])/format/GMI}",
723 // "${foo/([A-Z][a-z])/format/GMI}",
724 // );
725 // assert_text(
726 // "${foo/([A-Z][a-z])/format/funky}",
727 // "${foo/([A-Z][a-z])/format/funky}",
728 // );
729 // assert_text("${foo/([A-Z][a-z]/format/}", "${foo/([A-Z][a-z]/format/}");
730 assert_text(
731 "${foo/regex\\/format/options}",
732 "${foo/regex\\/format/options}",
733 );
734
735 // tricky regex
736 assert_snippet(
737 "${foo/m\\/atch/$1/i}",
738 &[Variable {
739 name: "foo".into(),
740 transform: Some(Transform {
741 regex: "m/atch".into(),
742 replacement: vec![FormatItem::Capture(1)],
743 options: "i".into(),
744 }),
745 default: None,
746 }],
747 );
748
749 // incomplete
750 assert_text("${foo///", "${foo///");
751 assert_text("${foo/regex/format/options", "${foo/regex/format/options");
752
753 // format string
754 assert_snippet(
755 "${foo/.*/${0:fooo}/i}",
756 &[Variable {
757 name: "foo".into(),
758 transform: Some(Transform {
759 regex: ".*".into(),
760 replacement: vec![FormatItem::Conditional(0, Tendril::new(), "fooo".into())],
761 options: "i".into(),
762 }),
763 default: None,
764 }],
765 );
766 assert_snippet(
767 "${foo/.*/${1}/i}",
768 &[Variable {
769 name: "foo".into(),
770 transform: Some(Transform {
771 regex: ".*".into(),
772 replacement: vec![FormatItem::Capture(1)],
773 options: "i".into(),
774 }),
775 default: None,
776 }],
777 );
778 assert_snippet(
779 "${foo/.*/$1/i}",
780 &[Variable {
781 name: "foo".into(),
782 transform: Some(Transform {
783 regex: ".*".into(),
784 replacement: vec![FormatItem::Capture(1)],
785 options: "i".into(),
786 }),
787 default: None,
788 }],
789 );
790 assert_snippet(
791 "${foo/.*/This-$1-encloses/i}",
792 &[Variable {
793 name: "foo".into(),
794 transform: Some(Transform {
795 regex: ".*".into(),
796 replacement: vec![
797 FormatItem::Text("This-".into()),
798 FormatItem::Capture(1),
799 FormatItem::Text("-encloses".into()),
800 ],
801 options: "i".into(),
802 }),
803 default: None,
804 }],
805 );
806 assert_snippet(
807 "${foo/.*/complex${1:else}/i}",
808 &[Variable {
809 name: "foo".into(),
810 transform: Some(Transform {
811 regex: ".*".into(),
812 replacement: vec![
813 FormatItem::Text("complex".into()),
814 FormatItem::Conditional(1, Tendril::new(), "else".into()),
815 ],
816 options: "i".into(),
817 }),
818 default: None,
819 }],
820 );
821 assert_snippet(
822 "${foo/.*/complex${1:-else}/i}",
823 &[Variable {
824 name: "foo".into(),
825 transform: Some(Transform {
826 regex: ".*".into(),
827 replacement: vec![
828 FormatItem::Text("complex".into()),
829 FormatItem::Conditional(1, Tendril::new(), "else".into()),
830 ],
831 options: "i".into(),
832 }),
833 default: None,
834 }],
835 );
836 assert_snippet(
837 "${foo/.*/complex${1:+if}/i}",
838 &[Variable {
839 name: "foo".into(),
840 transform: Some(Transform {
841 regex: ".*".into(),
842 replacement: vec![
843 FormatItem::Text("complex".into()),
844 FormatItem::Conditional(1, "if".into(), Tendril::new()),
845 ],
846 options: "i".into(),
847 }),
848 default: None,
849 }],
850 );
851 assert_snippet(
852 "${foo/.*/complex${1:?if:else}/i}",
853 &[Variable {
854 name: "foo".into(),
855 transform: Some(Transform {
856 regex: ".*".into(),
857 replacement: vec![
858 FormatItem::Text("complex".into()),
859 FormatItem::Conditional(1, "if".into(), "else".into()),
860 ],
861 options: "i".into(),
862 }),
863 default: None,
864 }],
865 );
866 assert_snippet(
867 "${foo/.*/complex${1:/upcase}/i}",
868 &[Variable {
869 name: "foo".into(),
870 transform: Some(Transform {
871 regex: ".*".into(),
872 replacement: vec![
873 FormatItem::Text("complex".into()),
874 FormatItem::CaseChange(1, CaseChange::Upcase),
875 ],
876 options: "i".into(),
877 }),
878 default: None,
879 }],
880 );
881 assert_snippet(
882 "${TM_DIRECTORY/src\\//$1/}",
883 &[Variable {
884 name: "TM_DIRECTORY".into(),
885 transform: Some(Transform {
886 regex: "src/".into(),
887 replacement: vec![FormatItem::Capture(1)],
888 options: Tendril::new(),
889 }),
890 default: None,
891 }],
892 );
893 assert_snippet(
894 "${TM_SELECTED_TEXT/a/\\/$1/g}",
895 &[Variable {
896 name: "TM_SELECTED_TEXT".into(),
897 transform: Some(Transform {
898 regex: "a".into(),
899 replacement: vec![FormatItem::Text("/".into()), FormatItem::Capture(1)],
900 options: "g".into(),
901 }),
902 default: None,
903 }],
904 );
905 assert_snippet(
906 "${TM_SELECTED_TEXT/a/in\\/$1ner/g}",
907 &[Variable {
908 name: "TM_SELECTED_TEXT".into(),
909 transform: Some(Transform {
910 regex: "a".into(),
911 replacement: vec![
912 FormatItem::Text("in/".into()),
913 FormatItem::Capture(1),
914 FormatItem::Text("ner".into()),
915 ],
916 options: "g".into(),
917 }),
918 default: None,
919 }],
920 );
921 assert_snippet(
922 "${TM_SELECTED_TEXT/a/end\\//g}",
923 &[Variable {
924 name: "TM_SELECTED_TEXT".into(),
925 transform: Some(Transform {
926 regex: "a".into(),
927 replacement: vec![FormatItem::Text("end/".into())],
928 options: "g".into(),
929 }),
930 default: None,
931 }],
932 );
933 }
934 // TODO port more tests from https://github.com/microsoft/vscode/blob/dce493cb6e36346ef2714e82c42ce14fc461b15c/src/vs/editor/contrib/snippet/test/browser/snippetParser.test.ts
935 }