Join two lines in Vim without moving the cursor

Another approach that wouldn't stomp on marks would be this:

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

Much more verbose but it prevents you from losing a mark.

  • :nnoremap - Non-recursive map
  • <silent> - Do not echo anything when the mapping is pressed
  • J - Key to map
  • :let p=getpos('.') - Store cursor position
  • <bar> - Command separator (| for maps, see :help map_bar)
  • join - The ex command for normal's J
  • <bar> - ...
  • call setpos('.', p) - Restore cursor position
  • <cr> - Run the commands

You can do it like:

:nnoremap <F2> mbJ`b

This assigns the following actions to the F2 key:

  1. That is, create a mark (mb, but NOTE if you had set previously the b mark, than it gets overwritten!)
  2. Join the lines
  3. Jump back to the previous mark (`b)

Tags:

Vim