9

I wanted to know if it is possible to trigger a user defined custom snippet when I create a file in vscode.

I started learning Golang recently and noticed that there is some boilerplate code that goes into creating the main.go file.

So I created my custom snippet for it and now now I can trigger the snippet manually and save me some keystrokes of typing.

I wanted to go one step further, so that whenever I create a new file named main.go from within VsCode, it should automatically fire that snippet and insert the biolerplate code for me, without me having to manually trigger the snippet.

Is this even possible ?

4
  • How are you creating the new file? That would be helpful info as there is more than one way to do so. Commented Apr 10, 2019 at 14:08
  • I am creating the file from within the vscode using the menu options in explorer. Commented Apr 10, 2019 at 14:09
  • You could easily do this by writing a simple VSCode extension. Commented Apr 10, 2019 at 16:49
  • 4
    Only if I knew how to write a "simple" extension, I wouldn't have asked on SO.!! Commented Apr 10, 2019 at 16:59

1 Answer 1

9

Check out this extension: Auto Snippet:

With this in your settings.json:

"autoSnippet.snippets": [
  { "pattern": "**/main.go", "snippet": "main-go-template" },
],

[Note that the example settings in the extension docs has a few syntax errors - use my example above - I have filed an issue with the creator.]

And then your snippet

"main-go-template": {
  "prefix": "zz",
  "body": [
    ...  // you can use tabstops and transforms just like regular snippets
  ]
  "description": "javascript template"
}

Then creating a new main.go file or opening an empty one should trigger the snippet.

It is a good idea to reload vscode whenever you make a change to this extension's settings.

Here is a demo of a gulpfile with common boilerplate:

demo of auto snippet extension


Also see this extension https://marketplace.visualstudio.com/items?itemName=bam.vscode-file-templates

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

Comments

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.