Search code examples
vimneovim

Is there a way to operate macro to all markers?


For example if a use ma mb etc to create some markers in buffer. Then i record a macro, then i want to execute macro to all these markers, how can i do to accomplish this goal

Maybe it can be completed by writing a function by lua or viml, or use some plugins or just a vim command is all accepted. I'd like someone can give a example function to make me learn more about neovim or vim


Solution

  • You can use getpos("'".mark_name) to obtain the position of a mark. And a macro can be executed with exe 'normal @'.macro_name.

    Which gives:

    function! s:exec(macro, marks) abort
      for mark in split(a:marks, '\zs\ze')
        call setpos('.', getpos("'".mark))
        exe 'normal @'.a:macro
      endfor
    endfunction
    
    command! -nargs=+ RunMacroOnMarks  call s:exec(<f-args>)
    

    Then if you've recorded a macro in register m and marked two positions a and b, it can be used with:

    :RunMacroOnMarks m ab
    

    Note: I've chosen to be explicit with the list of marks as we are likely to want to restrict the macro to a very limited number of registered positions.