程式碼縮排風格爭論不休,**Tab 寬度設定**直接影響可讀性與團隊一致性。Vim 透過 ~/.vimrc 三大參數控制 Tab 行為,本文完整說明並給出**主流語言推薦配置**。
| 參數 | 預設 | 功能 | 建議值 |
|---|---|---|---|
tabstop (ts) | 8 | **顯示時**一個 Tab 字元佔用的螢幕寬度 (空格數) | 4 (或 2) |
shiftwidth (sw) | 8 | **自動縮排/>>/<<** 使用的寬度 | 同 tabstop |
expandtab (et) | off | **輸入 Tab 鍵時插入空格而非 Tab 字元** | on (大多數語言) |
| 組合 | 按 Tab 鍵產生 | 顯示寬度 | 適用場景 |
|---|---|---|---|
noet ts=4 sw=4 | 真 Tab 字元 (\t) | 4 格 | Makefile、Go、Kernel C (強制 Tab) |
et ts=4 sw=4 | 4 空格 | 4 格 | **Python、Java、JS/TS、C/C++、Ruby、Rust** 主流推薦 |
et ts=2 sw=2 | 2 空格 | 2 格 | HTML/CSS、Vue/React 元件、YAML、Markdown |
noet ts=8 sw=8 | 真 Tab | 8 格 | 舊慣例、終端機顯示相容 |
:source % 或重開 Vim)
" === 通用基礎 ===
set number
set relativenumber
set cursorline
set wrap
set mouse=a
set undofile
set history=1000
set hlsearch incsearch
set ignorecase smartcase
" === 縮排核心 (根據專案類型二選一) ===
" 方案 A: 空格縮排 4 格 (Python, Java, C/C++, JS/TS, Rust, Go* 等)
set tabstop=4
set shiftwidth=4
set expandtab
set softtabstop=4 " 按退格鍵時視為 4 空格
" 方案 B: 空格縮排 2 格 (HTML, CSS, Vue, React, YAML, Markdown)
" set tabstop=2
" set shiftwidth=2
" set expandtab
" set softtabstop=2
" 方案 C: 真 Tab (Makefile, Kernel, Go 官方風格)
" set tabstop=8
" set shiftwidth=8
" set noexpandtab
" === 輔助:顯示不可見字元 ===
set list
set listchars=tab:▸\ ,trail:·,extends:»,precedes:«,nbsp:×
" 顯示 Tab 為 ▸、行尾空格為 ·、超出螢幕 » «、不換行空格 ×
" === 快速切換縮排風格 (對應不同專案) ===
command! Tab4 setlocal tabstop=4 shiftwidth=4 expandtab softtabstop=4
command! Tab2 setlocal tabstop=2 shiftwidth=2 expandtab softtabstop=2
command! Tab8 setlocal tabstop=8 shiftwidth=8 noexpandtab
command! TabGo setlocal tabstop=8 shiftwidth=8 noexpandtab
" 使用 :Tab4 / :Tab2 / :Tab8 / :TabGo 切換
.editorconfig)
# .editorconfig
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{html,css,scss,vue,js,ts,jsx,tsx,yaml,yml,md}]
indent_size = 2
[Makefile]
indent_style = tab
indent_size = 8
Vim 安裝 editorconfig-vim 外掛即可自動讀取,**無需手動切換**。
# vim: set ts=4 sw=4 et :
或在 ~/.vimrc 設 set modeline (預設開啟)。
" ~/.vim/ftplugin/python.vim
setlocal tabstop=4 shiftwidth=4 expandtab softtabstop=4
" ~/.vim/ftplugin/html.vim
setlocal tabstop=2 shiftwidth=2 expandtab softtabstop=2
" ~/.vim/ftplugin/go.vim
setlocal tabstop=8 shiftwidth=8 noexpandtab
:retab (依當前 et/ts/sw 重新格式化全檔)。:set list 顯示 ▸ (Tab) 與 · (空格)。:set paste 進入貼上模式 → 貼上 → :set nopaste,或用 :r !cat 讀取 stdin。**Tab 寬度無絕對標準,團隊一致性才是王道**。在 ~/.vimrc 設定通用預設 (建議 et ts=4 sw=4),再透過 **EditorConfig** 或 **ftplugin** 依專案/語言自動切換,配合 :retab 整理既有檔案,**一次設定,處處一致**,徹底告別「縮排大戰」。