vim : toggle number with relativenumber
with
setl nu!
I can toggle number (on/off), similar with relativenumber
setl rnu!
how I can toggle {off,number,relativenumber} ?
if &nu == 1
set rnu
elseif &rnu == 1
set nornu
else
set nu
endif
Because I love a logic puzzle, and really love it when a vim command fits on a single line for succinct repeats (@: is a personal favourite):
:exec &nu==&rnu? "se nu!" : "se rnu!"
This will maintain the same cycle. I think it is mainly because let &nu=1
will implicitly set norelativenumber - for reasons probably found in the documentation :)
For those who would like a more readable solution, the following is what I have in my .vimrc
" Relative or absolute number lines
function! NumberToggle()
if(&nu == 1)
set nu!
set rnu
else
set nornu
set nu
endif
endfunction
nnoremap <C-n> :call NumberToggle()<CR>
The cool thing about this is that you can hit ctrl + n to toggle between relative and absolute number modes!
As of Vim 7.3.1115 this has become a little more complicated to do.
The reason is that besides "no line numbers" and "absolute line numbers", there are now two settings for relative line numbers: ordinary "relative line numbers", and "relative line numbers with absolute number on the cursor line".
More technically speaking, all four combinations of 'number'
and 'relativenumber'
are now possible.
Here's how to toggle:
-
Toggle all four settings, no numbers → absolute → relative → relative with absolute on cursor line:
:exe 'set nu!' &nu ? 'rnu!' : ''
-
Toggle between no numbers → absolute → relative:
:let [&nu, &rnu] = [&nu+&rnu==0, &nu]
-
Toggle between no numbers → absolute → relative with absolute on cursor line:
:let [&nu, &rnu] = [!&rnu, &nu+&rnu==1]