Vim: remap key to toggle line numbering
Asked Answered
A

5

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?

Aussie answered 17/4, 2009 at 23:4 Comment(0)
I
39

In your .vimrc, add this:

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

Then pressing F2 will toggle line numbering.

Inappropriate answered 17/4, 2009 at 23:13 Comment(2)
This works perfectly for me, but just curious how would nonumber! implement the toggle function?Rode
With latest vim, add :set nonumber! norelativenumber! if you use both number and relative number.Terni
B
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.

Bolingbroke answered 18/4, 2009 at 0:31 Comment(1)
This should be flagged as right anwser because more complete! This is the lua version for Neovim vim.api.nvim_set_keymap("n", "<C-s>", ":set scrollbind! scrollbind?<CR>", { noremap = true, silent = true })Notification
P
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

Percolator answered 5/6, 2011 at 19:19 Comment(2)
Thanks for this, is great for any kind of toggle, not just number toggling.Revivalist
the new one way nmap <silent> <F11> :exec &nu==&rnu? "se nu!" : "se rnu!"<CR>Percolator
C
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)

Contra answered 18/4, 2009 at 0:50 Comment(2)
I've just used the second method you shared with us. It's the one i prefer, thank you :)Neumark
The second method is far more correct and easy than anything else here (so far). It should have been a separate and accepted answer.Steeplechase
L
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>
Lampoon answered 25/7, 2016 at 10:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.