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 range1,$, meaning every line in the filenormal @q— execute the macro in registerqas 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 afterV-selecting, just type:silent! norm @q - Combine with
:argdoto run across multiple files::argdo silent! %normal @q | update - Use
:set lazyredrawbefore the command and:set nolazyredrawafter to prevent screen flickering during large-file processing - Prefer
norm!(with bang) overnormwhen you want mappings to be ignored — e.g.,:silent! %normal! @q - Check
:help :silent,:help :normal, and:help :rangefor the full specification