Skip to content

Instantly share code, notes, and snippets.

@ultim8k
Last active June 19, 2024 21:53
Show Gist options
  • Save ultim8k/d8326a0cd7646356acf0dc3baf8e78ff to your computer and use it in GitHub Desktop.
Save ultim8k/d8326a0cd7646356acf0dc3baf8e78ff to your computer and use it in GitHub Desktop.
(un) comment multiple lines vim

From: http://stackoverflow.com/questions/1676632/whats-a-quick-way-to-comment-uncomment-lines-in-vim

For those tasks I use most of the time block selection.

Put your cursor on the first # character, press Ctrl``V (or Ctrl``Q for gVim), and go down until the last commented line and press x, that will delete all the # characters vertically.

For commenting a block of text is almost the same: First, go to the first line you want to comment, press Ctrl``V, and select until the last line. Second, press Shift``I``#``Esc (then give it a second), and it will insert a # character on all selected lines. For the stripped-down version of vim shipped with debian/ubuntu by default, type : s/^/# in the second step instead.

@jahooker
Copy link

@jahooker why do you need capital I? lower case i does not seem to work?

Not sure, @sureshvv.
That's just how Vim works.
See https://stackoverflow.com/questions/12399572/vim-how-to-insert-in-visual-block-mode and https://vim.fandom.com/wiki/Inserting_text_in_multiple_lines.

@Tweekism
Copy link

Tweekism commented Jan 5, 2024

@jahooker why do you need capital I? lower case i does not seem to work?

Its because in block selection mode, your selection might be, for example: 7 lines long by 3 columns wide. That makes it ambiguous where vi should place the cursor for inserting.

Shift-I means place the cursor on the left hand side of the block selection
Shift-A means place the cursor on the right hand side of the block selection

These commands of course come from Normal mode, where they mean:-
Shift-I Move to the start of the line and enter insert mode
Shift-A Move to the end of the line and enter insert mode

@BautistaJorge616
Copy link

BautistaJorge616 commented Feb 21, 2024

If you hit : vim and shows something like :'<,'> you need to do something like this:

SHIFT + v and select the code block
: you are gonna see something like this :'<,'> add to see :'<,'>s/^/#/ and hit enter

@Hemrajbhattarai
Copy link

This worked for me
:%s/^/#/g

@cwwaism what if you just want a few lines rather than entire file? Visual blocks easier than line numbers.

If you just want for certain lines do this. This will comment lines 7 to 10 and you can change it accordingly.
:7,10s/^/#/g

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment