How do I center or right-align lines of text using Vim's built-in Ex commands?
Answer
:%center 80
Explanation
Vim has three built-in Ex formatting commands — :left, :center, and :right — that align text within a specified column width. These work on any range, including visual selections, making them handy for formatting plain text, comments, headers, and ASCII art without any plugins.
How it works
:[range]center [width]— centers each line within [width] columns (default 80):[range]right [width]— right-aligns each line to [width] columns:[range]left [indent]— left-aligns and optionally adds [indent] spaces- The range can be
%(whole file),'<,'>(visual selection), or any line range
Example
Given text:
hello world
foo
a longer line of text
After :%center 40:
hello world
foo
a longer line of text
After :%right 40:
hello world
foo
a longer line of text
Tips
- Select lines visually with
Vthen press:— the range'<,'>is prefilled, so just typecenter 79and press<CR> - Combine with
gq(:set textwidth=79) for paragraph reflow followed by centering - These commands are especially useful for centering section headers in plain-text files, configuration comments, or formatted reports
- The width argument defaults to the value of
textwidthif set, or 80 otherwise