50

A lot of vim commands can take a number referring to the number of lines that the command will act on.

Is it possible to show the line numbers relative to the current line? Something like the following:

3: some text here
2: more text
1: This is the line above where the cursor is
0: The cursor is on this line
1: This is the line after the cursor
2: More text here
61

I just replied to a similar question here: How can I add line numbers to Vim?

Beginning with version 7.3, you can use the following:

set relativenumber

I actually use both relativenumber and number in my vimrc which will use relative numbers for all lines except the current line.

set number                     " Show current line number
set relativenumber             " Show relative line numbers
6

You can toggle relative numbering on and off using:

:set rnu    " toggle relative numbering on
:set rnu!   " toggle relative numbering off
5
function! NumberToggle()
  if(&relativenumber == 1)
    set norelativenumber
  else
    set relativenumber
  endif
endfunc

nnoremap <leader>nt :call NumberToggle()<cr>
  • 2
    Does the norelativenumber just turn off numbering altogether or does it switch to conventional numbering? – Nick J Adams Feb 3 '15 at 16:59
  • set number is the setting that controls the presences of numbers so it will only switch between rel and non-rel – shawndumas Feb 3 '15 at 17:05
  • 2
    The numbers.vim plugin also adds some more advanced relative number functionality, e.g. having the line your cursor occupies printing the non-relative number, and switching to non-relative numbering throughout the whole file when the vim window loses focus. – bronzehedwick Feb 3 '15 at 17:22
  • 1
    @shawndumas so is there a precedence of which numbers are shown? If for instance I had set number in my vimrc and set relativenumber / norelativenumber was called could it toggle between relative and standard numbering? – Nick J Adams Feb 3 '15 at 17:29
  • 1
    that is most correct – shawndumas Feb 3 '15 at 20:43
4

If you want to use a hotkey for toggling relative line number, here is a snippet in my vimrc:

" Toggle relative line number
nmap <C-L><C-L> :set invrelativenumber<CR>

In this case, I use ctrl-L twice to toggle it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.