Vim: Toggle Relative Numbers

Using relative line numbers is a great way to make navigation in vim more efficient, however, it can be a pain while pairing or when you need absolute line numbers. One way of making this process easier is to create a key binding which toggles relative line numbers. It can be done by adding the following function to your vimrc.

" in ~/.vimrc
set number relativenumber

let s:relative =1
function! ToggleRelative()
    if s:relative  == 0
        let s:relative = 1
        set nonumber
        set number relativenumber

        let s:relative = 0
        set nonumber
        set number norelativenumber


noremap <silent> <leader>a :call ToggleRelative()<CR>

The script above maps \a command to toggle relative line numbers.