10

I know these commands in Vim:

J : Join line below after current line
-J : Join current line after line above

but how do I join the line above after current line?

Reman
  • 7,931
  • 11
  • 55
  • 97

3 Answers3

7

You can also use the ex-command

:m-2|j
  • m-2 has the effect of moving the current line to 2 lines above its current position; this switches the position of the current line and the line above.
  • j joins the current line and the line above, inserting a space between the two. Use j! if you don't want the space.
  • | separates the 2 ex-commands

This ex-command is a short way of writing the following

:move .-2
:join  
doubleDown
  • 8,048
  • 1
  • 32
  • 48
1

There are many ways to do it. One would be… deleting the line above and appending it to the end of the line below:

k move up one line
^ move to the first printable character
y$ yank to the end of the line
"_d get rid of the now useless line by deleting it into the black hole register
$ move to the end of the line
p put the deleted text
romainl
  • 186,200
  • 21
  • 280
  • 313
  • 1
    It would be easier to first swap the lines and then `J`oin them (as [@WilliamPursell suggests](http://stackoverflow.com/questions/13609736/how-do-i-join-the-line-above-after-current-line#comment18659642_13609736)). – bitmask Nov 28 '12 at 16:46
  • Yes I know. I went for a "litteral" approach. I'd go with William Pursell's method too, actually. – romainl Nov 28 '12 at 17:10
  • Note that `J` does handle spaces differently from a verbatim join. That is, if one wants the results that would be produced by `J`, `k^d$k$p` would do something different! – bitmask Nov 28 '12 at 17:13
  • In my experience, `J`'s added space is almost always a problem. When I write text it's cool but it sucks when I join HTML tags. I tend to use `:j!` instead. – romainl Nov 28 '12 at 17:21
  • Thanks William and romainl! Swapping? When I've read about swapping in your messages I've found another solution. :m .-2 | :normal J – Reman Nov 28 '12 at 17:30
  • `gJ` does `J` without the space. – Dan Fitch Nov 28 '12 at 19:18
0

I added the below lines to my .vimrc. Now, in normal mode, I can either press @j or < leader >j. Leader for me is space. I've also seen people set it to ,.

" join with previous line with @j
let @j="kJ"
nnoremap <leader>j @j

If you haven't set leader yet, you can set it to space like this:

let mapleader = " "
let g:mapleader = " "
sathishvj
  • 1,394
  • 2
  • 17
  • 28
  • Why not skip the reg step and just `nnoremap j kJ`? Note this is the same as OPs `-J` in the question. – D. Ben Knoble Aug 09 '19 at 17:21
  • I used the register so that I could do a count at the beginning. 5kJ translates incorrectly to 5k and J which will join 2 lines that are 5 lines above the current one. Whereas 5@j will translate correctly to joining the previous 5 lines. – sathishvj Aug 30 '19 at 11:57