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

2

9

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.

Dane answered 3/12, 2018 at 17:56 Comment(1)
somewhat close #44827123Greff
A
16

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"
        }
      }
    ]
  }
}
Aerobiology answered 4/12, 2018 at 6:22 Comment(2)
Works great, thanks! Too bad you seemingly can't do this with snippets. I had never heard of multiCommand. Thanks!Dane
"editor.action.jumpToBracket", *2 before "editor.action.insertLineAfter", it avoid print in objet,array :)Trimer
D
1

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:

  1. Select what you want to log and hit Copy
  2. Go to where you want the log it
  3. Type log-clipboard and hit enter

Pretty close.

Dane answered 3/12, 2018 at 21:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.