Vim Tips Wiki

Reversing order of blocks of text

1,624pages on
this wiki
Add New Page
Talk0 Share
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.

Moving blocks of textEdit

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 class="myblock">
    ... html for second block, multiple lines ...
<div class="myblock">
    ... html for third block, multiple lines ...

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.

See alsoEdit


Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Also on Fandom

Random Wiki