21

I added:

set number
nnoremap <F2> :set nonumber!

to my vimrc file. Basically what it's supposed to do is let me press F2 to toggle line numbering but it's not working. What have I done wrong?

mtk
  • 13,221
  • 16
  • 72
  • 112
Nope
  • 34,682
  • 42
  • 94
  • 119

5 Answers5

39

In your .vimrc, add this:

set number
nnoremap <F2> :set nonumber!<CR>

Then pressing F2 will toggle line numbering.

mtk
  • 13,221
  • 16
  • 72
  • 112
Taurus Olson
  • 3,153
  • 2
  • 26
  • 21
  • 1
    This works perfectly for me, but just curious how would `nonumber!` implement the toggle function? – Wei Lin Apr 14 '15 at 00:15
  • With latest vim, add `:set nonumber! norelativenumber!` if you use both number and relative number. – mtk Jun 07 '16 at 07:41
25

This is what I use (with a different key binding):

nmap <f2> :set number! number?<cr>

The "number!" toggles the setting and "number?" reports the state.

Jeremy Cantrell
  • 26,392
  • 13
  • 55
  • 78
  • This should be flagged as right anwser because more complete! This is the `lua` version for Neovim `vim.api.nvim_set_keymap("n", "", ":set scrollbind! scrollbind?", { noremap = true, silent = true })` – Joannes Dec 12 '22 at 08:15
8
nmap <silent> <F11> :exec &nu==&rnu? "se nu!" : "se rnu!"<CR>

In new vim you can set both relative number and number at once, this way:

set nu rnu

enter image description here

SergioAraujo
  • 11,069
  • 3
  • 50
  • 40
5

This is one method:

map <silent> <F2> :if &number <Bar>
    \set nonumber <Bar>
        \else <Bar>
    \set number <Bar>
        \endif<cr>

(this one is nice 'cause I usually put foldcolumn in there as well)

This is another:

map <silent> <F2> :set invnumber<cr>

(direct method)

Rook
  • 60,248
  • 49
  • 165
  • 242
  • I've just used the second method you shared with us. It's the one i prefer, thank you :) – lucapette Jan 07 '11 at 09:30
  • 1
    The second method is far more correct and easy than anything else here (so far). It should have been a separate *and accepted* answer. – Alois Mahdal Apr 12 '13 at 11:54
2

I use this to toggle between relativenumber ( with current absolute line number) and no line numbering

nnoremap <silent> <leader>l :set relativenumber! <bar> set nu!<CR>
DaftWooly
  • 348
  • 3
  • 7