Toggling relative line-numbering in Vim

With the recent release of Lion, OS X users get access to the latest version of Vim. That includes the new relative line-numbering feature which looks particularly useful given Vim's many line-wise operations (see :help relativenumber for details).

However, it might not be something you want on all the time. Absolute line-numbering is useful in debugging and for providing context, and relative line-numbering could be slightly distracting given that it changes as you move around. So, you might want to toggle between the two modes.

Toggling between absolute and relative isn't as simple as :set relativenumber! though, because norelativenumber just turns off line-numbering rather than falling back to number.

So here's one way of handling things. First set your default numbering:

if exists('+relativenumber')
    set relativenumber
else
    set number
endif

Add a function to toggle between the two modes:

function! ToggleNumbering()
    if exists("+relativenumber")
        if &relativenumber
            set number
        else
            set relativenumber
        endif
    else
        set number!
    endif
endfunc

If the option isn't available, e.g. you're on a version earlier than 7.3, it falls back to toggling line-numbering on or off. If you were so inclined, you could do a version that cycled between the 3 possible states (off, absolute and relative), but I prefer it like this.

Finally, map a keyboard shortcut to trigger the function:

noremap <leader>n :call ToggleNumbering()<cr>

I use <leader> mappings a lot for my own personal shortcuts, but a lot of people seem to prefer the function keys. You can replace <leader>n with <f12> or whatever if that includes you.

Paste that lot into your .vimrc and continue on your merry way.

0 comments

Add a comment
You must have Javascript enabled to add a comment.
  (optional)