How do I center or right-align a block of text using Vim's built-in Ex commands?
Answer
:{range}center [width]
Explanation
Vim provides three built-in Ex commands for text alignment: :center, :right, and :left. These operate on a range of lines and pad them with spaces to produce the desired alignment, all without any plugin or external tool.
How it works
:[range]center [width]— center each line withinwidthcolumns (default:textwidth):[range]right [width]— right-align each line withinwidthcolumns:[range]left [indent]— left-align each line, optionally addingindentspaces
The [range] follows standard Vim range syntax: % for the whole file, '<,'> for a visual selection, or 1,5 for specific lines.
Example
Starting with these lines:
hello
world
Running :%center 40 produces:
hello
world
Running :%right 40 on the same lines:
hello
world
Tips
- If
widthis omitted,:centerand:rightusetextwidth(or 80 if unset) :left 0strips all leading whitespace from a range — useful for dedenting a block- Combine with a visual selection: select lines, press
:, then typecenter 72to center them within 72 columns - Great for ASCII banners, formatted comment headers, or aligned output in text files