@c -*-texinfo-*-@c This is part of the GNU Emacs Lisp Reference Manual.@c Copyright (C) 1990, 1991, 1992, 1993, 1994, 1998, 1999@c Free Software Foundation, Inc. @c See the file elisp.texi for copying conditions.@setfilename ../info/streams@node Read and Print, Minibuffers, Debugging, Top@comment node-name, next, previous, up@chapter Reading and Printing Lisp Objects @dfn{Printing} and @dfn{reading} are the operations of converting Lispobjects to textual form and vice versa. They use the printedrepresentations and read syntax described in @ref{Lisp Data Types}. This chapter describes the Lisp functions for reading and printing.It also describes @dfn{streams}, which specify where to get the text (ifreading) or where to put it (if printing).@menu* Streams Intro:: Overview of streams, reading and printing.* Input Streams:: Various data types that can be used as input streams.* Input Functions:: Functions to read Lisp objects from text.* Output Streams:: Various data types that can be used as output streams.* Output Functions:: Functions to print Lisp objects as text.* Output Variables:: Variables that control what the printing functions do.@end menu@node Streams Intro@section Introduction to Reading and Printing@cindex Lisp reader@cindex printing@cindex reading @dfn{Reading} a Lisp object means parsing a Lisp expression in textualform and producing a corresponding Lisp object. This is how Lispprograms get into Lisp from files of Lisp code. We call the text the@dfn{read syntax} of the object. For example, the text @samp{(a .@: 5)}is the read syntax for a cons cell whose @sc{car} is @code{a} and whose@sc{cdr} is the number 5. @dfn{Printing} a Lisp object means producing text that represents thatobject---converting the object to its @dfn{printed representation}(@pxref{Printed Representation}). Printing the cons cell describedabove produces the text @samp{(a .@: 5)}. Reading and printing are more or less inverse operations: printing theobject that results from reading a given piece of text often producesthe same text, and reading the text that results from printing an objectusually produces a similar-looking object. For example, printing thesymbol @code{foo} produces the text @samp{foo}, and reading that textreturns the symbol @code{foo}. Printing a list whose elements are@code{a} and @code{b} produces the text @samp{(a b)}, and reading thattext produces a list (but not the same list) with elements @code{a}and @code{b}. However, these two operations are not precisely inverse to each other.There are three kinds of exceptions:@itemize @bullet@itemPrinting can produce text that cannot be read. For example, buffers,windows, frames, subprocesses and markers print as text that startswith @samp{#}; if you try to read this text, you get an error. There isno way to read those data types.@itemOne object can have multiple textual representations. For example,@samp{1} and @samp{01} represent the same integer, and @samp{(a b)} and@samp{(a .@: (b))} represent the same list. Reading will accept any ofthe alternatives, but printing must choose one of them.@itemComments can appear at certain points in the middle of an object'sread sequence without affecting the result of reading it.@end itemize@node Input Streams@section Input Streams@cindex stream (for reading)@cindex input stream Most of the Lisp functions for reading text take an @dfn{input stream}as an argument. The input stream specifies where or how to get thecharacters of the text to be read. Here are the possible types of inputstream:@table @asis@item @var{buffer}@cindex buffer input streamThe input characters are read from @var{buffer}, starting with thecharacter directly after point. Point advances as characters are read.@item @var{marker}@cindex marker input streamThe input characters are read from the buffer that @var{marker} is in,starting with the character directly after the marker. The markerposition advances as characters are read. The value of point in thebuffer has no effect when the stream is a marker.@item @var{string}@cindex string input streamThe input characters are taken from @var{string}, starting at the firstcharacter in the string and using as many characters as required.@item @var{function}@cindex function input streamThe input characters are generated by @var{function}, which must supporttwo kinds of calls:@itemize @bullet@itemWhen it is called with no arguments, it should return the next character.@itemWhen it is called with one argument (always a character), @var{function}should save the argument and arrange to return it on the next call.This is called @dfn{unreading} the character; it happens when the Lispreader reads one character too many and wants to ``put it back where itcame from''. In this case, it makes no difference what value@var{function} returns.@end itemize@item @code{t}@cindex @code{t} input stream@code{t} used as a stream means that the input is read from theminibuffer. In fact, the minibuffer is invoked once and the textgiven by the user is made into a string that is then used as theinput stream. If Emacs is running in batch mode, standard input is usedinstead of the minibuffer. For example,@example(message "%s" (read t))@end examplewill read a Lisp expression from standard input and print the resultto standard output.@item @code{nil}@cindex @code{nil} input stream@code{nil} supplied as an input stream means to use the value of@code{standard-input} instead; that value is the @dfn{default inputstream}, and must be a non-@code{nil} input stream.@item @var{symbol}A symbol as input stream is equivalent to the symbol's functiondefinition (if any).@end table Here is an example of reading from a stream that is a buffer, showingwhere point is located before and after:@example@group---------- Buffer: foo ----------This@point{} is the contents of foo.---------- Buffer: foo ----------@end group@group(read (get-buffer "foo")) @result{} is@end group@group(read (get-buffer "foo")) @result{} the@end group@group---------- Buffer: foo ----------This is the@point{} contents of foo.---------- Buffer: foo ----------@end group@end example@noindentNote that the first read skips a space. Reading skips any amount ofwhitespace preceding the significant text. Here is an example of reading from a stream that is a marker,initially positioned at the beginning of the buffer shown. The valueread is the symbol @code{This}.@example@group---------- Buffer: foo ----------This is the contents of foo.---------- Buffer: foo ----------@end group@group(setq m (set-marker (make-marker) 1 (get-buffer "foo"))) @result{} #<marker at 1 in foo>@end group@group(read m) @result{} This@end group@groupm @result{} #<marker at 5 in foo> ;; @r{Before the first space.}@end group@end example Here we read from the contents of a string:@example@group(read "(When in) the course") @result{} (When in)@end group@end example The following example reads from the minibuffer. Theprompt is: @w{@samp{Lisp expression: }}. (That is always the promptused when you read from the stream @code{t}.) The user's input is shownfollowing the prompt.@example@group(read t) @result{} 23---------- Buffer: Minibuffer ----------Lisp expression: @kbd{23 @key{RET}}---------- Buffer: Minibuffer ----------@end group@end example Finally, here is an example of a stream that is a function, named@code{useless-stream}. Before we use the stream, we initialize thevariable @code{useless-list} to a list of characters. Then each call tothe function @code{useless-stream} obtains the next character in the listor unreads a character by adding it to the front of the list.@example@group(setq useless-list (append "XY()" nil)) @result{} (88 89 40 41)@end group@group(defun useless-stream (&optional unread) (if unread (setq useless-list (cons unread useless-list)) (prog1 (car useless-list) (setq useless-list (cdr useless-list))))) @result{} useless-stream@end group@end example@noindentNow we read using the stream thus constructed:@example@group(read 'useless-stream) @result{} XY@end group@groupuseless-list @result{} (40 41)@end group@end example@noindentNote that the open and close parentheses remain in the list. The Lispreader encountered the open parenthesis, decided that it ended theinput, and unread it. Another attempt to read from the stream at thispoint would read @samp{()} and return @code{nil}.@defun get-file-charThis function is used internally as an input stream to read from theinput file opened by the function @code{load}. Don't use this functionyourself.@end defun@node Input Functions@section Input Functions This section describes the Lisp functions and variables that pertainto reading. In the functions below, @var{stream} stands for an input stream (seethe previous section). If @var{stream} is @code{nil} or omitted, itdefaults to the value of @code{standard-input}.@kindex end-of-file An @code{end-of-file} error is signaled if reading encounters anunterminated list, vector, or string.@defun read &optional streamThis function reads one textual Lisp expression from @var{stream},returning it as a Lisp object. This is the basic Lisp input function.@end defun@defun read-from-string string &optional start end@cindex string to objectThis function reads the first textual Lisp expression from the text in@var{string}. It returns a cons cell whose @sc{car} is that expression,and whose @sc{cdr} is an integer giving the position of the nextremaining character in the string (i.e., the first one not read).If @var{start} is supplied, then reading begins at index @var{start} inthe string (where the first character is at index 0). If you specify@var{end}, then reading is forced to stop just before that index, as ifthe rest of the string were not there.For example:@example@group(read-from-string "(setq x 55) (setq y 5)") @result{} ((setq x 55) . 11)@end group@group(read-from-string "\"A short string\"") @result{} ("A short string" . 16)@end group@group;; @r{Read starting at the first character.}(read-from-string "(list 112)" 0) @result{} ((list 112) . 10)@end group@group;; @r{Read starting at the second character.}(read-from-string "(list 112)" 1) @result{} (list . 5)@end group@group;; @r{Read starting at the seventh character,};; @r{and stopping at the ninth.}(read-from-string "(list 112)" 6 8) @result{} (11 . 8)@end group@end example@end defun@defvar standard-inputThis variable holds the default input stream---the stream that@code{read} uses when the @var{stream} argument is @code{nil}.@end defvar@node Output Streams@section Output Streams@cindex stream (for printing)@cindex output stream An output stream specifies what to do with the characters producedby printing. Most print functions accept an output stream as anoptional argument. Here are the possible types of output stream:@table @asis@item @var{buffer}@cindex buffer output streamThe output characters are inserted into @var{buffer} at point.Point advances as characters are inserted.@item @var{marker}@cindex marker output streamThe output characters are inserted into the buffer that @var{marker}points into, at the marker position. The marker position advances ascharacters are inserted. The value of point in the buffer has no effecton printing when the stream is a marker, and this kind of printingdoes not move point.@item @var{function}@cindex function output streamThe output characters are passed to @var{function}, which is responsiblefor storing them away. It is called with a single character asargument, as many times as there are characters to be output, andis responsible for storing the characters wherever you want to put them.@item @code{t}@cindex @code{t} output streamThe output characters are displayed in the echo area.@item @code{nil}@cindex @code{nil} output stream@code{nil} specified as an output stream means to use the value of@code{standard-output} instead; that value is the @dfn{default outputstream}, and must not be @code{nil}.@item @var{symbol}A symbol as output stream is equivalent to the symbol's functiondefinition (if any).@end table Many of the valid output streams are also valid as input streams. Thedifference between input and output streams is therefore more a matterof how you use a Lisp object, than of different types of object. Here is an example of a buffer used as an output stream. Point isinitially located as shown immediately before the @samp{h} in@samp{the}. At the end, point is located directly before that same@samp{h}.@cindex print example@example@group---------- Buffer: foo ----------This is t@point{}he contents of foo.---------- Buffer: foo ----------@end group(print "This is the output" (get-buffer "foo")) @result{} "This is the output"@group---------- Buffer: foo ----------This is t"This is the output"@point{}he contents of foo.---------- Buffer: foo ----------@end group@end example Now we show a use of a marker as an output stream. Initially, themarker is in buffer @code{foo}, between the @samp{t} and the @samp{h} inthe word @samp{the}. At the end, the marker has advanced over theinserted text so that it remains positioned before the same @samp{h}.Note that the location of point, shown in the usual fashion, has noeffect.@example@group---------- Buffer: foo ----------This is the @point{}output---------- Buffer: foo ----------@end group@group(setq m (copy-marker 10)) @result{} #<marker at 10 in foo>@end group@group(print "More output for foo." m) @result{} "More output for foo."@end group@group---------- Buffer: foo ----------This is t"More output for foo."he @point{}output---------- Buffer: foo ----------@end group@groupm @result{} #<marker at 34 in foo>@end group@end example The following example shows output to the echo area:@example@group(print "Echo Area output" t) @result{} "Echo Area output"---------- Echo Area ----------"Echo Area output"---------- Echo Area ----------@end group@end example Finally, we show the use of a function as an output stream. Thefunction @code{eat-output} takes each character that it is given andconses it onto the front of the list @code{last-output} (@pxref{BuildingLists}). At the end, the list contains all the characters output, butin reverse order.@example@group(setq last-output nil) @result{} nil@end group@group(defun eat-output (c) (setq last-output (cons c last-output))) @result{} eat-output@end group@group(print "This is the output" 'eat-output) @result{} "This is the output"@end group@grouplast-output @result{} (10 34 116 117 112 116 117 111 32 101 104 116 32 115 105 32 115 105 104 84 34 10)@end group@end example@noindentNow we can put the output in the proper order by reversing the list:@example@group(concat (nreverse last-output)) @result{} "\"This is the output\""@end group@end example@noindentCalling @code{concat} converts the list to a string so you can see itscontents more clearly.@node Output Functions@section Output Functions This section describes the Lisp functions for printing Lispobjects---converting objects into their printed representation.@cindex @samp{"} in printing@cindex @samp{\} in printing@cindex quoting characters in printing@cindex escape characters in printing Some of the Emacs printing functions add quoting characters to theoutput when necessary so that it can be read properly. The quotingcharacters used are @samp{"} and @samp{\}; they distinguish strings fromsymbols, and prevent punctuation characters in strings and symbols frombeing taken as delimiters when reading. @xref{Printed Representation},for full details. You specify quoting or no quoting by the choice ofprinting function. If the text is to be read back into Lisp, then you should print withquoting characters to avoid ambiguity. Likewise, if the purpose is todescribe a Lisp object clearly for a Lisp programmer. However, if thepurpose of the output is to look nice for humans, then it is usuallybetter to print without quoting. Lisp objects can refer to themselves. Printing a self-referentialobject in the normal way would require an infinite amount of text, andthe attempt could cause infinite recursion. Emacs detects suchrecursion and prints @samp{#@var{level}} instead of recursively printingan object already being printed. For example, here @samp{#0} indicatesa recursive reference to the object at level 0 of the current printoperation:@example(setq foo (list nil)) @result{} (nil)(setcar foo foo) @result{} (#0)@end example In the functions below, @var{stream} stands for an output stream.(See the previous section for a description of output streams.) If@var{stream} is @code{nil} or omitted, it defaults to the value of@code{standard-output}.@defun print object &optional stream@cindex Lisp printerThe @code{print} function is a convenient way of printing. It outputsthe printed representation of @var{object} to @var{stream}, printing inaddition one newline before @var{object} and another after it. Quotingcharacters are used. @code{print} returns @var{object}. For example:@example@group(progn (print 'The\ cat\ in) (print "the hat") (print " came back")) @print{} @print{} The\ cat\ in @print{} @print{} "the hat" @print{} @print{} " came back" @print{} @result{} " came back"@end group@end example@end defun@defun prin1 object &optional streamThis function outputs the printed representation of @var{object} to@var{stream}. It does not print newlines to separate output as@code{print} does, but it does use quoting characters just like@code{print}. It returns @var{object}.@example@group(progn (prin1 'The\ cat\ in) (prin1 "the hat") (prin1 " came back")) @print{} The\ cat\ in"the hat"" came back" @result{} " came back"@end group@end example@end defun@defun princ object &optional streamThis function outputs the printed representation of @var{object} to@var{stream}. It returns @var{object}.This function is intended to produce output that is readable by people,not by @code{read}, so it doesn't insert quoting characters and doesn'tput double-quotes around the contents of strings. It does not add anyspacing between calls.@example@group(progn (princ 'The\ cat) (princ " in the \"hat\"")) @print{} The cat in the "hat" @result{} " in the \"hat\""@end group@end example@end defun@defun terpri &optional stream@cindex newline in printThis function outputs a newline to @var{stream}. The name standsfor ``terminate print''.@end defun@defun write-char character &optional streamThis function outputs @var{character} to @var{stream}. It returns@var{character}.@end defun@defun prin1-to-string object &optional noescape@cindex object to stringThis function returns a string containing the text that @code{prin1}would have printed for the same argument.@example@group(prin1-to-string 'foo) @result{} "foo"@end group@group(prin1-to-string (mark-marker)) @result{} "#<marker at 2773 in strings.texi>"@end group@end exampleIf @var{noescape} is non-@code{nil}, that inhibits use of quotingcharacters in the output. (This argument is supported in Emacs versions19 and later.)@example@group(prin1-to-string "foo") @result{} "\"foo\""@end group@group(prin1-to-string "foo" t) @result{} "foo"@end group@end exampleSee @code{format}, in @ref{String Conversion}, for other ways to obtainthe printed representation of a Lisp object as a string.@end defun@defmac with-output-to-string body...This macro executes the @var{body} forms with @code{standard-output} setup to feed output into a string. Then it returns that string.For example, if the current buffer name is @samp{foo},@example(with-output-to-string (princ "The buffer is ") (princ (buffer-name)))@end example@noindentreturns @code{"The buffer is foo"}.@end defmac@node Output Variables@section Variables Affecting Output@defvar standard-outputThe value of this variable is the default output stream---the streamthat print functions use when the @var{stream} argument is @code{nil}.@end defvar@defvar print-escape-newlines@cindex @samp{\n} in print@cindex escape charactersIf this variable is non-@code{nil}, then newline characters in stringsare printed as @samp{\n} and formfeeds are printed as @samp{\f}.Normally these characters are printed as actual newlines and formfeeds.This variable affects the print functions @code{prin1} and @code{print}that print with quoting. It does not affect @code{princ}. Here is anexample using @code{prin1}:@example@group(prin1 "a\nb") @print{} "a @print{} b" @result{} "ab"@end group@group(let ((print-escape-newlines t)) (prin1 "a\nb")) @print{} "a\nb" @result{} "ab"@end group@end example@noindentIn the second expression, the local binding of@code{print-escape-newlines} is in effect during the call to@code{prin1}, but not during the printing of the result.@end defvar@defvar print-escape-nonasciiIf this variable is non-@code{nil}, then unibyte non-@sc{ascii}characters in strings are unconditionally printed as backslash sequencesby the print functions @code{prin1} and @code{print} that print withquoting.Those functions also use backslash sequences for unibyte non-@sc{ascii}characters, regardless of the value of this variable, when the outputstream is a multibyte buffer or a marker pointing into one.@end defvar@defvar print-escape-multibyteIf this variable is non-@code{nil}, then multibyte non-@sc{ascii}characters in strings are unconditionally printed as backslash sequencesby the print functions @code{prin1} and @code{print} that print withquoting.Those functions also use backslash sequences for multibytenon-@sc{ascii} characters, regardless of the value of this variable,when the output stream is a unibyte buffer or a marker pointing intoone.@end defvar@defvar print-length@cindex printing limitsThe value of this variable is the maximum number of elements to print inany list, vector or bool-vector. If an object being printed has morethan this many elements, it is abbreviated with an ellipsis.If the value is @code{nil} (the default), then there is no limit.@example@group(setq print-length 2) @result{} 2@end group@group(print '(1 2 3 4 5)) @print{} (1 2 ...) @result{} (1 2 ...)@end group@end example@end defvar@defvar print-levelThe value of this variable is the maximum depth of nesting ofparentheses and brackets when printed. Any list or vector at a depthexceeding this limit is abbreviated with an ellipsis. A value of@code{nil} (which is the default) means no limit.@end defvar These variables are used for detecting and reporting circular and shared structure---but they are only defined in Emacs 21.@tindex print-circle@defvar print-circleIf non-@code{nil}, this variable enables detection of circular and shared structure in printing.@end defvar@tindex print-gensym@defvar print-gensymIf non-@code{nil}, this variable enables detection of uninterned symbols(@pxref{Creating Symbols}) in printing. When this is enabled,uninterned symbols print with the prefix @samp{#:}, which tells the Lispreader to produce an uninterned symbol.@end defvar