vimbuffervim-macros

Conditional action in a macro


In a VIM macro, how are the conditional actions handled?

 if condition is true
       do this
 else
       do something else

Basic example

File content:

_
abcdefg

The macro will do:

G^
if letter is one of the following letters: a e i o u
   gg$i0<ESC>
else
   gg$i1<ESC>
Gx

Repeated 7 times the buffer will be:

_0111011

So, how can I verify if a condition is true and then run an action?


Solution

  • As there's no "conditional" command in Vim, this cannot strictly be done with a macro. You can only use the fact that when a command in a macro beeps, the macro replay is aborted. Recursive macros use this fact to stop the iteration (e.g. when the j command cannot move to a following line at the end of the buffer).

    On the other hand, conditional logic is very easy in Vimscript, and a macro can :call any Vimscript function easily.

    Your example could be formulated like this:

    function! Macro()
        " Get current letter.
        normal! yl
        if @" =~# '[aeiou]'
            execute "normal! gg$i0\<ESC>"
        else
            execute "normal! gg$i1\<ESC>"
        endif
    endfunction