0

Context: The Golang VS Code extension has built-in snippets/macros for creating a fmt.PrintX statement from a given variable:

.print! before .print! after

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:

meth tabstops

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?

rioV8
29.7k4 gold badges48 silver badges68 bronze badges
asked Jul 24, 2022 at 13:35
1
  • use the extension Hypersnips, with a regex prefix you can capture the struct name Commented Jul 24, 2022 at 13:50

1 Answer 1

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.

golang struct snippet

answered Jul 24, 2022 at 18:24
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.