visual-studio-codevscode-snippets

Create a snippet in VS code that expands BLOCK_COMMENT_START certain times


I was looking to create n times the BLOCK_COMMENT_START in a line in my code. The BLOCK_COMMENT_START for language perl is #.

I want to create a line such as this:

####################

which contains n BLOCK_COMMENT_START in a line (in this case 20).

It can be any n times though, for instance where "editor.wordWrapColumn": 80, I want 80 times.

How to create such snippet in vs code.

The thing that I did was:

"Commented line": {
        "scope": "perl",
        "prefix": "coml",
        "body": [
            "BLOCK_COMMENT_START" // repeat it 20 times
        ],
        "description": "Single line comment"
    }

How to modify this snippet so it does the job?


Solution

  • There is no way to do what you want by simply using the built-in snippets. I think an extension could do it - and still use a snippet.

    Here is a way to do it using keybindings and an extension I wrote, Repeat Commands. Try this keybinding (in your keybindings.json):

    {
      "key": "alt+r",                     // whatever keybinding you want
      "command": "repeat-commands.runSequence",
      "args": {
    
        "description": "repeat perl comment character",
        
        "preCommands": [
          "cursorHome",
          "editor.action.commentLine",          // add a comment
          "cursorLeft",                         // if you have a space after the '#'
          "cursorColumnSelectLeft"              // select the '#'
        ],
        
        "commands": [                          // these will be repeated
          "editor.action.duplicateSelection"
        ],
    
                                               // one comment character already added above
        // "repeat": 5,                        // you can hard-code a number
        "repeat": "${getRepeatInput}",         // or ask for a number input
      },
    
        "when": "editorLangId === perl"
    },
    

    repeat comment characters with extension demo