#!/bin/sh -e
#
# tmux-vim-select-pane - send `<C-h/j/k/l>` keystroke if vim is running in pane
#
# for use in tmux config:
#
#   # put this in `~/.config/tmux/tmux.conf`
#   # smart pane switching with awareness of vim splits
#   bind -n C-k run-shell    '#{d:config_files}/bin/tmux-vim-select-pane -U'
#   bind -n C-j run-shell    '#{d:config_files}/bin/tmux-vim-select-pane -D'
#   bind -n C-h run-shell    '#{d:config_files}/bin/tmux-vim-select-pane -L'
#   bind -n C-l run-shell    '#{d:config_files}/bin/tmux-vim-select-pane -R'
#   bind -n "C-\\" run-shell '#{d:config_files}/bin/tmux-vim-select-pane -l'
#
# ---
# see: https://gist.github.com/mislav/5189704
# source: https://github.com/mislav/dotfiles/blob/master/bin/tmux-vim-select-pane

cmd="$(tmux display -p '#{pane_current_command}')"
cmd="$(basename "${cmd}" | tr '[:upper:]' '[:lower:]')"
pane_count="$(tmux list-panes | wc -l)"

if [ "${cmd%m}" = "vi" ] || [ "${pane_count}" -eq 1 ]; then
  direction="$(echo "${1#-}" | tr 'lLDUR' '\\hjkl')"
  # forward the keystroke to vim
  tmux send-keys "C-${direction}"
else
  tmux select-pane "$@"
fi

# # gets the tty of active tmux pane
# active_tty="$(tmux list-panes -F '#{pane_active}#{pane_tty}' | grep '^1')"
# # checks if there's a foreground vim process in attached to that tty
# if ps c -o 'state=,command=' -t "${active_tty#1}" \
#   | grep '+' | grep -iE '\bvim?\b' >/dev/null; then
#   direction="$(
#     echo "${1#-}" | sed -e 's/D/Down/' -e 's/U/Up/' -e 's/L/Left/' -e 's/R/Right/'
#   )"
#   # forward the keystroke to vim
#   tmux send-keys C-"${direction}"
# else
#   tmux select-pane "$@"
# fi
