Emacs lisp; how to make a string from a variable of any type?

倖福魔咒の 提交于 2020-01-14 10:12:44

问题


Like error messages for wrongly called functions show, eg.:

(message (file-attributes "."))

Produces the message:

"eval: Wrong type argument: stringp, ("/home14/tjones" 1 0 0 (20415 35598) (20211 19255) (20211 19255) 14 "lrwxrwxrwx" t ...)"

How do you do this type of translation intentionally, eg.:

(message (thing-to-string (file-attributes ".")))

To message something like:

("/home14/tjones" 1 0 0 (20415 35598) (20211 19255) (20211 19255) 14 "lrwxrwxrwx" t ...)

This is for debugging/info only. I'm assuming there's a way as message is doing it, but is this exposed to us users?


回答1:


Look into prin1-to-string and related functions (prin1, princ, etc). And do try the manual! http://www.gnu.org/software/emacs/manual/html_node/elisp/Output-Functions.html




回答2:


The first argument to message is supposed to be a format string (same as the one you pass to the format function. If you give it the format "%s" (or "%S" as in Stefan's answer.) it will stringify anything you give it as the next argument.

The capital S version will escape characters in the string so that it can be read again as an s-expression. In this case, I think that is what you want. So, you don't need to change your code very much to get what you are looking for:

(message "%S" (file-attributes "."))



回答3:


In your example, message did not do anything (it just refused to run), so the translation to string was done by the read-eval-print loop which caught the error and turned it into a text message. But yes, message can also do that, and it does that by calling format, which internally uses things like prin1-to-string. So (format "%S" <foo>) would do your thing-to-string.



来源:https://stackoverflow.com/questions/10755677/emacs-lisp-how-to-make-a-string-from-a-variable-of-any-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!