How do I center or right-align a range of lines in Vim?
Answer
:[range]center / :[range]right / :[range]left
Explanation
Vim has built-in Ex commands for text alignment: :center, :right, and :left. These work on any line range and are especially handy for formatting comments, banner text, or tabular output — all without leaving Vim.
How it works
:[range]center [width]— center lines withinwidthcolumns (default:textwidthor 80):[range]right [width]— right-align lines withinwidthcolumns:[range]left [indent]— left-align lines, setting optional indent level
The [range] can be % for the whole file, a line number, '<,'> for a visual selection, or any standard range.
Example
Given this text:
hello
world
After :%center 30, lines are centered in 30 columns:
hello
world
To right-align a visual selection to 40 columns:
:'<,'>right 40
To left-align (de-indent) a block to column zero:
:'<,'>left 0
Tips
- Combine with visual mode: select lines with
V, then type:center 60<CR> - When
widthis omitted, Vim usestextwidth(or 80 iftextwidthis 0) - These commands are pure text operations — they add or trim leading spaces and do not affect fold state or marks
- Use
:leftto uniformly remove indent from a block without specifying individual indent amounts