Last Updated: February 25, 2016
·
1.092K
· gvanderest

Get Vim to Surround Lines

I love (Mac)Vim, and I'm slowly getting more and more proficient at it, but since I deal with a lot of web programming, this one comes up a lot: How do I make certain lines into headings or paragraph tags?

To answer this, it's a little complex using my method, so I'll break it down into two steps:

Step 1: I want to specify which lines to match:
To do this, I use :g to search for lines and return them to me using regular expressions. For example, in my most recent need of it, all the headings started with a number:

:g/^[0-9]/

If you run this command alone, you will see what you end up with, an output of all the lines that start with a number. (You can also replace "[0-9]" with \d to specify "digits")

Step 2: I want to perform a string replace to wrap the line
In Vim, if you go to any line and type the following:

:s#^.*$#<p>&</p>#

This will replace the entirety of the line (the first part) with a paragraph tag (the second part), and the amersand (&) is a placeholder for "the content from the match."

The reason I used hashes (#) is because I know that HTML tags have a slash (/) in them, so in order to not need to escape, I just used a hash as my symbol for defining my regular expressions.

Step 3: I want to to both, together
You can probably see where this is going: You want to take step 1 and step 2 and put them together. Easy, just put them back-to-back!

:g/^[0-9]/s#^.*$#<p>&</p>#

And that's it!

Sure, it looks a little complicated to start-- but once you understand what it's doing, it makes some pretty good sense.

Also, this is a very simple example.. You could make it more complex and check for other things to make them paragraphs, or headings, or other tags that you might need.