1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package snippet implements the specification for the LSP snippet format.
7 // Snippets are "tab stop" templates returned as an optional attribute of LSP
8 // completion candidates. As the user presses tab, they cycle through a series of
9 // tab stops defined in the snippet. Each tab stop can optionally have placeholder
10 // text, which can be pre-selected by editors. For a full description of syntax
11 // and features, see "Snippet Syntax" at
12 // https://microsoft.github.io/language-server-protocol/specifications/specification-3-14/#textDocument_completion.
14 // A typical snippet looks like "foo(${1:i int}, ${2:s string})".
22 // A Builder is used to build an LSP snippet piecemeal.
23 // The zero value is ready to use. Do not copy a non-zero Builder.
25 // currentTabStop is the index of the previous tab stop. The
26 // next tab stop will be currentTabStop+1.
31 // Escape characters defined in https://microsoft.github.io/language-server-protocol/specifications/specification-3-14/#textDocument_completion under "Grammar".
32 var replacer = strings.NewReplacer(
38 func (b *Builder) WriteText(s string) {
39 replacer.WriteString(&b.sb, s)
42 func (b *Builder) PrependText(s string) {
46 b.sb.WriteString(rawSnip)
49 // WritePlaceholder writes a tab stop and placeholder value to the Builder.
50 // The callback style allows for creating nested placeholders. To write an
51 // empty tab stop, provide a nil callback.
52 func (b *Builder) WritePlaceholder(fn func(*Builder)) {
53 fmt.Fprintf(&b.sb, "${%d:", b.nextTabStop())
60 // WriteFinalTabstop marks where cursor ends up after the user has
61 // cycled through all the normal tab stops. It defaults to the
62 // character after the snippet.
63 func (b *Builder) WriteFinalTabstop() {
64 fmt.Fprint(&b.sb, "$0")
67 // In addition to '\', '}', and '$', snippet choices also use '|' and ',' as
68 // meta characters, so they must be escaped within the choices.
69 var choiceReplacer = strings.NewReplacer(
77 // WriteChoice writes a tab stop and list of text choices to the Builder.
78 // The user's editor will prompt the user to choose one of the choices.
79 func (b *Builder) WriteChoice(choices []string) {
80 fmt.Fprintf(&b.sb, "${%d|", b.nextTabStop())
81 for i, c := range choices {
85 choiceReplacer.WriteString(&b.sb, c)
87 b.sb.WriteString("|}")
90 // String returns the built snippet string.
91 func (b *Builder) String() string {
95 // nextTabStop returns the next tab stop index for a new placeholder.
96 func (b *Builder) nextTabStop() int {
97 // Tab stops start from 1, so increment before returning.
99 return b.currentTabStop