Formatting in Buffers

In this blog post we take a quick look at how to quickly format selected text and even entire buffers with just a few keystrokes.

Formatting Selected Content

We will demonstrate using the following un-formatted HTML file:

Initial Conditions
<div>
····<p>line·one</p>
······<p>line·two</p>
········<p>line·three</p>
····</div>
NORMAL
Top
1:1
 

We first move the cursor to the first line we would like to format:

Initial Conditions
2j
<div>
····<p>line·one</p>
······<p>line·two</p>
········<p>line·three</p>
····</div>
NORMAL
50%
3:1
 

Then create the selection by entering Visual Mode v and moving down a few lines:

Create the Selection
vj
<div>
····<p>line·one</p>
······<p>line·two</p>
········<p>line·three</p>
····</div>
VISUAL
67%
4:1
 

Finally, hitting = formats the selected lines:

Format Selection
=
<div>
····<p>line·one</p>
····<p>line·two</p>
····<p>line·three</p>
····</div>
NORMAL
50%
3:1
 

Note that Vim formatted only the lines contained within the selection (including the entire lines containing the cursors), but didn't format the other lines.

Entire Buffer

We can extend this example to formatting entire buffers. Starting with the same buffer as the previous example:

Initial Conditions
<div>
····<p>line·one</p>
······<p>line·two</p>
········<p>line·three</p>
····</div>
NORMAL
50%
3:1
 

The first step is to execute gg, which moves the cursor to the top of the buffer:

Initial Conditions
gg
<div>
····<p>line·one</p>
······<p>line·two</p>
········<p>line·three</p>
····</div>
NORMAL
Top
1:1
 

Next, we hit =, which tells Vim to format the lines traversed by the associated motion. We follow this with G, which indicates that we want to apply formatting from the current line to the bottom of the file:

Move to Top of Buffer
=G
<div>
········<p>line·one</p>
········<p>line·two</p>
········<p>line·three</p>
</div>
NORMAL
Top
1:1
5 lines indented

The end result shows that the entire buffer was formatted.