How can I activate relative line numbering in (and only in) Vim's visual mode?

editor, vim

Solution

There are no such events for visual mode (yet implemented; you could submit a patch). For entering visual mode, you can simply override the few commands that enter visual mode:

:nnoremap <silent> v v:<C-u>set nonu rnu<CR>gv
:nnoremap <silent> V V:<C-u>set nonu rnu<CR>gv
:nnoremap <silent> <C-v> <C-v>:<C-u>set nonu rnu<CR>gv

The restore of `'number'` is more difficult, because apart from explicitly exiting via `<Esc>`, there are many commands that stop visual mode. Best I can come up with is a trigger on `CursorMoved`:

vnoremap <Esc> <Esc>:set nu<CR>
:autocmd CursorMoved * if mode() !~# "[vV\<C-v>]" | set nu | endif

Problem

I’m trying to get Vim to switch to relative line numbering when I enter visual mode, and back to absolute numbering afterwards. I've noticed there's `InsertEnter` and `InsertLeave` autocmd events, which I could use like this: ``` autocmd InsertEnter :set rnu autocmd InsertLeave :set nu ``` Problem is, I can’t seem to find an equivalent for visual mode.

Original source