How to print special char in emacs lisp

For example, one line of code in my function

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

will print counts for each character. For non-printable characters like newline and tab, I want the result to look like this:

  \n:4 \t:6 

instead of printing a new line and tab literally. How can i do this?

+4
source share
3 answers

You can achieve this by linking some variables before printing.

 `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'. 

There also:

 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. 

They all work with prin1 , so you can use the %S code in the format. eg:.

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

As suggested by @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))) 

A substring is to cut out excess material from printf output. I don’t have much information about this team, so it cannot be perfect.

+3
source

There may be some code in emacs that can do this for you, but one way would be to write a function that converts special characters to a string:

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

Note that you need to use the string format, not the character, because you are actually writing multiple characters for each special character.

+1
source

Source: https://habr.com/ru/post/1492412/


All Articles