2013-07-20 64 views
4

例如,一行代碼在我的功能如何打印特殊字符中的Emacs Lisp

(message "char %c:%d" character count) 

將打印計數的每個字符。對於非打印字符,如換行和標籤,我想輸出的樣子:的

\n:4 
\t:6 

,而不是打印換行和標籤字面上。我怎樣才能做到這一點?

+0

我不認爲Emacs會以這種方式逃脫字符。我只看到它使用八進制代碼。無論如何,我認爲你可以在Bash中用'printf「%q」來做到這一點。所以你可以調用shell命令 - 這是否是一個好的解決方案,真正取決於你需要的情況。 – 2013-07-20 07:26:09

+0

任何其他方式都很好 - 只是不要直接打印它們。 emacs沒有內置的方法來做到這一點是令人驚訝的...... – RNA

+0

嗯......現在我試圖找到Emacs在做這種轉換的地方,這一切都深入到C代碼中,而且它看起來並不像可以直接從那裏獲得該功能。 – 2013-07-20 17:04:31

回答

1

有可能在Emacs的一些代碼的地方,可以爲你做這一點,但一個方法是編寫特殊字符轉換爲字符串的函數:

(defun print-char(c) 
    (case c 
    (?\n "\\n") 
    (?\t "\\t") 
    (t (string c)))) 

請注意,您需要使用字符串格式而不是字符,因爲您實際上是爲每個特殊字符寫入多個字符。

+0

謝謝,但它並不理想。除了換行符和製表符之外,可能會有更多特殊字符。將它們全部列在函數中將會很痛苦。 – RNA

3

至於建議的@wvxvw

(defun escaped-print (c) 
    (if (and (< c ?z) 
      (> c ?A)) 
     (string c) 
    (substring (shell-command-to-string (format "printf \"%%q\" \"%s\"" (string c))) 
       2 -1))) 

的子部分是從printf的輸出切出多餘的東西。我對這個命令並不瞭解,所以它可能並不完美。

5

您可以通過在打印之前綁定某些變量來實現的某些

`print-escape-newlines' is a variable defined in `C source code'. 
Its value is nil 

Documentation: 
Non-nil means print newlines in strings as `\n'. 
Also print formfeeds as `\f'. 

還有:

print-escape-nonascii 
    Non-nil means print unibyte non-ASCII chars in strings as \OOO. 

print-escape-multibyte 
    Non-nil means print multibyte characters in strings as \xXXXX. 

這些所有的工作與prin1,所以你可以在格式使用%S代碼。例如:

(let ((print-escape-newlines t)) 
    (format "%S" "new\nline"))