Move lines around in Neovim

Last Updated: 2023-02-05


One of my favorite hotkeys in VS Code is being able to move the current line or lines around using:

[ Mac: ⌥ + ↑/↓ ] [ Windows: Alt + ↑/↓ ]

Now that I’ve switched over to neovim it’s one of those commands I keep missing. There are ways to get the same result in Vim using the basic motions but it is not intuitive nor easy to remember.

Fortunately, I was able to pick up a golden nugget from 0 to LSP: Neovim From Scratch by ThePrimeagen.

theprimeagen_screencap

The magic formula is 🎩🐇:

vim.keymap.set("v", "J", ":m '>+1<CR>gv=gv")
vim.keymap.set("v", "K", ":m '<-2<CR>gv=gv")

How does it work?

This snippet enables moving the current selection up and down using shift+j or shift+k while in Visual Mode.

To apply the same mapping in normal and insert modes use this:

vim.keymap.set("n", "J", ":m .+1<CR>==")
vim.keymap.set("n", "K", ":m .-2<CR>==")
vim.keymap.set("i", "J", ":m .+1<CR>==gi")
vim.keymap.set("i", "K", ":m .-2<CR>==gi")