vimtricks.wiki Concise Vim tricks, one at a time.

How do I center-align or right-align lines of text in Vim without an external tool?

Answer

:[range]center [width]

Explanation

Vim's built-in :left, :center, and :right Ex commands align text without plugins or external tools. They operate on any line range and are handy for formatting comments, banners, or structured text in documentation and configuration files.

How it works

All three commands take an optional [width] argument (defaults to textwidth, or 80 if textwidth is 0):

  • :[range]left [indent] — Strips leading whitespace, then adds indent spaces (default 0)
  • :[range]center [width] — Centers each line within width columns
  • :[range]right [width] — Right-justifies each line within width columns

Example

Given these three lines:

hello
vim
a longer title

Running :%center 40 produces:

                 hello
                  vim
             a longer title

Running :%right 40 on the original:

                                hello
                                  vim
                         a longer title

Tips

  • Apply to a visual selection: :'<,'>center 60
  • Center only lines matching a pattern: :g/^===/center 78 — great for section headers in comments
  • All three commands are undoable with u
  • Use :'<,'>left to strip all leading whitespace from a selection (normalizes indent to column 0)
  • Use :[range]left 4 to set a uniform indent of 4 spaces across a range

Next

How do I generate multiple lines of text using a Vimscript for loop from the command line?