created September 8, 2009 · complexity basic · author Sean Whitton · version 7.0
It is often useful to record a macro – a series of commands that can be re-executed. This tip shows how to use a macro to move blocks of text: record the commands to move the first block, then replay the commands to move further blocks.
Moving blocks of text
One might have many blocks of text that are clearly delimited, but which need the order reversed, as in this example:
<div class="myblock"> ... html for first block, multiple lines ... </div> <div class="myblock"> ... html for second block, multiple lines ... </div> <div class="myblock"> ... html for third block, multiple lines ... </div>
To solve this problem, observe that the first block does not need to be moved. Go to the last line of the first block (in this case the </div>) then record a macro by typing:
- ma (set mark 'a')
- qa (start recording a macro to register a)
- jV/<\/div><CR> (select the next block – these commands work for this example)
- :m0<CR> (move the block to the beginning of the file)
- 'a (return to mark 'a')
- q (finish recording macro)
Now you should be able to run the macro with @a (and then @@ for each subsequent run) for each block you need to move.
For the impatient, move to the last line of your block and type maqajV/<\/div><CR>:m0<CR>'aq@a@@@@@@@@; keep doing @@ until the file is reordered appropriately.
Note that this won't work for nested <div> tags (in this example). The matchit.vim extension may allow you to use % instead.
- Macros overview