Learn Practice Daily golf Reference

How to comment out lines in Vim

Press gcc to comment out the current line, or gc with a motion for more: gcip for the paragraph. The same keys uncomment. Built into Neovim 0.10+; Vim 9.1 needs packadd comment.

Try it here

Silence the debug logs

The cursor is on the first console.log. gcip comments out the whole paragraph, both logs. Then you decide the tax log should stay: gcc on it uncomments just that line.

1 of 2Comment out both logs with gcip
4const rate = 0.2;
3const tax = price * rate;
2const total = price + tax;
1
5console.log('tax', tax);
1console.log('total', total);
NORMALLoading the editor…1/20.0s5:1

This editor needs a keyboard. Read on, and play it at your computer.

KeysWhat it does
gcccomment or uncomment the current line
3gcc or gc2jthis line and the two below
gcipthe paragraph (the block of lines between blank lines)
V then gcthe lines you selected
Ctrl-v, select down, I# Escno plugin needed: types # at the start of each selected line
Ctrl-v, select the markers, dno plugin needed: deletes the column of markers again
:5,10s/^/# / ↵adds # to the start of lines 5 to 10
:'<,'>s/^# // ↵removes # from the start of the selected lines
:'<,'>normal I// ↵types // before the text on each selected line, after the indent

How gc works

gc is an operator, like d for delete: it takes any motion or text object and toggles comments on those lines. So gcip is "comment inner paragraph", gcG comments to the end of the file, and gcc (the operator doubled) means the current line. If every line in the range is already a comment, gc uncomments them; if any isn't, it comments them all. The comment marker comes from the file type (// in JavaScript, # in Python and shell scripts, -- in Lua and SQL), set by the commentstring option, and goes at the indent of the lines rather than in column 0.

Without gc

On a Vim without the comment package or plugin, Visual Block mode does it. Put the cursor at the start of the first line, press Ctrl-v, move down to the last line, then I, type the marker and a space, and press Esc: the text appears on every line at once. To uncomment, select the column of markers the same way (press l to widen the block over the space too) and press d.

A substitute does the same in one command. Select the lines with V, press : (Vim types '<,'> for you) and add s/^/# /. When the marker contains slashes, use another separator so the slashes don't end the pattern: :'<,'>s#^#// #.