Tip 95Perform Arithmetic on the Replacement

The replacement field needn’t be a simple string. We can evaluate a Vim script expression and then use the result as the replacement string. Thus with a single command, we can promote every HTML header tag in a document.

Suppose that we have an HTML document like this:

 <h2>Heading number 1</h2>
 <h3>Number 2 heading</h3>
 <h4>Another heading</h4>

We want to promote each heading, turning <h2> into <h1>, <h3> into <h2>, and so on. To put it another way, we want to subtract one from the numeral part of all HTML header tags.

We’ll harness the substitute command to do it. Here’s the general idea: we write a pattern that matches the numeral portion of HTML header tags. Then ...

Get Practical Vim, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.