Skip to content

Instantly share code, notes, and snippets.

@shime
Forked from mislav/_readme.md
Last active December 18, 2015 01:49
Show Gist options
  • Save shime/5706445 to your computer and use it in GitHub Desktop.
Save shime/5706445 to your computer and use it in GitHub Desktop.

I use tmux splits (panes). Inside one of these panes there's a Vim process, and it has its own splits (windows).

In Vim I have key bindings C-h/j/k/l set to switch windows in the given direction. (Vim default mappings for windows switching are the same, but prefixed with C-W.) I'd like to use the same keystrokes for switching tmux panes.

An extra goal that I've solved with a dirty hack is to toggle between last active panes with C-\.

Here's how it should work:

  1. If I'm in "vim window 2", going in left (C-h) or down (C-j) direction should switch windows inside vim.
  2. However, if I'm in "vim window 3", going right (C-l) or down (C-j) should select the next tmux pane in that direction.

The solution

The solution has 3 parts:

  1. In ~/.tmux.conf, I bind the keys I want to execute a custom tmux-vim-select-pane command;
  2. tmux-vim-select-pane checks if the foreground process in the current tmux pane is Vim, then forwards the original keystroke to the vim process. Otherwise it simply switches tmux panes.
  3. In Vim, I set bindings for the same keystrokes to a custom function. The function tries to switch windows in the given direction. If the window didn't change, that means there are no more windows in the given direction inside vim, and it forwards the pane switching command to tmux by shelling out to tmux select-pane.

Installation

curl -fsSL https://gist.github.com/shime/5706445/raw/install.sh | bash -e
curl -fsSL https://gist.github.com/mislav/5189704/raw/tmux.conf \
>> ~/.tmux.conf
curl -fsSL https://raw.github.com/mislav/dotfiles/d0cc7f/bin/tmux-vim-select-pane \
-o /usr/local/bin/tmux-vim-select-pane
chmod +x /usr/local/bin/tmux-vim-select-pane
curl -fsSL https://raw.github.com/mislav/vimfiles/41bfa10/plugin/tmux_navigator.vim \
-o ~/.vim/plugin/tmux_navigator.vim --create-dirs
# Smart pane switching with awareness of vim splits
bind -n C-k run-shell 'tmux-vim-select-pane -U'
bind -n C-j run-shell 'tmux-vim-select-pane -D'
bind -n C-h run-shell 'tmux-vim-select-pane -L'
bind -n C-l run-shell 'tmux-vim-select-pane -R'
bind -n "C-\\" run-shell 'tmux-vim-select-pane -l'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment