Created
October 7, 2020 09:01
-
-
Save henrebotha/65dd825f560b90f2450a55cc8c3fbe2e to your computer and use it in GitHub Desktop.
Example script for switching working directory in shell & Vim using Tmux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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