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?
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"))
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With