DEV Community

Attila Gonda
Attila Gonda

Posted on

IntelliJ style line duplication in Visual Studio Code

Whenever I can, I use VSCode in favour of IntelliJ. It's more lightweight for my needs and more pleasing UX-wise as well.

But until now I really missed one thing from IDEA: the line/highlight duplication mechanism.

In IDEA there are two ways to duplicate code:

  1. Put the cursor somewhere and hit Ctrl + D. This will duplicate to down the active line
  2. Select a text and hit Ctrl + D. This will duplicate to right the selection

VSCode didn't have the second method but just until now!

Now you can create keyboard binding with editor.action.duplicateSelection action, and after adjusting some conditions it acts like the IntelliJ.

See the following keybindings.json file snippet:

{
  // ...

  { "key": "ctrl+d", "command": "editor.action.copyLinesDownAction",
      "when": "editorTextFocus && !editorReadonly && !editorHasSelection" },
  { "key": "ctrl+d", "command": "editor.action.duplicateSelection",
      "when": "editorTextFocus && !editorReadonly && editorHasSelection" },

  // ... 
}

As you can see there only difference between the when properties is a negation before editorHasSelection - if there is no text selected, work as previously, but if there is one, just copy the selection.

Because I switch between IDEA and Code regularly I often hit the combination in the wrong editor, but from now on, this will work as intended everywhere!

🎉

Top comments (1)

Collapse
 
vetlehlu profile image
vetlehlu

I have been looking for something like this for a while. Thanks, Attila!