我正在嘗試gnome-terminal
從命令行檢測當前的字元編碼。我嘗試過使用gconftool
:
$ gconftool-2 --get /apps/gnome-terminal/profiles/Default/encoding
current
$ gconftool-2 --type string --set /apps/gnome-terminal/profiles/Default/encoding
en_US.UTF-8
$ gconftool-2 --get /apps/gnome-terminal/profiles/Default/encoding
en_US.UTF-8
但是如果我現在進入gnome-terminal
選單並選擇Terminal->Set Character Encoding->ISO-8859-10
然後再次運行
$ gconftool-2 --get /apps/gnome-terminal/profiles/Default/encoding
en_US.UTF-8
因此,即使終端正在使用該編碼,編碼/apps/gnome-terminal/profiles/Default/encoding
也沒有改變。ISO-8859-10
所以它似乎gconftool
不能用來確定目前的編碼。
答案1
我建議檢查locale charmap
的輸出(報告 $LANG、$LC_CTYPE、$LC_ALL 設定的值)。此方法不會直接查詢終端,但對於大多數應用程式來說,正確設定區域設定並與終端保持一致至關重要。如果它報告實際行為之外的任何其他內容,則不僅是您的應用程序,而且幾乎所有其他應用程式都會在終端中出現異常行為,這不是您的錯。當然,用戶可以從選單中更改編碼,但是如果他們決定搬起石頭砸自己的腳,那麼您就沒有什麼可以/應該做的了。偵測錯誤的系統範圍設定不是您的任務。此外,您無法注意到用戶在應用程式運行時是否會切換編碼,因此我認為在啟動時驗證它沒有多大意義。
如果您確實需要檢查運行時行為,您可以發出轉義序列來查詢遊標位置(並以某種格式報告它,就像從鍵盤鍵入一樣),然後發出一些字節,例如形成單個字元UTF-8 中的多個字符,而任何其他編碼中的多個字符(同時禁用本地回顯,因此用戶按鍵不會使遊標前進),並再次查詢遊標位置。也許太麻煩了,而且確實不值得付出努力。
答案2
/apps/gnome-terminal/profiles/Default/encoding
這是一個半解決方案,解決了當等於 string時確定編碼的問題 current
。假設該字串current
表示gnome-terminal
應該使用當前區域設定。
檢查LANG
變數以確定編碼是很誘人的,但是根據這問題來了,這個不太可靠。相反,I18N::Langinfo
應該使用Perl 模組:
temp=$(gconftool-2 --get /apps/gnome-terminal/profiles/Default/encoding)
if [[ $temp == "current" ]] ; then
perl -MI18N::Langinfo=langinfo,CODESET -E 'say langinfo(CODESET())'
else
echo $temp
fi
請注意,此答案並未解決gnome-terminal
當使用者從gnome-terminal
選單手動變更編碼時確定編碼的問題。