vim: Continue macro after error in submacro?

If the failing command is a substitution that isn't finding its pattern, e.g.,

:%s/foo/bar/

when foo doesn't exist in the buffer, you can add the e flag to ignore that error, e.g.,

:%s/foo/bar/e

See

:help :s_flags

You can tell Vim to ignore the errors from some :ex commands by preceding them with :silent!. See

:help :silent


Edit Following the Addition of Example to the Question

Macro 1 and Macro 2 are both recursive and neither has any explicit mechanism for terminating the recursion. My guess is that one of Vim's internal tests for unlimited recursion is being triggered, which generates an error. If Macro 1 is generating such an error, then that error will terminate the execution of Wrapper Macro right after @w.

My suggestion would be to limit the number of times your macros are being executed by rewriting them as :ex commands and limiting the range of lines over which they are executed. For example:

qw:%s/\s\+$//^Mq
qe:%s/\n\n *}/\r}/^Mq

where ^M means typing your Enter or Return key. I haven't tested those together in your Wrapper Macro, but I think you'll be able to fix any mistakes I may have made.


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'

What worked for me was a combination of @Peter Rincker and @garyjohn answers. Seperately I just kept getting weird issues.

nnoremap <leader>rt :silent! %s/\s\+$//e<CR>
let @r='\rt'
let @t=':try|silent! exe "norm! @r"|endtry|w^M'

I think the silent! in the <leader>rt, and the pipe characters between the endtry and the w were the keys - simply having the line break after the endtry failed. The trys worked when I'd just enter them, but when run as a macro the error about the search text wasn't found would keep being raised.

Tags:

Vim

Macros