将行内注释与VSCode中的特定列对齐

问题描述 投票:4回答:2

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

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

为此:

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

尝试使用Better Align Extension,但实际上并没有用,因为它只能正确格式化具有等号的行,例如something = something。还有其他方法吗?预先感谢。

visual-studio-code alignment comments margin
2个回答
0
投票

您可以使用multi-command之类的宏扩展名进行操作。您确实需要对要对齐的注释向右的位置进行粗略的猜测。您不能简单地测量最远距离并使用它-您需要更多参与才能做到这一点。但是,您将在最后使用多光标,并且如果您不喜欢最终注释的位置(如演示中的后退和制表键将所有注释对齐的演示),则可以轻松地一次调整所有注释。

演示:

align comments

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

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

我为.js文件创建了该文件,但您可以为其他扩展名进行修改,例如

[。C和.php文件的resourceExtname =~ /\\.(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
      ]
    }
]

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


0
投票

comment-aligner扩展名很好地做到了

要设置键盘快捷键,请将以下内容添加到

首选项:打开键盘快捷键(JSON)

{   "key": "ctrl+cmd+]",
    "command": "extension.commentaligner" }
© www.soinside.com 2019 - 2024. All rights reserved.