Skip to content

Instantly share code, notes, and snippets.

@docwhat
Created June 22, 2012 15:29
Show Gist options
  • Save docwhat/2973488 to your computer and use it in GitHub Desktop.
Save docwhat/2973488 to your computer and use it in GitHub Desktop.
Wrapper function to save your cursor and window positions and your last search.
" Re-indents buffer.
nmap <silent> <Leader>g :call Preserve("normal gg=G")<CR>
" Removes all trailing whitespace in buffer.
nmap <silent> <Leader><space> :call Preserve("%s/\\s\\+$//e")<CR>
" A wrapper function to restore the cursor position, window position,
" and last search after running a command.
function! Preserve(command)
" Save the last search
let last_search=@/
" Save the current cursor position
let save_cursor = getpos(".")
" Save the window position
normal H
let save_window = getpos(".")
call setpos('.', save_cursor)
" Do the business:
execute a:command
" Restore the last_search
let @/=last_search
" Restore the window position
call setpos('.', save_window)
normal zt
" Restore the cursor position
call setpos('.', save_cursor)
endfunction
@raine
Copy link

raine commented May 7, 2014

Nice one. Any idea how to use within the command?

@docwhat
Copy link
Author

docwhat commented Mar 16, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment