Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two lines in Vim without moving the cursor

Tags:

vim

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

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

this is ^line one
this is line two

Merging by J produces:

this is line one ^this is line two

How can I produce:

this is ^line one this is line two

I have tried things like Ctrl + O and variations of ''. None of these seem to work. They go to the beginning of the line, not to the original cursor position.

like image 735
cledoux Avatar asked Feb 29 '12 19:02

cledoux


People also ask

How do I make multiple lines in one line in Vim?

When you want to merge two lines into one, position the cursor anywhere on the first line, and press J to join the two lines. J joins the line the cursor is on with the line below. Repeat the last command ( J ) with the . to join the next line with the current line.

How do I go down multiple lines in vim?

In normal mode or in insert mode, press Alt-j to move the current line down, or press Alt-k to move the current line up. After visually selecting a block of lines (for example, by pressing V then moving the cursor down), press Alt-j to move the whole block down, or press Alt-k to move the block up.

Which command joins next line to current line?

Joins consecutive lines. The J (join) command joins a specified number of lines together as one line. Number of consecutive lines, starting with the current line, to be joined to the current line.


2 Answers

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
like image 111
Randy Morris Avatar answered Nov 15 '22 10:11

Randy Morris


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)
like image 34
Zsolt Botykai Avatar answered Nov 15 '22 08:11

Zsolt Botykai