Multiple times during the day, I comment a line and then duplicate it with some minor changes. This whole action does not take much time individually but over the course of days and years, I think I’ve wasted a lot of time on this!

This has been overdue for a long time, and I should have created a snippet for this earlier, but never got around to it.

So, I’ll create a snippet which does exactly that and map it to keyboard shortcuts so that the same shortcut works across multiple programming languages.

create a snippet file

Press Ctrl+Shift+P and select Snippets: Configure Snippets. This will open a prompt for the language. Scroll to the javascript and press Enter. This creates a javascript.json file in the snippets folder.

The file has some comments within braces. Add the following within the braces

"dupcom": {
  "prefix": "dupcom",
  "body": [
   "$LINE_COMMENT $TM_CURRENT_LINE\n"
  ],
  "description": "comment line and duplicate below"
}

The first line dupcom is the name of the snippet. We will need this later. The prefix allows us to type a snippet (which we’ll not be doing)

In the body, we’re doing three things –

– adding a line comment to the current line. This takes the cursor to the next line

– adding the current line again

– finally, adding a new line at the end of the current line added

Create keyboard shortcut

Open keybindings.json by pressing Ctrl+Shift+P and selecting Preferences: Open Keyboard Shortcuts (JSON)

In the keybindings.json file, add the following shortcut –

{
  "key": "ctrl+shift+/",
  "command": "editor.action.insertSnippet",
  "when": "editorTextFocus && editorLangId == javascript",
  "args": {
    "langId": "javascript",
    "name": "dupcom"
  }
},

Here, the shortcut is Ctrl+Shift+/, but anything can be chosen that doesn’t conflict.

Adding this snippet for multiple languages

To make this work across multiple languages, we need to create multiple language files as in the first step and the snippets in them accordingly.

The keyboard shortcut given above to be added in keybindings.json can be duplicated for each language this is to be done for.

Reference: Snippets in Visual Studio Code