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

How do I run a macro on every line in the file silently, ignoring errors on lines where the macro fails?

Answer

:silent! %normal @q

Explanation

Combining :silent!, the % range, and :normal @q gives you a powerful pattern for applying a macro across an entire file while gracefully skipping lines that don't match the macro's expectations. Without silent!, the first failed operation (e.g., a failed search or motion) stops execution immediately. With it, errors are swallowed and processing continues to the next line.

How it works

  • :silent! — suppresses all error messages and prevents errors from halting the command
  • % — the range 1,$, meaning every line in the file
  • normal @q — execute the macro in register q as if typed in normal mode, starting fresh at each line
  • Combined: for each line in the file, move to it, run register q's macro, and if anything fails, skip silently to the next line

Example

You have a macro in q that appends a semicolon to lines ending with a closing parenthesis:

qq$a;<Esc>q

Running :%normal @q stops at the first blank line or non-matching line. Running:

:silent! %normal @q

processes every line — adding semicolons where applicable and silently moving on where it cannot.

Tips

  • Replace % with a visual selection range: :'<,'>silent! normal @q — or, inside command-line mode after V-selecting, just type :silent! norm @q
  • Combine with :argdo to run across multiple files: :argdo silent! %normal @q | update
  • Use :set lazyredraw before the command and :set nolazyredraw after to prevent screen flickering during large-file processing
  • Prefer norm! (with bang) over norm when you want mappings to be ignored — e.g., :silent! %normal! @q
  • Check :help :silent, :help :normal, and :help :range for the full specification

Next

How do I open a file in Netrw in a vertical split instead of the current window?