Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux Vim/Vi 進階配置技巧:語法高亮、滑鼠支援、自動縮進與 Tab 寬度優化

編輯:Linux 教學

前言

Vim (Vi Improved) 是 Linux 系統管理與開發核心編輯器。預設配置較保守,通過編輯 vimrc 可大幅提升編碼體驗。本文涵蓋配置檔定位、語法高亮、滑鼠模式、縮進自動化與 Tab 寬度客製化。

一、配置檔路徑與生效優先級

檔案作用域優先級
/etc/vim/vimrc 或 /usr/share/vim/vimrc系統級 (所有用戶)低
~/.vimrc用戶級 (當前用戶)高 (覆蓋系統設定)
~/.vim/vimrc用戶級 (現代結構)高

建議:編輯 ~/.vimrc,不污染系統環境,備份遷移方便。

二、啟用語法高亮

" ~/.vimrc
syntax on          " 開啟語法高亮核心引擎
filetype on        " 檢測檔案類型
filetype plugin on " 載入檔案類型專屬插件
filetype indent on " 載入檔案類型專屬縮進規則

系統級 vimrc 常預置 "syntax on (被註釋),取消註釋即可。

三、滑鼠支援模式

set mouse=a        " 所有模式 (正常/視覺/插入/命令) 啟用滑鼠
" 可選值: n=正常 v=視覺 i=插入 c=命令 r=hit-enter a=所有

啟用後:點擊移動游標、滾輪翻頁、視覺模式選取文字。
注意:終端機需支援滑鼠事件 (現代終端均支援),純文字主控台 (TTY) 無效。

四、自動縮進

set autoindent     " 新行自動沿用上一行縮進
set smartindent    " 針對 C 類語言智能縮進 (遇 { 增加、遇 } 減少)
set cindent        " 更嚴格的 C 風格縮進 (需配合 cinoptions)
" 推薦組合:
set autoindent
set smartindent

Python 等靠縮進語義語言,smartindent 可能誤判,建議依賴 filetype indent on 載入專屬縮進腳本。

五、Tab 寬度與空格轉換 (核心痛點)

" 顯示寬度
set tabstop=4      " Tab 顯示為 4 格寬度
set shiftwidth=4   " 自動縮進/<< >> 操作寬度 = 4
set softtabstop=4  " 編輯時按 Tab/Backspace 感覺寬度 = 4

" 核心策略:將 Tab 轉為空格 (Python/現代規範強制)
set expandtab      " 將 Tab 字元轉換為空格
set smarttab       " 行首按 Tab 依 shiftwidth,非行首依 tabstop

" 禁用 Tab 字元 (強制空格)
" set noexpandtab  " 保留 Tab 字元 (Makefile/Go 語言需求)

場景化預設

語言/場景推薦設定
Python / YAML / 現代 Webts=4 sw=4 sts=4 et
C / C++ / Javats=4 sw=4 sts=4 et (或 Google 風格 ts=2)
Go / Makefilets=4 sw=4 sts=4 noet (必須保留 Tab)
HTML / CSS / JSts=2 sw=2 sts=2 et

可用 autocmd FileType python setlocal ts=4 sw=4 et 實現按檔案類型自動切換。

六、一鍵切換 Tab/空格顯示 (除錯神技)

set list
set listchars=tab:▸\ ,trail:·,extends:»,precedes:«,nbsp:×
" 正常模式下輸入 :set list! 切換可見字元顯示

七、讓 vi 指令直接啟動 vim

# ~/.bashrc 或 /etc/profile
alias vi='vim'
# 重新載入: source ~/.bashrc

八、配置生效驗證

:set syntax?      " 應顯示 syntax=on
:set mouse?       " 應顯示 mouse=a
:set ts? sw? sts? et?  " 檢查縮進參數
:verbose set ts?  " 顯示最後設定該選項的腳本位置

結語

精心調教的 .vimrc 是開發者的得力助手。從 syntax on、set mouse=a、autoindent 到 expandtab 空格化策略,每一項配置都在減少認知負擔、避免縮進錯誤。建議建立個人化 .vimrc 並納入版本控制 (Git),隨時同步至各台工作機器。

Copyright © Windows教程網 All Rights Reserved