How do I center text on the current line using a built-in Vim command?
Answer
:ce
Explanation
Vim has three built-in ex commands for text alignment that most users never discover: :ce (center), :ri (right-justify), and :le (left-justify). These commands work directly on lines without any plugin and accept an optional column-width argument.
How it works
:ce [width]— centers the current line withinwidthcolumns. Defaults totextwidthif set, otherwise 80.:ri [width]— right-justifies the current line, padding with spaces on the left.:le [indent]— left-justifies by stripping leading whitespace, with an optional indent amount.
All three accept ranges, so you can align entire regions at once.
Example
Given a line with the cursor on it:
hello world
Running :.ce 40 produces:
hello world
Running :.ri 40 produces:
hello world
Running :.le strips any leading whitespace:
hello world
Tips
- Apply to the whole file with
:%ce 80to center all lines. - These commands are especially useful for formatting comment banners or README-style headers.
- In visual-line mode, select multiple lines first, then type
:ce— Vim fills in the'<,'>range automatically. - Set
textwidthbefore using:cewithout an argument so you don't need to specify the width each time.