Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

editor

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.

like image 605
Zack Voase Avatar asked Nov 12 '12 13:11

Zack Voase


People also ask

How does Vscode show relative line numbers?

Open the settings via cmd + , (on macOS) or via Preferences > Settings . Then search for "line numbers", and you should find the needed setting in the "Text Editor" section called "Editor: Line Numbers".


1 Answers

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
like image 149
Ingo Karkat Avatar answered Oct 01 '22 10:10

Ingo Karkat