How to move lines around in Neovim
Use move command to move highlighted lines with auto-indentations
2 min read
One of my favorite hotkeys in VS Code is being able to move the current line/s 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.
The magic formula is 🎩🐇:
vim.keymap.set("v", "J", ":m '>+1<CR>gv=gv") vim.keymap.set("v", "K", ":m '<-2<CR>gv=gv")
This enables moving a selected block of text with the proper indentation for every line.
How does it work?
This snippet enables moving the current selection up and down using
shift+k while in Visual Mode.
vim.keymap.set- is a Neovim wrapper function for setting keymaps
v- specifies this remap should only work in Visual modes
shift+kas the trigger
:m- calls the move command it moves the current line up or down
'>+1- specifies moving one line after the end of the current selection
<CR>- applies a carriage return not completely sure about this one
gv=gv- reselect selected lines and apply any indents
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")