Treewalker is a plugin that gives you the ability to move around your code in a syntax tree aware manner. It uses Treesitter under the hood for syntax tree awareness. It offers six subcommands: Up, Down, Right, and Left for movement, and SwapUp and SwapDown for intelligent node swapping.
Each movement command moves you through the syntax tree in an intuitive way.
- Up/Down - Moves up or down to the next neighbor node
- Right - Finds the next good child node
- Left - Finds the next good parent node
The swap commands intelligently swap nodes, including comments and attributes/decorators.
{
"aaronik/treewalker.nvim",
opts = {
highlight = true, -- Whether to briefly highlight the node after jumping to it
highlight_duration = 250, -- How long should above highlight last (in ms)
}
}
This is how I have mine mapped; in init.lua
:
vim.keymap.set({ 'n', 'v' }, '<C-k>', '<cmd>Treewalker Up<cr>', { noremap = true, silent = true })
vim.keymap.set({ 'n', 'v' }, '<C-j>', '<cmd>Treewalker Down<cr>', { noremap = true, silent = true })
vim.keymap.set({ 'n', 'v' }, '<C-l>', '<cmd>Treewalker Right<cr>', { noremap = true, silent = true })
vim.keymap.set({ 'n', 'v' }, '<C-h>', '<cmd>Treewalker Left<cr>', { noremap = true, silent = true })
vim.keymap.set('n', '<C-S-j>', '<cmd>Treewalker SwapDown<cr>', { noremap = true, silent = true })
vim.keymap.set('n', '<C-S-k>', '<cmd>Treewalker SwapUp<cr>', { noremap = true, silent = true })
I also utilize some
nvim-treesitter-textobjects
commands to round out the swap commands - <C-S-{j,k,l,h}>
just feel really good to me, so might as well get the
lateral swapping as well. (This is not something that Treewalker
needs to do as it already exists from other libraries)
vim.keymap.set('n', "<C-S-l>", ":TSTextobjectSwapNext @parameter.inner<CR>", { noremap = true, silent = true })
vim.keymap.set('n', "<C-S-h>", ":TSTextobjectSwapPrevious @parameter.inner<CR>", { noremap = true, silent = true })
The above can also be accomplished with nvim-treesitter using ts_utils. See this PR for an example of that!