Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print special char in emacs lisp

Tags:

emacs

elisp

For example, one line of code in my function

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

will print the counts for each character. For nonprintable chars, such as newline and tab, I want the output looks like:

 \n:4
 \t:6

instead of printing a newline and tab literally. how can I do that?

like image 950
RNA Avatar asked Jul 20 '13 00:07

RNA


3 Answers

You can achieve some of this by let-binding certain 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's 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.

These all work with prin1, so you can use the %S code in format. e.g.:

(let ((print-escape-newlines t))
  (format "%S" "new\nline"))
like image 86
phils Avatar answered Sep 22 '22 16:09

phils


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)))

The substring part is to cut out extra stuff from printf's output. I don't have a great deal of knowledge about this command, so it might not be flawless.

like image 20
Malabarba Avatar answered Sep 24 '22 16:09

Malabarba


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

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

Note that you need to use string format rather than character because you're actually writing multiple characters for each special character.

like image 44
justinhj Avatar answered Sep 25 '22 16:09

justinhj