Context: The Golang VS Code extension has built-in snippets/macros for creating a fmt.PrintX statement from a given variable:
Note how the variable name is filled in for me.
I frequently write methods, and the Golang extension's meth snippet, in my opinion, is slow, since there are 5 (!) tab stops:
So far, I've written a snippet that mimics the meth snippet:
"Struct Method": {
 "prefix": ".meth",
 "body": [
 "func (1ドル 2ドル) 3ドル(4ドル) 5ドル {",
 "\t6ドル",
 "}"
 ],
 "description": "some description"
}
And I would like this snippet to mimic the print! macro/snippet, where it fills in the variable name; for the method snippet, instead of filling a variable, it would automatically fill in the method receiver (1ドル and 2ドル) with the first letter of the struct name, and the full struct name in the second.
So, if I have the following struct:
type SomeStruct struct {}
and type:
SomeStruct.meth
then activate the snippet, it should output:
func (s SomeStruct) .(.) . {
 .
}
where each . is a tab stop.
Is this sort of snippet possible? If so, how can I write it so it does this?
- 
 use the extension Hypersnips, with a regex prefix you can capture the struct namerioV8– rioV82022年07月24日 13:50:53 +00:00Commented Jul 24, 2022 at 13:50
1 Answer 1
One thing you can do is to make a snippet in a keybinding that can parse the current line. Put this into your keybindings.json:
{
 "key": "alt+w",
 "command": "editor.action.insertSnippet",
 "args": {
 "snippet": "\n\nfunc (${TM_CURRENT_LINE/\\s*type\\s*(.)(.*)\\s* struct\\s*{}/${1:/downcase} 1ドル2ドル)/} 1ドル(2ドル) 3ドル {\n\t4ドル\n}"
 },
 // "when": "langId == golang"
}
The workflow is different than what you mentioned but is also easier - you don't have to type SomeStruct.meth. Just trigger the keybinding at the end of the type SomeStruct struct {} line as in the demo.
If you want to be anywhere in the document and trigger a snippet completion, then the HyperSnips extension may be the way to go.