Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 412
Philip Avatar asked Dec 03 '18 17:12

Philip


People also ask

How do you add a snippet in VS code?

Create your own snippets# To create or edit your own snippets, select User Snippets under File > Preferences (Code > Preferences on macOS), and then select the language (by language identifier) for which the snippets should appear, or the New Global Snippets file option if they should appear for all languages.

How do you add a screenshot to a VS code?

open the VSCode command palette by pressing Ctrl+Shift+P at the position where you want to paste the image on the markdown. select Paste Image or press Ctrl+Shift+V to paste the image. The image will be saved in the same folder as the pasted md file, and a reference code to the image will be generated in md.


1 Answers

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": "extension.multiCommand.execute",
  "args": { "command": "multiCommand.debug" }
},

It works for both your examples.

like image 124
Mark Avatar answered Sep 21 '22 17:09

Mark