Align inline comments to a certain column in VSCode

Viewed 3054

I'd like to organize the inline comments in VSCode so that they are all positioned in the same column. From this:

int a = 0; //comment 1
int b = 0;       //comment 2
int c = a*b;                    //comment 3

To this:

int a = 0;                      //comment 1
int b = 0;                      //comment 2
int c = a*b;                    //comment 3

Tried using Better Align Extension but that didn't really work, as it only formats correctly lines that have an equal sign, like something = something. Is there any other way to do this? Thanks in advance.

2 Answers

You can do it with a macro extension like multi-command. You do have to hard-code a rough guess as to how far to the right you want to align the comments. You can't simply measure the furthest and use that - you would need a more involved extension to do that. However, you will have multi-cursors at the end and it is easy to adjust all the comments at once if you don't like where they ended up as in the demo where backspacing and tabbing moves all the comments in alignment.

Demo:

align comments

Use some keybinding to trigger the macro:

{
  "key": "alt+w",                // whatever keybinding you choose
  "command": "extension.multiCommand.execute",
  "args": { "command": "multiCommand.alignComments" },
  "when": "editorTextFocus && !editorReadonly && resourceExtname =~ /\\.js/"
},

I made that for .js files but you can modify that for other extensions, like

resourceExtname =~ /\\.(js$|php)/ for .js and .php files.

And in your settings.json the actual macro:

"multiCommand.commands": [

  {
      "command": "multiCommand.alignComments",
      // "interval": 3000,
      "sequence": [
        "editor.action.insertCursorAtEndOfEachLineSelected",
         "cursorHomeSelect",
        {
          "command": "editor.action.insertSnippet",  // pad with lots of spaces's'
          "args": {
            // so capture group 1 is before the comment, add spaces after it
            "snippet": "${TM_SELECTED_TEXT/^([^;]+;)(\\s*)(?=\\/\\/.*)/$1                      /g}",
          }
        },

        "cursorHomeSelect",
        {
          "command": "editor.action.insertSnippet",
          "args": {
                   // keep first 25 characters or wherever you want to align
                   //   and then add the comments
            "snippet": "${TM_SELECTED_TEXT/(.{25})(\\s*)(.*)/$1$3/g}",  
          }
        },
        // "removeSecondaryCursors"  // to exit multi-cursor mode
      ]
    }
]

Just hit Escape to exit multi-cursor mode (or add that command to the end of the macro).

comment-aligner extension does this nicely

to setup a keyboard shortcut add the following to

Preferences: Open Keyboard Shortcuts (JSON)

{   "key": "ctrl+cmd+]",
    "command": "extension.commentaligner" }
Related