Skip to content

Instantly share code, notes, and snippets.

@jyurek
Last active February 12, 2024 10:37
Show Gist options
  • Save jyurek/7be666a88e06f68d45cf to your computer and use it in GitHub Desktop.
Save jyurek/7be666a88e06f68d45cf to your computer and use it in GitHub Desktop.
Create and switch sessions in tmux quickly
#!/bin/sh
tm() {
if [ -z $1 ]; then
tmux switch-client -l
else
if [ -z "$TMUX" ]; then
tmux new-session -As $1
else
if ! tmux has-session -t $1 2>/dev/null; then
TMUX= tmux new-session -ds $1
fi
tmux switch-client -t $1
fi
fi
}
tm $1
# tmux session tab complete function
_tmux_complete_session() {
local IFS=$'\n'
local cur=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( ${COMPREPLY[@]:-} $(compgen -W "$(tmux -q list-sessions | cut -f 1 -d ':')" -- "${cur}") )
}
complete -F _tmux_complete_session tm
# Toggle between the last two sessions
bind m switch-client -l
bind M command-prompt -p 'switch session:' "run \"tm '%%'\""
@calebhearth
Copy link

Zsh completion:

#compdef tm

_arguments "1: :(`tmux list-sessions -F'#S'`)"

# vim: filetype=zsh

Put that in a file called _tm somewhere in your fpath. I put mine in ~/.dotfiles/zsh/completions/_tm.

You'll need to run autoload -U compinit and compinit after _tm is added to your fpath in your .zshrc or wherever.

@calebhearth
Copy link

#!/bin/zsh

WORKING_DIRECTORY=$(cdpath=(. ~/code) cd $1 > /dev/null 2>&1 && pwd)
if [ -z "$TMUX" ]; then
  # not in tmux
  if [ -n "$WORKING_DIRECTORY" ]; then
    tmux new-session -As $1 -c $WORKING_DIRECTORY
  else
    tmux new-session -As $1 -c $HOME
  fi
else
  # inside tmux
  if tmux has-session -t $1 2> /dev/null; then
    tmux switch-client -t $1
  else
    if [ -n "$WORKING_DIRECTORY" ]; then
      TMUX= tmux new-session -ds $1 -c $WORKING_DIRECTORY
    else
      TMUX= tmux new-session -ds $1
    fi
    tmux switch-client -t $1
  fi
fi

Updated to automatically set the working directory (for the initial and successive windows) of new sessions to project folders, assuming that they live in ~/code. The cdpath portion of line 3 could be removed if you actually use cdpath.

No longer works with only sh.

@calebhearth
Copy link

Jon do you think it's time to move this to a project with a proper homebrew package and stuff?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment