How do I center or left-align lines of text using an Ex command?
Answer
:[range]center
Explanation
Vim provides three Ex commands for aligning text within a specified column width: :[range]left, :[range]center, and :[range]right. These are particularly useful for formatting comments, documentation headers, ASCII banners, or any structured text where column alignment matters.
How it works
:[range]left [indent]— left-justifies lines, optionally with a leading indent amount:[range]center [width]— centers lines within the given column width:[range]right [width]— right-justifies lines within the given column width
All three commands strip existing leading and trailing whitespace before applying alignment. If no width is specified, Vim uses textwidth (or 80 if unset).
Example
Given these lines selected with V2j:
hello
world
Running :'<,'>center 30 produces:
hello
world
Running :'<,'>right 30 produces:
hello
world
Tips
- Use
:%centerto center every line in the file - Combine with a visual selection: select lines, then type
:center 40<CR> :[range]left 4strips all leading whitespace and re-indents by 4 spaces — handy for dedenting a block without<motions- These commands work well for creating centered comment banners:
:.center 78