vimtricks.wiki Concise Vim tricks, one at a time.

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

  • gcc toggles comments on the current line
  • gc{motion} comments or uncomments lines covered by a motion
  • gcap toggles comments on the entire paragraph
  • gc in 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 gcgc to uncomment a contiguous block of commented lines
  • Neovim 0.10+ includes built-in commenting with the same gcc/gc keybindings — no plugin needed
  • Pair with gc} to comment from the cursor to the end of the paragraph

Next

How do I return to normal mode from absolutely any mode in Vim?