VS Code:基于状态的块注释/取消注释

问题描述

我在 Geany 中经常使用的一个功能是“基于状态”的块注释/取消注释,其中选定块中的注释行切换为未注释行,未注释行切换为已注释行。 Geany 使用修改后的注释代码“#~”(在 Python 中),因此它可以跟踪编辑器注释掉的行,而不是代码中的真正注释。

x = 1
#~ x = 2
y = 3
#~ y = 4

在 geany 中,突出显示整个块并按 Ctrl-e 给出

#~ x = 1
x = 2
#~ y = 3
y = 4

有没有办法在 VS Code 中获得类似的行为?

解决方法

您可以使用扩展名 Replace Rules

将此添加到您的 settings.json

  "replacerules.rules": {
    "Toggle Comment #~": {
      "find": ["^([ \\t]*)#~ (.*)$","^([ \\t]*)(?=[^ \\t])(?!#@# )(.*)$","^([ \\t]*)#@# (.*)$"],"replace": ["$1#@# $2","$1#~ $2","$1$2"]
    }
  }

因为查找替换是按顺序完成的,所以您必须用状态注释 (#~ ) 标记行以删除步骤 3 中的注释。

第 2 步模拟空白的贪婪非回溯 *

对于其他评论样式,您必须复制此规则。

您可以将其添加到键绑定中:

{
    "key": "ctrl+e","command": "replacerules.runRule","when": "editorTextFocus && !editorReadonly","args": {
        "ruleName": "Toggle Comment #~"
    }
}
,

试试我做的一个扩展:Toggle Line Comments。不过,我无法在 Geany 上对其进行测试。

toggling on/off line comments