萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux Vim 設定 Tab 寬度:.vimrc 中 set tabstop/shiftwidth/expandtab 完整說明

程式碼縮排風格爭論不休,**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=44 空格4 格**Python、Java、JS/TS、C/C++、Ruby、Rust** 主流推薦
et ts=2 sw=22 空格2 格HTML/CSS、Vue/React 元件、YAML、Markdown
noet ts=8 sw=8真 Tab8 格舊慣例、終端機顯示相容

寫入 ~/.vimrc (立即生效::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 / 模型行 / ftplugin)

1. EditorConfig (跨編輯器、專案根目錄 .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 外掛即可自動讀取,**無需手動切換**。

2. Vim 模型行 (檔案首/尾 5 行內)


# vim: set ts=4 sw=4 et :

或在 ~/.vimrc 設 set modeline (預設開啟)。

3. ftplugin (檔案類型專屬設定)


" ~/.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

常見操作技巧

  • 現有檔案 Tab ↔ 空格轉換::retab (依當前 et/ts/sw 重新格式化全檔)。
  • 檢測檔案實際縮排::set list 顯示 ▸ (Tab) 與 · (空格)。
  • 貼上程式碼亂縮排::set paste 進入貼上模式 → 貼上 → :set nopaste,或用 :r !cat 讀取 stdin。

結語

**Tab 寬度無絕對標準,團隊一致性才是王道**。在 ~/.vimrc 設定通用預設 (建議 et ts=4 sw=4),再透過 **EditorConfig** 或 **ftplugin** 依專案/語言自動切換,配合 :retab 整理既有檔案,**一次設定,處處一致**,徹底告別「縮排大戰」。

copyright © 萬盛學電腦網 all rights reserved