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

How do I record a macro to toggle comments on a line?

Answer

qaI// <Esc>jq

Explanation

This macro adds a // comment prefix to the beginning of the current line and moves down. For uncommenting, record a separate macro that removes the prefix.

How it works

Comment macro:

  1. qa — start recording to a
  2. I// — insert // at line start
  3. <Esc>j — return to normal mode, move down
  4. q — stop recording

Uncomment macro:

  1. qb — start recording to b
  2. ^3x — go to first non-blank, delete 3 chars (// )
  3. j — move down
  4. q — stop recording

Example

5@a comments 5 lines. 5@b uncomments them.

Tips

  • Adjust the prefix for different languages (#, --, /* */)
  • The vim-commentary plugin handles this automatically
  • Use visual mode + I// <Esc> for block commenting
  • Consider using norm I// with ranges for one-off use

Next

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