Prevent cursor moving up/down when TOC changes.

getpos()/setpos() combination does not account for changes of lines
count.  So if you do getpos, then remove lines _above_ it, then do
setpos -- it's going to be off.

The fix calculates the "diff", and adjusts saved position for that diff
(if any).
This commit is contained in:
Ivan Tishchenko 2015-11-27 03:05:39 +03:00
parent 8231433bad
commit d265df42f5

View File

@ -1144,6 +1144,10 @@ function! vimwiki#base#update_listing_in_buffer(strings, start_header,
endif endif
let old_cursor_pos = getpos('.') let old_cursor_pos = getpos('.')
let cursor_line = old_cursor_pos[1]
let is_cursor_after_listing = 0
let lines_diff = 0
if already_there if already_there
" delete the old listing " delete the old listing
@ -1152,9 +1156,19 @@ function! vimwiki#base#update_listing_in_buffer(strings, start_header,
while end_lnum <= line('$') && getline(end_lnum) =~# a:content_regex while end_lnum <= line('$') && getline(end_lnum) =~# a:content_regex
let end_lnum += 1 let end_lnum += 1
endwhile endwhile
let is_cursor_after_listing = ( cursor_line >= end_lnum )
" We'll be removing a range. But, apparently, if folds are enabled, Vim
" won't let you remove a range that overlaps with closed fold -- the entire
" fold gets deleted. So we temporarily disable folds, and then reenable
" them right back.
let foldenable_save = &l:foldenable
setlo nofoldenable
silent exe start_lnum.','.string(end_lnum - 1).'delete _' silent exe start_lnum.','.string(end_lnum - 1).'delete _'
let &l:foldenable = foldenable_save
let lines_diff = 0 - (end_lnum - start_lnum)
else else
let start_lnum = a:default_lnum let start_lnum = a:default_lnum
let is_cursor_after_listing = ( cursor_line > a:default_lnum )
let whitespaces_in_first_line = '' let whitespaces_in_first_line = ''
endif endif
@ -1164,6 +1178,7 @@ function! vimwiki#base#update_listing_in_buffer(strings, start_header,
\ '__Header__', '\='."'".a:start_header."'", '') \ '__Header__', '\='."'".a:start_header."'", '')
call append(start_lnum - 1, new_header) call append(start_lnum - 1, new_header)
let start_lnum += 1 let start_lnum += 1
let lines_diff += 1 + len(a:strings)
for string in a:strings for string in a:strings
call append(start_lnum - 1, string) call append(start_lnum - 1, string)
let start_lnum += 1 let start_lnum += 1
@ -1171,8 +1186,12 @@ function! vimwiki#base#update_listing_in_buffer(strings, start_header,
" append an empty line if there is not one " append an empty line if there is not one
if start_lnum <= line('$') && getline(start_lnum) !~# '\m^\s*$' if start_lnum <= line('$') && getline(start_lnum) !~# '\m^\s*$'
call append(start_lnum - 1, '') call append(start_lnum - 1, '')
let lines_diff += 1
endif endif
if is_cursor_after_listing
let old_cursor_pos[1] += lines_diff
endif
call setpos('.', old_cursor_pos) call setpos('.', old_cursor_pos)
endfunction "}}} endfunction "}}}