Difference between revisions of "Tmux"

From ArchWiki
Jump to: navigation, search
(Tips and tricks)
(flagged broken section links (interactive))
(Tag: wiki-scripts)
 
(142 intermediate revisions by 65 users not shown)
Line 1: Line 1:
 +
[[Category:Terminal emulators]]
 
[[es:Tmux]]
 
[[es:Tmux]]
 +
[[ja:Tmux]]
 
[[ru:Tmux]]
 
[[ru:Tmux]]
 
[[tr:Tmux]]
 
[[tr:Tmux]]
[[Category:Terminal emulators]]
+
[[zh-CN:Tmux]]
{{Article summary start}}
+
{{Related articles start}}
{{Article summary text|This article explains how to install and configure tmux.}}
+
{{Related|GNU Screen}}
{{Article summary heading|Related}}
+
{{Related articles end}}
{{Article summary wiki|GNU Screen}}
+
{{Article summary end}}
+
[http://tmux.sourceforge.net/ Tmux] is a "terminal multiplexer: it enables a number of terminals (or windows), each running a separate program, to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached."
+
  
Tmux is notable as a BSD-licensed alternative to [[Screen Tips|GNU Screen]]. Although similar, there are many differences between the programs, as noted on the [http://tmux.svn.sourceforge.net/viewvc/tmux/trunk/FAQ tmux FAQ page]. Most notably, tmux is currently under active development, in contrast to screen, which has not had a stable release since August 8, 2008.
+
[http://tmux.github.io/ Tmux] is a "terminal multiplexer: it enables a number of terminals (or windows), each running a separate program, to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached."
  
==Installation==
+
Tmux is a BSD-licensed alternative to [[GNU Screen]]. Although similar, there are many differences between the programs, as noted on the [https://raw.githubusercontent.com/tmux/tmux/master/FAQ tmux FAQ page].
[[pacman|Install]] {{Pkg|tmux}}, available in the [[Official Repositories]].
+
  
==Configuration==
+
== Installation ==
 +
[[Install]] the {{Pkg|tmux}} package.
 +
Optionally, install {{Aur|tmux-bash-completion}} to provide bash completion functions for tmux.
 +
 
 +
== Configuration ==
 
A user-specific configuration file should be located at {{ic|~/.tmux.conf}}, while a global configuration file should be located at {{ic|/etc/tmux.conf}}. Default configuration files can be found in {{Ic|/usr/share/tmux/}}.  
 
A user-specific configuration file should be located at {{ic|~/.tmux.conf}}, while a global configuration file should be located at {{ic|/etc/tmux.conf}}. Default configuration files can be found in {{Ic|/usr/share/tmux/}}.  
  
===Key bindings===
+
=== Key bindings ===
{| style="float:right;border:1px #cccccc solid;margin:5px;padding:5px;width:200px;"
+
|+ ''Prefix all commands with'' {{Ic|Ctrl-b}}
+
!Cmd
+
!Action
+
|-
+
|c
+
|Create a new window
+
|-
+
|n
+
|Change to next window
+
|-
+
|p
+
|Change to previous window
+
|-
+
|"
+
|Split pane horizontally
+
|-
+
|%
+
|Split pane vertically
+
|-
+
|,
+
|Rename current window
+
|-
+
|o
+
|Move to next pane
+
|}
+
  
By default, command key bindings are prefixed by Ctrl-b. For example, to vertically split a window type {{Ic|Ctrl-b %}}.
+
By default, command key bindings are prefixed by {{Ic|Ctrl-b}}. For example, to vertically split a window type {{Ic|Ctrl-b+%}}.
  
After splitting a window into multiple panes, you can resize a pane by the hitting prefix key (i.e. {{Ic|Ctrl-b}}) and, while continuing to hold Ctrl, press Left/Right/Up/Down. Swapping panes is achieved in the same manner, but by hitting ''o'' instead of a directional key.
+
After splitting a window into multiple panes, a pane can be resized by the hitting prefix key (e.g. {{Ic|Ctrl-b}}) and, while continuing to hold Ctrl, press Left/Right/Up/Down. Swapping panes is achieved in the same manner, but by hitting ''o'' instead of a directional key.
  
{{Tip|To mimic screen key bindings copy {{ic|/usr/share/tmux/screen-keys.conf}} to either of the configuration locations.}}
+
{{Tip|To mimic [[screen]] key bindings copy {{ic|/usr/share/tmux/screen-keys.conf}} to either of the configuration locations.}}
 +
 
 +
Key bindings may be changed with the bind and unbind commands in {{ic|tmux.conf}}. For example, the default prefix binding of {{Ic|Ctrl-b}} can be changed to {{Ic|Ctrl-a}} by adding the following commands in your configuration file:
  
Key bindings may be changed with the bind and unbind commands in {{ic|tmux.conf}}. For example, you can change the prefix key (i.e. {{Ic|Ctrl-b}}) to {{Ic|Ctrl-a}} by adding the following commands in your configuration file:
 
 
{{bc|
 
{{bc|
 
unbind C-b
 
unbind C-b
 
set -g prefix C-a
 
set -g prefix C-a
 +
bind C-a send-prefix
 
}}
 
}}
  
Additional ways to move between windows include:
+
{{Tip|Quote special characters to use them as prefix. You may also use {{ic|Alt}} (called Meta) instead of {{ic|Ctrl}}. For example: {{ic|set -g prefix m-'\'}}}}
 +
 
 +
Additional ways to move between windows include the following:
 +
 
 
  Ctrl-b l (Move to the previously selected window)
 
  Ctrl-b l (Move to the previously selected window)
 
  Ctrl-b w (List all windows / window numbers)
 
  Ctrl-b w (List all windows / window numbers)
Line 64: Line 45:
 
  Ctrl-b q  (Show pane numbers, when the numbers show up type the key to goto that pane)
 
  Ctrl-b q  (Show pane numbers, when the numbers show up type the key to goto that pane)
  
What if you have 10+ windows open? Tmux has a find-window option & keybinding.
+
Tmux has a find-window option & key binding to ease navigation of many windows:
 +
 
 
  Ctrl-b f <window name> (Search for window name)
 
  Ctrl-b f <window name> (Search for window name)
 
  Ctrl-b w (Select from interactive list of windows)
 
  Ctrl-b w (Select from interactive list of windows)
  
===Browsing URL's===
+
==== Copy Mode ====
To browse URL's inside tmux you must have {{aur|urlview}} installed and configured.
+
 
 +
A tmux window may be in one of several modes. The default permits direct access to the terminal attached to the window; the other is copy mode. Once in copy mode you can navigate the buffer including scrolling the history. Use vi or emacs-style key bindings in copy mode. The default is emacs, unless VISUAL or EDITOR contains ‘vi’
 +
 
 +
To enter copy mode do the following:
 +
 +
Ctrl-b [
 +
 
 +
You can navigate the buffer as you would in your default editor.
 +
 
 +
To quit copy mode, use one of the following keybindings:
 +
 
 +
vi mode:
 +
q
 +
emacs mode:
 +
Esc
 +
 
 +
=== Browsing URLs ===
 +
To browse URLs inside tmux you must have {{AUR|urlview}} installed and configured.
  
 
Inside a new terminal:
 
Inside a new terminal:
Line 77: Line 76:
 
  bind-key u capture-pane \; save-buffer /tmp/tmux-buffer \; new-window -n "urlview" '$SHELL -c "urlview < /tmp/tmux-buffer"'
 
  bind-key u capture-pane \; save-buffer /tmp/tmux-buffer \; new-window -n "urlview" '$SHELL -c "urlview < /tmp/tmux-buffer"'
  
=== Setting the correct term===
+
=== Setting the correct term ===
If you are using a 256 colour terminal, you will need to set the correct term in tmux. You can do this in either the {{ic|tmux.conf}}:
+
==== 256 colors ====
 +
If you are using a 256 colour terminal, you will need to set the correct term in tmux. As of [https://raw.githubusercontent.com/tmux/tmux/master/CHANGES tmux 2.1], this is now ''tmux''. You can do this in {{ic|tmux.conf}}:
  
  set -g default-terminal "screen-256color"  
+
  set -g default-terminal "tmux"  
  
or in your {{ic|.bashrc}} with a test like:
+
Other, older alternatives, include ''screen'', or ''screen-256color'':
  
  # for tmux: export 256color
+
  set -g default-terminal "screen-256color"
  [ -n "$TMUX" ] && export TERM=screen-256color
+
 
 +
Also, if tmux messes up, you can force tmux to assume that the terminal support 256 colors, by adding this in your .bashrc:
 +
 
 +
  alias tmux="tmux -2"
 +
 
 +
==== 24-bit color ====
 +
Tmux supports 24-bit color as of version 2.2 ([https://github.com/tmux/tmux/commit/427b8204268af5548d09b830e101c59daa095df9]). If your terminal supports 24-bit color (see this [https://gist.github.com/XVilka/8346728 gist]), add your terminal to the {{ic|terminal-overrides}} setting. For example, if you use [[Termite]], you would add:
 +
 
 +
set -ga terminal-overrides ",xterm-termite:Tc"
 +
 
 +
For other terminals, replace {{ic|xterm-termite}} with the relevant terminal type (stored in {{ic|$TERM}}). See the tmux(1) man page for details about the {{ic|Tc}} terminfo extension.
 +
 
 +
==== xterm-keys ====
 +
To enable xterm-keys in your {{ic|tmux.conf}}, you have to add the following line
 +
 
 +
set-option -g xterm-keys on
  
 
If you enable xterm-keys in your {{ic|tmux.conf}}, then you need to build a custom terminfo to declare the new escape codes or applications will not know about them. Compile the following with {{ic|tic}} and you can use "xterm-screen-256color" as your TERM:
 
If you enable xterm-keys in your {{ic|tmux.conf}}, then you need to build a custom terminfo to declare the new escape codes or applications will not know about them. Compile the following with {{ic|tic}} and you can use "xterm-screen-256color" as your TERM:
Line 107: Line 122:
  
 
=== Other Settings ===
 
=== Other Settings ===
Set scrollback to 10000 lines with
+
To limit the scrollback buffer to 10000 lines:
 
  set -g history-limit 10000
 
  set -g history-limit 10000
  
==Session initialization==
+
Terminal emulator settings can be overridden with
 +
set -ga terminal-overrides ',xterm*:smcup@:rmcup@'
 +
set -ga terminal-override ',rxvt-uni*:XT:Ms=\E]52;%p1%s;%p2%s\007'
 +
 
 +
Mouse can be toggled with
 +
bind-key m set-option -g mouse on \; display 'Mouse: ON'
 +
bind-key M set-option -g mouse off \; display 'Mouse: OFF'
 +
 
 +
=== Autostart with systemd ===
 +
 
 +
There are some notable advantages to starting a tmux server at startup.
 +
Notably, when you start a new tmux session, having the service already running reduces any delays in the startup.
 +
 
 +
Furthermore, any customization attached to your tmux session will be retained and your tmux session can be made to persist even if you have never logged in, if you have some reason to do that (like a heavily scripted tmux configuration or shared user tmux sessions).
 +
 
 +
The service below starts ''tmux'' for the specified user (i.e. start with {{ic|tmux@''username''.service}}):
 +
 
 +
{{hc|/etc/systemd/system/tmux@.service|<nowiki>
 +
[Unit]
 +
Description=Start tmux in detached session
 +
 
 +
[Service]
 +
Type=forking
 +
User=%I
 +
ExecStart=/usr/bin/tmux new-session -s %u -d
 +
ExecStop=/usr/bin/tmux kill-session -t %u
 +
 
 +
[Install]
 +
WantedBy=multi-user.target
 +
</nowiki>}}
 +
 
 +
{{Tip|You may want to add {{ic|1=WorkingDirectory=''custom_path''}} to customize working directory.}}
 +
 
 +
Alternatively, you can place this file within your [[systemd/User]] directory (without {{ic|1=User=%I}}), for example {{ic|~/.config/systemd/user/tmux.service}}. This way the tmux service will start when you log in, unless you also enable [[systemd/User#Automatic start-up of systemd user instances]].
 +
 
 +
== Session initialization ==
 
You can have tmux open a session with preloaded windows by including those details in your {{ic|~/.tmux.conf}}:
 
You can have tmux open a session with preloaded windows by including those details in your {{ic|~/.tmux.conf}}:
  
Line 135: Line 185:
 
  bind B source-file ~/.tmux/bar
 
  bind B source-file ~/.tmux/bar
  
==Troubleshooting==
+
== Troubleshooting ==
===Scrolling issues===
+
If you have issues scrolling with Shift-PageUp/Shift-PageDown in your terminal, try this:
+
  
set -g terminal-overrides 'xterm*:smcup@:rmcup@'
+
=== Scrolling issues ===
  
=== shift-f6 not working in midnight commander ===
+
If you have issues scrolling with Shift-Page Up/Down in your terminal, the following will remove the smcup and rmcup capabilities for any term that reports itself as anything beginning with {{ic|xterm}}:
  
If this key combination is not working with either TERM=screen or screen-256color, then from inside tmux, do
+
set -ga terminal-overrides ',xterm*:smcup@:rmcup@'
infocmp > screen (or screen-256color)
+
  
open the file in a text editor, and add the following to the bottom of that file:
+
This tricks the terminal emulator into thinking Tmux is a full screen application like pico or mutt[http://superuser.com/questions/310251/use-terminal-scrollbar-with-tmux], which will make the scrollback be recorded properly. Beware however, it will get a bit messed up when switching between windows/panes. Consider using Tmux's native scrollback instead.
kf16=\E[29~,
+
  
Then compile the file with {{ic|tic}}. The keys should be working now.
+
=== Mouse scrolling ===
  
==ICCCM Selection Integration==
+
{{Note|This interferes with selection buffer copying and pasting. To copy/paste to/from the selection buffer hold the shift key.}}
It is possible to copy a tmux paste buffer to an ICCCM selection, and vice-versa, by defining a shell command which interfaces tmux with an X11 selection interface. The following tmux config file snippet effectively integrates {{Ic|CLIPBOARD}} with the current tmux paste buffer using xclip:
+
 
 +
If you want to scroll with your mouse wheel, ensure mode-mouse is on in .tmux.conf
 +
set -g mouse on
 +
 
 +
You can set scroll History with:
 +
set -g history-limit 30000
 +
 
 +
For mouse wheel scrolling as from tmux 2.1 try adding one or both of these to ~/.tmux.conf
 +
    bind -T root WheelUpPane  if-shell -F -t = "#{alternate_on}" "send-keys -M" "select-pane -t =; copy-mode -e; send-keys -M"
 +
    bind -T root WheelDownPane if-shell -F -t = "#{alternate_on}" "send-keys -M" "select-pane -t =; send-keys -M"
 +
 
 +
Though the above will only scroll one line at a time, add this solution to scroll an entire page instead
 +
    bind -t vi-copy    WheelUpPane  page-up
 +
    bind -t vi-copy    WheelDownPane page-down
 +
    bind -t emacs-copy WheelUpPane  page-up
 +
    bind -t emacs-copy WheelDownPane page-down
 +
 
 +
=== Terminal emulator does not support UTF-8 mouse events ===
 +
 
 +
When the terminal emulator does not support the UTF-8 mouse events and the {{ic|mouse on}} tmux option is set, left-clicking inside the terminal window might paste strings like {{ic|[M#}} or {{ic|[Ma}} into the promt.
 +
 
 +
To solve this issue set:
 +
 
 +
set -g mouse-utf8 off
 +
 
 +
=== Shift+F6 not working in Midnight Commander ===
 +
 
 +
See [[Midnight Commander#Shift+F6 not working]].
 +
 
 +
== X clipboard integration ==
 +
 
 +
{{Tip|The tmux plugin [https://github.com/tmux-plugins/tmux-yank tmux-yank] provides similar functionality.}}
 +
 
 +
It is possible to copy tmux selection to X clipboard (and to X primary/secondary selection) and in reverse direction. The following tmux config file snippet effectively integrates X clipboard/selection with the current tmux selection using the program {{Pkg|xsel}}:
 +
 
 +
# Emacs style
 +
bind-key -t emacs-copy M-w copy-pipe "xsel -i -p -b"
 +
bind-key C-y run "xsel -o | tmux load-buffer - ; tmux paste-buffer"
 +
 
 +
# Vim style
 +
bind-key -t vi-copy y copy-pipe "xsel -i -p -b"
 +
bind-key p run "xsel -o | tmux load-buffer - ; tmux paste-buffer"
 +
 
 +
{{pkg|xclip}} could also be used for that purpose, unlike xsel it works better on printing raw bitstream that doesn't fit the current locale.  Nevertheless, it is neater to use <code>xsel</code> instead of <code>xclip</code>, because xclip does not close STDOUT after it has read from tmux's buffer.  As such, tmux doesn't know that the copy task has completed, and continues to wait for xclip's termination, thereby rendering tmux unresponsive.  A workaround is to redirect <code>STDOUT</code> of <code>xclip</code> to <code>/dev/null</code>, like in the following:
 +
 
 +
# Vim style
 +
bind-key -t vi-copy y copy-pipe "xclip -i -sel clip > /dev/null"
 +
bind-key p run "xclip -o -sel clip | tmux load-buffer -"
 +
 
 +
=== Urxvt middle click ===
 +
 
 +
{{Note|To use this, you need to enable mouse support}}
 +
 
 +
There is an unofficial perl extension (mentioned in the official [http://sourceforge.net/p/tmux/tmux-code/ci/master/tree/FAQ FAQ]) to enable copying/pasting in and out of urxvt with tmux via Middle Mouse Clicking.
 +
 
 +
First, you will need to download the perl script and place it into urxvts perl lib:
 +
 
 +
{{bc|wget http://anti.teamidiot.de/static/nei/*/Code/urxvt/osc-xterm-clipboard
 +
mv osc-xterm-clipboard /usr/lib/urxvt/perl/|
 +
}}
 +
 
 +
You will also need to enable that perl script in your .Xdefaults:
 +
 
 +
{{hc|~/.Xdefaults|
 +
...
 +
*URxvt.perl-ext-common: osc-xterm-clipboard
 +
...
 +
}}
 +
 
 +
Next, you want to tell tmux about the new function and enable mouse support (if you haven't already):
  
 
{{hc|~/.tmux.conf|
 
{{hc|~/.tmux.conf|
 
...
 
...
##CLIPBOARD selection integration
+
set-option -ga terminal-override ',rxvt-uni*:XT:Ms<nowiki>=</nowiki>\E]52;%p1%s;%p2%s\007'
##Requires prefix key before the command key
+
set -g mouse on
#Copy tmux paste buffer to CLIPBOARD
+
...
bind C-c run "tmux show-buffer <nowiki>|</nowiki> xclip -i -selection clipboard"
+
#Copy CLIPBOARD to tmux paste buffer and paste tmux paste buffer
+
bind C-v run "tmux set-buffer -- \"$(xclip -o -selection clipboard)\"; tmux paste-buffer"
+
 
}}
 
}}
  
If you get an output similar to {{ic| \346\227\245\346\234\254\350\252\236\343\201\247 }} when pasting utf-8 characters, try changing this line:
+
That's it. Be sure to end all instances of tmux before trying the new MiddleClick functionality.
{{bc|bind C-c run "tmux show-buffer <nowiki>|</nowiki> xclip -i -selection clipboard"}}
+
to this:
+
{{bc|bind C-p run "tmux save-buffer - <nowiki>|</nowiki> xclip -i -selection clipboard"}}
+
  
==Tips and tricks==
+
While in tmux, Shift+MiddleMouseClick will paste the clipboard selection while just MiddleMouseClick will paste your tmux buffer.
 +
Outside of tmux, just use MiddleMouseClick to paste your tmux buffer and your standard Ctrl-c to copy.
 +
 
 +
== Tips and tricks ==
 +
=== Start tmux with default session layout ===
 +
To setup your default Tmux session layout, you install {{AUR|tmuxinator}} from [[AUR]]. Test your installation with
 +
 
 +
tmuxinator doctor
 +
 
 +
==== Get the default layout values ====
 +
Start Tmux as usual and configure your windows and panes layout as you like. When finished, get the current layout values by executing (while you are still within the current Tmux session)
 +
 
 +
tmux list-windows
 +
 
 +
The output may look like this (two windows with 3 panes and 2 panes layout)
 +
 
 +
0: default* (3 panes) [274x83] [layout 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}] @2 (active)
 +
1: remote- (2 panes) [274x83] [layout e3d3,274x83,0,0[274x41,0,0,4,274x41,0,42,7]] @3                                       
 +
 
 +
The Interesting part you need to copy for later use begins after '''[layout...''' and excludes '''... ] @2 (active)'''. For the first window layout you need to copy e.g. '''20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}'''
 +
 
 +
==== Define the default tmux layout ====
 +
 
 +
Knowing this, you can exit the current tmux session. Following this, you create your default Tmux session layout by editing Tmuxinator's config file (Don't copy the example, get your layout values as described above)
 +
 
 +
{{hc|~/.tmuxinator/default.yml|<nowiki>
 +
name: default
 +
root: ~/
 +
windows:
 +
  - default:
 +
      layout: 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}
 +
      panes:
 +
        - clear
 +
        - vim
 +
        - clear && emacs -nw
 +
  - remote:
 +
      layout: 24ab,274x83,0,0{137x83,0,0,3,136x83,138,0,4}
 +
      panes:
 +
        -
 +
        -
 +
</nowiki>}}
 +
 
 +
The example defines two windows named "default" and "remote". With your determined layout values. For each pane you have to use at least one {{ic|-}} line. Within the first window panes you start the commandline "clear" in pane one, "vim" in pane two and "clear && emacs -nw" executes two commands in pane three on each Tmux start. The second window layout has two panes without defining any start commmands.
 +
 
 +
Test the new default layout with (yes, it is "mux"):
 +
 
 +
mux default
 +
 
 +
==== Autostart tmux with default tmux layout ====
 +
 
 +
If you like to start your terminal session with your default Tmux session layout edit
 +
{{hc|~/.bashrc|<nowiki>
 +
if [ -z "$TMUX" ]; then
 +
  mux default         
 +
fi                   
 +
</nowiki>}}
 +
 
 +
====Alternate approach for default session====
 +
Instead of using the above method, one can just write a bash script that when run, will create the default session and attach to it.
 +
Then you can execute it from a terminal to get the pre-designed configuration in that terminal
 +
 
 +
#!/bin/bash
 +
tmux new-session -d -n WindowName Command
 +
tmux new-window -n NewWindowName
 +
tmux split-window -v
 +
tmux selectp -t 1
 +
tmux split-window -h
 +
tmux selectw -t 1
 +
tmux -2 attach-session -d
  
 
===Start tmux in urxvt===
 
===Start tmux in urxvt===
Line 175: Line 352:
 
{{bc|<nowiki>urxvt -e bash -c "tmux -q has-session && exec tmux attach-session -d || exec tmux new-session -n$USER -s$USER@$HOSTNAME"</nowiki>}}
 
{{bc|<nowiki>urxvt -e bash -c "tmux -q has-session && exec tmux attach-session -d || exec tmux new-session -n$USER -s$USER@$HOSTNAME"</nowiki>}}
  
===Start tmux on every shell login===
+
=== Start tmux on every shell login ===
  
Simply add the following line of bash code to your .bashrc before your aliases; the code for other shells is very similar:
+
==== Bash ====
{{bc|<nowiki>[[ $TERM != "screen" ]] && exec tmux</nowiki>}}
+
 
 +
For bash, simply add the following line of bash code to your .bashrc before your aliases; the code for other shells is very similar:
  
 
{{hc|~/.bashrc|<nowiki>
 
{{hc|~/.bashrc|<nowiki>
 
# If not running interactively, do not do anything
 
# If not running interactively, do not do anything
 
[[ $- != *i* ]] && return
 
[[ $- != *i* ]] && return
[[ $TERM != screen* ]] && exec tmux</nowiki>}}
+
[[ -z "$TMUX" ]] && exec tmux
 +
</nowiki>}}
  
{{note|At first you may read screen as if we were using screen and not tmux, but tmux also uses screen for the TERM enviroment variable.}}
+
{{note|This snippet ensures that tmux is not launched inside of itself (something tmux usually already checks for anyway). tmux sets $TMUX to the socket it is using whenever it runs, so if $TMUX isn't set or is length 0, we know we aren't already running tmux.}}
  
And this snippet start only one session(unless you start some manually), on login, try attach at first, only create a session if no tmux is running.
+
Add the following snippet to start only one session (unless you start some manually), on login, try attach at first, only create a session if no tmux is running.
 
    
 
    
{{bc|<nowiki># TMUX
+
{{bc|<nowiki>
if which tmux 2>&1 >/dev/null; then
+
# TMUX
 +
if which tmux >/dev/null 2>&1; then
 
     #if not inside a tmux session, and if no session is started, start a new session
 
     #if not inside a tmux session, and if no session is started, start a new session
 
     test -z "$TMUX" && (tmux attach || tmux new-session)
 
     test -z "$TMUX" && (tmux attach || tmux new-session)
fi</nowiki>}}
+
fi
 +
</nowiki>}}
  
This snippet does the same thing, but also checks tmux is installed before trying to launch it. It also tries to reattach you to an existing tmux session at logout, so that you can shut down every tmux session quickly from the same terminal at logout.
+
The following snippet does the same thing, but also checks tmux is installed before trying to launch it. It also tries to reattach you to an existing tmux session at logout, so that you can shut down every tmux session quickly from the same terminal at logout.
{{bc|<nowiki># TMUX
+
{{bc|<nowiki>
if which tmux 2>&1 >/dev/null; then
+
# TMUX
 +
if which tmux >/dev/null 2>&1; then
 
     # if no session is started, start a new session
 
     # if no session is started, start a new session
 
     test -z ${TMUX} && tmux
 
     test -z ${TMUX} && tmux
Line 205: Line 387:
 
         tmux attach || break
 
         tmux attach || break
 
     done
 
     done
fi</nowiki>}}
+
fi
 +
</nowiki>}}
 +
 
 +
Another possibility is to try to attach to existing deattached session or start a new session:
 +
 
 +
{{bc|<nowiki>
 +
if [[ -z "$TMUX" ]] ;then
 +
    ID="`tmux ls | grep -vm1 attached | cut -d: -f1`" # get the id of a deattached session
 +
    if [[ -z "$ID" ]] ;then # if not available create a new one
 +
        tmux new-session
 +
    else
 +
        tmux attach-session -t "$ID" # if available attach to it
 +
    fi
 +
fi
 +
</nowiki>}}
 +
 
 +
==== Fish ====
 +
 
 +
{{Move|Fish}}
 +
 
 +
To start tmux on every shell login with fish, use the following:
 +
 
 +
{{hc|~/.config/fish/config.fish|<nowiki>
 +
# If not running interactively, do not do anything
 +
if status --is-interactive
 +
    if test -z (echo $TMUX)
 +
        tmux
 +
    end
 +
end
 +
</nowiki>}}
 +
 
 +
Alternatively, to start only one tmux session, or try to attach to another session on launch:
 +
{{hc|~/.config/fish/config.fish|<nowiki>
 +
if status --is-interactive
 +
    if test -z (echo $TMUX)
 +
        if not test (tmux attach)
 +
            tmux new-session
 +
        end
 +
    end
 +
end
 +
</nowiki>}}
 +
 
 +
{{note|Instead of using the shell config file, you can launch tmux when you start your terminal emulator. (i. e. urxvt -e tmux)}}
 +
 
 +
=== Start a non-login shell ===
 +
 
 +
Tmux starts a [http://unix.stackexchange.com/questions/38175 login shell] [http://comments.gmane.org/gmane.comp.terminal-emulators.tmux.user/5997 by default], which may result in multiple negative side effects:
 +
 
 +
* Users of [[Wikipedia:fortune (Unix)|fortune]] may notice that quotes are printed when creating a new panel.
 +
* The configuration files for login shells such as {{ic|~/.profile}} are interpreted each time a new panel is created, so commands intended to be run on session initialization (e.g. setting audio level) are executed.
 +
 
 +
To disable this behaviour, add to {{ic|~/.tmux.conf}}:
  
{{note|Instead of using the bashrc file, you can launch tmux when you start your terminal emulator. (i. e. urxvt -e tmux)}}
+
set -g default-command "${SHELL}"
  
===Use tmux windows like tabs===
+
=== Use tmux windows like tabs ===
  
The following settings added to {{ic|~/.tmux.conf}} allow to use tmux windows like tabs, such as those provided by the reference of these hotkeys — [[rxvt-unicode#urxvtq_with_tabbing|urxvt's tabbing extensions]]. An advantage thereof is that these virtual “tabs” are independent of the terminal emulator.
+
The following settings added to {{ic|~/.tmux.conf}} allow to use tmux windows like tabs, such as those provided by the reference of these hotkeys — [[rxvt-unicode#urxvtq_with_tabbing|urxvt's tabbing extensions]]{{Broken section link}}. An advantage thereof is that these virtual “tabs” are independent of the terminal emulator.
  
 
  #urxvt tab like window switching (-n: no prior escape seq)
 
  #urxvt tab like window switching (-n: no prior escape seq)
Line 222: Line 455:
 
Of course, those should not overlap with other applications' hotkeys, such as the terminal's. Given that they substitute terminal tabbing that might as well be deactivated, though.
 
Of course, those should not overlap with other applications' hotkeys, such as the terminal's. Given that they substitute terminal tabbing that might as well be deactivated, though.
  
It can also come handy to supplement the EOT hotkey {{Keypress|Ctrl}}+{{Keypress|d}} with one for tmux's detach:
+
It can also come handy to supplement the EOT hotkey {{ic|Ctrl+d}} with one for tmux's detach:
  
 
  bind-key -n C-j detach
 
  bind-key -n C-j detach
  
===Clients simultaneously interacting with various windows of a session===
+
=== Clients simultaneously interacting with various windows of a session ===
  
In [http://mutelight.org/articles/practical-tmux Practical Tmux], Brandur Leach writes:
+
In [http://mutelight.org/articles/practical-tmux Practical Tmux], Brandur Leach writes:
  
{{Box||Screen and tmux's behaviour for when multiple clients are attached to one session differs slightly. In Screen, each client can be connected to the session but view different windows within it, but in tmux, all clients connected to one session must view the same window.
+
: Screen and tmux's behaviour for when multiple clients are attached to one session differs slightly. In Screen, each client can be connected to the session but view different windows within it, but in tmux, all clients connected to one session must view the same window.
 
+
: This problem can be solved in tmux by spawning two separate sessions and synchronizing the second one to the windows of the first, then pointing a second new session to the first.
This problem can be solved in tmux by spawning two separate sessions and synchronizing the second one to the windows of the first, then pointing a second new session to the first.}}
+
  
 
The script “{{Ic|tmx}}” below implements this — the version here is slightly modified to execute “{{Ic|tmux new-window}}” if “1” is its second parameter. Invoked as {{Ic|tmx <base session name> [1]}} it launches the base session if necessary. Otherwise a new “client” session linked to the base, optionally add a new window and attach, setting it to kill itself once it turns “zombie”.
 
The script “{{Ic|tmx}}” below implements this — the version here is slightly modified to execute “{{Ic|tmux new-window}}” if “1” is its second parameter. Invoked as {{Ic|tmx <base session name> [1]}} it launches the base session if necessary. Otherwise a new “client” session linked to the base, optionally add a new window and attach, setting it to kill itself once it turns “zombie”.
Line 271: Line 503:
 
     if [[ -z "$TMUX" ]]; then
 
     if [[ -z "$TMUX" ]]; then
 
         echo "Launching copy of base session $base_session ..."
 
         echo "Launching copy of base session $base_session ..."
         # Session is is date and time to prevent conflict
+
         # Session id is date and time to prevent conflict
 
         session_id=`date +%Y%m%d%H%M%S`
 
         session_id=`date +%Y%m%d%H%M%S`
 
         # Create a new session (without attaching it) and link to base session  
 
         # Create a new session (without attaching it) and link to base session  
Line 292: Line 524:
 
added to {{ic|~/.tmux.conf}}. It causes tmux to resize a window based on the smallest client actually viewing it, not on the smallest one attached to the entire session.
 
added to {{ic|~/.tmux.conf}}. It causes tmux to resize a window based on the smallest client actually viewing it, not on the smallest one attached to the entire session.
  
An alternative taken from [http://sourceforge.net/mailarchive/forum.php?thread_name=CAPBqLKEC0MAFR%2BWUYqCuyd%3DKB47HK8CFSuAf%3Dd%3DW2H3F4fpMZw%40mail.gmail.com&forum_name=tmux-users] is to put the following ~/.bashrc:
+
An alternative taken from [http://comments.gmane.org/gmane.comp.terminal-emulators.tmux.user/2632] is to put the following ~/.bashrc:
  
 
{{hc|.bashrc|2=<nowiki>
 
{{hc|.bashrc|2=<nowiki>
Line 307: Line 539:
  
 
Citing the author:
 
Citing the author:
{{Box||"mksc foo" creates a always detached permanent client named "foo". It also
 
calls "rsc foo" to create a client to newly created session. "rsc foo"
 
creates a new client grouped by "foo" name. It has destroy-unattached
 
turned on so when I leave it, it kills client.
 
  
Therefore, when my computer looses network connectivity, all
+
: "mksc foo" creates a always detached permanent client named "foo". It also calls "rsc foo" to create a client to newly created session. "rsc foo" creates a new client grouped by "foo" name. It has destroy-unattached turned on so when I leave it, it kills client.
"foo.something" clients are killed while "foo" remains. I can then call
+
: Therefore, when my computer looses network connectivity, all "foo.something" clients are killed while "foo" remains. I can then call "rsc foo" to continue work from where I stopped.
"rsc foo" to continue work from where I stopped.}}
+
  
===Changing the configuration with tmux started===
+
=== Correct the TERM variable according to terminal type ===
 +
Instead of [[#Setting_the_correct_term|setting a fixed TERM variable in tmux]], it is possible to set the proper TERM (either {{ic|screen}} or {{ic|screen-256color}}) according to the type of your terminal emulator:
 +
 
 +
{{hc|~/.tmux.conf|
 +
## set the default TERM
 +
set -g default-terminal screen
 +
 
 +
## update the TERM variable of terminal emulator when creating a new session or attaching a existing session
 +
set -g update-environment 'DISPLAY SSH_ASKPASS SSH_AGENT_PID SSH_CONNECTION WINDOWID XAUTHORITY TERM'
 +
## determine if we should enable 256-colour support
 +
if "[[ ${TERM} =~ 256color || ${TERM} == fbterm ]]" 'set -g default-terminal screen-256color'
 +
}}
 +
 
 +
{{hc|1=~/.zshrc|2=
 +
## workaround for handling TERM variable in multiple tmux sessions properly from http://sourceforge.net/p/tmux/mailman/message/32751663/ by Nicholas Marriott
 +
if [[ -n ${TMUX} && -n ${commands[tmux]} ]];then
 +
        case $(tmux showenv TERM 2>/dev/null) in
 +
                *256color) ;&
 +
                TERM=fbterm)
 +
                        TERM=screen-256color ;;
 +
                *)
 +
                        TERM=screen
 +
        esac
 +
fi
 +
}}
 +
 
 +
=== Reload an updated configuration without restarting tmux ===
  
 
By default tmux reads {{ic|~/.tmux.conf}} only if it was not already running. To have tmux load a configuration file afterwards, execute:
 
By default tmux reads {{ic|~/.tmux.conf}} only if it was not already running. To have tmux load a configuration file afterwards, execute:
Line 347: Line 600:
 
A derived version to run ''irssi'' with the ''nicklist'' plugin can be found on [[Irssi#irssi_with_nicklist_in_tmux|its ArchWiki page]].
 
A derived version to run ''irssi'' with the ''nicklist'' plugin can be found on [[Irssi#irssi_with_nicklist_in_tmux|its ArchWiki page]].
  
===Terminal emulator window titles===
+
=== Terminal emulator window titles ===
 
If you SSH into a host in a tmux window, you'll notice the window title of your terminal emulator remains to be {{ic|user@localhost}} rather than {{ic|user@server}}. To allow the title bar to adapt to whatever host you connect to, set the following in {{ic|~/.tmux.conf}}
 
If you SSH into a host in a tmux window, you'll notice the window title of your terminal emulator remains to be {{ic|user@localhost}} rather than {{ic|user@server}}. To allow the title bar to adapt to whatever host you connect to, set the following in {{ic|~/.tmux.conf}}
  
Line 353: Line 606:
 
  set -g set-titles-string "#T"
 
  set -g set-titles-string "#T"
  
For {{ic|set-titles-string}}, {{ic|#T}} will display {{ic|user@host:~}} and change accordingly as you connect to different hosts. You can also set many more options here.
+
For {{ic|set-titles-string}}, {{ic|#T}} will display {{ic|user@host:~}} and change accordingly as you connect to different hosts.
 +
 
 +
=== Automatic layouting ===
 +
When creating new splits or destroying older ones the currently selected layout isn't applied. To fix that, add following binds which will apply the currently selected layout to new or remaining panes:
 +
 
 +
bind-key -n M-c kill-pane \; select-layout
 +
bind-key -n M-n split-window \; select-layout
 +
 
 +
=== Vim friendly configuration ===
 +
 
 +
See [https://gist.github.com/anonymous/6bebae3eb9f7b972e6f0] for a configuration friendly to [[vim]] users.
  
 
== See also ==
 
== See also ==
* [http://mutelight.org/articles/practical-tmux Practical Tmux] by Brandur Leach, providing a number of configuration tips
 
* [http://www.openbsd.org/faq/faq7.html#tmux Tmux tutorial] section from the OpenBSD FAQ
 
* [http://www.dayid.org/os/notes/tm.html Screen and tmux feature comparison] page by Dayid Alan
 
* [http://blog.hawkhost.com/2010/06/28/tmux-the-terminal-multiplexer/ Tmux tutorial Part 1] & [http://blog.hawkhost.com/2010/07/02/tmux-%E2%80%93-the-terminal-multiplexer-part-2  Part 2] blog posts on Hawk Host
 
* [https://raw.github.com/kooothor/Dotfiles/master/.tmux.conf tmux.conf] example with CPU bar and shortcut to search man pages and display them vertically
 
  
'''Forum threads'''
+
* [https://bbs.archlinux.org/viewtopic.php?id=84157&p=1 BBS topic]
* 2009-11-06 - Arch Linux - [https://bbs.archlinux.org/viewtopic.php?id=84157&p=1 Anyone loving Tmux in place of Screen? Info/Tips etc. URLs I've found]
+
* [http://www.dayid.org/os/notes/tm.html Screen and tmux feature comparison]
 +
* [https://github.com/Lokaltog/powerline powerline], a dynamic statusbar for tmux
 +
* [https://github.com/tmux-plugins Plugins for tmux]
 +
 
 +
'''Tutorials'''
 +
 
 +
* [http://mutelight.org/articles/practical-tmux Practical Tmux]
 +
* [http://www.openbsd.org/faq/faq7.html#tmux Tmux FAQ (OpenBSD)]
 +
* [http://www.openbsd.org/cgi-bin/man.cgi?query=tmux man page (OpenBSD)]
 +
* [http://blog.hawkhost.com/2010/06/28/tmux-the-terminal-multiplexer/ Tmux tutorial Part 1] and [http://blog.hawkhost.com/2010/07/02/tmux-%E2%80%93-the-terminal-multiplexer-part-2 Part 2]

Latest revision as of 10:57, 7 August 2016

Related articles

Tmux is a "terminal multiplexer: it enables a number of terminals (or windows), each running a separate program, to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached."

Tmux is a BSD-licensed alternative to GNU Screen. Although similar, there are many differences between the programs, as noted on the tmux FAQ page.

Installation

Install the tmux package. Optionally, install tmux-bash-completionAUR to provide bash completion functions for tmux.

Configuration

A user-specific configuration file should be located at ~/.tmux.conf, while a global configuration file should be located at /etc/tmux.conf. Default configuration files can be found in /usr/share/tmux/.

Key bindings

By default, command key bindings are prefixed by Ctrl-b. For example, to vertically split a window type Ctrl-b+%.

After splitting a window into multiple panes, a pane can be resized by the hitting prefix key (e.g. Ctrl-b) and, while continuing to hold Ctrl, press Left/Right/Up/Down. Swapping panes is achieved in the same manner, but by hitting o instead of a directional key.

Tip: To mimic screen key bindings copy /usr/share/tmux/screen-keys.conf to either of the configuration locations.

Key bindings may be changed with the bind and unbind commands in tmux.conf. For example, the default prefix binding of Ctrl-b can be changed to Ctrl-a by adding the following commands in your configuration file:

unbind C-b
set -g prefix C-a
bind C-a send-prefix
Tip: Quote special characters to use them as prefix. You may also use Alt (called Meta) instead of Ctrl. For example: set -g prefix m-'\'

Additional ways to move between windows include the following:

Ctrl-b l (Move to the previously selected window)
Ctrl-b w (List all windows / window numbers)
Ctrl-b <window number> (Move to the specified window number, the default bindings are from 0 – 9)
Ctrl-b q  (Show pane numbers, when the numbers show up type the key to goto that pane)

Tmux has a find-window option & key binding to ease navigation of many windows:

Ctrl-b f <window name> (Search for window name)
Ctrl-b w (Select from interactive list of windows)

Copy Mode

A tmux window may be in one of several modes. The default permits direct access to the terminal attached to the window; the other is copy mode. Once in copy mode you can navigate the buffer including scrolling the history. Use vi or emacs-style key bindings in copy mode. The default is emacs, unless VISUAL or EDITOR contains ‘vi’

To enter copy mode do the following:

Ctrl-b [

You can navigate the buffer as you would in your default editor.

To quit copy mode, use one of the following keybindings:

vi mode:

q

emacs mode:

Esc

Browsing URLs

To browse URLs inside tmux you must have urlviewAUR installed and configured.

Inside a new terminal:

bind-key u capture-pane \; save-buffer /tmp/tmux-buffer \; run-shell "$TERMINAL -e urlview /tmp/tmux-buffer"

Or inside a new tmux window (no new terminal needed):

bind-key u capture-pane \; save-buffer /tmp/tmux-buffer \; new-window -n "urlview" '$SHELL -c "urlview < /tmp/tmux-buffer"'

Setting the correct term

256 colors

If you are using a 256 colour terminal, you will need to set the correct term in tmux. As of tmux 2.1, this is now tmux. You can do this in tmux.conf:

set -g default-terminal "tmux" 

Other, older alternatives, include screen, or screen-256color:

set -g default-terminal "screen-256color"

Also, if tmux messes up, you can force tmux to assume that the terminal support 256 colors, by adding this in your .bashrc:

alias tmux="tmux -2"

24-bit color

Tmux supports 24-bit color as of version 2.2 ([1]). If your terminal supports 24-bit color (see this gist), add your terminal to the terminal-overrides setting. For example, if you use Termite, you would add:

set -ga terminal-overrides ",xterm-termite:Tc"

For other terminals, replace xterm-termite with the relevant terminal type (stored in $TERM). See the tmux(1) man page for details about the Tc terminfo extension.

xterm-keys

To enable xterm-keys in your tmux.conf, you have to add the following line

set-option -g xterm-keys on

If you enable xterm-keys in your tmux.conf, then you need to build a custom terminfo to declare the new escape codes or applications will not know about them. Compile the following with tic and you can use "xterm-screen-256color" as your TERM:

# A screen- based TERMINFO that declares the escape sequences
# enabled by the tmux config "set-window-option -g xterm-keys".
#
# Prefix the name with xterm- since some applications inspect
# the TERM *name* in addition to the terminal capabilities advertised.
xterm-screen-256color|GNU Screen with 256 colors bce and tmux xterm-keys,

# As of Nov'11, the below keys are picked up by
# .../tmux/blob/master/trunk/xterm-keys.c:
	kDC=\E[3;2~, kEND=\E[1;2F, kHOM=\E[1;2H,
	kIC=\E[2;2~, kLFT=\E[1;2D, kNXT=\E[6;2~, kPRV=\E[5;2~,
	kRIT=\E[1;2C,

# Change this to screen-256color if the terminal you run tmux in
# doesn't support bce:
	use=screen-256color-bce,

Other Settings

To limit the scrollback buffer to 10000 lines:

set -g history-limit 10000

Terminal emulator settings can be overridden with

set -ga terminal-overrides ',xterm*:smcup@:rmcup@'
set -ga terminal-override ',rxvt-uni*:XT:Ms=\E]52;%p1%s;%p2%s\007'

Mouse can be toggled with

bind-key m set-option -g mouse on \; display 'Mouse: ON'
bind-key M set-option -g mouse off \; display 'Mouse: OFF'

Autostart with systemd

There are some notable advantages to starting a tmux server at startup. Notably, when you start a new tmux session, having the service already running reduces any delays in the startup.

Furthermore, any customization attached to your tmux session will be retained and your tmux session can be made to persist even if you have never logged in, if you have some reason to do that (like a heavily scripted tmux configuration or shared user tmux sessions).

The service below starts tmux for the specified user (i.e. start with tmux@username.service):

/etc/systemd/system/tmux@.service
[Unit]
Description=Start tmux in detached session

[Service]
Type=forking
User=%I
ExecStart=/usr/bin/tmux new-session -s %u -d
ExecStop=/usr/bin/tmux kill-session -t %u

[Install]
WantedBy=multi-user.target
Tip: You may want to add WorkingDirectory=custom_path to customize working directory.

Alternatively, you can place this file within your systemd/User directory (without User=%I), for example ~/.config/systemd/user/tmux.service. This way the tmux service will start when you log in, unless you also enable systemd/User#Automatic start-up of systemd user instances.

Session initialization

You can have tmux open a session with preloaded windows by including those details in your ~/.tmux.conf:

new  -n WindowName Command
neww -n WindowName Command
neww -n WindowName Command

To start a session with split windows (multiple panes), include the splitw command below the neww you would like to split; thus:

new  -s SessionName -n WindowName Command
neww -n foo/bar foo
splitw -v -p 50 -t 0 bar
selectw -t 1 
selectp -t 0

would open 2 windows, the second of which would be named foo/bar and would be split vertically in half (50%) with foo running above bar. Focus would be in window 2 (foo/bar), top pane (foo).

Note: Numbering for sessions, windows and panes starts at zero, unless you have specified a base-index of 1 in your .conf

To manage multiple sessions, source separate session files from your conf file:

# initialize sessions
bind F source-file ~/.tmux/foo
bind B source-file ~/.tmux/bar

Troubleshooting

Scrolling issues

If you have issues scrolling with Shift-Page Up/Down in your terminal, the following will remove the smcup and rmcup capabilities for any term that reports itself as anything beginning with xterm:

set -ga terminal-overrides ',xterm*:smcup@:rmcup@'

This tricks the terminal emulator into thinking Tmux is a full screen application like pico or mutt[2], which will make the scrollback be recorded properly. Beware however, it will get a bit messed up when switching between windows/panes. Consider using Tmux's native scrollback instead.

Mouse scrolling

Note: This interferes with selection buffer copying and pasting. To copy/paste to/from the selection buffer hold the shift key.

If you want to scroll with your mouse wheel, ensure mode-mouse is on in .tmux.conf

set -g mouse on

You can set scroll History with:

set -g history-limit 30000

For mouse wheel scrolling as from tmux 2.1 try adding one or both of these to ~/.tmux.conf

   bind -T root WheelUpPane   if-shell -F -t = "#{alternate_on}" "send-keys -M" "select-pane -t =; copy-mode -e; send-keys -M"
   bind -T root WheelDownPane if-shell -F -t = "#{alternate_on}" "send-keys -M" "select-pane -t =; send-keys -M"

Though the above will only scroll one line at a time, add this solution to scroll an entire page instead

   bind -t vi-copy    WheelUpPane   page-up
   bind -t vi-copy    WheelDownPane page-down
   bind -t emacs-copy WheelUpPane   page-up
   bind -t emacs-copy WheelDownPane page-down

Terminal emulator does not support UTF-8 mouse events

When the terminal emulator does not support the UTF-8 mouse events and the mouse on tmux option is set, left-clicking inside the terminal window might paste strings like [M# or [Ma into the promt.

To solve this issue set:

set -g mouse-utf8 off

Shift+F6 not working in Midnight Commander

See Midnight Commander#Shift+F6 not working.

X clipboard integration

Tip: The tmux plugin tmux-yank provides similar functionality.

It is possible to copy tmux selection to X clipboard (and to X primary/secondary selection) and in reverse direction. The following tmux config file snippet effectively integrates X clipboard/selection with the current tmux selection using the program xsel:

# Emacs style
bind-key -t emacs-copy M-w copy-pipe "xsel -i -p -b"
bind-key C-y run "xsel -o | tmux load-buffer - ; tmux paste-buffer"
# Vim style
bind-key -t vi-copy y copy-pipe "xsel -i -p -b"
bind-key p run "xsel -o | tmux load-buffer - ; tmux paste-buffer"

xclip could also be used for that purpose, unlike xsel it works better on printing raw bitstream that doesn't fit the current locale. Nevertheless, it is neater to use xsel instead of xclip, because xclip does not close STDOUT after it has read from tmux's buffer. As such, tmux doesn't know that the copy task has completed, and continues to wait for xclip's termination, thereby rendering tmux unresponsive. A workaround is to redirect STDOUT of xclip to /dev/null, like in the following:

# Vim style
bind-key -t vi-copy y copy-pipe "xclip -i -sel clip > /dev/null"
bind-key p run "xclip -o -sel clip | tmux load-buffer -"

Urxvt middle click

Note: To use this, you need to enable mouse support

There is an unofficial perl extension (mentioned in the official FAQ) to enable copying/pasting in and out of urxvt with tmux via Middle Mouse Clicking.

First, you will need to download the perl script and place it into urxvts perl lib:

wget http://anti.teamidiot.de/static/nei/*/Code/urxvt/osc-xterm-clipboard
mv osc-xterm-clipboard /usr/lib/urxvt/perl/

You will also need to enable that perl script in your .Xdefaults:

~/.Xdefaults
...
*URxvt.perl-ext-common:		osc-xterm-clipboard
...

Next, you want to tell tmux about the new function and enable mouse support (if you haven't already):

~/.tmux.conf
...
set-option -ga terminal-override ',rxvt-uni*:XT:Ms=\E]52;%p1%s;%p2%s\007'
set -g mouse on
...

That's it. Be sure to end all instances of tmux before trying the new MiddleClick functionality.

While in tmux, Shift+MiddleMouseClick will paste the clipboard selection while just MiddleMouseClick will paste your tmux buffer. Outside of tmux, just use MiddleMouseClick to paste your tmux buffer and your standard Ctrl-c to copy.

Tips and tricks

Start tmux with default session layout

To setup your default Tmux session layout, you install tmuxinatorAUR from AUR. Test your installation with

tmuxinator doctor

Get the default layout values

Start Tmux as usual and configure your windows and panes layout as you like. When finished, get the current layout values by executing (while you are still within the current Tmux session)

tmux list-windows

The output may look like this (two windows with 3 panes and 2 panes layout)

0: default* (3 panes) [274x83] [layout 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}] @2 (active)
1: remote- (2 panes) [274x83] [layout e3d3,274x83,0,0[274x41,0,0,4,274x41,0,42,7]] @3                                         

The Interesting part you need to copy for later use begins after [layout... and excludes ... ] @2 (active). For the first window layout you need to copy e.g. 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}

Define the default tmux layout

Knowing this, you can exit the current tmux session. Following this, you create your default Tmux session layout by editing Tmuxinator's config file (Don't copy the example, get your layout values as described above)

~/.tmuxinator/default.yml
name: default
root: ~/
windows:
  - default:
      layout: 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}
      panes:
        - clear
        - vim
        - clear && emacs -nw
  - remote:
      layout: 24ab,274x83,0,0{137x83,0,0,3,136x83,138,0,4}
      panes:
        - 
        - 

The example defines two windows named "default" and "remote". With your determined layout values. For each pane you have to use at least one - line. Within the first window panes you start the commandline "clear" in pane one, "vim" in pane two and "clear && emacs -nw" executes two commands in pane three on each Tmux start. The second window layout has two panes without defining any start commmands.

Test the new default layout with (yes, it is "mux"):

mux default

Autostart tmux with default tmux layout

If you like to start your terminal session with your default Tmux session layout edit

~/.bashrc
 if [ -z "$TMUX" ]; then
   mux default          
 fi                     

Alternate approach for default session

Instead of using the above method, one can just write a bash script that when run, will create the default session and attach to it. Then you can execute it from a terminal to get the pre-designed configuration in that terminal

#!/bin/bash
tmux new-session -d -n WindowName Command
tmux new-window -n NewWindowName
tmux split-window -v
tmux selectp -t 1
tmux split-window -h
tmux selectw -t 1
tmux -2 attach-session -d

Start tmux in urxvt

Use this command to start urxvt with a started tmux session. I use this with the exec command from my .ratpoisonrc file.

urxvt -e bash -c "tmux -q has-session && exec tmux attach-session -d || exec tmux new-session -n$USER -s$USER@$HOSTNAME"

Start tmux on every shell login

Bash

For bash, simply add the following line of bash code to your .bashrc before your aliases; the code for other shells is very similar:

~/.bashrc
# If not running interactively, do not do anything
[[ $- != *i* ]] && return
[[ -z "$TMUX" ]] && exec tmux
Note: This snippet ensures that tmux is not launched inside of itself (something tmux usually already checks for anyway). tmux sets $TMUX to the socket it is using whenever it runs, so if $TMUX isn't set or is length 0, we know we aren't already running tmux.

Add the following snippet to start only one session (unless you start some manually), on login, try attach at first, only create a session if no tmux is running.

# TMUX
if which tmux >/dev/null 2>&1; then
    #if not inside a tmux session, and if no session is started, start a new session
    test -z "$TMUX" && (tmux attach || tmux new-session)
fi

The following snippet does the same thing, but also checks tmux is installed before trying to launch it. It also tries to reattach you to an existing tmux session at logout, so that you can shut down every tmux session quickly from the same terminal at logout.

# TMUX
if which tmux >/dev/null 2>&1; then
    # if no session is started, start a new session
    test -z ${TMUX} && tmux

    # when quitting tmux, try to attach
    while test -z ${TMUX}; do
        tmux attach || break
    done
fi

Another possibility is to try to attach to existing deattached session or start a new session:

if [[ -z "$TMUX" ]] ;then
    ID="`tmux ls | grep -vm1 attached | cut -d: -f1`" # get the id of a deattached session
    if [[ -z "$ID" ]] ;then # if not available create a new one
        tmux new-session
    else
        tmux attach-session -t "$ID" # if available attach to it
    fi
fi

Fish

Tango-go-next.pngThis article or section is a candidate for moving to Fish.Tango-go-next.png

Notes: please use the second argument of the template to provide more detailed indications. (Discuss in Talk:Tmux#)

To start tmux on every shell login with fish, use the following:

~/.config/fish/config.fish
# If not running interactively, do not do anything
if status --is-interactive
    if test -z (echo $TMUX)
        tmux
    end
end

Alternatively, to start only one tmux session, or try to attach to another session on launch:

~/.config/fish/config.fish
if status --is-interactive
    if test -z (echo $TMUX)
        if not test (tmux attach)
            tmux new-session
        end
    end
end
Note: Instead of using the shell config file, you can launch tmux when you start your terminal emulator. (i. e. urxvt -e tmux)

Start a non-login shell

Tmux starts a login shell by default, which may result in multiple negative side effects:

  • Users of fortune may notice that quotes are printed when creating a new panel.
  • The configuration files for login shells such as ~/.profile are interpreted each time a new panel is created, so commands intended to be run on session initialization (e.g. setting audio level) are executed.

To disable this behaviour, add to ~/.tmux.conf:

set -g default-command "${SHELL}"

Use tmux windows like tabs

The following settings added to ~/.tmux.conf allow to use tmux windows like tabs, such as those provided by the reference of these hotkeys — urxvt's tabbing extensions[broken link: invalid section]. An advantage thereof is that these virtual “tabs” are independent of the terminal emulator.

#urxvt tab like window switching (-n: no prior escape seq)
bind -n S-down new-window
bind -n S-left prev
bind -n S-right next
bind -n C-left swap-window -t -1
bind -n C-right swap-window -t +1

Of course, those should not overlap with other applications' hotkeys, such as the terminal's. Given that they substitute terminal tabbing that might as well be deactivated, though.

It can also come handy to supplement the EOT hotkey Ctrl+d with one for tmux's detach:

bind-key -n C-j detach

Clients simultaneously interacting with various windows of a session

In Practical Tmux, Brandur Leach writes:

Screen and tmux's behaviour for when multiple clients are attached to one session differs slightly. In Screen, each client can be connected to the session but view different windows within it, but in tmux, all clients connected to one session must view the same window.
This problem can be solved in tmux by spawning two separate sessions and synchronizing the second one to the windows of the first, then pointing a second new session to the first.

The script “tmx” below implements this — the version here is slightly modified to execute “tmux new-window” if “1” is its second parameter. Invoked as tmx <base session name> [1] it launches the base session if necessary. Otherwise a new “client” session linked to the base, optionally add a new window and attach, setting it to kill itself once it turns “zombie”.

tmx
#!/bin/bash

#
# Modified TMUX start script from:
#     http://forums.gentoo.org/viewtopic-t-836006-start-0.html
#
# Store it to `~/bin/tmx` and issue `chmod +x`.
#

# Works because bash automatically trims by assigning to variables and by 
# passing arguments
trim() { echo $1; }

if [[ -z "$1" ]]; then
    echo "Specify session name as the first argument"
    exit
fi

# Only because I often issue `ls` to this script by accident
if [[ "$1" == "ls" ]]; then
    tmux ls
    exit
fi

base_session="$1"
# This actually works without the trim() on all systems except OSX
tmux_nb=$(trim `tmux ls | grep "^$base_session" | wc -l`)
if [[ "$tmux_nb" == "0" ]]; then
    echo "Launching tmux base session $base_session ..."
    tmux new-session -s $base_session
else
    # Make sure we are not already in a tmux session
    if [[ -z "$TMUX" ]]; then
        echo "Launching copy of base session $base_session ..."
        # Session id is date and time to prevent conflict
        session_id=`date +%Y%m%d%H%M%S`
        # Create a new session (without attaching it) and link to base session 
        # to share windows
        tmux new-session -d -t $base_session -s $session_id
        if [[ "$2" == "1" ]]; then
		# Create a new window in that session
		tmux new-window
	fi
        # Attach to the new session & kill it once orphaned
	tmux attach-session -t $session_id \; set-option destroy-unattached
    fi
fi

A useful setting for this is

setw -g aggressive-resize on

added to ~/.tmux.conf. It causes tmux to resize a window based on the smallest client actually viewing it, not on the smallest one attached to the entire session.

An alternative taken from [3] is to put the following ~/.bashrc:

.bashrc
function rsc() {
  CLIENTID=$1.`date +%S`
  tmux new-session -d -t $1 -s $CLIENTID \; set-option destroy-unattached \; attach-session -t $CLIENTID
}

function mksc() {
  tmux new-session -d -s $1
  rsc $1
}

Citing the author:

"mksc foo" creates a always detached permanent client named "foo". It also calls "rsc foo" to create a client to newly created session. "rsc foo" creates a new client grouped by "foo" name. It has destroy-unattached turned on so when I leave it, it kills client.
Therefore, when my computer looses network connectivity, all "foo.something" clients are killed while "foo" remains. I can then call "rsc foo" to continue work from where I stopped.

Correct the TERM variable according to terminal type

Instead of setting a fixed TERM variable in tmux, it is possible to set the proper TERM (either screen or screen-256color) according to the type of your terminal emulator:

~/.tmux.conf
## set the default TERM
set -g default-terminal screen

## update the TERM variable of terminal emulator when creating a new session or attaching a existing session
set -g update-environment 'DISPLAY SSH_ASKPASS SSH_AGENT_PID SSH_CONNECTION WINDOWID XAUTHORITY TERM'
## determine if we should enable 256-colour support
if "[[ ${TERM} =~ 256color || ${TERM} == fbterm ]]" 'set -g default-terminal screen-256color'
~/.zshrc
## workaround for handling TERM variable in multiple tmux sessions properly from http://sourceforge.net/p/tmux/mailman/message/32751663/ by Nicholas Marriott
if [[ -n ${TMUX} && -n ${commands[tmux]} ]];then
        case $(tmux showenv TERM 2>/dev/null) in
                *256color) ;&
                TERM=fbterm)
                        TERM=screen-256color ;;
                *)
                        TERM=screen
        esac
fi

Reload an updated configuration without restarting tmux

By default tmux reads ~/.tmux.conf only if it was not already running. To have tmux load a configuration file afterwards, execute:

tmux source-file <path>

This can be added to ~/.tmux.conf as e. g.:

bind r source-file <path>

You can also do ^: and type :

source .tmux.conf

Template script to run program in new session resp. attach to existing one

This script checks for a program presumed to have been started by a previous run of itself. Unless found it creates a new tmux session and attaches to a window named after and running the program. If however the program was found it merely attaches to the session and selects the window.

#!/bin/bash

PID=$(pidof $1)

if [ -z "$PID" ]; then
    tmux new-session -d -s main ;
    tmux new-window -t main -n $1 "$*" ;
fi
    tmux attach-session -d -t main ;
    tmux select-window -t $1 ;
exit 0

A derived version to run irssi with the nicklist plugin can be found on its ArchWiki page.

Terminal emulator window titles

If you SSH into a host in a tmux window, you'll notice the window title of your terminal emulator remains to be user@localhost rather than user@server. To allow the title bar to adapt to whatever host you connect to, set the following in ~/.tmux.conf

set -g set-titles on
set -g set-titles-string "#T"

For set-titles-string, #T will display user@host:~ and change accordingly as you connect to different hosts.

Automatic layouting

When creating new splits or destroying older ones the currently selected layout isn't applied. To fix that, add following binds which will apply the currently selected layout to new or remaining panes:

bind-key -n M-c kill-pane \; select-layout
bind-key -n M-n split-window \; select-layout

Vim friendly configuration

See [4] for a configuration friendly to vim users.

See also

Tutorials