@@ -0,0 +1,367 @@
1+use anyhow::{anyhow, Result};
3+use crate::{util::lsp_pos_to_pos, OffsetEncoding};
5+#[derive(Debug, PartialEq, Eq)]
12+#[derive(Debug, PartialEq, Eq)]
13+pub enum FormatItem<'a> {
16+ CaseChange(usize, CaseChange),
17+ Conditional(usize, Option<&'a str>, Option<&'a str>),
20+#[derive(Debug, PartialEq, Eq)]
21+pub struct Regex<'a> {
23+ replacement: Vec<FormatItem<'a>>,
24+ options: Option<&'a str>,
27+#[derive(Debug, PartialEq, Eq)]
28+pub enum SnippetElement<'a> {
34+ value: Box<SnippetElement<'a>>,
38+ choices: Vec<&'a str>,
42+ default: Option<&'a str>,
43+ regex: Option<Regex<'a>>,
48+#[derive(Debug, PartialEq, Eq)]
49+pub struct Snippet<'a> {
50+ elements: Vec<SnippetElement<'a>>,
53+pub fn parse<'a>(s: &'a str) -> Result<Snippet<'a>> {
54+ parser::parse(s).map_err(|rest| anyhow!("Failed to parse snippet. Remaining input: {}", rest))
58+ use helix_core::regex;
59+ use once_cell::sync::Lazy;
63+ use super::{CaseChange, FormatItem, Regex, Snippet, SnippetElement};
66+ https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#snippet_syntax
68+ any ::= tabstop | placeholder | choice | variable | text
69+ tabstop ::= '$' int | '${' int '}'
70+ placeholder ::= '${' int ':' any '}'
71+ choice ::= '${' int '|' text (',' text)* '|}'
72+ variable ::= '$' var | '${' var }'
73+ | '${' var ':' any '}'
74+ | '${' var '/' regex '/' (format | text)+ '/' options '}'
75+ format ::= '$' int | '${' int '}'
76+ | '${' int ':' '/upcase' | '/downcase' | '/capitalize' '}'
77+ | '${' int ':+' if '}'
78+ | '${' int ':?' if ':' else '}'
79+ | '${' int ':-' else '}' | '${' int ':' else '}'
80+ regex ::= Regular Expression value (ctor-string)
81+ options ::= Regular Expression option (ctor-options)
82+ var ::= [_a-zA-Z] [_a-zA-Z0-9]*
89+ static DIGIT: Lazy<regex::Regex> = Lazy::new(|| regex::Regex::new(r"^[0-9]+").unwrap());
90+ static VARIABLE: Lazy<regex::Regex> =
91+ Lazy::new(|| regex::Regex::new(r"^[_a-zA-Z][_a-zA-Z0-9]*").unwrap());
92+ static TEXT: Lazy<regex::Regex> = Lazy::new(|| regex::Regex::new(r"^[^\$]+").unwrap());
94+ fn var<'a>() -> impl Parser<'a, Output = &'a str> {
98+ fn digit<'a>() -> impl Parser<'a, Output = usize> {
99+ filter_map(pattern(&DIGIT), |s| s.parse().ok())
102+ fn case_change<'a>() -> impl Parser<'a, Output = CaseChange> {
106+ map("upcase", |_| Upcase),
107+ map("downcase", |_| Downcase),
108+ map("capitalize", |_| Capitalize),
112+ fn format<'a>() -> impl Parser<'a, Output = FormatItem<'a>> {
117+ map(right("$", digit()), Capture),
119+ map(seq!("${", digit(), "}"), |seq| Capture(seq.1)),
120+ // '${' int ':' '/upcase' | '/downcase' | '/capitalize' '}'
121+ map(seq!("${", digit(), ":/", case_change(), "}"), |seq| {
122+ CaseChange(seq.1, seq.3)
124+ // '${' int ':+' if '}'
126+ seq!("${", digit(), ":+", take_until(|c| c == '}'), "}"),
127+ |seq| { Conditional(seq.1, Some(seq.3), None) }
129+ // '${' int ':?' if ':' else '}'
135+ take_until(|c| c == ':'),
137+ take_until(|c| c == '}'),
140+ |seq| { Conditional(seq.1, Some(seq.3), Some(seq.5)) }
142+ // '${' int ':-' else '}' | '${' int ':' else '}'
149+ take_until(|c| c == '}'),
152+ |seq| { Conditional(seq.1, None, Some(seq.4)) }
155+ map(pattern(&TEXT), Text),
159+ fn regex<'a>() -> impl Parser<'a, Output = Regex<'a>> {
160+ let replacement = reparse_as(take_until(|c| c == '/'), one_or_more(format()));
165+ take_until(|c| c == '/'),
169+ optional(take_until(|c| c == '}')),
171+ |(_, value, _, replacement, _, options)| Regex {
179+ fn tabstop<'a>() -> impl Parser<'a, Output = SnippetElement<'a>> {
182+ right("$", digit()),
183+ map(seq!("${", digit(), "}"), |values| values.1),
185+ |digit| SnippetElement::Tabstop { tabstop: digit },
189+ fn placeholder<'a>() -> impl Parser<'a, Output = SnippetElement<'a>> {
190+ // TODO: why doesn't parse_as work?
191+ // let value = reparse_as(take_until(|c| c == '}'), anything());
192+ let value = filter_map(take_until(|c| c == '}'), |s| {
193+ anything().parse(s).map(|parse_result| parse_result.1).ok()
196+ map(seq!("${", digit(), ":", value, "}"), |seq| {
197+ SnippetElement::Placeholder {
199+ value: Box::new(seq.3),
204+ fn choice<'a>() -> impl Parser<'a, Output = SnippetElement<'a>> {
210+ sep(take_until(|c| c == ',' || c == '|'), ","),
213+ |seq| SnippetElement::Choice {
220+ fn variable<'a>() -> impl Parser<'a, Output = SnippetElement<'a>> {
223+ map(right("$", var()), |name| SnippetElement::Variable {
230+ seq!("${", var(), ":", take_until(|c| c == '}'), "}",),
231+ |values| SnippetElement::Variable {
233+ default: Some(values.3),
237+ // ${var/value/format/options}
238+ map(seq!("${", var(), regex(), "}"), |values| {
239+ SnippetElement::Variable {
242+ regex: Some(values.2),
248+ fn text<'a>() -> impl Parser<'a, Output = SnippetElement<'a>> {
249+ map(pattern(&TEXT), SnippetElement::Text)
252+ fn anything<'a>() -> impl Parser<'a, Output = SnippetElement<'a>> {
253+ choice!(tabstop(), placeholder(), choice(), variable(), text())
256+ fn snippet<'a>() -> impl Parser<'a, Output = Snippet<'a>> {
257+ map(one_or_more(anything()), |parts| Snippet { elements: parts })
260+ pub fn parse(s: &str) -> Result<Snippet, &str> {
261+ snippet().parse(s).map(|(_input, elements)| elements)
266+ use super::SnippetElement::*;
270+ fn empty_string_is_error() {
271+ assert_eq!(Err(""), parse(""));
275+ fn parse_placeholders_in_function_call() {
282+ value: Box::new(Text("Arg1")),
287+ parse("match(${1:Arg1})")
292+ fn parse_placeholders_in_statement() {
299+ value: Box::new(Text("var")),
304+ value: Box::new(Text("value")),
308+ parse("local ${1:var} = ${1:value}")
318+ Tabstop { tabstop: 1 },
319+ Tabstop { tabstop: 2 },
323+ choices: vec!["one", "two", "three"]
328+ default: Some("foo"),
345+ parse("hello $1${2} ${1|one,two,three|} ${name:foo} $var $TM")
350+ fn regex_capture_replace() {
353+ elements: vec![Variable {
354+ name: "TM_FILENAME",
358+ replacement: vec![FormatItem::Capture(1)],
363+ parse("${TM_FILENAME/(.*).+$/$1/}")