David542
David542

Reputation: 110123

How to toggle (all) line numbers on or off

Let's say I have some combination of:

" one if not both is usually on
set number         " could be on or off
set relativenumber " could be on or off

Is there a way to toggle these on/off without losing information (not knowing what is set -- i.e., I would like to make a simple keyboard shortcut to toggle the visibility of the current line-number selection)? For example if I have only rnu set and I do:

:set number!

It really doesn't help me at all, since I'll still have rnu set and there will still be a line-number column on the left. If so, how could this be done?

Upvotes: 0

Views: 455

Answers (2)

SergioAraujo
SergioAraujo

Reputation: 11800

The one liner solution

:nnoremap <silent> <C-n> :let [&nu, &rnu] = [!&rnu, &nu+&rnu==1]<cr>

To understand what happens try:

:echo [&nu, !&rnu]

&nu ............. gets the value of number
!&rnu ........... the oposite value of relative number

For more :h nu

Upvotes: 0

Kent
Kent

Reputation: 195039

give this a try:

  • currently, I am mapping it to <F7> you can change the mapping if you like
  • I am using the global variable, you can change the scope if it is required

This function will disable all line-number displays and restore to the old line number settings.

function! MagicNumberToggle() abort
    if &nu + &rnu == 0
        let &nu = g:old_nu
        let &rnu = g:old_rnu
    else
        let g:old_nu = &nu
        let g:old_rnu = &rnu
        let &nu = 0
        let &rnu =0
    endif
endfunction
nnoremap <F7> :call MagicNumberToggle()<cr>

Upvotes: 1

Related Questions