问题
I'm trying to make a vscode snippet for python. Suppose I have a line of code like this:
my_var = call_some_function()
I'd like to double click on my_var to select it, hit a key, and it produces the following result:
my_var = call_some_function()
LOGGER.debug("my_var: %s", my_var)
<cursor is here>
Also it should work for an expression too, like if I select "x + y + z" in this line and hit the key:
call_function(x + y + z)
It should produce:
call_function(x + y + z)
LOGGER.debug("x + y + z: %s", x + y + z)
<cursor is here>
Obviously using a debugger is better. But sometimes you cannot use a debugger.
回答1:
As @Alex's link suggests, I think you will need to use a macro extension to get this to work. I prefer multi-command because it has an interval delay available (which is absolutely necessary for some macros but not yours).
In your settings:
"multiCommand.commands": [
{
"command": "multiCommand.debug",
"sequence": [
"editor.action.clipboardCopyAction",
"editor.action.insertLineAfter",
{
"command": "editor.action.insertSnippet",
"args": {
"snippet": "LOGGER.debug(\"$CLIPBOARD: %s\", $CLIPBOARD)\n$0"
}
},
]
}
]
This will copy your selection first to the clipboard so it can be used later by the snippet. Then insert an empty line below and insert the snippet there (in case the line below already has some code on it).
Trigger this with a keybinding:
{
"key": "ctrl+alt+d",
"command": "multiCommand.debug",
}
It works for both your examples.
回答2:
This isn't exactly what was asked for, but is close, using the $CLIPBOARD variable:
"log-clipboard": {
"prefix": "log-clipboard",
"body": [
"LOGGER.debug('$CLIPBOARD: %s', $CLIPBOARD)",
"$0"
],
"description": "Log an expression from the clipboard"
}
To use:
- Select what you want to log and hit Copy
- Go to where you want the log it
- Type log-clipboard and hit enter
Pretty close.
来源:https://stackoverflow.com/questions/53599250/how-can-i-insert-a-snippet-on-a-new-line-with-vscode