Line operations for everyday use
Code is often edited by manipulating whole lines of code. Therefore, it is very practical to learn the essential operations for line manipulations and how to perform them in VSCode.
Today, we will look at:
Selecting lines of code
Moving lines of code
Duplicating lines of code
Deleting lines of code
Cutting lines of code
Let’s get started.
Usually people are used to expanding selection down to select code on multiple lines (Shift + Down
), which creates a selection that doesn’t cover the start and end of the lines that we want:
This is actually fine because Visual Studio Code will try to do “the right thing” for certain operations:
The partially selected lines of code can still be moved up and down with the Move Line Down or Move Line Up command (
Alt + Down/Up
)The partially selected lines of code can still be deleted with the Delete Line command (
Ctrl + Shift + K
)The partially selected lines of code can still be indended (
Tab
,Shift + Tab
)
However, for other operations, we have to select lines properly first with the Expand Line Selection command (Ctrl + L
) which first selects the line of code where our cursor is placed and then selects the next lines when executed repeatedly. Therefore no matter where the cursor is positioned, we can select the whole lines of code:
The great thing is that if we started with an incomplete selection of lines from the first scenario, we can press Ctrl + L
and VSCode will “correct” the selection to cover whole lines!
Now the usual Copy, Cut, Delete and other operations will do what we expect. The Move Line and Delete Line commands explained above still work and can be used.
With whole lines selected, we can use the Duplicate Selection command (no default shortcut) to duplicate them below.
VSCode is also smart enough to perform some line operations without having to select anything before (placing the cursor at the desired line is enough):
Copy the whole line with
Ctrl + C
Paste the whole line with
Ctrl + P
(will place the line above the cursor)Cut the whole line with
Ctrl + X
Move the line up and down with the Move Line Down or Move Line Up commands (
Alt + Down/Up
)Delete the whole line with the Delete Line command (
Ctrl + Shift + K
)Duplicate the whole line with the Duplicate Selection command
And the last tip: we can duplicate a line at the cursor position simply by executing copy and paste (Ctrl + C, Ctrl + P
), no selection necessary. This will, of course, put the line in the clipboard, but it is a very quick operation that doesn’t require a new command or key binding.
I hope you learned a trick or two today,
Petr