Skip to content

Instantly share code, notes, and snippets.

@henrebotha
Created October 7, 2020 09:01
Show Gist options
  • Save henrebotha/65dd825f560b90f2450a55cc8c3fbe2e to your computer and use it in GitHub Desktop.
Save henrebotha/65dd825f560b90f2450a55cc8c3fbe2e to your computer and use it in GitHub Desktop.
Example script for switching working directory in shell & Vim using Tmux
#! /usr/bin/env zsh
# Call this script as ./dir-switch.zsh /desired/directory
set -e
trap 'echo ERROR at $0 $LINENO; return' ERR
active_window=$(tmux list-windows | rg '\(active\)' | sed 's/:.\+//g')
panes=("${(@f)$(tmux list-panes -F '#{pane_index}')}")
active_pane=$(tmux list-panes -F '#{pane_active} #{pane_index}' | rg '^1' | sed 's/^1 //g')
pane=$active_pane
destination=$1
pane_pid=$(tmux list-panes -F '#{pane_index} #{pane_pid}' | rg "^$pane" | sed 's/^.\+ //g')
vim_running=$(ps ar -o cmd= -o stat= --ppid "$pane_pid" | rg '\+' | rg '^vim' || echo '')
if [ -n "$vim_running" ]; then
# Send Esc then ^C, in case we have some half-typed command
tmux send-keys -t $pane 'Escape'
tmux send-keys -t $pane 'C-c'
tmux send-keys -t $pane -l ":cd $destination"
tmux send-keys -t $pane 'Enter'
fi
# We need to not only exclude zsh, but also the ps command itself.
process_running=$(ps ar -o cmd= -o stat= --ppid "$pane_pid" | rg '\+' | rg -v '(zsh|ps ar)' || echo '')
if [ -n "$process_running" ]; then
tmux send-keys -t $pane 'C-z'
sleep 0.1
fi
tmux send-keys -t $pane -l "cd $destination"
tmux send-keys -t $pane 'Enter'
if [ -n "$process_running" ]; then
tmux send-keys -t $pane -l 'fg'
tmux send-keys -t $pane 'Enter'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment