A Perl script controls Tmux configuration

Magical Window

Article from Issue 152/2013
Author(s):

Instead of manually rearranging windows in a development environment time and time again, the Tmux terminal multiplexer can restore them from a configuration script.

If you don't use a development environment such as Eclipse but mostly rely on the command line in a terminal, you will certainly be familiar with screen. Among other things, this legacy terminal utility ensures that, after network problems, the initiator of an aborted SSH session can continue without problems exactly where they stopped typing. The screen utility sits between users and applications running in the terminal and tricks the application into believing that an attentive user is still at the keyboard, even if they have long since left the office for a weekend break.

As you know, the Unix world has not stood still over the past 20 years, and a relatively young project named Tmux [2] has been set up to improve and replace Screen. Like Screen, Tmux offers the user several sessions, which in turn comprise windows; in Screen lingo, this does not mean desktop windows, but switchable text interfaces in the same terminal window. Using keyboard shortcuts, Tmux can subdivide each window again by creating vertically or horizontally arranged panes, all of which are visible at the same time (Figure 1).

Figure 1: Two tmux commands divide the window into two horizontal panes, and then the right pane into two vertical panes.

Tmux runs on all major platforms. If you work on a Linux desktop but use a MacBook on the road, you will find the same windows and panes in both environments.

Servers and Clients

An automatically launched Tmux server keeps track of active sessions, and the user can remotely control them at the command line. The tmux command creates new sessions or closes them later, adds more windows or deletes them, integrates or removes panes, and scales panes up or down. For developer environments with multiple windows and panes, it makes sense to save the time-consuming configuration in a source code repository and display it again, when needed, with a single command.

Tmux can also launch applications in panes, for example, your favorite editor, which in turn loads a project file. Another pane could start the test suite, and a third could use tail to display the end of a log file.

Changes Desirable

A newly installed Tmux has some weird keyboard shortcuts. To make sure keystrokes are interpreted by the intermediate terminal multiplexer – and not by the applications running in a Tmux session, like the editor – you need to type what is known as a prefix. A vanilla Tmux installation uses Ctrl+B by default, a keyboard shortcut that not only causes repetitive strain injury with frequent use but also is a common Vi command, and thus a no-go.

Fortunately, Tmux lets you change everything, so experienced users will quickly put together their own .tmux.conf file after the install; my file is documented in my GitHub repository [3]. It is ultimately only based on general recommendations, such as setting a screen-compatible prefix with Ctrl+A and using vim-style combinations for the rest: H=left, J= down, K=up, L=right. This removes the need to enter Emacs-style text commands to toggle between panes; instead, you can use <Prefix> H to go to the left-hand panel.

Of course, customized shortcuts have a couple of drawbacks; for example, everyone speaks a different Tmux dialect and flaps around like a bug on its back in anyone else's environment. However, Tmux understands written commands, introduced with the <Prefix>: keyboard shortcut (prefix followed by a colon), which you type in the opening status line.

Tmux also understands the same commands at the shell prompt, meaning your own scripts for creating a window group can be used globally. For example, the Perl script in Listing 1 issues the

Listing 1

tmux-setup

01 #!/usr/local/bin/perl -w
02 #############################
03 # tmux-setup for log4perl
04 # Mike Schilli, 2013
05 # (m@perlmeister.com)
06 #############################
07 use strict;
08 use Sysadm::Install
09   qw( tap cd sysrun );
10 use Log::Log4perl qw(:easy);
11 use Getopt::Std;
12 sub tmux;  # declare function
13
14 my ($home) = glob "~";
15 my $session = "log4perl";
16
17 getopts "vk", \my %opts;
18
19 my $loglevel = $INFO;
20 $loglevel = $DEBUG
21   if $opts{v};
22
23 Log::Log4perl->easy_init(
24  $loglevel);
25
26 if ($opts{k}) {
27  tmux "kill-session", "-t",
28    $session;
29  exit 0;
30 }
31
32 tmux "source",
33   "$home/.tmux.conf";
34
35 if (0 == system "tmux",
36  "has-session",
37  "-t", $session)
38 {
39  DEBUG "Session $session ",
40   "already exists";
41 } else {
42  DEBUG "Creating session ",
43   $session";
44  tmux "new-session", "-s",
45    $session,
46    "-d";
47  tmux "split-window", "-h";
48  tmux "split-window", "-v";
49  tmux "send-keys", "-t",
50    "$session:0.0",
51    "vim -p `find . -name " .
52    "'*.pm' | head -2`",
53    "C-m";
54  tmux "send-keys", "-t",
55    "$session:0.1",
56    "perl Makefile.PL; " .
57      "make test",
58    "C-m";
59  tmux "send-keys", "-t",
60    "$session:0.2",
61    "vim t/*.t", "C-m";
62 }
63
64 tmux "attach", "-t",
65   $session;
66
67 #############################
68 sub tmux {
69 #############################
70  my ($stdout, $stderr, $rc)
71    = tap "tmux", @_;
72
73  return $rc;
74 }
tmux kill-session

command with the session name log4perl in line 27, if the user runs the script with the -k option. The command opens a connection to the Tmux server (if it is running), finds the session, and then winds it up.

Once Only

The -v (verbose) option tells Listing 1 to set the Log4perl configuration to the $DEBUG logging level; $INFO would mean far less talk. To avoid the need for the script to write out every single Tmux command, the tmux() function in lines 68-74 calls tmux via the shell. The tap() function from the CPAN Sysadm::Install module triggers this. Because I wanted to avoid having to use parentheses when calling tmux(), line 12 declares it as a function in the current namespace.

Line 32 calls source to parse the configuration file .tmux.conf from the user's home directory. Tmux should actually do this automatically, but the version I used didn't comply – this looks like a bug. Additionally, in line 36, it uses the tmux has-session command to discover whether the Tmux session to be established is already running and drops down to attach in line 64 if the session is running and the script only needs to join it.

If the session is unknown, the new-session command in line 44 creates a new session named log4perl. The session name refers to the Log4perl project in whose Git repository it acts as a developer environment. The -d (detach) parameter at the end of the Tmux command stipulates that the script should not immediately enter the session and display the GUI but wait patiently for the attach command in line 64 before showing the user anything.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Table of Contents: 152

    We look at SharePoint integration and show you how to manage Active Directory from Linux. But first, a special story on a dangerous new class of intrusion tools.

  • Perl: Q&A for the Web

    Catalyst is the Ruby on Rails of the Perl universe. When you are developing a web application like a quiz, using the MVC framework is really convenient and helps keep the underlying components cleanly separated.

  • Perl – Vagrant Package

    The Vagrant package provides easy management of virtual machines with VirtualBox as the hypervisor on the command line. Provisioning tools like Puppet let customers try out products in pre-installed environments.

  • Perl: Tricks with Vim

    The Vim editor has any number of tricks for helping you avoid unnecessary typing. In this month’s article, we look at some effort-saving Vim techniques for Perl hackers.

  • Perl: Perl Debugger

    The Perl interpreter, perl, doesn’t often crash, but if it happens, not even the excellent Perl debugger will be able to help you.

comments powered by Disqus

Direct Download

Read full article as PDF:

Price $2.95

News

njobs Europe
What:
Where:
Country:
Njobs Netherlands Njobs Deutschland Njobs United Kingdom Njobs Italia Njobs France Njobs Espana Njobs Poland
Njobs Austria Njobs Denmark Njobs Belgium Njobs Czech Republic Njobs Mexico Njobs India Njobs Colombia