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

How do I center, right-align, or left-align lines of text using Vim's built-in Ex commands?

Answer

:center, :right, :left

Explanation

Vim includes three built-in Ex commands for text alignment that most users never discover: :center, :right, and :left. They align the selected lines within a given column width (defaulting to textwidth or 80 columns) without requiring any plugin.

How it works

  • :center [width] — centers each line within the specified column width
  • :right [width] — right-aligns each line to the specified column width
  • :left [margin] — left-aligns each line, optionally adding a leading margin

All three accept a [range], so you can target specific lines, a visual selection, or the entire file.

Example

Given these three lines:

foo
some longer text
x

Running :%center 20 produces:

        foo
  some longer text
         x

Running :%right 20 produces:

                 foo
    some longer text
                   x

Tips

  • Use with a visual selection: select lines in visual mode, then type :center 40 (Vim auto-inserts the range :'<,'>)
  • Combine :center with a header or banner comment:
    :put ='=== My Section ===' | -1center 79
    
  • :left 4 is a fast way to indent a block of lines by exactly 4 spaces without touching shiftwidth
  • The width argument overrides textwidth for that single command only
  • Works in both Vim and Neovim

Next

How do I rename a variable across all case variants (snake_case, camelCase, MixedCase) at once?