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

How do I comment out an entire paragraph or code block with a single motion using vim-commentary?

Answer

gcip

Explanation

The vim-commentary plugin exposes gc as a comment operator, which means it composes with any Vim motion or text object. Combining it with ip (inner paragraph) lets you toggle comments on an entire contiguous block of non-blank lines in one keystroke — no visual selection required.

How it works

  • gc — the comment/uncomment operator (from vim-commentary)
  • ip — the inner paragraph text object: all contiguous non-blank lines around the cursor
  • Together, gcip toggles comments on every line in the current paragraph

Because gc is a true operator, it works with any motion or text object:

  • gc3j — comment the current line plus the 3 lines below
  • gcG — comment from the cursor to the end of the file
  • gcii — comment the current indentation block (requires a text-object plugin)
  • gci{ — comment everything inside the nearest {} block

Example

Given this Go code (cursor anywhere in the block):

func greet(name string) {
    msg := fmt.Sprintf("Hello, %s", name)
    fmt.Println(msg)
}

Press gcip to toggle comments:

// func greet(name string) {
//     msg := fmt.Sprintf("Hello, %s", name)
//     fmt.Println(msg)
// }

Tips

  • gcip is idempotent — pressing it again uncomments the block
  • gcc toggles a single line; gc is the operator form for motions
  • The comment style is detected from the file type automatically
  • Works in any language vim-commentary knows about (which is nearly all of them)

Next

How do I run a shell command on a range of lines in normal mode and replace them with the output?