【问题标题】:Align inline comments to a certain column in VSCode将内联注释与 VSCode 中的某一列对齐
【发布时间】:2020-01-30 19:59:14
【问题描述】:

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

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


    【解决方案1】:

    comment-aligner 扩展很好地做到了这一点

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

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

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

    【讨论】:

      【解决方案2】:

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

      演示:

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

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

      我为.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
            ]
          }
      ]
      

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

      【讨论】:

      • 漂亮的 gif 演示和来源。
      猜你喜欢
      • 2022-10-18
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      相关资源
      最近更新 更多