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:
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:
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
:
Now that we have set the mark, execute the join by executing J:
As we saw before, the cursor jumped. Now, we simply jump back to the mark we previously set using `z:
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>
.