Search code examples
visual-studio-codecode-snippets

How can I insert a snippet on a new line with vscode?


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.


Solution

  • Updating the answer because you no longer need an extension to do this. As of vscode v1.77 there is a new builtin command runCommands which acts like a macro and can run a series of commands.

    {
      "key": "ctrl+alt+d",
      "command": "runCommands",
      "args":{
        "commands": [
          "editor.action.clipboardCopyAction",
          "editor.action.insertLineAfter",
          {
            "command": "editor.action.insertSnippet",
            "args": {
              "snippet": "LOGGER.debug(\"$CLIPBOARD: %s\", $CLIPBOARD)\n$0"
            }
          }
        ]
      }
    }