Xah Lee, 2010-08-07
This is a short tutorial on printing in emacs lisp. If you don't know elisp, first take a look at Emacs Lisp Basics.
The most basic printing function is “message”. Here's a example:
; printing (message "hi") ; printing variable values (message "Her age is: %d " 16) ; %d is for number (message "Her name is: %s " "Vicky") ; %s is for string (message "Her mid init is: %c " 86) ; %c is for character in ascii code
Note: You can see all past output from “message” in the buffer named “*Messages*”. You can switch to it by 【Alt+x switch-to-buffer】.
The “message” function prints to the special buffer “*Messages*”. That buffer is special, because it is the general output destination for any messages from emacs, designed to be read by human.
For example, it automatically truncate the top entries when the buffer reaches some size. Also, when a message is repeated many times, it automatically condense the repeated lines. And if the a message is a huge line, the line is truncated automatically.
;; print a line many times (setq xx 1) (while (< xx 20) (message "yay") (setq xx (1+ xx)) ) (switch-to-buffer "*Messages*")
In the above example, you'll just see: “yay [19 times]”.
(info "(elisp)Displaying Messages")
When writing a elisp script that does batch processing, it's best to print to your own buffer.
For example, suppose you have a elisp batch script that do find
and replace on all files in a dir. For each file visited, it prints
out the file path. If you use (message …), it prints to the
“*Messages*” buffer, which automatically roll off the top if you have
more than a hundred lines. Also, it may intermix your script's output
with output from other emacs activities.
Here's a example of printing to your own buffer:
(with-output-to-temp-buffer "*my output*" (mapc 'my-process-file (find-lisp-find-files inputDir "\\.html$")) (princ "Done.\n") (switch-to-buffer "*my output*") )
Elisp provides the “print” function. The basic syntax is this:
(print OBJECT)
The “OBJECT” is any elisp object you want to print. It can be any lisp datatype, such as string, number, list, …, etc.
How a lisp object is converted to string for printing is done by the “format” function. Use describe-function to lookup its docs.
For example, if you want better control on how your numbers are formatted, you can do:
(print (format …))
Elisp provide several other convenient functions to control printing. Here's a summary of their differences:
| Function Name | Purpose | Comment |
|---|---|---|
| print with newline. | output can be read back by “read”. | |
| prin1 | like print, but does not add newline. | output can be read back by “read”. |
| princ | print without newline nor delimiters. | For human reading. Output can not be read back |
(info "(elisp) Output Functions")