Helper function that you can use for other porpuses
" Utility function that save last search and cursor position " http://technotales.wordpress.com/2010/03/31/preserve-a-vim-function-that-keeps-your-state/ " video from vimcasts.org: http://vimcasts.org/episodes/tidying-whitespace if !exists('*Preserve') function! Preserve(command) try " Preparation: save last search, and cursor position. let l:win_view = winsaveview() let l:old_query = getreg('/') silent! execute 'keepjumps ' . a:command finally " Clean up: restore previous search history, and cursor position call winrestview(l:win_view) call setreg('/', l:old_query) endtry endfunction endif
Here is a solution using the specified function, its advantage: it does not take any register
" join lines without moving the cursor (gJ prevent adding spaces between lines joined) nnoremap J :call Preserve("exec 'normal! J'")<cr> nnoremap gJ :call Preserve("exec 'normal! gJ'")<cr>
BTW: more than two examples of how you can use the Preserve function
"Remove extra spaces at the end of the line
fun! CleanExtraSpaces() call Preserve('%s/\s\+$//ge') endfun com! Cls :call CleanExtraSpaces() au! BufwritePre * :call CleanExtraSpaces()
"Full Reident File
call Preserve('exec "normal! gg=G"')
source share