5

I am trying to make Alt-M in zsh attach to a tmux session.

Content of .zshrc:

tmux-open() {
  tmux attach
}
zle -N tmux-open
bindkey '^[m' tmux-open

When I press Alt-M, instead of attaching to the tmux session, I get:

open terminal failed: not a terminal

Calling tmux-open from the zsh prompt attaches to the tmux session. What is the problem with the key binding?

2 Answers2

1

This is caused by zsh purposely sestting stdin/out to /dev/null, see `man zlezsh:

User-defined widgets, being implemented as shell functions, can execute any normal shell command. They can also run other widgets (whether built-in or user-defined) using the zle builtin command. The standard input of the function is redirected from /dev/null to prevent external commands from unintentionally blocking ZLE by reading from the terminal, ...

A solution, as described here, is to restore the file descriptors back to /dev/tty:

tmux-open() {
    (
        exec </dev/tty
        exec <&1
        tmux attach
    )
}
Petr
  • 62,528
  • 13
  • 153
  • 317
0

A possible alternative is to make a keybinding that just types the command tmux attach:

bindkey -s '^[m' 'tmux attach\n'

That will work when the prompt is on an empty command line

Klas Mellbourn
  • 42,571
  • 24
  • 140
  • 158
  • This unfortunately becomes much more difficult when `tmux` is to be run as a part of a more complex function. – Petr Aug 15 '23 at 20:00