Skip to content

Instantly share code, notes, and snippets.

@Kipparis
Last active January 12, 2024 15:14
Show Gist options
  • Save Kipparis/2954ff2fa24a4592828724a851f1d0f2 to your computer and use it in GitHub Desktop.
Save Kipparis/2954ff2fa24a4592828724a851f1d0f2 to your computer and use it in GitHub Desktop.
tmux aware nvim pane navigation
" tmux aware navigation
lua << EOF
function pane_switch(direction)
local vim_hotkeys = { up = "k", down = "j", left = "h", right = "l", }
local tmux_hotkeys = { up = "U", down = "D", left = "L", right = "R", }
local before_switch_winnr = vim.fn.winnr()
vim.api.nvim_feedkeys(
vim.api.nvim_replace_termcodes("<C-w>"..vim_hotkeys[direction], true, false, true),
'nx', -- without `x` mode winnr will return same value for before/after
false
)
local after_switch_winnr = vim.fn.winnr()
-- run tmux command only when needed
if (before_switch_winnr == after_switch_winnr) and (vim.fn.exists('$TMUX') == 1) then
local obj = vim.system(
{'tmux', 'select-pane', '-'..tmux_hotkeys[direction]},
{ text = true }
):wait() -- Run synchronously
end
end
-- create this mappings and function with autocommands
-- :h lua-guide-autocommand-create
-- :h lua-guide-autocommands-group
vim.keymap.set('n', '<C-j>', function() pane_switch('down') end,
{ desc = 'Tmux-aware switch pane to bottom' })
vim.keymap.set('n', '<C-k>', function() pane_switch('up') end,
{ desc = 'Tmux-aware switch pane to up' })
vim.keymap.set('n', '<C-h>', function() pane_switch('left') end,
{ desc = 'Tmux-aware switch pane to left' })
vim.keymap.set('n', '<C-l>', function() pane_switch('right') end,
{ desc = 'Tmux-aware switch pane to right' })
EOF
@Kipparis
Copy link
Author

Kipparis commented Jan 12, 2024

Created this gist, for several reasons (in order of their priority to me):

  1. wanted to simplify my setup and make it more configurable. pane switching is not something you'd like to install with packages. (as a more funny case, I remember javascript package which tells if number is negative
    1. source plugin which I tried to simplify is too robust for this simple task. my 15 lines of code against 140 lines of source code.
  2. get experience with lua in vim

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment