How do I quickly toggle comments on lines of code in Vim?
Answer
gcc / gc{motion}
Explanation
The vim-commentary plugin by Tim Pope provides a simple, operator-based way to comment and uncomment code. It automatically uses the correct comment syntax for the current filetype — // for JavaScript, # for Python, " for Vimscript, and so on.
How it works
gcctoggles comments on the current linegc{motion}comments or uncomments lines covered by a motiongcaptoggles comments on the entire paragraphgcin visual mode toggles comments on the selected lines- If the target lines are uncommented, it comments them; if already commented, it uncomments them
Example
Given this Python code with the cursor on line 2:
def greet(name):
print(f"Hello, {name}")
return True
Pressing gcc on line 2 produces:
def greet(name):
# print(f"Hello, {name}")
return True
Selecting all three lines with Vjj and pressing gc:
# def greet(name):
# print(f"Hello, {name}")
# return True
Tips
- Install with any plugin manager:
Plug 'tpope/vim-commentary' - Use
gcgcto uncomment a contiguous block of commented lines - Neovim 0.10+ includes built-in commenting with the same
gcc/gckeybindings — no plugin needed - Pair with
gc}to comment from the cursor to the end of the paragraph