How do I quickly comment and uncomment code in Vim with a plugin?
Answer
gcc
Explanation
The vim-commentary plugin by Tim Pope provides a minimal yet powerful way to toggle comments in any programming language. Instead of manually typing comment characters and managing edge cases, gcc toggles a comment on the current line, and gc works as an operator with any motion or text object.
How it works
gcctoggles commenting on the current linegc{motion}toggles commenting over a motion or text objectgcin visual mode toggles commenting on the selected linesgcgcorgcuuncomments a contiguous block of commented lines
The plugin detects the correct comment style using Vim's 'commentstring' option, so it automatically works with any filetype that has proper syntax settings.
Examples
gcc " toggle comment on current line
gcap " toggle comment on the current paragraph
gc5j " toggle comment on the next 5 lines
gcii " toggle comment on the current indent level (with vim-indent-object)
Before and after
With the cursor on a JavaScript line, pressing gcc:
const x = 42;
Becomes:
// const x = 42;
Pressing gcc again uncomments the line back to its original form.
Commenting multiple lines
Use gc with a motion to comment a range. For example, gcap on a Python function:
def greet(name):
msg = f"Hello {name}"
print(msg)
Becomes:
# def greet(name):
# msg = f"Hello {name}"
# print(msg)
Using with counts
You can prefix gcc with a count to comment multiple lines:
3gcc " toggle comment on the current line and the next 2 lines
Custom comment strings
If a filetype does not have the correct comment style, set it in your vimrc:
autocmd FileType apache setlocal commentstring=#\ %s
Tips
- Vim-commentary respects indentation: it places comment characters at the correct indent level, not at column 0
- Pair with vim-repeat so
.repeats the last comment toggle - For Neovim users, Comment.nvim offers a similar experience with additional features like block comments (
gbc) and support for JSX/TSX contexts - Works beautifully with text objects:
gcitcomments inside an HTML tag,gci}comments inside curly braces