动机

在日常开发中,我会使用 Tmux 来管理多个终端窗口和会话。而如果服务器重启,通常需要重新手动建立会话。
tmux-resurrecttmux-continuum 这两个插件的组合可以让你:

  • tmux-resurrect: 手动保存和恢复 tmux 会话
  • tmux-continuum: 自动保存会话,并在 tmux 启动时自动恢复

两者结合使用,可以实现真正的”无缝工作”体验——即使系统重启,你的工作环境也能完整恢复。


安装

1. 安装 TPM (Tmux Plugin Manager)

首先需要安装 tmux 插件管理器:

1
git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm

2. 配置 ~/.tmux.conf

1
vi ~/.tmux.conf

在末尾添加以下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 插件列表
set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-resurrect'
set -g @plugin 'tmux-plugins/tmux-continuum'

# resurrect 配置
# 恢复 vim 会话
set -g @resurrect-strategy-vim 'session'
# 恢复 neovim 会话
set -g @resurrect-strategy-nvim 'session'
# 恢复面板内容
set -g @resurrect-capture-pane-contents 'on'
# 恢复 bash 历史(可选)
set -g @resurrect-save-bash-history 'on'
# 恢复每个面板的工作目录
set -g @resurrect-dir-names 'on'

# Continuum 配置
# 自动保存间隔(分钟),默认是 15 分钟
set -g @continuum-save-interval '5'
# 启用自动恢复
set -g @continuum-restore 'on'
# 显示保存状态(在状态栏显示最后保存时间)
set -g status-right 'Continuum: #{continuum_status}'

# 初始化 TPM(必须放在配置文件最底部)
run '~/.tmux/plugins/tpm/tpm'

3. 安装插件

在 tmux 会话中执行以下操作:

  1. 重新加载配置:

    1
    tmux source ~/.tmux.conf
  2. 安装插件:按 Ctrl + b 然后按 Shift + I(大写 I)

    • 稍等几秒钟,会看到提示:”TMUX environment reloaded. Done, press ESCAPE to continue.”
    • ESC 键退出
  3. 检查安装状态:

    1
    ls ~/.tmux/plugins/

使用

Resurrect 需要手动操作

  • 手动保存所有会话: 在任意 tmux 会话中:Ctrl + bCtrl + s

    • 底部显示:”Tmux environment saved!”
  • 手动恢复所有会话: Ctrl + bCtrl + r

    • 底部显示:”Tmux restore complete!”

Continuum 则会自动操作

  • ✅ 每 15 分钟自动保存一次会话
  • ✅ Tmux 启动时自动恢复上次的会话
  • ✅ 在状态栏显示保存状态

查看保存状态

在状态栏右侧会显示 Continuum 的状态:

  • 显示距离上次保存的时间
  • 或显示 “off” 如果自动保存被禁用

其他配置

自定义恢复的程序

默认情况下,resurrect 会恢复大多数程序,但你可以自定义:

1
2
# 恢复更多程序
set -g @resurrect-processes 'vim nvim emacs man less more tail top htop ssh'

更新插件

在 tmux 会话中按 Ctrl + bU(大写 U),选择要更新的插件。


卸载

如果需要卸载插件:

  1. ~/.tmux.conf 中删除相关配置
  2. 删除插件目录:
    1
    2
    rm -rf ~/.tmux/plugins/tmux-resurrect
    rm -rf ~/.tmux/plugins/tmux-continuum
  3. 重新加载配置:tmux source ~/.tmux.conf

参考资源