mercredi 18 février 2015

Getting started with tmux

Are you already familiar with gnu screen? tmux does the same but better. Its purpose is to manage a collection of pseudo terminal. Start multiple sessions, create multiple windows and split windows (a.k.a panes). Sessions can be detached, when you close your remote SSH connection and reattached when you reconnect. See what it look like:

Each tmux command can be mapped to a keyboard shortcut prefixed by C-b. Screen user can specify C-a in the configuration. Here are a few commands to get started.

Either type them in your shell, prompt for a command using C-b :, use a predefined or custom shortcut. The examples below show as often as possible what you can do with a tmux command or with a keyboard shortcut. For in depth information, read the man page: % man tmux

Get started with tmux sessions

  • This puts you in a tmux session named 0.
    % tmux
    
  • Detach the session using the command or hit C-b d and create another.
    % tmux detach
    [detached]
    % tmux
    
  • List sessions with:
    % tmux ls
    0: 1 windows (created Mon Feb 16 18:26:52 2015) [160x51]
    1: 1 windows (created Mon Feb 16 18:26:56 2015) [160x51] (attached)
    
  • Now rename the first session with:
    % tmux rename-session -t 0 mysession
    % tmux ls
    1: 1 windows (created Mon Feb 16 18:26:56 2015) [160x51] (attached)
    mysession: 1 windows (created Mon Feb 16 18:26:52 2015) [160x51]
    
  • Attach and detach your current session with C-b d and reattach / detach the first session.
    % tmux attach
    % tmux detach
    % tmux attach -t mysession
    
  • Kill a session with:
    % tmux kill-session -t mysession

Get started with tmux windows

  • Create 2 new windows using the command or hit C-b c.
    % tmux new-window
  • Rename the current window using the command or hit C-b ,.
    % tmux rename-window mywindow
  • Switch between windows can be done in many ways. Use the command or hit C-b 0 to switch to the 0 indexed window. Same goes for the Nth window.
    % tmux select-window -t 0
  • Cycle back and forth between windows: C-b n (next), C-b p (previous).
    % tmux next-window
    % tmux previous-window
    
  • To kill a window, either use a command, exit your shell or hit C-b &.
    % tmux kill-window -t 0

Get started with tmux panes

  • Split the window in a top and bottom panes C-b ".
    % tmux split-window
  • Split the window in a left and right panes C-b %.
    % tmux split-window -h
  • Split the window in a top and bottom panes and give a 20% height to the new bottom pane.
    % tmux split-window -p 20
  • To change the layout use a command or cycle through layouts with C-b Space (that's the space bar).
    % tmux select-layout main-horizontal
    % tmux next-layout
    
  • Get the pane numbers: C-b q.
    % tmux display-panes
  • To cycle through panes C-b o or use directional arrows C-b Up, C-b Right, C-b Down, C-b Left.
    % tmux select-pane -U
    % tmux select-pane -R
    % tmux select-pane -D
    % tmux select-pane -L
    
  • Kill panes: C-b x.
    % tmux kill-pane

Configuration

tmux's default configuration file is ~/.tmux.conf. Here's a self explanatory snapshot of mine. Don't worry about monitoring activity or content, I'll explain it later.

# Thanks to http://mutelight.org/practical-tmux
# and https://gist.github.com/anonymous/6bebae3eb9f7b972e6f0
# Changing the default prefix key
# because C-b is not acceptable, vim uses it
set-option -g prefix C-a
bind-key C-a last-window
bind-key a send-prefix

# Allows for faster key repetition
set-option -s escape-time 0

# Status bar
# Highlighting current window using specified colour
set-window-option -g window-status-current-bg red

# Monitor for content, useful to ne notified
# when a long process has finished.
# Lauch your command with:
# $ YOUR_COMMAND; echo '==== Process finished'
set-window-option -g monitor-content '==== Process finished'

# Background and foreground status bar colors
set-option -g status-bg black
set-option -g status-fg white

# Easy-to-remember split pane commands
bind-key | split-window -h
bind-key - split-window -v
unbind-key '"'
unbind-key %

# Moving between panes with vim movement keys
bind-key h select-pane -L
bind-key j select-pane -D
bind-key k select-pane -U
bind-key l select-pane -R

# Moving between windows with vim movement keys
bind-key -r C-h select-window -t :-
bind-key -r C-l select-window -t :+
# Thanks to http://mutelight.org/practical-tmux
# and https://gist.github.com/anonymous/6bebae3eb9f7b972e6f0
# Changing the default prefix key because C-b is not acceptable, vi uses it
set-option -g prefix C-a
bind-key C-a last-window
bind-key a send-prefix

# Conf reload made easy
unbind-key r
bind-key r source-file ~/.tmux.conf

# Allows for faster key repetition
set-option -s escape-time 0

# Raises the 2000 default limit
set-option -g history-limit 10000

# Status bar
# Highlighting current window using specified colour
set-window-option -g window-status-current-bg red

# Background and foreground status bar colors
set-option -g status-bg black
set-option -g status-fg white

# Monitor for content, useful to ne notified when a long process has finished.
# Lauch your command with: $ YOUR_COMMAND; echo '==== Process finished'
set-window-option -g monitor-content '==== Process finished'

# Easy-to-remember split pane commands
bind-key | split-window -h
bind-key - split-window -v
unbind-key '"'
unbind-key %

# vi friendly when in copy mode
set-option -g mode-keys vi
bind -t vi-copy 'v' begin-selection
bind -t vi-copy 'y' copy-selection

# Tmux configuration with this vim plugin:
# https://github.com/christoomey/vim-tmux-navigator
# Smart pane switching with awareness of vim splits
is_vim='echo "#{pane_current_command}" | grep -iqE "(^|\/)g?(view|n?vim?)(diff)?$"'
bind -n C-h if-shell "$is_vim" "send-keys C-h" "select-pane -L"
bind -n C-j if-shell "$is_vim" "send-keys C-j" "select-pane -D"
bind -n C-k if-shell "$is_vim" "send-keys C-k" "select-pane -U"
bind -n C-l if-shell "$is_vim" "send-keys C-l" "select-pane -R"
bind -n C-\ if-shell "$is_vim" "send-keys C-\\" "select-pane -l"

# Restoring Clear Screen
bind l send-keys 'C-l'

# Moving between windows with vi movement keys
bind-key -r C-h select-window -t :-
bind-key -r C-l select-window -t :+

SSH key forwarding

If you use an SSH forwarded key, your tmux session will loose its authentication socket when you reconnect. That means if your working with github and public/private SSH key pairs, you will be prompted for a password. All is explained here and see below for a shell function to the rescue. Put the following lines in you shell rc file like ~/.bashrc or ~/.zshrc

# Predictable SSH authentication socket location.
# http://qq.is/tutorial/2011/11/17/ssh-keys-through-screen.html
SOCK="/tmp/ssh-agent-$USER-screen"
if test $SSH_AUTH_SOCK && [ $SSH_AUTH_SOCK != $SOCK ]
then
    rm -f /tmp/ssh-agent-$USER-screen
    ln -sf $SSH_AUTH_SOCK $SOCK
    export SSH_AUTH_SOCK=$SOCK
fi

Scripting

Each time you create a new session you can use some tmux commands to create windows and panes for you. Lauching some frequently used commands can be useful too.

# Start vim in the first window
send-keys vi C-m

# Creates a new window and start logging files
new-window -a -n devlogs
send-keys 'tail -f /var/log/apache2/error.log' C-m

# Focus on the first window
select-window -t 0

Save this file in ~/.tmux/dev and source it with % tmux source-file ~/.tmux/dev

Project creation with tmuxinator

Scripting tmux can be tedious. Fortunately, there is tmuxinator. Describe your needs in a YAML file and tmuxinator generates the tmux scripting. Create a project with:

% tmuxinator new mywork

See one of my tmuxinator project file:

# ~/.tmuxinator/mywork.yml
name: mywork
root: ~/mywork

windows:
  - editor: vi
  - devlogs:
      # Can't set window activity in tmux.conf
      # as the window doesn't exist yet
      - tmux set-window-option -tmywork:devlogs monitor-activity on
      - tail -f /var/log/apache2/error.log
  - grunt:
      - grunt server

Then start or reattach your project with:

% tmuxinator start mywork

You can use the shorthand command mux which is aliased to tmuxinator.

Monitoring activity

Monitoring a window for activity can be useful for example when new logs appear. But by doing set-window-option -g monitor-activity on, you'll monitor every window. Prefer to monitor activity for a specified window: set-window-option -t 0 monitor-activity on

Monitoring inactivity

tmux can monitor inactivity or silence for a specified interval (see monitor-silence in the man page). If nothing happens for x seconds tmux will warn you. I find this not so useful. I prefer to be warned when a long process has finished. Hence, these configuration lines and the shell script below will help:

# Monitor for content, useful to ne notified
# when a long process has finished.
# Lauch your command with:
# $ YOUR_COMMAND; echo '==== Process finished'

set-window-option -g monitor-content '==== Process finished'

The monitored command can be run using a shell function, saving some keystrokes:

function monitorcmd()
{
    clear;
    eval $@
    echo '==== Process finished'
}

Then use % monitorcmd my-script.sh with arguments 42.

Working with tmux, vim and REPLs

From vim you can interact with any tmux pane. You want to stay in your editor When you need to execute some code in a REPL, you will want to stay in your editor. Writing code in an REPL has never been easy. Here I used the vim-slime plugin send text from vim to any tmux pane. If that pane runs a REPL, the selected code from your editor will be executed. This screenshot is worth many words:

There are many vim plugins to deal with tmux, here are two I'm aware of:
- tbone
- vimux

Also note there's a seemless vim splits and tmux pane navigation plugin and configuration you can find here: vim-tmux-navigator. It will allow you to use <C-h>, <C-j>, <C-k> and <C-l> for switching between vim windows as well as for tmux panes. The drawback is you can't use <C-l> for clearing the screen as it has been remapped. You can always bind the l key in tmux: bind l send-keys 'C-l'

I use a small vim functions to open and close a bottom pane taking 20% of the window's height:

" Prevents variable from being over written when sourcing ~/.vimrc
if exists('g:tmux_pane_open') == 0
  let g:tmux_pane_open = 0
endif

function! ToggleTmuxPane()
  if g:tmux_pane_open == 0
    call system('tmux split-window -v -p 20')
    let g:tmux_pane_open = 1
  else
    call system('tmux kill-pane -t 0.1')
    let g:tmux_pane_open = 0
  endif
endfunction

nnoremap <leader>to :call ToggleTmuxPane()

Scroll, copy and paste mode

Scroll mode

PageUp/PageDown won't work inside a tmux session, so I can scroll up when tailing a log file or see the output of a compilation? Use C-b [ to enter scroll mode then vi movements or PageUp/PageDown to go up and down.

Copy mode

First enter visual mode, by hitting the Space bar. Then use vi movements or arrows to extend the selection. Hit Enter to copy. If you're not happy with default key bindings, you can remap them to use v to enter visual and y to yank. See my tmux configuration.

Paste mode

Enter insert mode in a file you're editing with vim for example. Hit C-b ] to paste the content you previously copied.

Pair programing

If you allow users to connect to your machine, they will be able to attach a tmux session of yours. Again a screenshot is worth many words. Here two terminals are attach to the same tmux session:

Aucun commentaire: