scatterd-dotfiles/bin/tat
Chris Toomey fa18537afd Update tat script to also work from within tmux
The existing script would fail if run from within tmux as the default
behavior would cause a nested tmux session which is bad. This update
detects if the current context is within tmux and properly handles this
by creating a detached session and switching to it as needed.

The idea with this is for tat to behave correctly regardless of context,
which I believe this update achieves. Existing users and workflows all
work identically, but now this adds support for a workflow that remains
within tmux at all times.

I prefer to remain within tmux all the time, rather than falling back to
the shell, navigating to another directory, and then creating the
session from there. With this update, I split a pane in the current tmux
window, navigate to the directory for the new session, and use `tat` to
open (or attach) to the new-session without ever leaving tmux.

I actually [have a binding that I use for this][], `C-b` (I am
"breaking" out a new session), that is mapped to `bind C-b send-keys
'tat && exit' 'C-m'`, which also cleans up the pane.

The reason for wanting this workflow is I am pretty strict about keeping
a tmux session focused to a single project (~ maps to a git repo). I
regularly want to reference another app and will use this workflow to
quickly open that project in a new session.

A "detached" session is one which has no clients attached. [From the man
page entry][] for `new-session`: `The new session is attached to the
current terminal unless -d is given.` This essentially creates it in the
background, preventing nesting. Then the script can attach the current
client using the `switch-client` command.

[have a binding that I use for this]: 01cc928672/tmux/tmux.conf (L89)
[From the man page entry]: http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux&sec=1
2014-12-09 13:06:49 -05:00

30 lines
584 B
Bash
Executable file

#!/bin/sh
#
# Attach or create tmux session named the same as current directory.
session_name="$(basename "$PWD" | tr . -)"
not_in_tmux() {
[ -z "$TMUX" ]
}
session_exists() {
tmux list-sessions | sed -E 's/:.*$//' | grep -q "^$session_name$"
}
create_detached_session() {
(TMUX='' tmux new-session -Ad -s "$session_name")
}
create_if_needed_and_attach() {
if not_in_tmux; then
tmux new-session -As "$session_name"
else
if ! session_exists; then
create_detached_session
fi
tmux switch-client -t "$session_name"
fi
}
create_if_needed_and_attach