Mac – vim: Continue macro after error in submacro

macrosvim

I'm in the process of beautifying some source code using vim. {1}

I've created a couple of vim macros that do the individual steps: removing trailing whilespace, removing empty lines after {, removing empty lines before {, that kind of stuff.

Now, I want to create a macro that executes all the individual macros in sequence. However, once the first recursive macro terminates (because it can no longer find any matches -> matching error), my "wrapper" macro terminates, too.

Is there a way to make a vim macro continue after a submacro generated an error?

{1} I know about automatic reformatters. I might even use them on my current problem. I merely mentioned source reformatting for the example's sake. Do not post any answers about this source beautifier or that. The question is not about code reformatting per se, but about vim macros.

Example:

  • Macro 1 – trimming trailing whitespace – qw/\s\+$d$@wq
  • Macro 2 – deleting empty lines before } – qe/\n\n *}dd@eq
  • Wrapper Macro – retabbing, Macro 1, Macro 2 – qr:retab@w@eq

When I execute the wrapper – @r – it will retab, then execute Macro 1 until no more trailing whitespace are found, then terminate (without executing Macro 2).

Clarification:

What I am looking for is how to call a submacro so that when that submacro terminates, the calling macro continues?

Best Answer

I suggest you use :try to "absorb" the submacro's error.

Here is a silly example:

:let @a='f|dt|@a'
:let @q=':try|exe "norm! @a"|endtry^Mj0@q'
@q

Your wrapper macro would look something like this:

let @r=':retab^M:try|exe "norm! @w"|endtry|try|exe "norm! @e"|endtry^M'