Improving the "J" Command with a Key Map

Vim's built-in J command can be used to join the current line with the next line, which can be a very handy tool for keeping text "clean" when editing. Let's take a quick look at the default behavior. Starting from the following buffer, execute J:

Before Default
Line·one
Line·two
Line·three
NORMAL
Top
1:6
 
After Default
J
Line·one·Line·two
Line·three
NORMAL
Top
1:9
 

Note that the second line has merged with the first, but the cursor jumped after joining the lines, which is a bit disorienting. We would prefer to join lines without having the cursor move, so in this tip we will develop a simple keymap that achieved this. For comparison, here is a quick demo of the buffer before and after the improved keymap:

Before Improved
Line·one
Line·two
Line·three
NORMAL
Top
1:6
 
After Improved
<A-j>
Line·one·Line·two
Line·three
NORMAL
Top
1:6
 

Let's set this up, step by step. Since the default J moves the cursor, our goal is to have the cursor return to the original location, which we can achieve by setting a mark to record the cursor position before we execute J. We can use any lower-case letter, let's use z:

Set Mark
mz
Line·one
Line·two
Line·three
NORMAL
Top
1:6
 

Now that we have set the mark, execute the join by executing J:

Join Lines
J
Line·one·Line·two
Line·three
NORMAL
Top
1:9
 

As we saw before, the cursor jumped. Now, we simply jump back to the mark we previously set using `z:

Jump to Mark
`z
Line·one·Line·two
Line·three
NORMAL
Top
1:6
 

Now that we have compiled the steps required to get the behavior we want, let's combine the steps into the following keymap:

vim.keymap.set("n", "<A-j>", "mzJ`z")

Note that for demonstration purposes this mapping sets the alternate keymap to A-J. If you prefer this functionality over the default, then you can also override the default keymap directly by using J instead of <A-J>.