Join my free Bash scripting course on Udemy 👀

Using relative line numbers in vim

December 31, 2020  ‐ 2 min read

Writing code in an editor without line numbers is like fries without salt. It's not that I'm using line numbers that often, but it just doesn't look right.

Enabling them in VIM can be done in the .vimrc by adding the following line.

" ~/.vimrc

set number " Enable line numbers

Or you can run it as an command like :set number to enable it in your current vim session. Changing the setting like this just won't persist. So when you close and open vim again the line numbers are gone again.

Either way, the result this has is the following. Line numbers are shown in our .vimrc file and any other file we open.

  1 " ~/.vimrc
  3 set number " Enable line numbers

Since VIM version 7.3, and in Neovim too, we can show relative line numbers. Which helps for commands that strike multiple lines. We can enable this by adding set relativenumber to our .vimrc. As with regular line number this works as a command too.

  1 " ~/.vimrc
  3 set number          " Enable line numbers
  4 set relativenumber  " Enable relative line numbers

Now that we added the setting for relative line numbers, our line numbers as shown as below. For the current line we are at we see the actual line number, for other lines we see the distance from our current line.

  2 " ~/.vimrc
3   set number          " Enable line numbers
  1 set relativenumber  " Enable relative line numbers

Pay attention to the set number setting as well, without it only the relative numbers are shown. So the current line would otherwise be numbered 0.

Jeff Kreeftmeijer wrote more extensively about line numbers in vim and open-sourced a sweet vim plugin for automatically switching between absolute and relative line numbers.