2

How can I create a custom shortcut for generating code that will print a selected variable in vscode?

[1] arr = [1,2,3,4]  # I press double left mouse button on 'arr'
[2] print(arr)       # Then I press <magic shortcut> (Ctrl+p for example)
                     # And vscode generate [2] row automatically

You can provide your method for fast debugging by print().

Mark
  • 143,421
  • 24
  • 428
  • 436

3 Answers3

7

If, instead of selecting the variable, you just put the cursor at the end of the line, you can do this with a simple keybinding that inserts a snippet and no need for a macro. Keybinding:

{
  "key": "alt+w",
  "command": "editor.action.insertSnippet",
  "args": {
              // works with cursor end of line, no selection
              // output: print(arr)
    "snippet": "\n${TM_CURRENT_LINE/(\\s*)(\\w*)\\b.*/print($2)/}"
  }
},

If you want this output print(“arr”: arr), use this keybinding:

{
  "key": "alt+w",
  "command": "editor.action.insertSnippet",
  "args": {
              // works with cursor end of line, no selection
              // output: print(“arr”: arr)
    "snippet": "\n${TM_CURRENT_LINE/(\\s*)(\\w*)\\b.*/print(\"$2\": $2)/}"
  }
},

For these simpler versions, the variable must be the first word in the line.


Older answer:

Unfortunately, this seems difficult to do with a simple snippet. A new snippet would be inserted where the cursor is - and under your scenario that would be on your chosen variable - and then the rest of that first line is still there after the snippet.

It is relatively easy to do with a macro extension which allows you to perform multiple commands, like multi-command or another.

After installing the extension, in your settings:

  "multiCommand.commands": [

   {
     "command": "multiCommand.printVariable",

     "sequence": [
       "editor.action.clipboardCopyAction",
       "editor.action.insertLineAfter",
       {
         "command": "type",
         "args": {
           "text": "print("
         }
       },
       "editor.action.clipboardPasteAction",
       {
         "command": "type",
         "args": {
           "text": ")"
         }
       },
     ]
   }
},

and then set up some keybinding in keybindings.json:

{
  "key": "alt+q",
  "command": "extension.multiCommand.execute",
  "args": { "command": "multiCommand.printVariable" },

  // use the following if you wish to limit the command to python files
  "when": "resourceExtname == .py"
},

demo of macro snippet

As the demo gif shows, the selected text can be anywhere on the line and if there is code on the line immediately below the print() statement will be inserted where you expect.

Caution: This will save your selected variable to the clipboard so that will be overwritten.


If your variable is always at the beginning of the line and selected, you can use the simpler macro:

"multiCommand.commands": [

 {
   "command": "multiCommand.printVariable",
   "sequence": [
     {
      "command": "editor.action.insertSnippet",
      "args": {
                 // selected variable is at beginning of line
          "snippet": "${TM_CURRENT_LINE}\nprint(${TM_SELECTED_TEXT})"
        }
      },
      "cursorEndSelect",    // select to end and delete
      "editor.action.clipboardCutAction"
    ]
  }
]
Mark
  • 143,421
  • 24
  • 428
  • 436
  • 1
  • What If I want to have variable name to be also there like → print(“arr”: arr)? – Jeena Apr 09 '20 at 23:07
  • @Jeena I edited the answer with a version to output `print(“arr”: arr)` with cursor at end of line. If that doesn't work for you, let me know. And an upvote would be appreciated if so. Thanks. – Mark Apr 10 '20 at 06:18
  • I am able to get the variable name in the front. But then if select the variable I want to add print, it gets deleted and then adds the print statement. Example: This is what I want → `self._import(file) print(“self._import(file):”, self._import(file))` This is what I get → `print(“self._import(file):”, self._import(file))` The argument that I had selected will be deleted. And if I go to the end of the line and click `alt+w` I get the print message as `print(“self:”, self)` instead of `print(“self._import(file):”, self._import(file))` – Jeena Apr 13 '20 at 17:36
  • If I could give a bounty to only one stack overflow that has helped my every day this would be the one. Bless you @Mark for this – Timothee W Mar 01 '23 at 10:33
0

It might be not the solution you're looking for, but using Windows and working with Mouse and Keyboard shortcuts of all kinds, i payed for a license of the commercial software "ATNSOFT Key Manager" (their Website).

There is also a demo-version, but with limited functions.

Using this, you could specify in what programs or windows your function will work, so it's independent from the software you want to work with.

You could, for example, copy that var name in your editor and specify the key-combo [CTRL]+[P] to paste a newline character, the print command and your copied var name to your editor. No programming needed, you just define a "rule" what to do, where to do it and when it should be done.

I'm not affiliated with ANTSOFT in any ways and i like free and open software, but that's one of the commercial windows-tools i'm glad to have.

But of course you can give Autohotkey a try, seems like it should be able to do this, too.

xph
  • 937
  • 3
  • 8
  • 16
0

Some additional information and a little tweak to the answer of Mark:

The custom shortcut JSON of VS Code can be opened with F1 or Ctrl+Shift+P -> Preferences: Open Keyboard Shortcuts (JSON) and with the code below you can type the variable name on a new line then press Ctrl+D to select the variable then press Ctrl+; (next to L on US keyboard layout) to replace it with the print("var:", var):

// Place your key bindings in this file to override the defaults
[
    {
        "key": "ctrl+;",
        "command": "editor.action.insertSnippet",
        "args": {
            // works together with Ctrl+L or Ctrl+D to select the line first
            // output: print(“arr”: arr)
            "snippet": "${TM_SELECTED_TEXT/(\\s*)(\\w*)\\b.*/print(\"$2:\", $2)/}"
        }
    },
]
user299831
  • 437
  • 1
  • 5
  • 15