Contents

tmux-vim: Advanced Terminal Configuration for Developers

tmux-vim: Advanced Terminal Configuration for Developers

In this post, I’ll share my tmux-vim configuration project, which provides a comprehensive terminal setup optimized for modern development workflows. This configuration enhances productivity through advanced tmux and Vim customization.

Project Overview

The tmux-vim project delivers a complete terminal environment configuration that combines the power of tmux (terminal multiplexer) with Vim’s extensibility. This setup is designed for developers who spend significant time in the terminal and want to maximize their productivity.

Why tmux and Vim?

tmux Benefits

  • Session Management: Persistent terminal sessions across disconnections
  • Window Management: Multiple terminal windows in a single session
  • Pane Splitting: Split terminals for multitasking
  • Scripting: Automation through tmux scripting
  • Remote Work: Seamless remote development experience

Vim Advantages

  • Modal Editing: Efficient text editing with modes
  • Extensibility: Rich plugin ecosystem
  • Keyboard Navigation: Fast navigation without mouse
  • Consistency: Same editor across all environments
  • Performance: Lightweight and fast

Configuration Architecture

Project Structure

tmux-vim/
├── tmux/
│   ├── tmux.conf
│   ├── plugins/
│   └── scripts/
├── vim/
│   ├── vimrc
│   ├── plugins/
│   ├── colors/
│   └── autoload/
├── install.sh
├── update.sh
└── README.md

tmux Configuration

Main Configuration

# ~/.tmux.conf

# Set prefix key to Ctrl-a
unbind C-b
set-option -g prefix C-a
bind-key C-a send-prefix

# Enable mouse support
set -g mouse on

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

# Increase scrollback buffer
set -g history-limit 10000

# Enable focus events
set -g focus-events on

# Window and pane indexing
set -g base-index 1
setw -g pane-base-index 1

# Renumber windows when a window is closed
set -g renumber-windows on

# Set window title
set -g set-titles on
set -g set-titles-string "#T - #W"

# Status bar configuration
set -g status-position bottom
set -g status-justify left
set -g status-style 'bg=#1e1e1e fg=#ffffff'
set -g status-left-length 40
set -g status-right-length 150

# Status bar content
set -g status-left ' #[fg=#00ff00]#S #[fg=#ffffff]| '
set -g status-right ' #[fg=#00ff00]%Y-%m-%d %H:%M #[fg=#ffffff]| #[fg=#00ff00]#{battery_percentage} #[fg=#ffffff]| #[fg=#00ff00]#{cpu_percentage} #[fg=#ffffff]| #[fg=#00ff00]#{ram_percentage} '

# Window status
setw -g window-status-current-style 'bg=#00ff00 fg=#000000 bold'
setw -g window-status-style 'bg=#333333 fg=#ffffff'

# Pane border
set -g pane-border-style 'fg=#333333'
set -g pane-active-border-style 'fg=#00ff00'

# Message styling
set -g message-style 'bg=#1e1e1e fg=#ffffff'

# Key bindings
bind | split-window -h
bind - split-window -v
unbind '"'
unbind %

# Pane navigation
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R

# Pane resizing
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

# Window navigation
bind -r C-h select-window -t :-
bind -r C-l select-window -t :+

# Copy mode
setw -g mode-keys vi
bind -T copy-mode-vi v send-keys -X begin-selection
bind -T copy-mode-vi y send-keys -X copy-pipe-and-cancel 'pbcopy'
bind -T copy-mode-vi r send-keys -X rectangle-toggle

# Plugin management
set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-sensible'
set -g @plugin 'tmux-plugins/tmux-resurrect'
set -g @plugin 'tmux-plugins/tmux-continuum'
set -g @plugin 'tmux-plugins/tmux-yank'
set -g @plugin 'tmux-plugins/tmux-battery'
set -g @plugin 'tmux-plugins/tmux-cpu'
set -g @plugin 'tmux-plugins/tmux-prefix-highlight'

# Plugin configuration
set -g @resurrect-capture-pane-contents 'on'
set -g @continuum-restore 'on'
set -g @continuum-save-interval '15'

# Initialize TMUX plugin manager
run '~/.tmux/plugins/tpm/tpm'

Plugin Configuration

# ~/.tmux/plugins/tpm/tpm

# TPM (Tmux Plugin Manager) configuration
# This file is automatically generated by TPM

# Plugin installation directory
set-environment -g TMUX_PLUGIN_MANAGER_PATH '~/.tmux/plugins'

# Plugin list
set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-sensible'
set -g @plugin 'tmux-plugins/tmux-resurrect'
set -g @plugin 'tmux-plugins/tmux-continuum'
set -g @plugin 'tmux-plugins/tmux-yank'
set -g @plugin 'tmux-plugins/tmux-battery'
set -g @plugin 'tmux-plugins/tmux-cpu'
set -g @plugin 'tmux-plugins/tmux-prefix-highlight'

# Initialize TPM
run '~/.tmux/plugins/tpm/tpm'

Vim Configuration

Main Vim Configuration

" ~/.vimrc

" General settings
set nocompatible
set encoding=utf-8
set fileencoding=utf-8
set fileencodings=utf-8,ucs-bom,gb18030,gbk,gb2312,cp936
set termencoding=utf-8

" Display settings
set number
set relativenumber
set ruler
set showcmd
set showmode
set showmatch
set matchtime=1
set scrolloff=3
set sidescrolloff=5
set display=lastline
set wrap
set linebreak

" Search settings
set hlsearch
set incsearch
set ignorecase
set smartcase
set gdefault

" Indentation
set autoindent
set smartindent
set cindent
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set shiftround

" File handling
set autoread
set autowrite
set confirm
set nobackup
set nowritebackup
set noswapfile
set undofile
set undodir=~/.vim/undodir

" Command line
set wildmenu
set wildmode=longest:full,full
set wildignore=*.o,*.obj,*.dylib,*.bin,*.dll,*.exe
set wildignore+=*/tmp/*,*.so,*.swp,*.zip,*.pyc,*.pyo,*.class
set wildignore+=.git,.svn,.hg,.bzr,.DS_Store
set wildignore+=*.jpg,*.jpeg,*.png,*.gif,*.bmp,*.tiff
set wildignore+=*.pdf,*.doc,*.docx,*.xls,*.xlsx,*.ppt,*.pptx

" Performance
set lazyredraw
set ttyfast
set synmaxcol=200
set updatetime=300

" Key mappings
let mapleader = " "
let maplocalleader = "\\"

" Normal mode mappings
nnoremap <leader>w :w<CR>
nnoremap <leader>q :q<CR>
nnoremap <leader>x :x<CR>
nnoremap <leader>e :e<Space>
nnoremap <leader>f :find<Space>

" Buffer navigation
nnoremap <leader>bn :bnext<CR>
nnoremap <leader>bp :bprevious<CR>
nnoremap <leader>bd :bdelete<CR>
nnoremap <leader>ba :ball<CR>

" Window navigation
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l

" Window resizing
nnoremap <C-Up> :resize +2<CR>
nnoremap <C-Down> :resize -2<CR>
nnoremap <C-Left> :vertical resize -2<CR>
nnoremap <C-Right> :vertical resize +2<CR>

" Quick escape
inoremap jk <ESC>
inoremap kj <ESC>

" Search and replace
nnoremap <leader>s :%s/\<<C-r><C-w>\>//g<Left><Left>
vnoremap <leader>s :s/\<<C-r><C-w>\>//g<Left><Left>

" Clear search highlighting
nnoremap <leader><space> :noh<CR>

" Plugin management with vim-plug
call plug#begin('~/.vim/plugged')

" Essential plugins
Plug 'tpope/vim-sensible'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-rhubarb'

" File navigation
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'scrooloose/nerdtree'
Plug 'Xuyuanp/nerdtree-git-plugin'

" Syntax highlighting
Plug 'sheerun/vim-polyglot'
Plug 'vim-syntastic/syntastic'

" Status line
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'

" Colorschemes
Plug 'morhetz/gruvbox'
Plug 'dracula/vim', { 'as': 'dracula' }
Plug 'joshdick/onedark.vim'

" Language-specific plugins
Plug 'fatih/vim-go', { 'do': ':GoUpdateBinaries' }
Plug 'rust-lang/rust.vim'
Plug 'python-mode/python-mode', { 'for': 'python', 'branch': 'develop' }
Plug 'davidhalter/jedi-vim'

" Development tools
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'airblade/vim-gitgutter'
Plug 'majutsushi/tagbar'
Plug 'mileszs/ack.vim'

call plug#end()

" Plugin configurations
" Gruvbox colorscheme
set background=dark
colorscheme gruvbox

" Airline configuration
let g:airline_powerline_fonts = 1
let g:airline_theme = 'gruvbox'
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#formatter = 'unique_tail'

" NERDTree configuration
let g:NERDTreeWinSize = 30
let g:NERDTreeShowHidden = 1
let g:NERDTreeIgnore = ['\.pyc$', '__pycache__', '\.git$', '\.DS_Store']

" FZF configuration
let g:fzf_layout = { 'down': '~40%' }
let g:fzf_preview_window = ['right:50%', 'ctrl-/']

" Syntastic configuration
let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0

" GitGutter configuration
let g:gitgutter_enabled = 1
let g:gitgutter_map_keys = 0

" COC configuration
let g:coc_global_extensions = [
  \ 'coc-json',
  \ 'coc-python',
  \ 'coc-rust-analyzer',
  \ 'coc-go',
  \ 'coc-tsserver'
  \ ]

" Custom functions
function! ToggleNERDTree()
    if exists("g:NERDTree") && g:NERDTree.IsOpen()
        NERDTreeClose
    else
        NERDTreeFind
    endif
endfunction

function! ToggleTagbar()
    if exists("g:tagbar") && g:tagbar.IsOpen()
        TagbarClose
    else
        TagbarOpen
    endif
endfunction

" Key mappings for custom functions
nnoremap <leader>n :call ToggleNERDTree()<CR>
nnoremap <leader>t :call ToggleTagbar()<CR>

" File type specific settings
autocmd FileType python setlocal expandtab shiftwidth=4 tabstop=4
autocmd FileType javascript setlocal expandtab shiftwidth=2 tabstop=2
autocmd FileType html setlocal expandtab shiftwidth=2 tabstop=2
autocmd FileType css setlocal expandtab shiftwidth=2 tabstop=2
autocmd FileType go setlocal noexpandtab shiftwidth=4 tabstop=4
autocmd FileType rust setlocal expandtab shiftwidth=4 tabstop=4

Installation Script

Automated Installation

#!/bin/bash
# install.sh

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running on supported OS
check_os() {
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="linux"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macos"
    else
        print_error "Unsupported operating system: $OSTYPE"
        exit 1
    fi
    print_status "Detected OS: $OS"
}

# Install dependencies
install_dependencies() {
    print_status "Installing dependencies..."
    
    if [[ "$OS" == "linux" ]]; then
        # Update package list
        sudo apt-get update
        
        # Install tmux
        if ! command -v tmux &> /dev/null; then
            sudo apt-get install -y tmux
        fi
        
        # Install vim
        if ! command -v vim &> /dev/null; then
            sudo apt-get install -y vim
        fi
        
        # Install git
        if ! command -v git &> /dev/null; then
            sudo apt-get install -y git
        fi
        
        # Install curl
        if ! command -v curl &> /dev/null; then
            sudo apt-get install -y curl
        fi
        
    elif [[ "$OS" == "macos" ]]; then
        # Check if Homebrew is installed
        if ! command -v brew &> /dev/null; then
            print_error "Homebrew is required but not installed. Please install Homebrew first."
            exit 1
        fi
        
        # Install tmux
        if ! command -v tmux &> /dev/null; then
            brew install tmux
        fi
        
        # Install vim
        if ! command -v vim &> /dev/null; then
            brew install vim
        fi
    fi
    
    print_status "Dependencies installed successfully"
}

# Install TPM (Tmux Plugin Manager)
install_tpm() {
    print_status "Installing TPM (Tmux Plugin Manager)..."
    
    if [[ ! -d ~/.tmux/plugins/tpm ]]; then
        git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm
        print_status "TPM installed successfully"
    else
        print_warning "TPM already installed"
    fi
}

# Install vim-plug
install_vim_plug() {
    print_status "Installing vim-plug..."
    
    if [[ ! -f ~/.vim/autoload/plug.vim ]]; then
        curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
            https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
        print_status "vim-plug installed successfully"
    else
        print_warning "vim-plug already installed"
    fi
}

# Backup existing configurations
backup_configs() {
    print_status "Backing up existing configurations..."
    
    # Backup tmux config
    if [[ -f ~/.tmux.conf ]]; then
        mv ~/.tmux.conf ~/.tmux.conf.backup.$(date +%Y%m%d_%H%M%S)
        print_status "Backed up existing .tmux.conf"
    fi
    
    # Backup vim config
    if [[ -f ~/.vimrc ]]; then
        mv ~/.vimrc ~/.vimrc.backup.$(date +%Y%m%d_%H%M%S)
        print_status "Backed up existing .vimrc"
    fi
}

# Install configurations
install_configs() {
    print_status "Installing configurations..."
    
    # Create necessary directories
    mkdir -p ~/.vim/undodir
    mkdir -p ~/.vim/plugged
    
    # Copy tmux configuration
    cp tmux/tmux.conf ~/.tmux.conf
    print_status "Installed tmux configuration"
    
    # Copy vim configuration
    cp vim/vimrc ~/.vimrc
    print_status "Installed vim configuration"
}

# Install plugins
install_plugins() {
    print_status "Installing plugins..."
    
    # Install tmux plugins
    ~/.tmux/plugins/tpm/bin/install_plugins
    
    # Install vim plugins
    vim +PlugInstall +qall
    
    print_status "Plugins installed successfully"
}

# Main installation function
main() {
    print_status "Starting tmux-vim configuration installation..."
    
    check_os
    install_dependencies
    backup_configs
    install_tpm
    install_vim_plug
    install_configs
    install_plugins
    
    print_status "Installation completed successfully!"
    print_status "Please restart your terminal or run 'tmux new-session' to start using tmux"
    print_status "Run ':PlugInstall' in vim to install additional plugins if needed"
}

# Run main function
main "$@"

Advanced Features

tmux Scripts

#!/bin/bash
# ~/.tmux/scripts/dev-session.sh

# Create a development session with multiple windows
tmux new-session -d -s dev -n main
tmux send-keys -t dev:main 'cd ~/projects' Enter

# Create additional windows
tmux new-window -t dev -n editor
tmux new-window -t dev -n server
tmux new-window -t dev -n logs
tmux new-window -t dev -n git

# Configure windows
tmux send-keys -t dev:editor 'vim' Enter
tmux send-keys -t dev:server 'python -m http.server 8000' Enter
tmux send-keys -t dev:logs 'tail -f /var/log/syslog' Enter
tmux send-keys -t dev:git 'git status' Enter

# Split main window
tmux split-window -t dev:main -h
tmux split-window -t dev:main -v

# Attach to session
tmux attach-session -t dev

Vim Functions

" Custom Vim functions

" Function to toggle between absolute and relative line numbers
function! ToggleLineNumbers()
    if &number && &relativenumber
        set nonumber norelativenumber
    elseif &number
        set relativenumber
    else
        set number
    endif
endfunction

" Function to format JSON
function! FormatJSON()
    :%!python -m json.tool
endfunction

" Function to remove trailing whitespace
function! RemoveTrailingWhitespace()
    let l:save_cursor = getpos(".")
    :%s/\s\+$//e
    call setpos('.', l:save_cursor)
endfunction

" Key mappings for custom functions
nnoremap <leader>ln :call ToggleLineNumbers()<CR>
nnoremap <leader>fj :call FormatJSON()<CR>
nnoremap <leader>rtw :call RemoveTrailingWhitespace()<CR>

Productivity Tips

tmux Workflow

  1. Session Management: Use descriptive session names
  2. Window Organization: Group related tasks in windows
  3. Pane Layouts: Use consistent pane layouts
  4. Resurrection: Save and restore sessions automatically
  5. Scripting: Automate common workflows

Vim Productivity

  1. Modal Editing: Master normal, insert, and visual modes
  2. Motion Commands: Learn efficient navigation
  3. Text Objects: Use text objects for precise editing
  4. Macros: Record and replay complex operations
  5. Plugins: Use plugins to extend functionality

Customization Options

Theme Customization

# tmux theme customization
set -g status-bg '#1e1e1e'
set -g status-fg '#ffffff'
set -g window-status-current-bg '#00ff00'
set -g window-status-current-fg '#000000'

Key Binding Customization

" Custom key bindings
nnoremap <leader>ff :Files<CR>
nnoremap <leader>fg :Rg<CR>
nnoremap <leader>fb :Buffers<CR>
nnoremap <leader>fh :History<CR>

Troubleshooting

Common Issues

  1. Plugin Installation: Ensure plugin managers are properly installed
  2. Key Conflicts: Check for conflicting key bindings
  3. Performance: Disable unused plugins for better performance
  4. Compatibility: Ensure terminal supports required features

Debugging

# tmux debugging
tmux -V  # Check version
tmux list-sessions  # List active sessions
tmux show-options  # Show current options

# vim debugging
:version  # Check vim version
:scriptnames  # List loaded scripts
:PlugStatus  # Check plugin status

Lessons Learned

Configuration Management

  • Version Control: Keep configurations in version control
  • Backup Strategy: Always backup existing configurations
  • Modular Design: Separate concerns into different files
  • Documentation: Document custom configurations

Productivity Optimization

  • Muscle Memory: Consistent key bindings improve efficiency
  • Workflow Integration: Integrate with existing workflows
  • Customization: Tailor configurations to specific needs
  • Learning Curve: Invest time in learning advanced features

Future Enhancements

Advanced Features

  • LSP Integration: Language Server Protocol support
  • Git Integration: Advanced git workflow integration
  • Debugging: Integrated debugging capabilities
  • Testing: Test runner integration

Performance Improvements

  • Lazy Loading: Load plugins on demand
  • Caching: Cache frequently used data
  • Optimization: Profile and optimize configurations
  • Memory Management: Efficient memory usage

Conclusion

The tmux-vim configuration project demonstrates how proper terminal setup can significantly improve developer productivity. Key achievements include:

  • Comprehensive Setup: Complete tmux and Vim configuration
  • Plugin Management: Automated plugin installation and management
  • Customization: Extensive customization options
  • Documentation: Clear documentation and usage instructions
  • Automation: Automated installation and update scripts

The project is available on GitHub and provides a solid foundation for terminal-based development workflows.


This project represents my exploration into terminal productivity optimization and showcases how proper configuration can transform the development experience. The lessons learned here continue to influence my approach to development environment setup and productivity optimization.