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 開啟 UTF-8 檔案顯示亂碼?四大編碼參數完整解析與修正

編輯:關於 Linux

Vim 顯示亂碼核心在於四個編碼相關選項設定不當:encoding、termencoding、fileencoding、fileencodings。理解其運作機制即可精準修正。

四大參數角色解析

參數角色建議值
encodingVim 內部記憶體編碼 (緩衝區、暫存器、腳本字串)utf-8 (不可中途變更,僅在 .vimrc 設定)
termencoding終端機顯示編碼 (Vim 將 internal encoding 轉為此編碼輸出)若終端為 UTF-8 可不設;SSH 連線若為 Big5/GBK 則設為對應值
fileencoding當前檔案磁碟儲存編碼 (讀取時偵測、寫入時轉換)由 Vim 自動偵測設定,不可手動修正已讀檔案
fileencodings自動偵測優先順序列表 (嚴格→寬鬆)ucs-bom,utf-8,cp936,gb18030,big5,euc-jp,euc-kr,latin1

推薦 .vimrc 設定

" 內部編碼
set encoding=utf-8
set langmenu=zh_CN.UTF-8
language message zh_CN.UTF-8

" 終端編碼 (視實際環境調整)
" set termencoding=utf-8

" 自動偵測優先順序
set fileencodings=ucs-bom,utf-8,cp936,gb18030,big5,euc-jp,euc-kr,latin1

臨時指定編碼開啟檔案

:e ++enc=utf-8 filename.txt
:e ++enc=gbk filename.txt

常見場景對策

  • SSH 連線亂碼:本地終端為 UTF-8,遠端終端為 GBK → 保持 encoding=utf-8,設定 termencoding=gbk 讓 Vim 顯示時轉碼,編輯不丟字。
  • GVim (圖形介面):termencoding 無效,GTK2 固定 UTF-8,Windows 版 GVim 忽略此選項。
  • 強制另存新編碼::set fileencoding=gbk → :w。

Vim 編碼設定

核心原則: encoding=utf-8 固定內部編碼,fileencodings 由嚴格到寬鬆排序,termencoding 僅在終端編碼與內部不同時設定。亂碼多半是 fileencodings 順序錯誤導致誤判,調整順序即可解決 90% 情況。
Copyright © Windows教程網 All Rights Reserved