2

We have some custom snippets we provide as part of our VS Code extension via key bindings and a snippets json file:

{
  "key": "ctrl+shift+i",
  "mac": "cmd+shift+i",
  "command": "editor.action.insertSnippet"
},

...

"snippets": [
  {
    "language": "xml",
    "path": "./snippets/xml.json"
  }
]

We would like a button to add one particular snippet to the editor at the current cursor position.

How do I programmatically I invoke the part of "editor.action.insertSnippet" after the user has selected the snippet?

2 Answers 2

1

I posted this issue on the vscode repo.

jrieken responded with the following reply:

The insertSnippet-command accepts an argument which is either the name of a snippet or a snippet itself. So, either { snippet: "console.log($1)$0"} for an inline snippet or { langId: "csharp", name: "myFavSnippet" } referencing an existing snippet.

Sign up to request clarification or add additional context in comments.

4 Comments

So it's been over a year now, and the docs aren't updated with that information. I tried with the {langId: 'blah', name: 'mySnippet'} and either I'm doing something wrong (entirely possible), or it doesn't actually support that option. Also that conversation got locked so I couldn't comment there.
@joshea As I understand it, the language identifiers need to be from this list. Also, you might want to make sure mySnippet is already defined. If it is not, this might be helpful in understanding how to create it.
Yeah I have all that, and the actual langId I had was javascriptreact, which is on that list. I'll just triple check that the snippet is defined. Knowing me I probably have a typo in the name or something.
@joshea I also had no luck inserting an existing snippet programmatically using e.g. editor.insertSnippet({ langId: "javascript", name: "module_exports" } - though I might have the syntax wrong. It seems a string is required like the doco says. Sure, the "editor.action.insertSnippet" keybinding command takes those fancy "langId" and "name" args but not editor.insertSnippet. However, as @Mike-Lischke suggested, I managed to programmatically do it using e.g. vscode.commands.executeCommand("editor.action.insertSnippet", { langId: "javascript", name: "For Loop" }).
0

You can run any registered command via vscode.commands.executeCommand. See also the vscode namespace API.

1 Comment

Thank you, Mike. What is the command for inserting a selected snippet (that does not involve the user picking one)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.