DEV Community

Cover image for Tmux Personalizado - Cores, Status Bar e Plugins Úteis
Rafael Dutra for apsis-cc

Posted on • Edited on

Tmux Personalizado - Cores, Status Bar e Plugins Úteis

Status bar do tmux com o tema Catppuccin Frappé, igual ao usado neste post Catppuccin Frappé — catppuccin/tmux, licença MIT

1. Onde Mora a Configuração do Tmux

Nas duas primeiras partes desta série, vimos os conceitos do tmux e os comandos para navegar entre sessões, janelas e painéis. Tudo isso funciona com os padrões de fábrica — mas o tmux só realmente "gruda" no fluxo de trabalho quando é ajustado ao gosto de quem usa: prefixo mais confortável, atalhos no estilo vi, status bar informativa e plugins que resolvem problemas recorrentes. Em vez de montar um exemplo genérico, este artigo usa como base uma configuração real, em uso diário, com tema Catppuccin e integração com Docker e Git direto na status bar.

Toda essa personalização mora em um único arquivo: ~/.tmux.conf. Ele é lido quando o servidor tmux inicia; para aplicar mudanças em uma sessão já em execução, sem reiniciar tudo, recarrega-se manualmente:

tmux source-file ~/.tmux.conf
Enter fullscreen mode Exit fullscreen mode

Mapear isso para uma combinação de teclas dentro do próprio .tmux.conf evita ter que digitar o comando inteiro toda vez que uma linha é ajustada:

unbind r
bind r source-file ~/.tmux.conf
Enter fullscreen mode Exit fullscreen mode

2. Prefixo, Atalhos e Popups

O prefixo padrão Ctrl+b é uma escolha histórica (evitar conflito com o Ctrl+a do GNU Screen), mas boa parte da comunidade prefere algo mais perto do canto do teclado. Aqui a escolha caiu sobre Ctrl+x:

# Alterar a tecla Leader (Prefix) de Ctrl+b para Ctrl+x
set -g prefix C-x
unbind C-b
bind C-x send-prefix
Enter fullscreen mode Exit fullscreen mode

Divisão de painéis mantendo o diretório atual, navegação estilo vi e redimensionamento com shift+direção:

# Split mantendo o diretório atual
bind '"' split-window -v -c "#{pane_current_path}"
bind '%' split-window -h -c "#{pane_current_path}"

# Navegação entre painéis (estilo vim)
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R

# Redimensionar painéis com shift+seta
bind -r H resize-pane -L 5
bind -r J resize-pane -D 5
bind -r K resize-pane -U 5
bind -r L resize-pane -R 5

# Copy mode com vi keys
setw -g mode-keys vi
bind -T copy-mode-vi v send -X begin-selection
bind -T copy-mode-vi y send -X copy-selection-and-cancel
Enter fullscreen mode Exit fullscreen mode

O -r nos binds de resize permite repetir o atalho várias vezes seguidas sem apertar o prefixo de novo a cada aperto — útil quando um painel precisa crescer bem mais que 5 colunas/linhas de uma vez.

Um recurso menos comum: display-popup, que abre uma janela flutuante por cima da sessão sem criar um painel novo — ótimo para uma checagem rápida sem bagunçar o layout atual:

bind D display-popup -w 80% -h 80% -E "docker stats"
bind P display-popup -w 80% -h 80% -b rounded -s "fg=black" -S "fg=cyan" -E "zsh"
Enter fullscreen mode Exit fullscreen mode

-E roda o comando e fecha o popup assim que ele termina; P abre um shell solto (zsh) num popup com borda arredondada, útil para rodar algo pontual sem sair da janela atual nem abrir um painel permanente.

3. Cores e Status Bar com Catppuccin

Status bar do tmux com o tema Catppuccin Mocha Catppuccin Mocha, outro flavor do mesmo tema — catppuccin/tmux, licença MIT

Escrever cada cor da status bar manualmente (como status-style bg=colour235,fg=colour250) funciona, mas dá trabalho para manter consistente em todos os elementos — painéis, mensagens, janela ativa. O plugin catppuccin/tmux resolve isso fornecendo uma paleta e um conjunto de módulos prontos:

set -g @catppuccin_flavor "frappe"
set -g @catppuccin_window_status_style "rounded"
set -g @catppuccin_window_text "#H"
set -g @catppuccin_window_current_text "#W"
set -g @catppuccin_session_text " #I:#S"
Enter fullscreen mode Exit fullscreen mode

O flavor frappe é uma das quatro variações de paleta do Catppuccin (as outras são latte, macchiato e mocha) — trocar essa única linha muda o esquema de cores inteiro, sem tocar em mais nada. As cores de base do frappe aparecem depois no arquivo, para uso em outros elementos que o módulo do Catppuccin não cobre diretamente:

set -g @ctp_bg "#303446"        # Base
set -g @ctp_surface_1 "#51576d" # Surface1
set -g @ctp_fg "#c6d0f5"        # Text
set -g @ctp_mauve "#ca9ee6"     # Mauve
set -g @ctp_crust "#232634"     # Crust
Enter fullscreen mode Exit fullscreen mode

Um detalhe que vale a pena copiar: detecção de sessão SSH via diretiva condicional do próprio tmux, deixando a status bar visivelmente diferente (laranja) sempre que a sessão está numa máquina remota — um lembrete visual de "cuidado, você não está local":

%if "#{SSH_CLIENT}"
set -g status-style "bg=#fe640b,fg=#ffffff"
set -g message-style "bg=#e64553,fg=#ffffff"
%else
set -g status-style "bg=#e78284,fg=#232634"
set -g message-style "bg=#ea999c,fg=#232634"
%endif
Enter fullscreen mode Exit fullscreen mode

%if/%else/%endif são avaliados quando o tmux lê o arquivo, com base em uma variável de formato — aqui, #{SSH_CLIENT} só é diferente de vazio quando a conexão veio via SSH.

A composição da status bar é feita concatenando pedaços com -a (append), em vez de escrever uma string gigante numa linha só:

set-option -g status-position top
set -g status-left-length 100
set -g status-right-length 100
set -g status-left ""
set -g window-status-format ""
set -g window-status-current-format ""

# Sessão + hostname
set -gF status-left "#[fg=#babbf1]   ##H "
set -ag status-left "#{E:@catppuccin_status_session}"

# Badge de SSH, aparece só quando conectado remotamente
set -ag status-left '#([ -n "$SSH_CLIENT" ] && echo "#[fg=#ffffff bg=#fe640b bold] SSH #[default]") '

# Containers Docker rodando / parados, CPU e memória agregadas
set -ag status-left "#[fg=#a6d189,bold] #(docker ps -q 2>/dev/null | wc -l | tr -d ' ')#[fg=#626880]/#[fg=#e78284]#(docker ps -aq --filter status=exited 2>/dev/null | wc -l | tr -d ' ') "
set -ag status-left "#[fg=#ef9f76] #(docker stats --no-stream --format '{{.CPUPerc}}' 2>/dev/null | sed 's/[^0-9.]//g' | awk '{sum+=$1} END {print int(sum*10)/10}')%% "
set -ag status-left "#[fg=#85c1dc] #(docker stats --no-stream --format '{{.MemUsage}}' 2>/dev/null | awk -F'/' 'NR==1{print $1}' | tr -d ' ') "

# Aplicação atual, uptime e métricas do host (plugins, seção 5)
set -g status-right "#{E:@catppuccin_status_application}"
set -ag status-right "#{E:@catppuccin_status_uptime}"
set -agF status-right "#{E:@catppuccin_status_cpu}"
set -agF status-right "#{E:@catppuccin_status_ram}"
set -agF status-right "#{E:@catppuccin_status_load}"
set -agF status-right "#{E:@catppuccin_status_battery}"
Enter fullscreen mode Exit fullscreen mode

#(comando) roda um shell command e injeta a saída direto na status bar — é assim que os containers Docker ativos e o uso de CPU/memória aparecem atualizados a cada status-interval (60 segundos, por padrão, para não pesar rodando docker stats toda hora):

set -g status-interval 60
Enter fullscreen mode Exit fullscreen mode

Por fim, os painéis também ganham borda colorida e um cabeçalho informativo, mostrando o comando rodando, a branch git do diretório atual (via #(cd #{pane_current_path} && git branch --show-current)) e o horário:

set -g pane-border-lines single
set -g pane-border-status top
set -g pane-active-border-style "fg=#e5c890,bold"
set -g pane-border-style "fg=#006b6b"
set -g pane-border-format " #{?pane_active,#[fg=#a6d189 bold]▶ #[fg=#85c1dc bold],#[fg=#626880]}#{pane_current_command} #[align=right]#[fg=#ca9ee6]#(cd #{pane_current_path} && git branch --show-current 2>/dev/null | sed '/^$/d; s/^/  /; s/$/ /') #[fg=#626880]· #[fg=#00ffff]%H:%M #[fg=#626880]· #[fg=#a6d189]#P "
Enter fullscreen mode Exit fullscreen mode

#{?pane_active,X,Y} é um condicional de formato: mostra X se o painel estiver ativo, Y caso contrário — é assim que só o painel focado ganha a seta destacada.

4. Tmux Plugin Manager (TPM)

O TPM (Tmux Plugin Manager) é o método padrão da comunidade para instalar e gerenciar plugins, de forma parecida com o vim-plug no Vim:

git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm
Enter fullscreen mode Exit fullscreen mode

No ~/.tmux.conf, plugins são declarados com set -g @plugin, e a linha que inicializa o TPM precisa ficar sempre por último no arquivo:

set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-resurrect'
set -g @plugin 'jimeh/tmuxifier'
set -g @plugin 'tmux-plugins/tmux-battery'
set -g @plugin 'tmux-plugins/tmux-cpu'
set -g @plugin 'tmux-plugins/tmux-prefix-highlight'
set -g @plugin 'tmux-plugins/tmux-online-status'
set -g @plugin 'tmux-plugins/tmux-yank'
set -g @plugin 'tmux-plugins/tmux-continuum'

run -b '~/.tmux/plugins/tpm/tpm'
Enter fullscreen mode Exit fullscreen mode

O Catppuccin, nesta configuração, não está na lista @plugin — foi clonado manualmente e carregado com um run direto, apontando pro caminho do repositório:

git clone https://github.com/catppuccin/tmux.git ~/.config/tmux/plugins/catppuccin/tmux
Enter fullscreen mode Exit fullscreen mode
run ~/.config/tmux/plugins/catppuccin/tmux/catppuccin.tmux
Enter fullscreen mode Exit fullscreen mode

As duas formas funcionam — @plugin 'catppuccin/tmux' via TPM também seria válido — mas o run direto evita que uma atualização do TPM (prefix + U) mexa acidentalmente na versão do tema enquanto ele ainda está sendo ajustado.

Depois de salvar o arquivo e recarregar (prefix + r), os plugins da lista @plugin são instalados de dentro do próprio tmux com prefix + I (maiúsculo). Para atualizar todos: prefix + U. Para remover os que foram tirados da lista: prefix + alt + u.

5. Plugins que Realmente Valem a Pena

  • tmux-resurrect: salva o estado completo de sessões, janelas e painéis em disco (prefix + Ctrl+s) e restaura tudo depois (prefix + Ctrl+r). Com @resurrect-strategy-vim/@resurrect-strategy-nvim setados como session, ele delega a restauração do buffer do editor para a própria sessão de Vim/Neovim salva, em vez de só reabrir os arquivos:
  set -g @resurrect-capture-pane-contents 'on'
  set -g @resurrect-strategy-nvim 'session'
  set -g @resurrect-strategy-vim 'session'
Enter fullscreen mode Exit fullscreen mode
  • tmux-continuum: complementa o tmux-resurrect salvando o estado automaticamente a cada alguns minutos, sem precisar lembrar de acionar o atalho manualmente:
  set -g @continuum-restore 'on'
  set -g @continuum-save-interval '15'
Enter fullscreen mode Exit fullscreen mode
  • tmuxifier: gerencia layouts de sessão pré-definidos por projeto (o equivalente, dentro do ecossistema de plugins do TPM, ao que ferramentas como tmuxinator/tmuxp fazem via script — assunto da próxima parte desta série).

  • tmux-battery / tmux-cpu: expõem #{battery_percentage} e #{cpu_percentage} como variáveis de formato, usadas pelos módulos @catppuccin_status_battery e @catppuccin_status_cpu na status bar.

  • tmux-prefix-highlight: mostra um indicador visual assim que o prefixo é pressionado — útil para confirmar que o tmux "ouviu" o Ctrl+x antes de digitar o atalho seguinte, especialmente relevante quando o prefixo foi trocado do padrão.

  • tmux-online-status: expõe #{online_status}, para exibir se a máquina tem conectividade de rede direto na status bar.

  • tmux-yank: melhora a integração do copy mode com a área de transferência do sistema operacional (útil especialmente sobre SSH ou em WSL, onde essa integração não funciona por padrão).

6. Exemplo de .tmux.conf Completo

Juntando o conteúdo das seções anteriores num arquivo funcional (a configuração real usada no dia a dia, com o tema Catppuccin Frappe):

# ~/.tmux.conf

# Prefixo
set -g prefix C-x
unbind C-b
bind C-x send-prefix

# Reload
unbind r
bind r source-file ~/.tmux.conf

# Popups úteis
bind D display-popup -w 80% -h 80% -E "docker stats"
bind P display-popup -w 80% -h 80% -b rounded -s "fg=black" -S "fg=cyan" -E "zsh"

# Comportamento
set -g mouse on
set-option -g allow-rename off
set-option -g automatic-rename-format '#{b:pane_current_path}'
set -g default-terminal "tmux-256color"
set -g base-index 1
set -g pane-base-index 1
set -g renumber-windows on
set -g history-limit 50000
set -sg escape-time 10
set -g focus-events on
set -g display-time 2000

# Painéis e navegação
bind '"' split-window -v -c "#{pane_current_path}"
bind '%' split-window -h -c "#{pane_current_path}"
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
bind -r H resize-pane -L 5
bind -r J resize-pane -D 5
bind -r K resize-pane -U 5
bind -r L resize-pane -R 5
setw -g mode-keys vi
bind -T copy-mode-vi v send -X begin-selection
bind -T copy-mode-vi y send -X copy-selection-and-cancel

# SSH: status bar laranja quando conectado remotamente
%if "#{SSH_CLIENT}"
set -g status-style "bg=#fe640b,fg=#ffffff"
set -g message-style "bg=#e64553,fg=#ffffff"
%else
set -g status-style "bg=#e78284,fg=#232634"
set -g message-style "bg=#ea999c,fg=#232634"
%endif
set-option -g status-position top
set -g status-interval 60

# Catppuccin
set -g @catppuccin_flavor "frappe"
set -g @catppuccin_window_status_style "rounded"
set -g @catppuccin_window_text "#H"
set -g @catppuccin_window_current_text "#W"
set -g @catppuccin_session_text " #I:#S"

# Plugins (TPM)
set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-resurrect'
set -g @resurrect-capture-pane-contents 'on'
set -g @resurrect-strategy-nvim 'session'
set -g @resurrect-strategy-vim 'session'
set -g @plugin 'jimeh/tmuxifier'
set -g @plugin 'tmux-plugins/tmux-battery'
set -g @plugin 'tmux-plugins/tmux-cpu'
set -g @plugin 'tmux-plugins/tmux-prefix-highlight'
set -g @plugin 'tmux-plugins/tmux-online-status'
set -g @plugin 'tmux-plugins/tmux-yank'
set -g @plugin 'tmux-plugins/tmux-continuum'
set -g @continuum-restore 'on'
set -g @continuum-save-interval '15'

run ~/.config/tmux/plugins/catppuccin/tmux/catppuccin.tmux

# Status bar
set -g status-left-length 100
set -g status-right-length 100
set -g status-left ""
set -g window-status-format ""
set -g window-status-current-format ""
set -gF status-left "#[fg=#babbf1]   ##H "
set -ag status-left "#{E:@catppuccin_status_session}"
set -ag status-left '#([ -n "$SSH_CLIENT" ] && echo "#[fg=#ffffff bg=#fe640b bold] SSH #[default]") '
set -ag status-left "#[fg=#a6d189,bold] #(docker ps -q 2>/dev/null | wc -l | tr -d ' ')#[fg=#626880]/#[fg=#e78284]#(docker ps -aq --filter status=exited 2>/dev/null | wc -l | tr -d ' ') "
set -ag status-left "#[fg=#ef9f76] #(docker stats --no-stream --format '{{.CPUPerc}}' 2>/dev/null | sed 's/[^0-9.]//g' | awk '{sum+=$1} END {print int(sum*10)/10}')%% "
set -ag status-left "#[fg=#85c1dc] #(docker stats --no-stream --format '{{.MemUsage}}' 2>/dev/null | awk -F'/' 'NR==1{print $1}' | tr -d ' ') "
set -g status-right "#{E:@catppuccin_status_application}"
set -ag status-right "#{E:@catppuccin_status_uptime}"
set -agF status-right "#{E:@catppuccin_status_cpu}"
set -agF status-right "#{E:@catppuccin_status_ram}"
set -agF status-right "#{E:@catppuccin_status_load}"
set -agF status-right "#{E:@catppuccin_status_battery}"

# Painéis: borda com comando atual, branch git e horário
setw -g monitor-activity on
set -g visual-activity off
setw -g monitor-silence 0
set -g pane-border-lines single
set -g pane-border-status top
set -g pane-active-border-style "fg=#e5c890,bold"
set -g pane-border-style "fg=#006b6b"
set -g pane-border-format " #{?pane_active,#[fg=#a6d189 bold]▶ #[fg=#85c1dc bold],#[fg=#626880]}#{pane_current_command} #[align=right]#[fg=#ca9ee6]#(cd #{pane_current_path} && git branch --show-current 2>/dev/null | sed '/^$/d; s/^/  /; s/$/ /') #[fg=#626880]· #[fg=#00ffff]%H:%M #[fg=#626880]· #[fg=#a6d189]#P "
set -g window-active-style "bg=default"
set -g window-style "bg=default"

run -b '~/.tmux/plugins/tpm/tpm'
Enter fullscreen mode Exit fullscreen mode

7. Conclusão e Próximos Passos

Com prefixo ajustado, tema Catppuccin aplicado e a status bar mostrando o que realmente importa no dia a dia — containers Docker, uso de CPU/memória, branch git do painel ativo, indicador de SSH — o tmux deixa de ser apenas funcional e passa a se adaptar ao fluxo de quem usa. No último artigo desta série, o assunto são exemplos reais de uso avançado: scripts de sessão automatizados, layouts fixos para desenvolvimento, sincronização de painéis entre múltiplos servidores e ajustes finos de performance.


Imagem de capa: Logo do tmux, por Jason Long — Wikimedia Commons

Referências:

  1. tmux GitHub Wiki — Plugins
  2. Tmux Plugin Manager (TPM)
  3. catppuccin/tmux
  4. tmux-resurrect

Top comments (0)