Table of Contents

How To Show Line Numbers In Vim

Setting line number in vim is very easy. The command to do that is "set nu". Here is how you do that...

  1. First open your file in vim
  2. Go to command line mode by typing colon :
  3. Type set nu and press Enter

Checkout the snapshot for details...

Once you press set nu, you will see numbers on the left as shown below...

To disable the numbers just type :set nu!

How to set relative line numbers in Vim

"set nu" will set the numbers from the beginning of file starting from 0. Lot of times it is useful to start the numbers from the current line where the cursor is that is called relative numbering.

To set the relative numbering the command is "set relativenumber". Here is how you do it.

Open your file in vim

  1. Go to command mode by typing colon ":"
  2. Type command "set relativenumber" and press enter

Checkout the snapshot below...

To disable just do "set relativenumber!"

How to Turn On line number and relative number together in VIM

Sometimes I find it useful to turn on both line numbers and relative numbers. You can achieve that by typing both commands "set nu" and "set relativenumber" one after the another in any order.

set nu
set relativenumber

Another way to achieve above in a single line is

set number relativenumber

Here is how it looks like...

How to Setup shortcut key for "set nu" and "set relativenumber" in Vim

If vim is your main working editor, you might have to run "set nu" and "set relativenumber" multiple times. We can set an alias/shortcut key in vim to speed up the process. For example I have the following map key set in ~/.vimrc, to toggle line numbers.

let mapleader=","
nnoremap ,s :set nu<CR>
nnoremap ,ss :set nu!<CR>

Then to turn on the line numbers, just press ,s and to turn off press ,ss

Above key mapping is useful. You can also set something like this to toggle on and off relative line numbers too. But then you will be adding two more map keys. To make it easier, there is an open source utility on github which someone has written for toggling line numbers and relative line numbers.

Please go to following line to know more about this...

Related Posts