1% BEGIN LICENSE BLOCK
2% Version: CMPL 1.1
3%
4% The contents of this file are subject to the Cisco-style Mozilla Public
5% License Version 1.1 (the "License"); you may not use this file except
6% in compliance with the License.  You may obtain a copy of the License
7% at www.eclipse-clp.org/license.
8%
9% Software distributed under the License is distributed on an "AS IS"
10% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
11% the License for the specific language governing rights and limitations
12% under the License.
13%
14% The Original Code is  The ECLiPSe Constraint Logic Programming System.
15% The Initial Developer of the Original Code is  Cisco Systems, Inc.
16% Portions created by the Initial Developer are
17% Copyright (C) 1994 - 2006 Cisco Systems, Inc.  All Rights Reserved.
18%
19% Contributor(s):
20%
21% END LICENSE BLOCK
22%
23% @(#)umsio.tex 1.8 94/10/20
24%
25
26% \comment{@(\#)text2.mss       20.3 9/19/88}
27% \part{text2, root = `manual.mss'}
28\chapter{Input and Output}
29\label{chapio}
30%HEVEA\cutdef[1]{section}
31%----------------------------------------------------------------------
32\section{Streams}
33%----------------------------------------------------------------------
34\index{input/output}
35Input and output in {\eclipse} is done via communication channels
36called \defnotioni{streams}{stream}.
37They are usually associated with I/O devices (a file, a terminal,
38a socket, a pipe), or in-memory queues or buffers.
39
40The streams may be opened for input only
41(\defnotion{read mode}\index{mode!read}),
42output only (\defnotion{write mode}\index{mode!write}),
43or for both input and output (\defnotion{update mode}\index{mode!update}).
44
45%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
46\subsection{Predefined Streams}
47\label{streams}
48%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
49Every {\eclipse} session defines the following symbolic stream names, which
50indicate the \aboutidx{current streams} for certain categories of input/output:
51\begin{quote}
52\begin{description}
53\item[\Indextt{input}]
54  Used by the input predicates that do not have an explicit stream argument,
55  e.g., \bipref{read/1}{../bips/kernel/ioterm/read-1.html}.
56  This is by default the same as user_input and stdin, but can be redirected.
57\item[\Indextt{output}]
58  Used by the output predicates that do not have an explicit stream argument,
59  e.g., \bipref{write/1}{../bips/kernel/ioterm/write-1.html}.
60  This is by default the same as user_output and stdout, but can be redirected.
61\item[\Indextt{error}]
62  Output for error messages and all messages about exceptional states.
63  This is by default the same as user_error and stderr, but can be redirected.
64\item[\Indextt{warning_output}]
65  Used by the system or user programs to output warning messages.
66  This is by default the same as user_output and stdout, but can be redirected.
67\item[\Indextt{log_output}]
68  Used by the system for information messages (e.g. garbage collection),
69  or by user programs for e.g. messages about computational progress.
70  This is by default the same as user_output and stdout, but can be redirected.
71\end{description}
72\end{quote}
73
74The above streams can be freely redirected, but are initially set to one
75of the following three \aboutidx{default streams}, to which they will
76also be reset whenever a redirection ends:
77\begin{quote}
78\begin{description}
79\item[\Indextt{user_input}]
80  The default input stream.
81  This is initially the same as stdin, but can be redirected.
82\item[\Indextt{user_output}]
83  The default output stream.
84  This is initially the same as stdout, but can be redirected.
85\item[\Indextt{user_error}]
86  The default error stream.
87  This is initially the same as stderr, but can be redirected.
88\end{description}
89\end{quote}
90
91Finally, there are the four predefined \aboutidx{standard streams},
92which cannot be closed or redirected.  Apart from the \notationidx{null}
93stream, there is usually no need to refer to them explicitly:
94\begin{quote}
95\begin{description}
96\item[\Indextt{stdin}]
97  The standard input stream.
98\item[\Indextt{stdout}]
99  The standard output stream.
100\item[\Indextt{stderr}]
101  The standard error stream.
102\item[\Indextt{null}]
103  A dummy stream, output to it is discarded, on input it always
104  gives end of file.
105\end{description}
106\end{quote}
107In a stand-alone {\eclipse} stdin, stdout and stderr are connected
108to the corresponding standard I/O descriptors of the process.
109In an embedded {\eclipse}, the meaning of stdin, stdout and
110stderr is determined by the {\eclipse} initialization options.
111
112\begin{center}
113\begin{tabular}{|l|l|l|}
114\hline
115Current Stream  & Default Stream & Standard Stream\\
116\hline
117\hline
118input           & user_input  & stdin\\
119\hline
120output          & user_output & stdout\\
121warning_output  & user_output & stdout\\
122log_output      & user_output & stdout\\
123\hline
124error           & user_error  & stderr\\
125\hline
126                &             & null\\
127\hline
128\end{tabular}
129
130Initial assignment of symbolic stream names
131\end{center}
132
133For compatibility with Prolog systems, the system accepts the stream
134name \notationidx{user} in certain places.  Its meaning is
135identical to \notation{stdin} and \notation{stdout},
136depending on the context where it is used.
137
138%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
139\subsection{Stream Handles and Aliases}
140%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
141Streams can be identified by anonymous
142\aboutidx{stream handles} or by symbolic names.\footnote{%
143    Earlier {\eclipse} versions identified streams by small integers, which
144    is now deprecated, except for some foreign language interfaces. If needed,
145    the number is available as the physical_stream stream property.}
146Most of the built-in predicates that require a stream to be specified
147have a stream argument at the first position,
148e.g., \notation{write(Stream, Term)}. This argument can be either a
149stream handle or a symbolic stream name.
150
151Streams that are opened by programs should preferably use stream handles,
152as this allows the system to better keep track of their lifetime.
153Nevertheless, alias names can be given, either immediately when a stream is
154newly opened (e.g. with \bipref{open/4}{../bips/kernel/iostream/open-4.html}),
155or later via redirection
156(\bipref{set_stream/2}{../bips/kernel/iostream/set_stream-2.html}).
157A stream can have more than one symbolic alias.
158
159To obtain a handle when only an alias is known, use
160\bipref{get_stream/2}{../bips/kernel/iostream/get_stream-2.html}:
161\begin{quote}
162\begin{verbatim}
163get_stream(StreamOrAlias, Handle)
164\end{verbatim}
165\end{quote}
166\bipref{get_stream/2}{../bips/kernel/iostream/get_stream-2.html} can also
167be used to check whether two stream names are aliases of each other.
168
169Note that stream handles are not normal Prolog terms!  They
170can not be assembled, decomposed, or occur literally in Prolog text. 
171
172%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
173\subsection{Opening New Streams}
174%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
175\label{openstream}
176
177Streams provide a uniform interface to a variety of I/O devices and
178pseudo-devices. The following table gives an overview of how
179streams on the different devices are opened.
180\begin{center}
181\begin{tabular}{|c|l|}
182\hline
183I/O device      &       How to open             \\
184\hline
185\hline
186tty             &
187implicit (\notation{stdin}, \notation{stdout}, \notation{stderr}) or
188\bipref{open/3}{../bips/kernel/iostream/open-3.html} of a device file \\
189\hline
190file            &
191\biptxtref{open(\pattern{FileName},~\pattern{Mode},~\pattern{Stream})}{open/3}%
192{../bips/kernel/iostream/open-3.html}           \\
193\hline
194string          &
195\biptxtref{open(string(\pattern{String}),~\pattern{Mode},~\pattern{Stream})}%
196{open/3}{../bips/kernel/iostream/open-3.html}           \\
197\hline
198queue           &
199\biptxtref{open(queue(\pattern{String}),~\pattern{Mode},~\pattern{Stream})}%
200{open/3}{../bips/kernel/iostream/open-3.html}           \\
201\hline
202pipe            &       \bipref{exec/2}{../bips/kernel/opsys/exec-2.html},
203                        \bipref{exec/3}{../bips/kernel/opsys/exec-3.html} and
204                        \bipref{exec_group/3}%
205{../bips/kernel/opsys/exec_group-3.html}        \\
206\hline
207socket          &       \bipref{socket/3}{../bips/kernel/iostream/socket-3.html}
208                        and
209                    \bipref{accept/3}{../bips/kernel/iostream/accept-3.html} \\
210\hline
211null            &       implicit (null stream)  \\
212\hline
213\end{tabular}
214
215How to open streams onto the different I/O devices
216\end{center}
217
218Most streams are opened for input or output by means of the
219\bipref{open/3}{../bips/kernel/iostream/open-3.html}
220or
221\bipref{open/4}{../bips/kernel/iostream/open-4.html}
222predicate.
223The goals
224\begin{quote}
225\begin{verbatim}
226open(SourceSink, Mode, Stream)
227open(SourceSink, Mode, Stream, Options)
228\end{verbatim}
229\end{quote}
230open a communication channel with \about{SourceSink}.
231
232If \about{SourceSink} is an atom or a string, a file is being opened
233and \about{SourceSink} takes
234the form of a file name in the host machine environment.
235{\eclipse} uses an operating
236system independent path name syntax, where the components are separated by
237forward slashes.
238The following forms are possible:
239\begin{itemize}
240\item absolute path name, e.g., \notation{/usr/peter/prolog/file.pl};
241\item relative to the current directory, e.g., \notation{prolog/file.pl};
242\item relative to the own home directory, e.g.,
243       \verb:~:\notation{/prolog/file.pl};
244\item start with an environment variable, e.g.,
245      \notation{\$HOME/prolog/file.pl};
246\item relative to a user's home directory, e.g.,
247       \verb:~:\notation{peter/prolog/file.pl} (UNIX only);
248\item specifying a drive name, e.g., \notation{//C/prolog/file.pl}
249       (Windows only).
250\end{itemize}
251Note that path names usually have to be quoted (in single or double quotes)
252because they contain non-alphanumeric characters.
253
254If \about{SourceSink} is of the form \notation{string(\pattern{InitString})} a
255    pseudo-file
256in memory is opened, see section \ref{stringio}.
257
258If \about{SourceSink} is of the form \notation{queue(\pattern{InitString})} a
259pseudo-pipe in memory is opened, see section \ref{queueio}.
260
261\about{Mode} must be one of the atoms \notation{read}, \notation{write},
262\notation{append} or \notation{update},
263which means that the stream is to be opened for input, output, output at the
264end of the existing stream, or both input and output, respectively.
265Opening a file in \notation{write} mode will create it if it does not exist,
266and erase the previous contents if it does exist.
267Opening a file in \notation{append} mode will keep the current contents
268of the file and start writing at its end.
269
270\about{Stream} is a symbolic stream identifier or an uninstantiated variable.
271If it is uninstantiated, the system will bind it to an anonymous stream handle:
272\begin{quote}
273\begin{verbatim}
274[eclipse 1]: open(new_file, write, Stream).
275Stream = $&(stream(7))
276Yes (0.00s cpu)
277\end{verbatim}
278\end{quote}
279If the stream argument is an atomic name, this name becomes an alias
280for the (hidden) stream number:
281\begin{quote}
282\begin{verbatim}
283[eclipse 1]: open(new_file, write, new_stream).
284yes.
285\end{verbatim}
286\end{quote}
287This is equivalent to
288\begin{verbatim}
289[eclipse 1]: open(new_file, write, _, [alias(new_stream)]).
290yes.
291\end{verbatim}
292The stream identifier (symbolic or handle) may then be used in predicates
293which have a named stream as one of their arguments. For example
294\begin{quote}
295\begin{verbatim}
296open("foo", update, Stream), write(Stream, subject), close(Stream).
297\end{verbatim}
298\end{quote}
299will write the atom
300\about{subject} to the file `foo' and close the stream subsequently.
301
302
303It is recommended style \emph{not} to use symbolic stream names in code that is
304meant to be reused. This is because these stream names are global,
305there is the possibility of name clashes, and the code will not be reentrant.
306It is cleaner to open streams with a variable for the stream identifier
307and pass the resulting handle as an argument wherever it is needed.
308
309\defnotion{Socket streams} are not opened with \predspec{open/3}, but with the
310special primitives
311\bipref{socket/3}{../bips/kernel/iostream/socket-3.html} and
312\bipref{accept/3}{../bips/kernel/iostream/accept-3.html}.
313More details are in chapter \ref{sockets}.
314
315%The predicate
316%\bipref{pipe/2}{../bips/kernel/obsolete/pipe-2.html} is used to
317%open a UNIX pipe, i.e., two streams, {\it In} for reading and {\it Out}
318%for writing, which are connected together using the {\it pipe(2)}
319%system call.
320%This mechanism is normally used to communicate with other processes
321%which were forked by the main process.
322
323A further group of primitives which open streams implicitly consists of
324\bipref{exec/2}{../bips/kernel/opsys/exec-2.html},
325\bipref{exec/3}{../bips/kernel/opsys/exec-3.html}
326and \bipref{exec_group/3}{../bips/kernel/opsys/exec_group-3.html}.
327They open \defnotion{pipe streams} which connect directly to the I/O channels of
328the executed process. See chapter \ref{chapopsys} for details.
329
330
331
332%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
333\subsection{Closing Streams}
334%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
335
336A stream lives until it is closed.  Streams that are only referenced
337by handle are closed automatically, either on failure across the
338open/3,4 predicate, or after all copies of their handle become unused
339and garbage collected.  This means that no extra precautions have to
340be taken to ensure that streams are closed on failure or when
341aborting.  Handle-streams can optionally be closed explicitly if their
342lifetime is statically known in the program.  Streams that have
343aliases cannot be closed automatically:  all aliases must be closed
344explicitly.
345
346The predicates
347\bipref{close/1}{../bips/kernel/iostream/close-1.html},
348\biptxtref{2}{close/2}{../bips/kernel/iostream/close-2.html}
349\begin{quote}
350\preddef{close(\pattern{Stream})}\\
351\preddef{close(\pattern{Stream},\pattern{Options})}
352\end{quote}
353are used to explicitly close an open stream.
354If a stream has several alias names, closing any of them will close
355the actual stream. All the other aliases should be closed as well
356(or redirected to streams that are still open),
357because otherwise they will continue
358to refer to an identifier of the already closed stream.
359
360When an attempt is made to close a redirected system stream (e.g.,
361\notation{output}),
362the stream is closed, but the system stream is reset to its default setting.
363
364%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
365\subsection{Redirecting Streams}
366%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
367
368\index{redirecting streams}\index{streams!redirecting}
369The \bipref{set_stream/2}{../bips/kernel/iostream/set_stream-2.html}
370primitive can be used to redirect an already existing symbolic stream
371to a new actual stream.
372This is particularly useful to redirect e.g., the default \notation{output}
373stream:
374\begin{quote}
375\begin{verbatim}
376set_stream(output, MyStream)
377\end{verbatim}
378\end{quote}
379so that all standard output is redirected to some other destination
380(e.g., an opened file instead of the terminal).
381Note that the stream modes (read/write) must be compatible.
382The redirection is terminated by calling
383\begin{quote}
384\begin{verbatim}
385close(output)
386\end{verbatim}
387\end{quote}
388which will reestablish the original meaning of the output stream
389by resetting it to the user_output default stream.
390
391
392%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
393\subsection{Finding Streams}
394%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
395The predicate
396\begin{quote}
397\preddef{current_stream(?\pattern{Stream})}\indextt{current_stream/1}
398\end{quote}
399can be used to backtrack over all the currently opened streams,
400and obtain handles for them (but not their aliases).
401
402
403%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
404\subsection{Stream Properties}
405%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
406A stream's properties can be accessed using
407\bipref{get_stream_info/3}{../bips/kernel/iostream/get_stream_info-3.html}:
408\begin{quote}
409\preddef{get_stream_info(%
410+\pattern{Stream},~+\pattern{Property},~-\pattern{Value})}
411\end{quote}
412e.g., its mode, line number, file name etc.
413Some stream properties can be modified using
414\bipref{set_stream_property/3}%
415{../bips/kernel/iostream/set_stream_property-3.html}:
416\begin{quote}
417\preddef{set_stream_property(%
418+\pattern{Stream},~+\pattern{Property},~+\pattern{Value})}
419\end{quote}
420e.g., the end-of-line sequence used, the flushing behaviour, the event-raising
421behaviour, the prompt etc.
422
423
424%----------------------------------------------------------------------
425\section{Communication via Streams}
426%----------------------------------------------------------------------
427The contents of a stream may be interpreted in one of
428three basic ways.
429The first one is to
430consider it as a sequence of characters, so that the basic unit to
431be read or written is a character. The second one interprets
432the stream as a sequence of tokens, thus providing an interface
433to the Prolog lexical analyzer and the third one is to consider a stream as
434a sequence of Prolog terms.
435
436%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
437\subsection{Character I/O}
438%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
439The \biprefni{get/1,2}{../bips/kernel/iochar/get-1.html}%
440\indextt{get/1}\indextt{get/2}
441and
442\biprefni{put/1,2}{../bips/kernel/iochar/put-1.html}%
443\indextt{put/1}\indextt{put/2}
444predicates corresponds to the first way
445of looking at streams. The call
446\begin{quote}
447\begin{verbatim}
448get(Char)
449\end{verbatim}
450\end{quote}
451takes the next character from
452the current input stream and matches it as a single character with Char.
453Note that a character in {\eclipse} is represented as an integer corresponding
454to the ISO-8859-1 (iso_latin_1) code of the character.
455If the end of file has been reached then an exception is raised and -1
456is returned.
457The call
458\begin{quote}
459\begin{verbatim}
460put(Char)
461\end{verbatim}
462\end{quote}
463puts the char Char on to the current output stream.
464The predicates
465\begin{quote}
466\begin{verbatim}
467get(Stream, Char)
468\end{verbatim}
469\end{quote}
470 and
471\begin{quote}
472\begin{verbatim}
473put(Stream, Char)
474\end{verbatim}
475\end{quote}
476work similarly on the specified
477stream.
478
479The input and output is normally buffered by {\eclipse}.
480To make I/O in \defnotion{raw mode}\index{mode!raw}, without buffering, the
481predicates
482\biprefni{tyi/1,2}{../bips/kernel/iochar/tyi-1.html}%
483\indextt{tyi/1}\indextt{tyi/2}
484and
485\biprefni{tyo/1,2}{../bips/kernel/iochar/tyo-1.html}%
486\indextt{tyo/1}\indextt{tyo/2}
487are provided.
488
489%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
490\subsection{Token I/O}
491\index{token}
492%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
493The predicates
494\bipref{read_token/2}{../bips/kernel/iochar/read_token-2.html} and
495\bipref{read_token/3}{../bips/kernel/iochar/read_token-3.html}:
496\begin{quote}
497\preddef{read_token(\pattern{Token},~\pattern{Class})}\\
498\preddef{read_token(\pattern{Stream},~\pattern{Token},~\pattern{Class})}
499\end{quote}
500represent the second way of interpreting stream contents.
501They read the next token from the current
502input stream, unify it with \about{Token},
503and its token class is unified with \about{Class}.
504A token is either a sequence of characters with the same or compatible
505\Index{character class}, e.g., ab_1A, then it is a Prolog constant
506or variable, or a single character, e.g., ')'.
507The \Index{token class} represents the type of the token and
508its special meaning, e.g., \notation{fullstop}, \notation{comma},
509\notation{open_par}, etc.
510The exact definition of character classes and tokens can be found in
511appendices \ref{charclass} and \ref{tokendef}, respectively.
512
513A further, very flexible possibility to read a sequence of
514characters is provided by the built-in
515\bipref{read_string/5}{../bips/kernel/iochar/read_string-5.html}
516\begin{quote}
517\preddef{read_string(%
518\pattern{Stream},~\pattern{SepChars},~\pattern{PadChars},~\pattern{Separator},~\pattern{String})}
519\end{quote}
520Here, the input is read up to a specified delimiter,
521and returned as an {\eclipse} string.
522
523In particular, one line of input can be read as follows:
524\begin{quote}
525\begin{verbatim}
526read_line(Stream, String) :-
527    read_string(Stream, end_of_line, "", _Separator, String).
528\end{verbatim}
529\end{quote}
530The \about{SepChar} argument allows the specification of padding
531characters, which will be ignored before and after separators.
532Once a string has been read, string manipulation predicates like
533\bipref{split_string/4}{../bips/kernel/stratom/split_string-4.html}
534can be used to break it up into even smaller components.
535
536
537
538%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
539\subsection{Term I/O}
540%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
541The \biprefni{read/1,2}{../bips/kernel/ioterm/read-1.html}%
542\indextt{read/1}\indextt{read/2}
543and
544\biprefni{write/1,2}{../bips/kernel/ioterm/write-1.html}%
545\indextt{write/1}\indextt{write/2}
546predicates  correspond to
547the third way of looking at streams.
548For input, the goal
549\begin{quote}
550\begin{verbatim}
551read(Term)
552\end{verbatim}
553\end{quote}
554 reads the next {\eclipse} term from the
555current input
556stream and unifies it with \about{Term}. The input term must be followed by a
557full stop, that is, a '.' character followed by a layout
558character (tab, space or newline) or by the end of file.
559The exact definition of the term syntax can be found in appendix
560\ref{chapsyntax}.
561
562If end of file has been reached then
563an exception is raised, the default handler causes the atom
564\notation{end_of_file} to be returned.
565A term may be read from a stream other than the current input stream by
566the call
567\begin{quote}
568\begin{verbatim}
569read(Stream, Term)
570\end{verbatim}
571\end{quote}
572which reads the term from the named stream.
573
574For additional information about other options for reading terms,
575in particular for how to get variable names, refer to
576\bipref{readvar/3}{../bips/kernel/ioterm/readvar-3.html},
577\bipref{read_term/2}{../bips/kernel/ioterm/read_term-2.html} and
578\bipref{read_term/3}{../bips/kernel/ioterm/read_term-3.html}.
579For reading and processing complete {\eclipse} source code files, use the
580\bipref{library(source_processor)}{../bips/lib/source_processor/index.html}.
581
582
583
584For output, the goal
585\begin{quote}
586\begin{verbatim}
587write(Term)
588\end{verbatim}
589\end{quote}
590writes \about{Term} to the current output stream.
591This is done by taking the current operator declarations into account. Output
592produced by the
593\biprefni{write/1,2}{../bips/kernel/ioterm/write-1.html}%
594\indextt{write/1}\indextt{write/2}
595predicate is not (necessarily) in
596a form suitable for subsequent input to a Prolog program using the
597\bipref{read/1}{../bips/kernel/ioterm/read-1.html}
598predicate, for this purpose
599\biprefni{writeq/1,2}{../bips/kernel/ioterm/writeq-1.html}%
600\indextt{writeq/1}\indextt{writeq/2}
601is to be used.
602The goal
603\begin{quote}
604\begin{verbatim}
605write(Stream, Term)
606\end{verbatim}
607\end{quote}
608writes \about{Term} to the named output stream.
609For more details about how to output terms in different formats, see
610section \ref{secoutputformats}.
611
612%The predicate \begin{quote}\begin{verbatim}
613%display(Term)\end{verbatim}\end{quote}
614%\index{display/1}
615%outputs the {\it Term} on the current output stream in the functor syntax,
616%ignoring possible operator declarations.
617
618%The predicate \begin{quote}\begin{verbatim}
619%readvar(Stream, Term, VarList)\end{verbatim}\end{quote}
620%%\index{readvar/3}
621%can be used to read a term from the specified stream
622%and obtain the list of variable names contained in the {\it Term}.
623%{\it VarList} is a list of pairs {\tt [VarName\verb'|'Var]} where
624%{\it VarName} is the atom corresponding to the variable name
625%and {\it Var} is the corresponding variable.
626
627When the flag \notationidx{variable_names} is switched off,
628the output predicates are not able to write free variables
629in their source form, i.e., with the correct variable names.
630Then the variables are output in the form
631\begin{quote}
632\begin{verbatim}
633_N
634\end{verbatim}
635\end{quote}
636where \about{N} is a number which identifies the variable (but note that these
637numbers may change on garbage collection and can therefore not be used to
638identify the variable in a more permanent way).
639Occasionally the number will be prefixed with the lower-case letter
640\notation{l},
641indicating that the variable is in a short-lived memory area called the
642local stack (see \ref{chapmemory}).%
643\index{variable!output}\index{output of variables}
644
645%It is possible to pass any input stream to the {\eclipse} compiler
646%using the predicate
647%\index{compile_stream/1}
648%\begin{quote}\begin{verbatim}
649%compile_stream(Stream)\end{verbatim}\end{quote}
650%and it is of course possible to mix the compilation with
651%other input predicates.
652%If, for example, the file {\bf a.pl} contains the following data
653%\begin{quote}\begin{verbatim}
654%p(1).
655%p(2).
656%end_of_file.
657%p(3).
658%\end{verbatim}\end{quote}
659%it is possible to execute
660%\begin{quote}\begin{verbatim}
661%[eclipse 1]: open('a.pl', read, a).
662%
663%yes.
664%[eclipse 2]: read(a, X).
665%
666%X = p(1)
667%yes.
668%[eclipse 3]: compile_stream(a).
669%a.pl    compiled 40 bytes in 0.00 seconds
670%
671%yes.
672%[eclipse 4]: read(a, X).
673%
674%X = p(3)
675%yes.
676%[eclipse 5]: p(X).
677%
678%X = 2
679%yes.
680%\end{verbatim}\end{quote}
681
682
683%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
684\subsection{Newlines}
685%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
686
687Newlines should be output using either
688\bipref{nl/0}{../bips/kernel/iochar/nl-0.html},
689\bipref{nl/1}{../bips/kernel/iochar/nl-1.html},
690\bipref{writeln/1}{../bips/kernel/ioterm/writeln-1.html},
691\bipref{writeln/2}{../bips/kernel/ioterm/writeln-2.html},
692or using the \notation{\%n} format with
693\bipref{printf/2}{../bips/kernel/ioterm/printf-2.html},
694\bipref{printf/3}{../bips/kernel/ioterm/printf-3.html}.
695All those will produce a LF or CRLF sequence, depending on the
696stream property settings (see
697\bipref{set_stream_property/3}%
698{../bips/kernel/iostream/set_stream_property-3.html}).
699
700
701%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
702\subsection{General Parsing and Text Generation}
703%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
704
705Reading and writing of I/O formats that cannot be handled by the methods
706discussed above are probably best done using Definite Clause Grammar
707(DCG) rules. See chapter \ref{dcg} for details.
708
709
710%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
711\subsection{Flushing}
712%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
713On most devices, output is buffered, i.e., any output does not appear
714\index{buffered output}\index{output!buffered}
715immediately on the file, pipe or socket, but goes into a buffer first.
716To make sure the data is actually written to the device, the stream
717usually has to be flushed using
718\bipref{flush/1}{../bips/kernel/iostream/flush-1.html}.
719If this is forgotten, the receiving end of a pipe or socket may hang
720in a blocking read operation.
721
722It is possible to configure a stream such that it is automatically
723flushed at every line end (see
724\bipref{set_stream_property/3}%
725{../bips/kernel/iostream/set_stream_property-3.html}).
726
727
728%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
729\subsection{Prompting}
730%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
731Input streams on terminals can be configured to print a prompt
732whenever input is required, see
733\bipref{set_stream_property/3}%
734{../bips/kernel/iostream/set_stream_property-3.html}.
735
736
737%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
738\subsection{Positioning}
739%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
740Streams that are opened on files or strings can be positioned,
741i.e., the read/write position can be moved forward or backwards.
742This is not possible on pipes, sockets, queues and terminals.
743
744To specify a position in the file
745to write to or read from, the predicate
746\bipref{seek/2}{../bips/kernel/iostream/seek-2.html}
747is provided. The
748call
749\begin{quote}
750\begin{verbatim}
751seek(Stream, Pointer)
752\end{verbatim}
753\end{quote}
754moves the current position in the
755file (the 'file pointer') to the offset \about{Pointer} (a number specifying
756the length in bytes) from
757the start of the file.
758If \about{Pointer} is the atom \notation{end_of_file}, the
759current position is moved to the end of the file.
760Hence a file could be open in \notation{append} mode using
761\begin{quote}
762\begin{verbatim}
763open(File, update, Stream), seek(Stream, end_of_file)
764\end{verbatim}
765\end{quote}
766The current position in a file may be found by the predicate
767\bipref{at/2}{../bips/kernel/iostream/at-2.html}.
768The call
769\begin{quote}
770\begin{verbatim}
771at(Stream, Pointer)
772\end{verbatim}
773\end{quote}
774unifies \about{Pointer} with the current position in the file.
775The predicate
776\begin{quote}
777\begin{verbatim}
778at_eof(Stream)
779\end{verbatim}
780\end{quote}
781succeeds if the current position in the given stream
782is at the file end.
783
784
785%----------------------------------------------------------------------
786\section{In-memory Streams}
787%----------------------------------------------------------------------
788There are two kinds of in-memory streams, string streams and queues.
789String streams behave much like files, they can be read, written,
790positioned etc, but they are implemented as buffer in memory.
791Queues are intended mainly for message-passing-style communication
792between \eclipse and a host language, and they are also implemented as
793memory buffers.
794
795\subsection{String Streams}
796\label{stringio}
797In {\eclipse} it is possible to associate a stream with a Prolog string
798in its memory, and this string is then used in the same way as a file
799for the input and output operations.
800A string stream is opened like a file by a call to the
801\bipref{open/3}{../bips/kernel/iostream/open-3.html} predicate:
802\begin{quote}
803\notation{open(string(\pattern{InitString}),~\pattern{Mode},~\pattern{Stream})}
804\end{quote}
805where \about{InitString} can be a {\eclipse} string or a variable and represents
806the initial contents of the string stream.
807If a variable is supplied for \about{InitString}, the initial value of the
808string
809stream is the empty string and the variable is bound to this value:
810\begin{quote}
811\begin{verbatim}
812[eclipse 1]: open(string(S), update, s).
813S = ""
814yes.
815\end{verbatim}
816\end{quote}
817Once a string stream is opened, all predicates using streams
818can take it as argument and perform I/O on it.
819In particular the predicates
820\bipref{seek/2}{../bips/kernel/iostream/seek-2.html} and
821\bipref{at/2}{../bips/kernel/iostream/at-2.html}
822can be used with them.
823
824While writing into a stream changes the stream contents destructively,
825the initial string that has been opened will never be affected.
826The new stream contents can be retrieved either by reading from the string
827stream, or as a whole by using
828\bipref{get_stream_info/3}{../bips/kernel/iostream/get_stream_info-3.html}:
829\begin{quote}
830\begin{verbatim}
831[eclipse 1]: S = "abcdef", open(string(S), write, s), write(s, ---).
832
833S = "abcdef"
834yes.
835[eclipse 2]: get_stream_info(s, name, S).
836
837S = "---def"
838yes.
839[eclipse 3]: seek(s, 1), write(s, .), get_stream_info(s, name, S).
840
841S = "-.-def"
842yes.
843[eclipse 4]: seek(s, end_of_file), write(s, ine),
844             get_stream_info(s, name, S).
845
846S = "-.-define"
847yes.
848\end{verbatim}
849\end{quote}
850
851
852\subsection{Queue streams}
853\label{queueio}
854A queue stream is opened by the
855\bipref{open/3}{../bips/kernel/iostream/open-3.html} predicate:
856\begin{quote}
857\notation{open(queue(\pattern{InitString}),~\pattern{Mode},~\pattern{Stream})}
858\end{quote}
859The initial queue contents is \about{InitString}.
860It can be seen as a string which gets extended at its end on writing
861and consumed at its beginning on reading.
862\begin{quote}
863\begin{verbatim}
864[eclipse 11]: open(queue(""), update, q), write(q, hello), write(q," wo").
865yes.
866[eclipse 12]: read_string(q, " ", "", _, X).
867S = "hello"
868yes.
869[eclipse 13]: write(q, "rld"), read(q, X).
870S = world
871yes.
872[eclipse 14]: at_eof(q).
873yes.
874\end{verbatim}
875\end{quote}
876It is not allowed to seek on a queue. Therefore, once something is read
877from a queue, it is no longer accessible. A queue is considered to be
878at its end-of-file position when it is currently empty, however this
879is no longer the case when the queue is written again.
880
881A useful feature of queues is that they can raise a synchronous event
882when data arrives on the empty queue. To create such an event-raising
883queue, this has to be specified as an option when opening the queue with
884\bipref{open/4}{../bips/kernel/iostream/open-4.html}.
885In the example we have chosen the same name for the stream and for the
886event, which is not necessary but convenient when the same handler
887is going to be used for different queues:
888\begin{quote}
889\begin{verbatim}
890[eclipse 1]: [user].
891 handle_queue_event(Q) :-
892        read_string(Q, "", "", _, Data),
893        printf("Queue %s received data: %s\n", [Q,Data]).
894yes.
895[eclipse 2]: set_event_handler(eventq, handle_queue_event/1).
896yes.
897[eclipse 3]: open(queue(""), update, eventq, [event(eventq)]).
898yes.
899[eclipse 4]: write(eventq, hello).
900Queue eventq received data: hello
901yes.
902\end{verbatim}
903\end{quote}
904
905
906%----------------------------------------------------------------------
907\section{Term Output Formats}
908\label{secoutputformats}
909%----------------------------------------------------------------------
910
911\subsection{Write_term and Printf}
912
913The way {\eclipse} terms are printed can be customised in a number of ways.
914The most flexible predicates to print terms are
915\bipref{write_term/3}{../bips/kernel/ioterm/write_term-3.html}
916and
917\bipref{printf/3}{../bips/kernel/ioterm/printf-3.html}.
918They both allow all variants of term output, but the format is
919specified in a different way.
920\index{output options}
921The following figure gives an overview.
922\vfill %<<<<<<<<<<<<<<<<<<<<<<
923
924\newlength{\WidthOne}\settowidth{\WidthOne}{\notation{variables(anonymous)}}
925\newlength{\WidthTwo}\settowidth{\WidthTwo}{char~for}
926\newlength{\WidthThree}\setlength{\WidthThree}{\textwidth}%
927\addtolength{\WidthThree}{-\WidthOne}%
928\addtolength{\WidthThree}{-\WidthTwo}%
929\addtolength{\WidthThree}{-36pt}
930\begin{center}
931%\begin{tabular}{|p{3.5cm}|p{1.5cm}|p{10cm}|}
932\begin{tabular}{|p{\WidthOne}|p{\WidthTwo}|p{\WidthThree}|}
933\hline
934\parbox{\WidthOne}{
935  Output option for\\
936  \predspec{write_term/2,3}
937}
938                        & \parbox{\WidthTwo}{Format\\
939                                                char for\\
940                                                printf\\
941                                                \%..w}
942                            & \parbox{\WidthThree}{Meaning} \\
943\hline
944\hline
945\notation{as(term)}     &   & do not assume any particular meaning of the
946                                                                printed term \\
947\hline
948\notation{as(clause)}   & \notation{C}
949                             & print the term as a clause (apply clause
950                                                            transformations) \\
951\hline
952\notation{as(goal)}     & \notation{G}
953                             & print the term as a goal (apply goal
954                                                            transformations) \\
955\hline
956\notation{attributes(none)}
957                        &   & do not print any variable attributes \\
958\hline
959\notation{attributes(pretty)}
960                        & \notation{m}
961                            & print attributes using the corresponding print
962                                                                    handlers \\
963\hline
964\notation{attributes(full)}
965                        & \notation{M}
966                            & print the full contents of all variable
967                                                                   attributes\\
968\hline
969\notation{compact(false)}
970                        &   & print extra blank space (around operators, after
971                                        commas, etc.) for better readability \\
972\hline
973\notation{compact(true)}
974                        & \notation{K}
975                            & don't print blank space unless necessary \\
976\hline
977\notation{depth(\pattern{Max})}
978                        & \notation{<\pattern{Max}>}
979                            & print the term only up to a maximum nesting
980                                    depth of \about{Max} (a positive integer) \\
981\hline
982\notation{depth(0)}     &   & observe the stream-specific or global flag
983                                                      \notation{print_depth} \\
984\hline
985\notation{depth(full)}  & \notation{D}
986                            & print the whole term (may loop when the term is
987                                                                    cyclic!) \\
988\hline
989\notation{dotlists(false)}
990                        &   & write lists in square bracket notation, e.g.,
991                                                             \notation{[a,b]} \\
992\hline
993\notation{dotlists(true)}
994                        & \notation{.}
995                             & write lists as terms with functor
996                                                               \predspec{./2} \\
997\hline
998\notation{newlines(false)}
999                        &   & print newlines inside quotes as the escape
1000                                                           sequence \verb:\n: \\
1001\hline
1002\notation{newlines(true)}
1003                        & \notation{N}
1004                            & print newlines as line breaks even inside
1005                                                                       quotes \\
1006\hline
1007\notation{nl(false)}
1008                        &   & do not add a newline \\
1009\hline
1010\notation{nl(true)}
1011                        & \notation{L}
1012                            & print a newline sequence (as with nl/1) after
1013			      the term. If this is used together with the
1014			      fullstop(true) option, this newline serves as
1015			      the blank space after the fullstop \\
1016\hline
1017\notation{fullstop(false)}
1018                        &   & do not add a fullstop \\
1019\hline
1020\notation{fullstop(true)}
1021                        & \notation{F}
1022			    & terminate the term with a fullstop, so
1023			    it can be read back.  If necessary, an
1024			    extra space will be inserted before the
1025			    fullstop, in order to separate it from the
1026			    end of the term \\
1027\hline
1028\notation{numbervars(false)}
1029                        &   & do not treat \predspec{'\$VAR'/1} terms
1030                                                                    specially \\
1031\hline
1032\notation{numbervars(true)}
1033                        & \notation{I}
1034                            & print terms of the form
1035                             \notation{'\$VAR'(\pattern{N})} as named
1036                              variables: \notation{'\$VAR'(0)} is printed as
1037                              \notation{A}, \notation{'\$VAR'(25)}
1038                              as \notation{Z}, \notation{'\$VAR'(26)} as
1039                              \notation{A1} and so on. When the
1040                              argument is an atom or a string, just this
1041                              argument is printed. \\
1042\hline
1043\notation{operators(true)}
1044                        &   & obey operator declarations and print
1045                                                        prefix/infix/postfix \\
1046\hline
1047\notation{operators(false)}
1048                        & \notation{O}
1049                            & ignore operator declarations and print functor
1050                                                                    notation \\
1051\hline
1052\notation{portrayed(false)}
1053                        &   & do not use \predspec{portray/1,2} \\
1054\hline
1055\notation{portrayed(true)}
1056                        & \notation{P}
1057                            & call the user-defined predicate
1058                                          \predspec{portray/1,2} for printing \\
1059\hline
1060\notation{precedence(Prec)}
1061                        &   & print assuming given context precedence \\
1062\hline
1063\notation{quoted(false)}
1064                        &   & do not print quotes around strings or atoms \\
1065\hline
1066\notation{quoted(true)}
1067                        & \notation{Q}
1068                            & quote strings and atoms if necessary \\
1069\hline
1070\notation{transform(true)}
1071                        &   & apply portray transformations (write macros) \\
1072\hline
1073\notation{transform(false)}
1074                        & \notation{T}
1075                            & do not apply portray transformations (write
1076                                                                    macros). \\
1077\hline
1078\notation{variables(default)}
1079                        &   & print variables using their source name (if
1080                                                                   available) \\
1081\hline
1082\notation{variables(raw)}
1083                        & \notation{v}
1084                             & print variables using a system-generated name,
1085                                                       e.g., \notation{_123} \\
1086\hline
1087\notation{variables(full)}
1088                        & \notation{V}
1089                             & print variables using source name followed by a
1090                                          number, e.g., \notation{Alpha_132} \\
1091\hline
1092\notation{variables(anonymous)}
1093                        & \notation{_}
1094                             & print every variable as a simple underscore \\
1095\hline
1096\end{tabular}
1097
1098Overview of term output options (see \predspec{write_term/3} for more details)
1099\label{outputoptions}
1100\end{center}
1101The
1102\bipref{write_term/2}{../bips/kernel/ioterm/write_term-2.html} and
1103\bipref{write_term/3}{../bips/kernel/ioterm/write_term-3.html}
1104predicates print a single {\eclipse} term and accept a list of
1105output options (first column in the table).
1106
1107The
1108\bipref{printf/2}{../bips/kernel/ioterm/printf-2.html} and
1109\bipref{printf/3}{../bips/kernel/ioterm/printf-3.html}
1110predicates are similar to C's printf(3) function, but provide
1111additional format characters for printing {\eclipse} terms.
1112\index{format string}\index{output!format string}
1113The basic format string for printing arbitrary terms is \notation{\%w}.
1114Additional format characters can go between \notation{\%} and \notation{w},
1115according to the second column in the table.
1116
1117For example, the following pairs of printing goals are equivalent:
1118\begin{quote}
1119\begin{verbatim}
1120printf("%mw",  [X])  <->   write_term(X, [attributes(pretty)])
1121printf("%O.w", [X])  <->   write_term(X, [operators(false),dotlist(true)])
1122printf("%5_w", [X])  <->   write_term(X, [depth(5),variables(anonymous)])
1123\end{verbatim}
1124\end{quote}
1125
1126
1127\subsection{Other Term Output Predicates}
1128
1129The other term output predicates
1130\bipref{write/1}{../bips/kernel/ioterm/write-1.html},
1131\bipref{writeln/1}{../bips/kernel/ioterm/writeln-1.html},
1132\bipref{writeq/1}{../bips/kernel/ioterm/writeq-1.html},
1133\bipref{write_canonical/1}{../bips/kernel/ioterm/write_canonical-1.html},
1134\bipref{display/1}{../bips/kernel/ioterm/display-1.html},
1135\bipref{print/1}{../bips/kernel/ioterm/print-1.html}
1136can all be defined in terms of \predspec{write_term/2} (or, similarly
1137in terms of \predspec{printf/2}) as follows:
1138\begin{quote}
1139\begin{verbatim}
1140write(X)   :- write_term(X, [numbervars(true)]).
1141writeln(X) :- write_term(X, [numbervars(true)]), nl.
1142writeq(X)  :- write_term(X, [variables(raw), attributes(full),
1143              transform(false), quoted(true), depth(full),
1144              numbervars(true)]).
1145write_canonical(X) :-
1146              write_term(X, [variables(raw), attributes(full),
1147              transform(false), quoted(true), depth(full),
1148              dotlist(true), operators(false)]).
1149display(X) :- write_term(X, [dotlist(true), operators(false)]).
1150print(X)   :- write_term(X, [portrayed(true), numbervars(true)]).
1151\end{verbatim}
1152\end{quote}
1153
1154
1155\subsection{Default Output Options}
1156
1157It is possible to set default output options for an output stream
1158in order to globally affect all output to this particular stream.
1159The
1160\bipref{set_stream_property/3}%
1161{../bips/kernel/iostream/set_stream_property-3.html}
1162predicate can be used to assign default options (in the same form as
1163accepted by \predspec{write_term/3}) to a stream.
1164These options will then be observed by all output predicates which do not
1165override the particular option.
1166
1167%HEVEA\cutend
1168