Elisp: Print, Output
Here's a summary of most basic elisp printing functions:
(message FORMAT-STRING &rest ARGS)
print a format string to the message buffer.
(insert &rest ARGS)
instert string to current buffer, at cursor position.
(print OBJECT &optional PRINTCHARFUN)
print lisp object. Output can be read back by function
Optional arg for a target buffer, or other functions.
(prin1 OBJECT &optional PRINTCHARFUN)
like print, but does not add newline at end.
(princ OBJECT &optional PRINTCHARFUN)
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 ;; %d is decimal number (message "age is: %d " 16) ;; %s is for string (message "name is: %s " "Joe") ;; %c is char by unicode codepoint in decimal (message "Mid init is: %c " 65) ;; 65 is A
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, because the Messages buffer scrolls off.
(setq xbuff (generate-new-buffer "*my output*")) (print "something" xbuff) (switch-to-buffer xbuff )
“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")) ; (x y) (prin1 '("x" "y")) ; ("x" "y")
(with-output-to-temp-buffer BUFNAME &rest BODY)
Bind ‘standard-output’ to buffer BUFNAME, eval BODY, then show that buffer.
This construct makes buffer BUFNAME empty before running BODY.
It does not make the buffer current for BODY.
Instead it binds ‘standard-output’ to that buffer, so that output
generated with ‘prin1’ and similar functions in BODY goes into the buffer.
(setq xbuff (generate-new-buffer "*my output*")) (with-output-to-temp-buffer xbuff ;; this is inserted in current buffer (insert "xyz") ;; this is printed in buffer xbuff (print "abc")) (switch-to-buffer xbuff )
Elisp, Writing Scritpts
If you have a question, put $5 at patreon and message me.