Join two lines in vim without moving the cursor

How can I join two lines in vim and leave the cursor in its original position instead of going to the merge point?

For example, take the following two lines with the cursor at the position indicated by the carriage:

this is ^line one this is line two 

Merging with J causes:

 this is line one ^this is line two 

How can I create:

 this is ^line one this is line two 

I tried things like CTRL-O and options. '' None of this works. They go to the beginning of the line, and not to the starting position of the cursor.

+6
source share
3 answers

Another approach that would not stamp the markers would be the following:

 :nnoremap <silent> J :let p=getpos('.')<bar>join<bar>call setpos('.', p)<cr> 

Much more details, but this prevents you from losing the mark.

  • :nnoremap - non-recursive map
  • <silent> - Do not echo anything when you click on a display
  • J - Key to the map
  • :let p=getpos('.') - Save cursor position
  • <bar> - command separator ( | for maps, see :help map_bar )
  • join - ex command for regular J
  • <bar> -...
  • call setpos('.', p) - Restore cursor position
  • <cr> - Run the commands
+9
source

You can do it like:

 :nnoremap <F2> mbJ`b 

In this case, the F2 key assigns the following actions:

  • That is, create a label ( m b , but NOTE , if the b sign was previously set, how is it overwritten!)
  • J in rows
  • Return to previous mark ( ` b )
+4
source

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"') 
0
source

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


All Articles