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

How do I comment out all lines matching a pattern at once using vim-commentary?

Answer

:g/pattern/Commentary

Explanation

vim-commentary exposes Commentary as an Ex command that toggles comments on the current line, making it composable with Vim's :global command. By combining :g/pattern/Commentary you can comment or uncomment every line matching a regex in one shot — without macros, visual selection, or manual counting.

How it works

  • :g/{pattern}/{cmd} runs {cmd} on every line where {pattern} matches
  • Commentary (from vim-commentary) toggles the comment state of the current line using the filetype-appropriate comment string
  • The result: a single command that targets exactly the lines you want and comments/uncomments them atomically

Example

You have a Python file and want to comment out all print() debugging lines:

result = calculate()
print("debug:", result)
final = result * 2
print("final:", final)
return final

Run :g/print/Commentary:

result = calculate()
# print("debug:", result)
final = result * 2
# print("final:", final)
return final

Running it again uncomments them (since Commentary toggles).

Tips

  • Use :v/pattern/Commentary (the inverse global) to comment out all lines that do not match a pattern
  • Scope the operation to a range: :10,50g/TODO/Commentary to target only lines 10–50
  • Pair with '<,'>g/pattern/Commentary after a visual selection to limit the range to the selection
  • This pattern works with any vim-commentary-aware filetype: Python (#), Lua (--), JavaScript (//), Vim script ("), and more

Next

How do I copy files to a target directory using netrw's marking system?