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

I wrote a function to remove extra space in a file:

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

The problem is that the cursor position is set to [1, 1] after the substitution command. I do not want the cursor to move at all, so I tried to keep the cursor position and reset 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 same thing happens, as if the cursor call had no effect. Any ideas?

+6
source share
2 answers
  • :execute is for evaluating Ex commands, but cursor() is a built-in function. You must call it with :call cursor(a:cursor_pos[1], a:cursor_pos[2]) . In addition, you do not need :normal in your function to execute the command :substitute ; just write %s/\s\+$//e .
  • Here is the corresponding setpos() function, which is easier to :call setpos('.', a:cursor_pos)
  • Hops in the buffer can still change the view, i.e. what part of the buffer is visible. To avoid this, you need to use winsaveview() / winrestview() (including the cursor position).
  • Your function still captures the search history and has other disadvantages, such as the rejection of unmodifiable buffers. Especially for this specific, very general functionality, there are several solutions, for example, DeleteTrailingWhitespace plugin . (There are links to alternative plugins on the plugin page.) Don't use (badly) reinvent the wheel when you don't need it!
+8
source

Try ticking:

 mark ` %s/\s\+$//e normal `` 
+3
source

Source: https://habr.com/ru/post/957318/


All Articles