matatu blog

Brian writes about computing

Metaterm

Jan 31, 2019

Fun with tmux

The tmux, terminal multiplexer, like gnu screen, allows one to have multiple terminal sessions at once.

tmux    

If you split a window into panes, with ctrl-B (or with ctrl-A if you set it up that way) + " or tmux split-window, you can see two shell sessions at the same time.

tmux split-window    

The default vertical split puts a session on top and another on the bottom and a cute horizontal line in between, drawn with pretty line drawing characters.

$ echo 'top'
top
$
────────────────
$ echo 'bottom'
bottom
$    

A SUPER cute feature is the ability to send keys from one half to the other. Note that enter sends a "\n".

$ echo top
top
$
──────────────────────────────────────
$ tmux send-keys -t 0 'echo top' enter
$ █    

In fact, this is so cute that it could be made into a nice workflow -- type into one half and see the output in another half. The nice thing about this is that it will work even if the output is lengthy, or you are on a remote connection and want a history, or you are in some other console environment (docker, rails, python debugger session) and want to be able to keep track of what you are sending.

$ pwd
/home/bduggan
$ date
Thu Jan 31 21:23:14 EST 2019
$ echo 123
123 
──────────────────────────────────────
> pwd
> date
> echo 123
> █    

Let's write a little program to implement this.

#!/usr/bin/env perl6

loop {
    my $str = prompt '> ' or last;
    run <<tmux send-keys -t 0 -l "$str">>;
    run <<tmux send-keys -t 0 enter>>;
}    

Let's try it out!

 $ echo 'how now brown cow'
 how now brown cow
 $ echo "a b c"
 a b c
 $ seq 2 5
 2
 3
 4
 5
 $

 ──────────────────────────────────────
 > echo 'how now brown cow'
 > echo "a b c"
 > seq 2 5
 > ^D
 $ █    

Conclusions

  • tmux can help with making a meta-terminal -- letting you send commands from somewhere else.
  • run in Perl 6 is a handy way to spawn a command.
  • << and >> is an interpolating word-quoting construct that works with strings enclosed in quotation marks.
  • prompt returns a falsey value when it receives an end-of-file indicator.
  • Further work

  • Adding macros, history, and custom commands is left as an exercise to the reader.
  • Tying this to other tmux commands (like capturing output)
  • Spawning searching commands like fzf
  • What else?