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

How do I quickly comment and uncomment code with vim-commentary?

Answer

gcc (toggle line), gc{motion} (toggle range)

Explanation

vim-commentary by Tim Pope provides a simple way to toggle comments. It detects the correct comment syntax based on the file type.

How it works

  • gcc toggles commenting on the current line
  • gc{motion} toggles comments over a motion
  • gcip toggles comments on the current paragraph
  • gc in visual mode toggles comments on the selection

Example

In a Python file:

def hello():
    print("hello")

gcc on the print line comments it: # print("hello") gcc again uncomments it.

Tips

  • Install: Plug 'tpope/vim-commentary'
  • Automatically detects comment syntax per filetype
  • gcgc uncomments a block of adjacent comments
  • Works with counts: 3gcc comments 3 lines
  • :set commentstring=//\ %s sets the comment format

Next

How do you yank a single word into a named register?