Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save the current cursor position and load it later in Vimscript?

Tags:

vim

I've written a function for removing the excess white space in a file:

let g:trim_whitespace = 1

function! TrimWhitespace()
    if g:trim_whitespace
        normal :%s/\s\+$//e
    endif
endfunction

The issue is that the cursor position is set to [1, 1] after the substitution command. I don't want the cursor to move at all, so I tried to save the cursor position and reset it after the substitute command:

let a:cursor_pos = getpos(".")
normal :%s/\s\+$//e
exec cursor(a:cursor_pos[1], a:cursor_pos[2])

But still the exact same thing happens, as if the call to cursor had no effect. Any ideas?

like image 475
Hubro Avatar asked Nov 04 '13 06:11

Hubro


1 Answers

Try placing a mark:

mark `
%s/\s\+$//e
normal ``
like image 61
romainl Avatar answered Sep 20 '22 11:09

romainl