首页 > 解决方案 > VSCode 可以逐行进行块注释吗?

问题描述

ctrl + /这是我在 VS Code 中使用注释 HTML 代码的示例:


    <!-- </label>
    <label>Confirm Your Email:
        <!-- <input type="email" name="emailConfirm" required>
    <!-- </label>
    <label> -->
        <input type="checkbox" name="termsAgree" required/>
            I agree to the <a href="/legal/terms/">Terms & Conditions</a>. -->
    </label> -->

  1. 选择整个代码块ctrl+/并评论整个事情
  2. 选择了一段代码并ctrl+/取消注释一行,但它只是添加了一个新注释,从而破坏了较大的注释
  3. 再次做#2,现在这是一场噩梦

当我使用ctrl + /CSS 代码块时,我遇到了同样的问题。在 PHP 代码中没有问题,因为它用于//逐行注释

我怎样才能改变这种行为?

我也在想:

<!-- </label> -->
<!-- <label>Confirm Your Email: -->
    <!-- <input type="email" name="emailConfirm" required> -->
</label>
<label>
    <!-- <input type="checkbox" name="termsAgree" required/> -->
        <!-- I agree to the <a href="/legal/terms/">Terms & Conditions</a>. -->
<!-- </label> -->

请忽略 html 无效的事实。这只是我在这个例子中使用的一个随机块。

标签: visual-studio-codecommentskeyboard-shortcuts

解决方案


我刚刚做了一个扩展,Toggle Line Comments,它使用你的“愚蠢的方法”来单独切换每一行。

这是一个运行良好的代码演示:

逐行切换评论



原答案:

是的,vscode 可以逐行阻止注释,但该功能不是内置的。您将不得不使用宏命令,在这里我使用了multi-command,将行分开并对每个行应用块注释。

把它放进你的settings.json

"multiCommand.commands": [

  {
    "command": "multiCommand.blockHTMLCommentByLine",
    "sequence": [
      "editor.action.insertCursorAtEndOfEachLineSelected",
      "cursorHomeSelect",
      "editor.action.blockComment",
      "cancelSelection",
    ]
  }
]

它将您的选择分成单独的行,然后在每行上切换块注释。

添加键绑定以触发该宏 -重载ctrl+/键绑定(将其放入您的keybindings.json):

{
  "key": "ctrl+/",
  "command": "extension.multiCommand.execute",
  "args": { "command": "multiCommand.blockHTMLCommentByLine" },
  // "when": "editorTextFocus && editorHasSelection && resourceExtname =~ /\\.(html|css|scss)/"
  "when": "editorTextFocus && editorHasSelection && resourceExtname =~ /\\.html/"
},

我将它限制在.html文件中,但您可以看到如何在 otherwhen子句中包含其他扩展名。

演示:

每行切换块注释


如果要评论整行,则必须选择整行。


推荐阅读