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.
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.
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.
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.
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 pressedJ
- 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 commandsYou can do it like:
:nnoremap <F2> mbJ`b
This assigns the following actions to the F2 key:
b
mark, than it gets overwritten!)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With