将内联注释与 VSCode 中的某个列对齐

Dan*_*iel 7 comments margin alignment visual-studio-code

我想在 VSCode 中组织内联注释,以便它们都位于同一列中。由此:

int a = 0; //comment 1
int b = 0;       //comment 2
int c = a*b;                    //comment 3
Run Code Online (Sandbox Code Playgroud)

对此:

int a = 0;                      //comment 1
int b = 0;                      //comment 2
int c = a*b;                    //comment 3
Run Code Online (Sandbox Code Playgroud)

尝试使用 Better Align Extension 但这并没有真正起作用,因为它只能正确格式化具有等号的行,例如 something = something。有没有其他方法可以做到这一点?提前致谢。

Mar*_*ark 2

您可以使用诸如multi-command之类的宏扩展来完成此操作。您必须对要将注释向右对齐多远的粗略猜测进行硬编码。你不能简单地测量最远的距离并使用它 - 你需要一个更复杂的扩展来做到这一点。但是,最后您将有多个光标,如果您不喜欢它们最终的位置,那么可以很容易地立即调整所有注释,如演示中的退格和制表符移动所有注释对齐。

演示:

对齐评论

使用一些键绑定来触发宏:

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

我为.js文件做了这个,但你可以修改其他扩展名,例如

resourceExtname =~ /\\.(js$|php)/ 对于 .js 和 .php 文件。

在你的settings.json中实际的宏:

"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
      ]
    }
]
Run Code Online (Sandbox Code Playgroud)

只需点击Escape即可退出多光标模式(或将该命令添加到宏的末尾)。