Search code examples
visual-studio-codecomments

Multiple line to single line comment find & replace


what's the quickest way for me, in VSCode, to find and replace a comment structured like this:

/**
 * Comment here
 */

With:

// Comment here

Bearing in mind here the actual comment itself should persist, so just the comment syntax being changed.

I'm hoping there is an easy find & replace operation I haven't come across before that I can perform in the editor.

Thanks!


Solution

  • Unless there is a vscode command to toggle a doc comment (which would make this much easier) you can do it with an extension that can run multiple finds and replaces and commands.

    Using Find and Transform, an extension I wrote, make this keybinding (in your keybindings.json):

    {
      "key": "alt+s",                   // whatever keybinding you want 
      "command": "findInCurrentFile",
      "args": {
        // 2 finds and 2 replaces
        "find": ["(^[ \t]*\\/\\*\\*\n)([\\s\n\\S]*?)(^\\s*\\*\\/\n)", "^([ \t]*) \\*\\s*(.*)"],
        "replace": ["$2", "$1$2"],
    
        "isRegex": true,
        "cursorMoveSelect": "$1$2",      // select the result for the postCommands to act on
        "postCommands": ["editor.action.commentLine", "cancelSelection"]
      },
    }
    

    The first find captures the entire jdoc-style comment and keeps only the interior lines. The second find and replace removes the leading * from those lines.

    The result is then selected so that the postCommands can be run adding line comments.

    [I didn't spend a lot of time on the regex's so double-check those.]

    swap comments from jdoc to line comments demo