Conditional action in a macro

In a VIM macro, how are conditional actions handled?

 if condition is true
       do this
 else
       do something else

Basic example

File contents:

_
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

The buffer is repeated 7 times:

_0111011

So, how can I check if the condition is true and then trigger the action?

+4
source share
2 answers

Since there is no “conditional" command in Vim, this cannot be strictly executed using a macro. You can only use the fact that when a command in macros beeps, macro playback is interrupted. Recursive macros use this fact to stop iteration (for example, when a command jcannot go to the next line at the end of the buffer).

, Vimscript, :call Vimscript.

:

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

( ) , . ( ) :

G:s/\v([aeiou])|./\=strlen(submatch(1)) ? 1 : 0/g<CR>gggJ

:.

G  " go to the first non-blank character on the last line

" replace each vowel with 1 and everything else with 0
:s/\v([aeiou])|./\=strlen(submatch(1)) ? 1 : 0/g<CR>

gg " go to the first line
gJ " and append the line below

, ( abolish.vim) , vimscript.

:global, , (), /, :g ( ), , :g, /.

| (:help :bar) if/else, . :

DMY: 09/10/2011 to 10/11/2012
DMY: 13/12/2011
MDY: 10/09/2011 to 11/10/2012
MDY: 12/13/2011

DMY: 2011-10-09 to 2012-11-10
DMY: 2011-12-13
MDY: 2011-10-09 to 2012-11-10
MDY: 2011-12-13

( :execute . ):

:exe 'g/^DMY:/s/\v(\d\d)\D(\d\d)\D(\d{4})/\3-\2-\1/g' |
      g/^MDY:/s/\v(\d\d)\D(\d\d)\D(\d{4})/\3-\1-\2/g
+2

Source: https://habr.com/ru/post/1543591/


All Articles