2009-12-01 19 views
2

我有一個小的elisp腳本,它在區域或整個文件上應用Perl :: Tidy。作爲參考,這裏的腳本(從EmacsWiki借用):如何設置shell-command-on-region輸出的編碼?

(defun perltidy-command(start end) 
"The perltidy command we pass markers to." 
(shell-command-on-region start 
         end 
         "perltidy" 
         t 
         t 
         (get-buffer-create "*Perltidy Output*"))) 

(defun perltidy-dwim (arg) 
"Perltidy a region of the entire buffer" 
(interactive "P") 
(let ((point (point)) (start) (end)) 
(if (and mark-active transient-mark-mode) 
    (setq start (region-beginning) 
      end (region-end)) 
    (setq start (point-min) 
     end (point-max))) 
(perltidy-command start end) 
(goto-char point))) 

(global-set-key "\C-ct" 'perltidy-dwim) 

我使用的是當前Emacs 23.1的Windows(EmacsW32)。我遇到的問題是,如果我將該腳本應用於UTF-8編碼文件(狀態欄中的「U(Unix)」),則輸出將返回Latin-1編碼,即每個非編碼文件有兩個或更多字符ASCII源字符。

有沒有什麼辦法可以解決這個問題?

編輯:問題似乎在我的​​使用(set-terminal-coding-system 'utf-8-unix)來解決。任何人都有其他解決方案,請繼續寫下來!

回答

2

引用爲shell-command-on-regionC-h f shell-command-on-region RET)的文檔:

要在輸入和輸出到外殼命令轉換非ASCII字符 指定的編碼系統中,使用C-X RETÇ 該命令之前。默認情況下,輸入(來自當前緩衝區) 採用與用於保存文件「buffer-file-coding-system」的相同編碼系統進行編碼。如果輸出要替換該區域,則從該相同編碼系統對其進行解碼。

非交互參數是START,END,COM​​MAND, OUTPUT-BUFFER,REPLACE,ERROR-BUFFER和DISPLAY-ERROR-BUFFER。 非交互呼叫者可以通過綁定 `編碼 - 讀取系統'和`編碼 - 系統可寫入'指定編碼系統。

換句話說,你會做這樣的事情

(let ((coding-system-for-read 'utf-8-unix)) 
    (shell-command-on-region ...)) 

這是未經測試,不知道的coding-system-for-read值(或者-write呢?或者還有?)應該是在你的情況是什麼。我想你也可以利用OUTPUT-BUFFER參數並將輸出指向一個緩衝區,該緩衝區的編碼系統被設置爲你所需要的。

另一種選擇可能是在perltidy調用中擺動區域設置,但是再次沒有關於您現在使用的更多信息,也沒有辦法在類似於您的系統上進行實驗,我只能提示。

2

下面是shell-command-on-region文件

To specify a coding system for converting non-ASCII characters 
in the input and output to the shell command, use C-x RET c 
before this command. By default, the input (from the current buffer) 
is encoded using coding-system specified by `process-coding-system-alist', 
falling back to `default-process-coding-system' if no match for COMMAND 
is found in `process-coding-system-alist'. 

在執行時,它看起來在第一編碼從process-coding-system-alist系統,如果它是零,然後從default-process-coding-system看起來。

如果您想更改編碼,您可以將您的轉換選項添加到process-coding-system-alist,下面是它的內容。

Value: (("\\.dz\\'" no-conversion . no-conversion) 
... 
("\\.elc\\'" . utf-8-emacs) 
("\\.utf\\(-8\\)?\\'" . utf-8) 
("\\.xml\\'" . xml-find-file-coding-system) 
... 
("" undecided)) 

或者,如果您沒有設置process-coding-system-alist,它是零,你可以在你的編碼選項分配到default-process-coding-system

例如:

(setq default-process-coding-system '(utf-8 . utf-8)) 

(如果輸入編碼爲utf-8 ,然後輸出編碼爲utf-8

(setq default-process-coding-system '(undecided-unix . iso-latin-1-unix)) 

我也寫了一個post關於這個如果你想要的細節。