我该如何通过一个快捷键(如崇高的键盘快捷键)向选择内容或整个行添加注释?

时间:2020-10-10 11:11:36

标签: visual-studio-code

如果我注释选定的文本,则仅在Sublime Text中注释该文本,而在VSCode中,整行不只是注释选定的文本。

我该如何解决?

2 个答案:

答案 0 :(得分:1)

您可以通过选择文本并单击ALT+SHIFT+A-“切换阻止评论”选项来注释掉行的一部分。

https://i.imgur.com/q7K7udz.gif

答案 1 :(得分:0)

使用宏扩展名macro-commander,您可以执行我认为想要的操作-如果选择的内容少于整行,则切换块注释;否则,如果在行或整行中均未选择任何内容,则切换块注释

enter image description here

在您的settings.json中使用它:

"macros": {

  "commentSelection" : [
  
    { 
      "javascript": [

        "const editor = vscode.window.activeTextEditor;",
        "const document = editor.document;",
        "const selection = editor.selection;",

        // Get the trimmed "word(s)" of the selection
        "const word = document.getText(selection).trim();",

        // Get the full line of text on the line of the selection
        "let lineNumber = selection.start.line;",
        "const line = document.lineAt(lineNumber).text.trim();",

        // `!word` means the cursor is on the line but nothing selected
        "let selectionEqualsEntireLine = !word || (line === word);",

        "if (selectionEqualsEntireLine) vscode.commands.executeCommand('editor.action.commentLine');",
        "else vscode.commands.executeCommand('editor.action.blockComment');",
      ]
    }
  ]

以及触发它的键绑定:

{
  "key": "ctrl+;",                       // use whatever keybinding you wish
  "command": "macros.commentSelection"
}


或者,更简单些,尝试这些键绑定,根本不使用宏:

  {
    "key": "ctrl+;",
    "command": "editor.action.blockComment",
    "when": "editorTextFocus && editorHasSelection"
  },

  {
    "key": "ctrl+;",
    "command": "editor.action.commentLine",
    "when": "editorTextFocus && !editorHasSelection"
  },

与宏的唯一区别是,如果您选择了所有文本-使用宏将获得行注释,使用这些键绑定将获得块注释。我不确定您喜欢哪个版本。