Vim Macro on Every Line of Visual Selection

后端 未结 3 1741
时光说笑
时光说笑 2021-01-29 19:28

I\'d like to run a macro on every line in a selection, rather than totalling up the number of lines in my head. For instance, I might write a macro to transform:



        
3条回答
  •  無奈伤痛
    2021-01-29 19:33

    Select the lines then press : to enter command mode. Vim will automatically fill in '<,'>, which restricts the range to the selected lines. For your example you can use the :s command to do the swap:

    :'<,'>s/\(\w\+\), \(\w\+\)/\2, \1/
    

    This will swap two words separated by a comma on every line in the visual selection.

    You can also use '< and '> like any other bookmark or line position, e.g. as part of a movement command, so in normal mode d'< will delete from the current cursor position to the start of the first line in the visual selection. The marks remain in effect even if the block is not longer visually highlighted.

    If you want to replay a recorded macro on every line the you need to execute the macro with the :normal command. Unfortunately the :normal command does not operate on a range of lines, but you can fix that with the :global command. This runs an :ex command on every line that matches a regex, so you can do this:

    :'<,'>g/^/ norm @a
    

    Explanation:

    :'<,'>       for every line in the visual block
    g/^/         on every line that matches the regex /^/ - i.e. every line
    norm         run in normal mode
    @a           the macro recorded in a
    

提交回复
热议问题