Vim: Reformatting a text file into HTML

If you have ever had to reformat a Word document or plain text file into HTML it can get a bit arduous. Vim, along with Tim Pope's Surround plugin, can help...

Say you have a title you want to quickly surround with <h1> tags:

The quick brown fox jumps over the lazy dog

to:

<h1>The quick brown fox jumps over the lazy dog</h1>

and any paragraphs that need to be put in <p> tags.

Now, you can do this manually, but when the file is a pretty long it gets pretty tiring...

Bring on vim-surround

Tim Pope has created a feast of Vim plugins, and the one we are going to use here is 'surround'. This module makes it possible to to surround any snippet of text with almost any string you want. What's more it also understands HTML or XML tags, so it automatically add the / to closing tags.

I'm going to jump straight to using the surround, but I'd recommend installing the plugin using Vundle.

The most simplistic way of handling this is to follow the instructions on the surround page:

Press a capital V (for linewise visual mode) followed by S<p>. 

<p> 
  Hello world! 
</p>

That's brilliant! Lots of keystrokes saved. But I think we could save some more using Vim macros. In my opinion this is one of Vims best features, allowing you to quickly record a series of keystrokes which you can replay as and when you need them.

To record a macro press q followed by the key you want to use to access the macro later. For a paragraph macro I use p. You should then see recording in the Vim status bar. Now type the keystroke sequence, in this case:

VS<p>

Then stop the marco recording with q.

Now to use the macro, position your cursor on the line you need to surround and press:

@p

That's it - two keystrokes!

For the headings, record a macro like this:

qhVS<h1>q

Then replay it like this:

@h

Then to replay it again:

@@

There are a number of ways that we could speed this up even further. For example, adding )j just before stopping the macro recording will move the cursor to the line following the closing tag, so you're closer to the next string you need to surround in tags.

There we go...

No doubt there are some easier ways to speed this job up. For example, manually adding Markdown and then feeding it through a parser. However, the surround plugin and Vim macros are great tools to have at your disposal.