tmux’s default key sequence to enter copy mode and begin a search of the terminal history/scrollback is pretty awkward: Ctrl + b [ Ctrl + r if you’re using the default emacs-style copy mode bindings, or Ctrl + b [ ? if you’re using the vim-style bindings.

Browsers use much easier shortcuts for searching the page. In Chrome and Firefox:

  • Ctrl + f begins a search
  • Ctrl + g goes to the next match
  • Ctrl + Shift + g goes to the previous match

You wouldn’t want to bind Ctrl + f in a terminal emulator because it’s likely to conflict with keyboard shortcuts used by apps running in the terminal. So GNOME Terminal uses a similar set of Ctrl + Shift-based shortcuts instead:

  • Ctrl + Shift + f begins a search
  • Ctrl + Shift + g goes to the next match
  • Ctrl + Shift + h goes to the previous match

Apps like tmux that run inside a terminal can’t use Ctrl + Shift: Ctrl-modified keys are case-insensitive in terminal apps.

These tmux key bindings are designed to be as close as possible to Chrome, Firefox and GNOME Terminal’s, while avoiding Ctrl + f or Ctrl + Shift:

  • Ctrl + Alt + f begins a search

  • Ctrl + g goes to the next match. tmux’s default key binding n also works.

  • Ctrl + h or Ctrl + Alt + g goes to the previous match. tmux’s default key binding N also works.

  • tmux’s default Esc key binding will clear the search (as it also does in browsers and GNOME Terminal). If you’re using tmux’s vi-style copy mode key bindings Esc will leave you in copy mode, q will clear the search and exit copy mode.

To add the bindings paste this snippet into your ~/.tmux.conf file:

bind -n C-M-f copy-mode \; command-prompt -i -p "(search up)" "send -X search-backward-incremental \"%%%\""
bind -T copy-mode-vi C-M-f copy-mode \; command-prompt -i -p "(search up)" "send -X search-backward-incremental \"%%%\""
bind -T copy-mode-vi C-g send -X search-again
bind -T copy-mode-vi C-M-g send -X search-reverse
bind -T copy-mode-vi C-h send -X search-reverse

The snippet is for tmux’s vi-style copy mode bindings. If you’re using emacs-style replace copy-mode-vi with just copy-mode.

These key bindings do incremental search: it highlights all matches and jumps to the first match as you type the search query, instead of waiting for you to hit Enter. If you’re using emacs-style bindings then the default Ctrl + r and Ctrl + s bindings for starting a search from copy mode already do an incremental search. If you’re using vi-style bindings then the default copy mode bindings ? and / do a non-incremental search (an excremental search). To make ? and / do incremental search add these lines to your ~/.tmux.conf:

bind -T copy-mode-vi / command-prompt -i -p "(search down)" "send -X search-forward-incremental \"%%%\""
bind -T copy-mode-vi ? command-prompt -i -p "(search up)" "send -X search-backward-incremental \"%%%\""
All posts tagged “tmux”: