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

How do I enable relative line numbers in Vim?

Answer

:set relativenumber

Explanation

The :set relativenumber command displays line numbers relative to the cursor position instead of absolute line numbers. The current line shows 0 (or the absolute line number if combined with number), and all other lines show their distance from the cursor. This makes it trivial to count lines for motions like 5j, 12dd, or 8yy.

How it works

  • :set relativenumber (or :set rnu for short) enables relative line numbers
  • :set norelativenumber (or :set nornu) disables them
  • :set relativenumber! toggles the setting on and off

Example

With the cursor on the line containing current line, the gutter shows:

  3  first line
  2  second line
  1  third line
  0  current line
  1  fifth line
  2  sixth line
  3  seventh line

You can immediately see that first line is 3 lines above and seventh line is 3 lines below. To delete down to sixth line, just type 2dd — no mental arithmetic needed.

Hybrid line numbers

Combine relativenumber with number to get the best of both worlds — the current line shows its absolute line number while all other lines show relative distances:

:set number relativenumber

This displays:

  3  first line
  2  second line
  1  third line
 42  current line
  1  fifth line
  2  sixth line
  3  seventh line

The current line shows 42 (the actual line number), which is useful for debugging and referencing error messages.

Tips

  • Add set number relativenumber to your vimrc to enable hybrid line numbers permanently
  • Use :set rnu! to quickly toggle relative numbers on and off
  • Relative numbers make vertical motions like 5j, 10k, 7dd, and 3yy much faster because you can see the exact count in the gutter
  • Some users prefer to auto-toggle between relative and absolute numbers based on mode — showing relative in normal mode and absolute in insert mode — using autocommands:
augroup numbertoggle
  autocmd!
  autocmd InsertLeave * set relativenumber
  autocmd InsertEnter * set norelativenumber
augroup END
  • If performance is a concern with very large files, relative line numbers can cause slight redraw overhead — disable them with :set nornu if you notice lag

Next

How do I edit multiple lines at once using multiple cursors in Vim?