Make comments of VSCode start at column position 0

Here is a later and better way to do it: https://stackoverflow.com/a/72311327/836330


It is a little tricky, but test this out. You need a macro extension like multi-command.

In your keybindings.json:

 {                   // disable ctrl+/ for js/php files only
   "key": "ctrl+/",
   "command": "-editor.action.commentLine",
   "when": "editorTextFocus && !editorReadonly && resourceExtname =~ /\\.(js$|php)/"
 },

{                   // call the macro multiCommand.insertCommentColumn0 when
                     // commenting a single line
  "key": "ctrl+/",
  "command": "extension.multiCommand.execute",
  "args": { "command": "multiCommand.insertCommentColumn0" },
  "when": "!editorHasSelection && editorTextFocus && !editorReadonly && resourceExtname =~ /\\.(js$|php)/" 
},      

{                    // call the macro multiCommand.AddCommentColumn0MultipleLines when
                     // commenting more than one line
  "key": "ctrl+/",
  "command": "extension.multiCommand.execute",
  "args": { "command": "multiCommand.AddCommentColumn0MultipleLines" },
  "when": "editorHasSelection && editorTextFocus && !editorReadonly && resourceExtname =~ /\\.(js$|php)/" 
},

 {                   // call the command editor.action.removeCommentLine when
                     // commenting a single or multiple line(s)
   "key": "ctrl+shift+/",
   "command": "editor.action.removeCommentLine",
   "when": "!editorHasSelection && editorTextFocus && !editorReadonly && resourceExtname =~ /\\.(js$|php)/"
 },

In your settings.json, the macros:

"multiCommand.commands": [

  {
    "command": "multiCommand.insertCommentColumn0",
    "sequence": [
      "cursorLineStart",
      {
        "command": "type",
        "args": {
          "text": "// "
        }
      },
    ]
  },
  {
    "command": "multiCommand.AddCommentColumn0MultipleLines",
    "sequence": [
      "editor.action.insertCursorAtEndOfEachLineSelected",        
      "cursorLineStart",
      {
        "command": "type",
        "args": {
          "text": "// "
        }
      },
      "removeSecondaryCursors"
    ]
  },

This resourceExtname =~ /\\.(js$|php)/ restricts the keybindings to .js and .php files (and not .json files). You can change that if you want the keybindings to apply to more file types.

Ctrl+/ to apply the comment characters at column position 0 and Ctrl+Shift+Ctrl to remove the comment characters.

You can change those keys to whatever you want. Note it isn’t (and currently cannot be) a simple toggle using Ctrl+/ – with a keybinding there is no way to detect whether a comment already exists. You would need an extension to get that kind of functionality.

demo of inserting comments at column zero


One downside of this method is that if you select multiple lines and comment them, you will lose that mult-line selection (as can be seen in the demo).

Leave a Comment