vim – Stop cursor from moving when toggle line numbering

I’ve set up some options in my .vimrc so that it toggles to relative line numbering when in visual modes and switches back to absolute when hitting escape. The problem is every time I switch modes, it brings the cursor back to the first column. I am trying to stop this.

My original code is as follows and is inspired by this post.

So my code is

autocmd InsertEnter * :set norelativenumber
autocmd InsertLeave * :set relativenumber

function! SetLineNumbersVisual()
   set relativenumber
   return
endfunction

function! ResetLineNumbering()
   set norelativenumber
   return
endfunction

map <Esc> :call ResetLineNumbering()<CR>

vnoremap <silent> <expr> <SID>SetLineNumbersVisual SetLineNumbersVisual()
nnoremap <silent> <script> v v<SID>SetLineNumbersVisual
nnoremap <silent> <script> V V<SID>SetLineNumbersVisual
nnoremap <silent> <script> <C-v> <C-v><SID>SetLineNumbersVisual

augroup LineNumberSwap
   autocmd!
   autocmd InsertEnter * call ResetLineNumbering()
   autocmd InsertLeave * call ResetLineNumbering()
   autocmd CursorHold * call ResetLineNumbering()
augroup END

So that code swaps to relative when in any visual mode and then upon exiting brings it back to absolute. What is also does it constantly move the cursor back to the first column.

To fix this I tried determining the cursor position before setting the mode and then forcing the cursor to move back, but does this doesn’t seem to work.

function! SetLineNumbersVisual()
   let l:cur_pos = getpos(".")
   set relativenumber
   call cursor(l:cur_pos[1],l:cur_pos[2])
   return
endfunction

function! ResetLineNumbering()
   let l:cur_pos = getpos(".")
   set norelativenumber
   call cursor(l:cur_pos[1],l:cur_pos[2])
   return
endfunction

Isn’t fixing the problem though.

Facebook Comments

Loading...

(Visited 3 times, 1 visits today)