Elisp: Print, Output
Here's a summary of most basic elisp printing functions:
message→ print to the message buffer.
insert→ print to current buffer, at cursor position.
prin1→ like print, but does not add newline at end.
princ→ print without newline nor delimiters. For human reading.
Simple Printing with “message”
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
You can see past output of the
message function in the buffer named “*Messages*”. You can view the buffer
view-echo-area-messages 【Ctrl+h e】.
The “*Messages*” buffer is a special buffer, because it is the general output destination for any messages from emacs.
For example, it automatically truncates the top entries when the buffer reaches some size (see variable messages-buffer-max-lines). Also, when a message is repeated many times, it automatically condenses the repeated lines. And if a message is a huge line, the line is truncated automatically. Here's a example.
;; 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, it prints “yay [19 times]” instead of the “yay” line for 19 times.
Print to Your Own Buffer
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.
;; example of printing to a temp buffer ;; prints all file path ending in html (require 'find-lisp) (with-output-to-temp-buffer "*my output*" (mapc (lambda (x) (print x)) (find-lisp-find-files "/home/xah/web/ergoemacs_org/emacs/" "\\.html$")) (switch-to-buffer "*my output*"))
In the above example, any call to print in “my-process-file” is output to your temp buffer.
“print” and “prin1” function
Elisp provides the
The “OBJECT” is any elisp object you want to print. It can be any lisp datatype, such as string, number, list, buffer, frame, …, etc.
There's also a function named
prin1. This is same as
“princ” for Human-Friendly Output
princ is similar to
(princ '("x" "y")) ; result display is (x y) (prin1 '("x" "y")) ; result display is ("x" "y")
Elisp, Writing Scritpts
If you have a question, put $5 at patreon and message me.