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

How do I right-justify a line of text to a specific width using a built-in Vim command?

Answer

:right

Explanation

Vim has three built-in Ex commands for text alignment that most users never discover: :right [width] right-justifies lines, :left [width] left-justifies (strips leading whitespace), and :center [width] centres them. These work on the current line or a range without any plugins, making them handy for formatting structured text, ASCII art, comment banners, and tabular data.

How it works

  • :right — right-justify the current line to textwidth (or 80 if textwidth is 0)
  • :right 60 — right-justify to column 60
  • :left — remove leading whitespace (left-justify)
  • :center 72 — centre within 72 columns
  • :{range}right {width} — apply to a range of lines

The command pads lines with leading spaces so that the last visible character lands on the specified column.

Example

Given two lines selected in visual mode:

Chapter 1
A Brief Introduction

After :'<,'>right 40:

                               Chapter 1
                   A Brief Introduction

After :'<,'>center 40 instead:

          Chapter 1
          A Brief Introduction

Tips

  • Select lines with V, then type :right 80<CR> — Vim auto-fills '<,'> so the range applies to your selection
  • Use % as the range to justify the entire file: :%right 80
  • The width argument defaults to textwidth; set :set textwidth=72 if you want consistent alignment without always typing a number
  • These commands are great for creating comment section headers: select a blank line, type :center 78, then fill it with = signs

Next

How do I search for a character by its ASCII or Unicode code point value in a Vim pattern?