Reversing order of blocks of text

From Vim Tips Wiki

Jump to: navigation, search
Tip 1632 Printable Monobook Previous Next

created 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.

[edit] 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.

[edit] See also

[edit] Comments

Personal tools