Change comment symbol location when using VSCode "Toggle Line Comment" command

Viewed 61

Is it possible to customize the location of the comment symbol ('#' when using Python) in VSCode?

For example, if my code is:

def my_func():
    value = 1

and I press CMD-/ on line 2, I get:

def my_func():
   # value = 1

I would prefer to get:

def my_func():
#    value = 1

Is there a way to modify the default behavior?

VSCode: 1.67.1
MacOS: 12.3.1

1 Answers

There is no built-in way to do that. You will need an extension. See https://stackoverflow.com/a/59448448/836330 for a previous answer using a different extension. Here is a better answer using an extension I made in the meantime, Find and Transform. But there are restrictions as noted below.

Make this keybinding (in your keybindings.json):

{
  "key": "alt+/",                    // unfortunately, this cannot be ctrl+/
  "command": "findInCurrentFile",
  "args": {

  {
    "key": "alt+r",
    "command": "findInCurrentFile",
    "args": {
      "preCommands": [
        "cursorEnd",
        "cursorHomeSelect",
        "cursorHomeSelect"
      ],

      "replace": "${LINE_COMMENT}${TM_CURRENT_LINE}",

      "restrictFind": "line"   // works on multiple lines, see the demo
    },
    "when": "editorLangId == python"   // if you want to limit it to a language
  },
}

You can use whatever keybinding you want, but not Ctrl+/ because then toggle off will not work.

Ctrl+/ will work to toggle off comments if you do not use it in the keybinding above to add comments.

Note: For this to work well you need to disable the following setting (which I have shown disabled for a particular language, python):

"[python]": {
  "editor.comments.insertSpace": false
}

That goes into your settings.json.

add comments at column 0

Related