Skip to content

Latest commit

 

History

History
276 lines (253 loc) · 10 KB

docs.org

File metadata and controls

276 lines (253 loc) · 10 KB

Development Docs

Table of Contents

Links

Specification

TJ

Vscode

Code

https://github.com/microsoft/vscode/tree/6b921dda5c679c6ca1928a4505567c533ede72f9/src/vs/editor/contrib/snippet/browser

Docs

Program Structure

Loading

  • Install or update the snippet repo with git
    • Clone is synchronous; pull runs asynchronously (start-process).
    • When git finishes (success or failure) all caches are cleared.
  • Read from package.json location
  • Get version and check it
"engines": {
    "vscode": "^1.11.0"
},
  • Read in language locations
"contributes": {
    "snippets": [
        {
            "language": [
                "plaintext",
                "markdown",
                "tex",
                "html",
                "global",
                "all"
            ],
            "path": "./snippets/global.json"
        },
        {
            "language": ["license"],
            "path": "./snippets/license.json"
        },
  • Convert Emacs major mode to VSCode language identifiers (snippy-emacs-to-vscode-lang-alist, exact major-mode match, so derived modes need their own entry) and append snippy-global-languages.
  • Search by languages. Get all paths for languages (deduplicated, a file listed under several languages is read once).
  • Read all language snippet files. Broken or missing files are skipped with a message instead of an error.
  • Merge them together for search.
  • Precompute propertized completion candidates (one per prefix; different snippets may share a prefix, duplicates inside one snippet are dropped).
  • When prefix given search for snippet.
  • If found expand it.

Caching

Two global caches, both cleared by snippy--clear-caches:

  • snippy--file-cache: file path -> parsed JSON alist.
  • snippy--language-cache: buffer language list -> (MERGED . CANDIDATES). Buffers with the same languages share the same lists (eq).

snippy--clear-caches also forgets snippy--package-json-content. It runs after install/update and when snippy-refresh-snippets is called interactively.

Expansion

snippy-transform-snippet-body converts the body in this order (the order matters, each step relies on the previous one):

  1. Join an array body into one string divided with \n (snippy-expand-snippet).
  2. Escape backticks: literal in VSCode, Elisp evaluation in Yasnippet. Double a backslash before { ( ) " ': literal in VSCode, but an escape that Yasnippet drops (LaTeX \left\{, Swift "\(x)"). Escape pairs like \\ and \$ are kept as they are.
  3. Drop transforms: ${1/re/fmt/flags} -> ${1}, ${VAR/re/fmt/} -> ${VAR}.
  4. Variables: $VAR, ${VAR}, ${VAR:default}.
    • Known, non-empty value: inserted with \ $ ` } escaped (plain text).
    • Empty or unknown: the default is used (defaults are snippet syntax and may contain fields, e.g. ${TM_SELECTED_TEXT:${1:text}}).
    • Unknown without default: left as-is.
    • Escape pairs (\\, \$) are skipped: \$VAR is left as-is, but \\$VAR is a backslash followed by the value.
  5. Escape every unescaped $(, also with whitespace before the paren ($ (, $$ (): literal text in VSCode, Elisp code in Yasnippet. This runs before the choices step, so it only sees the snippet’s own text and a snippet can’t fake a generated choice field. Escape pairs and VSCode choices ${N|...|} are skipped (step 6 escapes their text).
  6. Choices: ${1|a,b|} -> ${1:$$(yas-choose-value '("a" "b"))}.
    • \, is hidden as NUL before splitting so it stays in the choice.
    • Whitespace around each choice is trimmed, unless the choice is only whitespace (the markdown task list ${1| ,x|} needs a single space). Empty choices are dropped.
    • Each choice is printed as an Elisp string, then \ { } $ ` are escaped (octal escapes) so Yasnippet doesn’t parse them.
  7. Placeholders: keep the first ${N:default}, turn ${N} and repeated ${N:...} into the mirror $N (Yasnippet doesn’t like duplicates).
  8. Give it to yas-expand-snippet.

Completion

  • snippy-capf returns the precomputed candidates when snippy-minor-mode is on.
  • The prefix boundary includes special characters (!@#$%_&*^-), so snippy should be the first capf when merging backends.
  • The candidate carries its snippet as a text property, so the exit function expands the chosen snippet even if several share a prefix. Without properties it falls back to a prefix lookup.
  • Every exit status expands, including exact: with the default UI, completing for when fori also exists still expands for.
  • Called interactively, it completes with snippy’s candidates only.

LSP snippet fix

snippy-fix-lsp-snippet-mode adds :filter-return advice to eglot--snippet-expansion-fn. The returned function is wrapped so string snippets go through snippy-transform-snippet-body first. Only Eglot’s expansions are touched: snippy’s own and plain Yasnippet expansions are not transformed twice.

Favorite snippets

Most generic: c (for argv[] (prefix . fora) (body . [for (int ${1:i} = ${2:1}; $1 < argc; $1++) {$0 }]) (description . ‘for’ loop for cmdline arguments)) JSON:

"for argv[]": {
    "prefix": "fora",
    "body": ["for (int ${1:i} = ${2:1}; $1 < argc; $1++) {$0", "}"],
    "description": "'for' loop for cmdline arguments"
},

Choices: css (align-items (prefix . ai) (body . align-items: ${1|flex-start,flex-end,center,baseline,stretch,start,end,self-start,self-end|};) (description . initial value: stretch)) JSON:

"align-items": {
    "prefix": "ai",
    "body": "align-items: ${1|flex-start,flex-end,center,baseline,stretch,start,end,self-start,self-end|};",
    "description": "initial value: stretch"
},

Hacks

Example multiple choices in yasnippet: $$ Needed for elisp evalution https://pragmaticemacs.wordpress.com/2017/06/25/multiple-choices-in-yasnippets/

# -*- mode: snippet -*-
# name: align-items
# key: ai
# --
Importance: ${1:$$(yas-choose-value '("high" "average" "below average"))}
Difficulty: ${2:$$(yas-choose-value '("easy" "hard"))}
$0

Yasnippet don’t like this: It goes to the last one: So we replace all duplicates and leave only one.

# -*- mode: snippet -*-
# name: For Loop
# key: for
# --
for (let ${1:index} = 0; ${1:index} < ${2:array}.length; ${1:index}++) {
    const ${3:element} = ${2:array}[${1:index}];
    $0
}

Choices with special characters: VSCode choices are plain text, but inside $$(...) Yasnippet still parses $, {, } and backticks, and the Elisp reader handles \. So after prin1-to-string these are replaced with octal escapes (e.g. $ -> \\044), which the Elisp reader turns back into the original character.

Known limitations

Deliberate differences from VSCode that won’t be fixed (pinned by tests: the “Limitations” section, and snippy-tests-transform-drops-transforms for transforms):

  • Transforms (${1/re/fmt/flags}) are dropped, not applied.
  • An unknown variable without a default stays as $VAR; VSCode turns it into a placeholder holding its name.
  • A choice field stays empty until it is visited: yas-choose-value only runs when the field is entered. VSCode shows the first option.
  • A variable inside a variable’s default is not resolved: ${TM_SELECTED_TEXT:$TM_LINE_NUMBER} inserts the text $TM_LINE_NUMBER. VSCode inserts the line number.

Testing

Tests are in snippy-tests.el (ERT). They use temporary snippet directories and let-bound caches, so they never touch the real install.

emacs -batch -L /path/to/yasnippet -L . -l test/snippy-tests.el -f ert-run-tests-batch-and-exit
  • The install/update tests need git (skipped otherwise).
  • The LSP fix tests load the built-in Eglot (skipped otherwise).
  • Known limitations are tested as they currently behave, so changing one means updating its test.

Variables & Functions

User Variables:

  • snippy-install-dir
  • snippy-source
  • snippy-global-languages
  • snippy-emacs-to-vscode-lang-alist

Internal Variables:

  • snippy–min-vscode-version
  • snippy–package-json-content
  • snippy–file-cache
  • snippy–language-cache
  • snippy–buffer-language
  • snippy–merged-snippets
  • snippy–computed-candidates
  • snippy–capf-properties

User Functions:

  • snippy-install-or-update-snippets
  • snippy-refresh-snippets
  • snippy-expand
  • snippy-fix-lsp-snippet-mode
  • snippy-capf
  • snippy-minor-mode
  • global-snippy-minor-mode

Public functions:

  • snippy-transform-snippet-body
  • snippy-expand-snippet

Internal functions:

  • snippy–get-snippet-dir
  • snippy–clear-caches
  • snippy–get-package-data
  • snippy–clean-version
  • snippy–check-engine-version
  • snippy–get-vscode-language-name
  • snippy–update-buffer-language
  • snippy–get-all-paths-for-language
  • snippy–get-all-snippets-paths
  • snippy–get-current-language-path
  • snippy–compute-candidates
  • snippy–find-snippet-by-prefix
  • snippy–comment-syntax-p
  • snippy–get-variable-value
  • snippy–replace-matches
  • snippy–choice-to-elisp
  • snippy–wrap-eglot-expansion-fn
  • snippy–doc-buffer
  • snippy–turn-on