This is mit-scheme-ref.info, produced by texi2any version 6.7 from
scheme.texinfo.

This manual documents MIT/GNU Scheme 11.0.90.

   Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994,
1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
2019, 2020 Massachusetts Institute of Technology

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.2 or any later version published by the Free Software
     Foundation; with no Invariant Sections, with no Front-Cover Texts
     and no Back-Cover Texts.  A copy of the license is included in the
     section entitled "GNU Free Documentation License."
INFO-DIR-SECTION Programming Languages
START-INFO-DIR-ENTRY
* MIT/GNU Scheme Reference: (mit-scheme-ref).
                                Reference Manual
END-INFO-DIR-ENTRY


File: mit-scheme-ref.info,  Node: Blocking Mode,  Next: Terminal Mode,  Prev: Output Procedures,  Up: Input/Output

14.7 Blocking Mode
==================

An interactive port is always in one of two modes: "blocking" or
"non-blocking".  This mode is independent of the terminal mode: each can
be changed independently of the other.  Furthermore, if it is an
interactive I/O port, there are separate blocking modes for input and
for output.

   If an input port is in blocking mode, attempting to read from it when
no input is available will cause Scheme to "block", i.e. suspend itself,
until input is available.  If an input port is in non-blocking mode,
attempting to read from it when no input is available will cause the
reading procedure to return immediately, indicating the lack of input in
some way (exactly how this situation is indicated is separately
specified for each procedure or operation).

   An output port in blocking mode will block if the output device is
not ready to accept output.  In non-blocking mode it will return
immediately after performing as much output as the device will allow
(again, each procedure or operation reports this situation in its own
way).

   Interactive ports are initially in blocking mode; this can be changed
at any time with the procedures defined in this section.

   These procedures represent blocking mode by the symbol 'blocking',
and non-blocking mode by the symbol 'nonblocking'.  An argument called
MODE must be one of these symbols.  A PORT argument to any of these
procedures may be any port, even if that port does not support blocking
mode; in that case, the port is not modified in any way.

 -- procedure: input-port-blocking-mode input-port
 -- procedure: output-port-blocking-mode output-port
     Returns the blocking mode of INPUT-PORT or OUTPUT-PORT.  Returns
     '#f' if the given port doesn't support blocking mode.

 -- procedure: set-input-port-blocking-mode! input-port mode
 -- procedure: set-output-port-blocking-mode output-port mode
     Changes the blocking mode of INPUT-PORT or OUTPUT-PORT to be MODE
     and returns an unspecified value.

 -- procedure: with-input-port-blocking-mode input-port mode thunk
 -- procedure: with-output-port-blocking-mode output-port mode thunk
     THUNK must be a procedure of no arguments.

     Binds the blocking mode of INPUT-PORT or OUTPUT-PORT to be MODE,
     and calls THUNK.  When THUNK returns, the original blocking mode is
     restored and the values yielded by THUNK are returned.

 -- obsolete procedure: port/input-blocking-mode input-port
 -- obsolete procedure: port/set-input-blocking-mode input-port mode
 -- obsolete procedure: port/with-input-blocking-mode input-port mode
          thunk
 -- obsolete procedure: port/output-blocking-mode output-port
 -- obsolete procedure: port/set-output-blocking-mode output-port mode
 -- obsolete procedure: port/with-output-blocking-mode output-port mode
          thunk
     These procedures are *deprecated*; instead use the corresponding
     procedures above.


File: mit-scheme-ref.info,  Node: Terminal Mode,  Next: Format,  Prev: Blocking Mode,  Up: Input/Output

14.8 Terminal Mode
==================

A port that reads from or writes to a terminal has a "terminal mode";
this is either "cooked" or "raw".  This mode is independent of the
blocking mode: each can be changed independently of the other.
Furthermore, a terminal I/O port has independent terminal modes both for
input and for output.

   A terminal port in cooked mode provides some standard processing to
make the terminal easy to communicate with.  For example, under unix,
cooked mode on input reads from the terminal a line at a time and
provides editing within the line, while cooked mode on output might
translate linefeeds to carriage-return/linefeed pairs.  In general, the
precise meaning of cooked mode is operating-system dependent, and
furthermore might be customizable by means of operating-system
utilities.  The basic idea is that cooked mode does whatever is
necessary to make the terminal handle all of the usual user-interface
conventions for the operating system, while keeping the program's
interaction with the port as normal as possible.

   A terminal port in raw mode disables all of that processing.  In raw
mode, characters are directly read from and written to the device
without any translation or interpretation by the operating system.  On
input, characters are available as soon as they are typed, and are not
echoed on the terminal by the operating system.  In general, programs
that put ports in raw mode have to know the details of interacting with
the terminal.  In particular, raw mode is used for writing programs such
as text editors.

   Terminal ports are initially in cooked mode; this can be changed at
any time with the procedures defined in this section.

   These procedures represent cooked mode by the symbol 'cooked', and
raw mode by the symbol 'raw'.  An argument called MODE must be one of
these symbols.  A PORT argument to any of these procedures may be any
port, even if that port does not support terminal mode; in that case,
the port is not modified in any way.

 -- procedure: input-port-terminal-mode input-port
 -- procedure: output-port-terminal-mode output-port
     Returns the terminal mode of INPUT-PORT or OUTPUT-PORT.  Returns
     '#f' if the given port is not a terminal port.

 -- procedure: set-input-port-terminal-mode! input-port mode
 -- procedure: set-output-port-terminal-mode! output-port mode
     Changes the terminal mode of INPUT-PORT or OUTPUT-PORT to be MODE
     and returns an unspecified value.

 -- procedure: with-input-port-terminal-mode input-port mode thunk
 -- procedure: with-output-port-terminal-mode output-port mode thunk
     THUNK must be a procedure of no arguments.

     Binds the terminal mode of INPUT-PORT or OUTPUT-PORT to be MODE,
     and calls THUNK.  When THUNK returns, the original terminal mode is
     restored and the values yielded by THUNK are returned.

 -- obsolete procedure: port/input-terminal-mode input-port
 -- obsolete procedure: port/set-input-terminal-mode input-port mode
 -- obsolete procedure: port/with-input-terminal-mode input-port mode
          thunk
 -- obsolete procedure: port/output-terminal-mode output-port
 -- obsolete procedure: port/set-output-terminal-mode output-port mode
 -- obsolete procedure: port/with-output-terminal-mode output-port mode
          thunk
     These procedures are *deprecated*; instead use the corresponding
     procedures above.


File: mit-scheme-ref.info,  Node: Format,  Next: Custom Output,  Prev: Terminal Mode,  Up: Input/Output

14.9 Format
===========

The procedure 'format' is very useful for producing nicely formatted
text, producing good-looking messages, and so on.  MIT/GNU Scheme's
implementation of 'format' is similar to that of Common Lisp, except
that Common Lisp defines many more directives.(1)

   'format' is a run-time-loadable option.  To use it, execute

     (load-option 'format)

once before calling it.

 -- procedure: format destination control-string argument ...
     Writes the characters of CONTROL-STRING to DESTINATION, except that
     a tilde ('~') introduces a "format directive".  The character after
     the tilde, possibly preceded by prefix parameters and modifiers,
     specifies what kind of formatting is desired.  Most directives use
     one or more ARGUMENTs to create their output; the typical directive
     puts the next ARGUMENT into the output, formatted in some special
     way.  It is an error if no argument remains for a directive
     requiring an argument, but it is not an error if one or more
     arguments remain unprocessed by a directive.

     The output is sent to DESTINATION.  If DESTINATION is '#f', a
     string is created that contains the output; this string is returned
     as the value of the call to 'format'.  In all other cases 'format'
     returns an unspecified value.  If DESTINATION is '#t', the output
     is sent to the current output port.  Otherwise, DESTINATION must be
     an output port, and the output is sent there.

     This procedure performs discretionary output flushing (*note Output
     Procedures::).

     A 'format' directive consists of a tilde ('~'), optional prefix
     parameters separated by commas, optional colon (':') and at-sign
     ('@') modifiers, and a single character indicating what kind of
     directive this is.  The alphabetic case of the directive character
     is ignored.  The prefix parameters are generally integers, notated
     as optionally signed decimal numbers.  If both the colon and
     at-sign modifiers are given, they may appear in either order.

     In place of a prefix parameter to a directive, you can put the
     letter 'V' (or 'v'), which takes an ARGUMENT for use as a parameter
     to the directive.  Normally this should be an exact integer.  This
     feature allows variable-width fields and the like.  You can also
     use the character '#' in place of a parameter; it represents the
     number of arguments remaining to be processed.

     It is an error to give a format directive more parameters than it
     is described here as accepting.  It is also an error to give colon
     or at-sign modifiers to a directive in a combination not
     specifically described here as being meaningful.

     '~A'
          The next ARGUMENT, which may be any object, is printed as if
          by 'display'.  '~MINCOLA' inserts spaces on the right, if
          necessary, to make the width at least MINCOL columns.  The '@'
          modifier causes the spaces to be inserted on the left rather
          than the right.

     '~S'
          The next ARGUMENT, which may be any object, is printed as if
          by 'write'.  '~MINCOLS' inserts spaces on the right, if
          necessary, to make the width at least MINCOL columns.  The '@'
          modifier causes the spaces to be inserted on the left rather
          than the right.

     '~%'
          This outputs a '#\newline' character.  '~N%' outputs N
          newlines.  No ARGUMENT is used.  Simply putting a newline in
          CONTROL-STRING would work, but '~%' is often used because it
          makes the control string look nicer in the middle of a
          program.

     '~~'
          This outputs a tilde.  '~N~' outputs N tildes.

     '~NEWLINE'
          Tilde immediately followed by a newline ignores the newline
          and any following non-newline whitespace characters.  With an
          '@', the newline is left in place, but any following
          whitespace is ignored.  This directive is typically used when
          CONTROL-STRING is too long to fit nicely into one line of the
          program:

               (define (type-clash-error procedure arg spec actual)
                 (format
                  #t
                  "~%Procedure ~S~%requires its %A argument ~
                   to be of type ~S,~%but it was called with ~
                   an argument of type ~S.~%"
                  procedure arg spec actual))

               (type-clash-error 'vector-ref
                                 "first"
                                 'integer
                                 'vector)

               prints

               Procedure vector-ref
               requires its first argument to be of type integer,
               but it was called with an argument of type vector.

          Note that in this example newlines appear in the output only
          as specified by the '~%' directives; the actual newline
          characters in the control string are suppressed because each
          is preceded by a tilde.

   ---------- Footnotes ----------

   (1) This description of 'format' is adapted from 'Common Lisp, The
Language', second edition, section 22.3.3.


File: mit-scheme-ref.info,  Node: Custom Output,  Next: Prompting,  Prev: Format,  Up: Input/Output

14.10 Custom Output
===================

MIT/GNU Scheme provides hooks for specifying that specified objects have
special written representations.  There are no restrictions on the
written representations.

 -- procedure: define-print-method predicate print-method
     Defines the print method for objects satisfying PREDICATE to be
     PRINT-METHOD.  The PREDICATE argument must be a unary procedure
     that returns true for the objects to print specially, and
     PRINT-METHOD must be a binary procedure that accepts one of those
     objects and a textual output port.

     Although PRINT-METHOD can print the object in any way, we strongly
     recomment using one of the following special printers.

 -- procedure: standard-print-method name [get-parts]
     The NAME argument may be a unary procedure, a string, or a symbol;
     if it is a procedure it is called with the object to be printed as
     its argument and should return a string or a symbol.  The GET-PARTS
     argument, if provided, must be a unary procedure that is called
     with the object to be printed and must return a list of objects.
     If GET-PARTS is not provided, it defaults to a procedure that
     returns an empty list.

     The output generated by this method is in a standard format:
          #[<name> <hash> <part>...]
     where '<name>' is the string or symbol from NAME as printed by
     'display', '<hash>' is a unique nonnegative integer generated by
     calling 'hash-object' on the object, and the '<part>'s are the
     result of calling GET-PARTS as printed by 'write' and separated by
     spaces.

     One significant advantage of print methods generated by
     'standard-print-method' is that the parts returned by GET-PARTS are
     examined when searching for circular structure (as by 'write') or
     shared structure (as by 'write-shared').  In effect the printer
     sees one of these objects as a compound object containing those
     parts.

 -- procedure: bracketed-print-method name printer
     The NAME argument may be a unary procedure, a string, or a symbol;
     if it is a procedure it is called with the object to be printed as
     its argument and should return a string or a symbol.  The PRINTER
     argument must be a binary procedure, which is called with the
     object to print and a textual output port as its arguments.

     Similar to 'standard-print-method', this procedure prints an object
          #[<name> <hash><output>]
     where '<name>' is the string or symbol from NAME as printed by
     'display', '<hash>' is a unique nonnegative integer generated by
     calling 'hash-object' on the object, and '<output>' is the text
     written by PRINTER.

     This procedure has the benefit of printing objects using the
     standard bracketed form, but because its OUTPUT is unstructured can
     not be examined for sharing or circularity.  Generally speaking
     it's preferable to use 'standard-print-method' instead.

   The following are deprecated procedures that have been replaced by
the above.

 -- obsolete procedure: set-record-type-unparser-method! record-type
          unparser-method
     This procedure is *deprecated*; instead use
          (define-print-method (record-constructor RECORD-TYPE)
            UNPARSER-METHOD)
     provided that UNPARSER-METHOD is really a print method.

 -- obsolete procedure: unparser/set-tagged-vector-method! tag
          unparser-method
 -- obsolete procedure: unparser/set-tagged-pair-method! tag
          unparser-method
     These procedures arg *deprecated*.  There is no direct replacement
     for them.

     These were primarily used by 'define-structure', which now
     generates new-style print methods.  If you have other uses of
     these, it should be possible to translate them to use
     'define-print-method' with hand-written predicates.

 -- obsolete procedure: standard-unparser-method name procedure
     This procedure is *deprecated*; it is currently an alias for
     'bracketed-print-method'.

 -- obsolete procedure: with-current-unparser-state unparser-state
          procedure
     This procedure is *deprecated*, with no direct replacement.  In
     general just use PROCEDURE without wrapping it.


File: mit-scheme-ref.info,  Node: Prompting,  Next: Textual Port Primitives,  Prev: Custom Output,  Up: Input/Output

14.11 Prompting
===============

This section describes procedures that prompt the user for input.  Why
should the programmer use these procedures when it is possible to do
prompting using ordinary input and output procedures?  One reason is
that the prompting procedures are more succinct.  However, a second and
better reason is that the prompting procedures can be separately
customized for each user interface, providing more natural interaction.
The interfaces for Edwin and for GNU Emacs have already been customized
in this fashion; because Edwin and Emacs are very similar editors, their
customizations provide very similar behavior.

   Each of these procedure accepts an optional argument called PORT,
which if given must be an I/O port.  If not given, this port defaults to
the value of '(interaction-i/o-port)'; this is initially the console I/O
port.

 -- procedure: prompt-for-command-expression prompt [port]
     Prompts the user for an expression that is to be executed as a
     command.  This is the procedure called by the REP loop to read the
     user's expressions.

     If PROMPT is a string, it is used verbatim as the prompt string.
     Otherwise, it must be a pair whose car is the symbol 'standard' and
     whose cdr is a string; in this case the prompt string is formed by
     prepending to the string the current REP loop "level number" and a
     space.  Also, a space is appended to the string, unless it already
     ends in a space or is an empty string.

     The default behavior of this procedure is to print a fresh line, a
     newline, and the prompt string; flush the output buffer; then read
     an object and return it.  v Under Edwin and Emacs, before the
     object is read, the interaction buffer is put into a mode that
     allows expressions to be edited and submitted for input using
     specific editor commands.  The first expression that is submitted
     is returned as the value of this procedure.

 -- procedure: prompt-for-command-char prompt [port]
     Prompts the user for a single character that is to be executed as a
     command; the returned character is guaranteed to satisfy
     'char-graphic?'.  If at all possible, the character is read from
     the user interface using a mode that reads the character as a
     single keystroke; in other words, it should not be necessary for
     the user to follow the character with a carriage return or
     something similar.

     This is the procedure called by 'debug' and 'where' to read the
     user's commands.

     If PROMPT is a string, it is used verbatim as the prompt string.
     Otherwise, it must be a pair whose car is 'standard' and whose cdr
     is a string; in this case the prompt string is formed by prepending
     to the string the current REP loop "level number" and a space.
     Also, a space is appended to the string, unless it already ends in
     a space or is an empty string.

     The default behavior of this procedure is to print a fresh line, a
     newline, and the prompt string; flush the output buffer; read a
     character in raw mode, echo that character, and return it.

     Under Edwin and Emacs, instead of reading a character, the
     interaction buffer is put into a mode in which graphic characters
     submit themselves as input.  After this mode change, the first such
     character submitted is returned as the value of this procedure.

 -- procedure: prompt-for-expression prompt [port]
     Prompts the user for an expression.

     The prompt string is formed by appending a colon and a space to
     PROMPT, unless PROMPT already ends in a space or is the null
     string.

     The default behavior of this procedure is to print a fresh line, a
     newline, and the prompt string; flush the output buffer; then read
     an object and return it.

     Under Edwin and Emacs, the expression is read in the minibuffer.

 -- procedure: prompt-for-evaluated-expression prompt [environment
          [port]]
     Prompts the user for an evaluated expression.  Calls
     'prompt-for-expression' to read an expression, then evaluates the
     expression using ENVIRONMENT; if ENVIRONMENT is not given, the REP
     loop environment is used.

 -- procedure: prompt-for-confirmation prompt [port]
     Prompts the user for confirmation.  The result yielded by this
     procedure is a boolean.

     The prompt string is formed by appending the string '" (y or n)? "'
     to PROMPT, unless PROMPT already ends in a space or is the null
     string.

     The default behavior of this procedure is to print a fresh line, a
     newline, and the prompt string; flush the output buffer; then read
     a character in raw mode.  If the character is '#\y', '#\Y', or
     '#\space', the procedure returns '#t'; If the character is '#\n',
     '#\N', or '#\rubout', the procedure returns '#f'.  Otherwise the
     prompt is repeated.

     Under Edwin or Emacs, the confirmation is read in the minibuffer.


File: mit-scheme-ref.info,  Node: Textual Port Primitives,  Next: Parser Buffers,  Prev: Prompting,  Up: Input/Output

14.12 Textual Port Primitives
=============================

This section describes the low-level operations that can be used to
build and manipulate textual I/O ports.  The purpose of these operations
is to allow programmers to construct new kinds of textual I/O ports.

   The mechanisms described in this section are exclusively for textual
ports; binary ports can't be customized.  In this section, any reference
to a "port" that isn't modified by "textual" or "binary" is assumed to
be a textual port.

   The abstract model of a textual I/O port, as implemented here, is a
combination of a set of named operations and a state.  The state is an
arbitrary object, the meaning of which is determined by the operations.
The operations are defined by a mapping from names to procedures.

   The set of named operations is represented by an object called a
"textual port type".  A port type is constructed from a set of named
operations, and is subsequently used to construct a port.  The port type
completely specifies the behavior of the port.  Port types also support
a simple form of inheritance, allowing you to create new ports that are
similar to existing ports.

   The port operations are divided into two classes:

Standard operations
     There is a specific set of standard operations for input ports, and
     a different set for output ports.  Applications can assume that the
     standard input operations are implemented for all input ports, and
     likewise the standard output operations are implemented for all
     output ports.

Custom operations
     Some ports support additional operations.  For example, ports that
     implement output to terminals (or windows) may define an operation
     named 'y-size' that returns the height of the terminal in
     characters.  Because only some ports will implement these
     operations, programs that use custom operations must test each port
     for their existence, and be prepared to deal with ports that do not
     implement them.

* Menu:

* Textual Port Types::
* Constructors and Accessors for Textual Ports::
* Textual Input Port Operations::
* Textual Output Port Operations::


File: mit-scheme-ref.info,  Node: Textual Port Types,  Next: Constructors and Accessors for Textual Ports,  Prev: Textual Port Primitives,  Up: Textual Port Primitives

14.12.1 Textual Port Types
--------------------------

The procedures in this section provide means for constructing port types
with standard and custom operations, and accessing their operations.

 -- procedure: make-textual-port-type operations port-type
     Creates and returns a new port type.  OPERATIONS must be a list;
     each element is a list of two elements, the name of the operation
     (a symbol) and the procedure that implements it.  PORT-TYPE is
     either '#f' or a port type; if it is a port type, any operations
     implemented by PORT-TYPE but not specified in OPERATIONS will be
     implemented by the resulting port type.

     OPERATIONS need not contain definitions for all of the standard
     operations; the procedure will provide defaults for any standard
     operations that are not defined.  At a minimum, the following
     operations must be defined: for input ports, 'read-char' and
     'peek-char'; for output ports, either 'write-char' or
     'write-substring'.  I/O ports must supply the minimum operations
     for both input and output.

     If an operation in OPERATIONS is defined to be '#f', then the
     corresponding operation in PORT-TYPE is _not_ inherited.

     If 'read-char' is defined in OPERATIONS, then any standard input
     operations defined in PORT-TYPE are ignored.  Likewise, if
     'write-char' or 'write-substring' is defined in OPERATIONS, then
     any standard output operations defined in PORT-TYPE are ignored.
     This feature allows overriding the standard operations without
     having to enumerate them.

 -- procedure: textual-port-type? object
 -- procedure: textual-input-port-type? object
 -- procedure: textual-output-port-type? object
 -- procedure: textual-i/o-port-type? object
     These predicates return '#t' if OBJECT is a port type, input-port
     type, output-port type, or I/O-port type, respectively.  Otherwise,
     they return '#f'.

 -- obsolete procedure: make-port-type operations port-type
 -- obsolete procedure: port-type? object
 -- obsolete procedure: input-port-type? object
 -- obsolete procedure: output-port-type? object
 -- obsolete procedure: i/o-port-type? object
     These procedures are *deprecated*; use the procedures defined
     above.

 -- obsolete procedure: port-type/operations port-type
 -- obsolete procedure: port-type/operation-names port-type
 -- obsolete procedure: port-type/operation port-type symbol
     These procedures are *deprecated* and will be removed in the near
     future.  There are no replacements planned.


File: mit-scheme-ref.info,  Node: Constructors and Accessors for Textual Ports,  Next: Textual Input Port Operations,  Prev: Textual Port Types,  Up: Textual Port Primitives

14.12.2 Constructors and Accessors for Textual Ports
----------------------------------------------------

The procedures in this section provide means for constructing ports,
accessing the type of a port, and manipulating the state of a port.

 -- procedure: make-textual-port port-type state
     Returns a new port with type PORT-TYPE and the given STATE.  The
     port will be an input, output, or I/O port according to PORT-TYPE.

 -- procedure: textual-port-type textual-port
     Returns the port type of TEXTUAL-PORT.

 -- procedure: textual-port-state textual-port
     Returns the state component of TEXTUAL-PORT.

 -- procedure: set-textual-port-state! textual-port object
     Changes the state component of TEXTUAL-PORT to be OBJECT.  Returns
     an unspecified value.

 -- procedure: textual-port-operation textual-port symbol
     Returns the operation named SYMBOL for TEXTUAL-PORT.  If
     TEXTUAL-PORT has no such operation, returns '#f'.

 -- procedure: textual-port-operation-names textual-port
     Returns a newly allocated list whose elements are the names of the
     operations implemented by TEXTUAL-PORT.

 -- obsolete procedure: make-port port-type state
 -- obsolete procedure: port/type textual-port
 -- obsolete procedure: port/state textual-port
 -- obsolete procedure: set-port/state! textual-port object
 -- obsolete procedure: port/operation textual-port symbol
 -- obsolete procedure: port/operation-names port
     These procedures are *deprecated*; use the procedures defined
     above.


File: mit-scheme-ref.info,  Node: Textual Input Port Operations,  Next: Textual Output Port Operations,  Prev: Constructors and Accessors for Textual Ports,  Up: Textual Port Primitives

14.12.3 Textual Input Port Operations
-------------------------------------

This section describes the standard operations on textual input ports.
Following that, some useful custom operations are described.

 -- operation on textual input port: read-char port
     Removes the next character available from PORT and returns it.  If
     PORT has no more characters and will never have any (e.g. at the
     end of an input file), this operation returns an end-of-file
     object.  If PORT has no more characters but will eventually have
     some more (e.g. a terminal where nothing has been typed recently),
     and it is in non-blocking mode, '#f' is returned; otherwise the
     operation hangs until input is available.

 -- operation on textual input port: peek-char port
     Reads the next character available from PORT and returns it.  The
     character is _not_ removed from PORT, and a subsequent attempt to
     read from the port will get that character again.  In other
     respects this operation behaves like 'read-char'.

 -- operation on textual input port: char-ready? port k
     'char-ready?' returns '#t' if at least one character is available
     to be read from PORT.  If no characters are available, the
     operation waits up to K milliseconds before returning '#f',
     returning immediately if any characters become available while it
     is waiting.

 -- operation on textual input port: read-string port char-set
 -- operation on textual input port: discard-chars port char-set
     These operations are like 'read-char', except that they read or
     discard multiple characters at once.  All characters up to, but
     excluding, the first character in CHAR-SET (or end of file) are
     read from PORT.  'read-string' returns these characters as a newly
     allocated string, while 'discard-chars' discards them and returns
     an unspecified value.  These operations hang until sufficient input
     is available, even if PORT is in non-blocking mode.  If end of file
     is encountered before any input characters, 'read-string' returns
     an end-of-file object.

 -- operation on textual input port: read-substring port string start
          end
     Reads characters from PORT into the substring defined by STRING,
     START, and END until either the substring has been filled or there
     are no more characters available.  Returns the number of characters
     written to the substring.

     If PORT is an interactive port, and at least one character is
     immediately available, the available characters are written to the
     substring and this operation returns immediately.  If no characters
     are available, and PORT is in blocking mode, the operation blocks
     until at least one character is available.  Otherwise, the
     operation returns '#f' immediately.

     This is an extremely fast way to read characters from a port.

 -- procedure: input-port/read-char textual-input-port
 -- procedure: input-port/peek-char textual-input-port
 -- procedure: input-port/char-ready? textual-input-port k
 -- procedure: input-port/read-string textual-input-port char-set
 -- procedure: input-port/discard-chars textual-input-port char-set
 -- procedure: input-port/read-substring textual-input-port string start
          end
     Each of these procedures invokes the respective operation on
     TEXTUAL-INPUT-PORT.  For example, the following are equivalent:

          (input-port/read-char TEXTUAL-INPUT-PORT)
          ((textual-port-operation TEXTUAL-INPUT-PORT 'read-char)
           TEXTUAL-INPUT-PORT)

   The following custom operations are implemented for input ports to
files, and will also work with some other kinds of input ports:

 -- operation on textual input port: eof? port
     Returns '#t' if PORT is known to be at end of file, otherwise it
     returns '#f'.

 -- operation on textual input port: chars-remaining port
     Returns an estimate of the number of characters remaining to be
     read from PORT.  This is useful only when PORT is a file port in
     binary mode; in other cases, it returns '#f'.

 -- operation on textual input port: buffered-input-chars port
     Returns the number of unread characters that are stored in PORT's
     buffer.  This will always be less than or equal to the buffer's
     size.

 -- operation on textual input port: input-buffer-size port
     Returns the maximum number of characters that PORT's buffer can
     hold.

 -- operation on textual input port: set-input-buffer-size port size
     Resizes PORT's buffer so that it can hold at most SIZE characters.
     Characters in the buffer are discarded.  SIZE must be an exact
     non-negative integer.


File: mit-scheme-ref.info,  Node: Textual Output Port Operations,  Prev: Textual Input Port Operations,  Up: Textual Port Primitives

14.12.4 Textual Output Port Operations
--------------------------------------

This section describes the standard operations on output ports.
Following that, some useful custom operations are described.

 -- operation on textual output port: write-char port char
     Writes CHAR to PORT and returns an unspecified value.

 -- operation on textual output port: write-substring port string start
          end
     Writes the substring specified by STRING, START, and END to PORT
     and returns an unspecified value.  Equivalent to writing the
     characters of the substring, one by one, to PORT, but is
     implemented very efficiently.

 -- operation on textual output port: fresh-line port
     Most output ports are able to tell whether or not they are at the
     beginning of a line of output.  If PORT is such a port, end-of-line
     is written to the port only if the port is not already at the
     beginning of a line.  If PORT is not such a port, an end-of-line is
     unconditionally written to the port.  Returns an unspecified value.

 -- operation on textual output port: flush-output port
     If PORT is buffered, this causes its buffer to be written out.
     Otherwise it has no effect.  Returns an unspecified value.

 -- operation on textual output port: discretionary-flush-output port
     Normally, this operation does nothing.  However, ports that support
     discretionary output flushing implement this operation identically
     to 'flush-output'.

 -- procedure: output-port/write-char textual-output-port char
 -- procedure: output-port/write-substring textual-output-port string
          start end
 -- procedure: output-port/fresh-line textual-output-port
 -- procedure: output-port/flush-output textual-output-port
 -- procedure: output-port/discretionary-flush-output
          textual-output-port
     Each of these procedures invokes the respective operation on
     TEXTUAL-OUTPUT-PORT.  For example, the following are equivalent:

          (output-port/write-char TEXTUAL-OUTPUT-PORT CHAR)
          ((textual-port-operation TEXTUAL-OUTPUT-PORT 'write-char)
           TEXTUAL-OUTPUT-PORT CHAR)

 -- procedure: output-port/write-string textual-output-port string
     Writes STRING to TEXTUAL-OUTPUT-PORT.  Equivalent to

          (output-port/write-substring TEXTUAL-OUTPUT-PORT
                                       STRING
                                       0
                                       (string-length STRING))

   The following custom operations are generally useful.

 -- operation on textual output port: buffered-output-chars port
     Returns the number of unwritten characters that are stored in
     PORT's buffer.  This will always be less than or equal to the
     buffer's size.

 -- operation on textual output port: output-buffer-size port
     Returns the maximum number of characters that PORT's buffer can
     hold.

 -- operation on textual output port: set-output-buffer-size port size
     Resizes PORT's buffer so that it can hold at most SIZE characters.
     Characters in the buffer are discarded.  SIZE must be an exact
     non-negative integer.

 -- operation on textual output port: x-size port
     Returns an exact positive integer that is the width of PORT in
     characters.  If PORT has no natural width, e.g. if it is a file
     port, '#f' is returned.

 -- operation on textual output port: y-size port
     Returns an exact positive integer that is the height of PORT in
     characters.  If PORT has no natural height, e.g. if it is a file
     port, '#f' is returned.

 -- procedure: output-port/x-size textual-output-port
     This procedure invokes the custom operation whose name is the
     symbol 'x-size', if it exists.  If the 'x-size' operation is both
     defined and returns a value other than '#f', that value is returned
     as the result of this procedure.  Otherwise, 'output-port/x-size'
     returns a default value (currently '80').

     'output-port/x-size' is useful for programs that tailor their
     output to the width of the display (a fairly common practice).  If
     the output device is not a display, such programs normally want
     some reasonable default width to work with, and this procedure
     provides exactly that.

 -- procedure: output-port/y-size textual-output-port
     This procedure invokes the custom operation whose name is the
     symbol 'y-size', if it exists.  If the 'y-size' operation is
     defined, the value it returns is returned as the result of this
     procedure; otherwise, '#f' is returned.


File: mit-scheme-ref.info,  Node: Parser Buffers,  Next: Parser Language,  Prev: Textual Port Primitives,  Up: Input/Output

14.13 Parser Buffers
====================

The "parser buffer" mechanism facilitates construction of parsers for
complex grammars.  It does this by providing an input stream with
unbounded buffering and backtracking.  The amount of buffering is under
program control.  The stream can backtrack to any position in the
buffer.

   The mechanism defines two data types: the "parser buffer" and the
"parser-buffer pointer".  A parser buffer is like an input port with
buffering and backtracking.  A parser-buffer pointer is a pointer into
the stream of characters provided by a parser buffer.

   Note that all of the procedures defined here consider a parser buffer
to contain a stream of Unicode characters.

   There are several constructors for parser buffers:

 -- procedure: textual-input-port->parser-buffer textual-input-port
 -- obsolete procedure: input-port->parser-buffer textual-input-port
     Returns a parser buffer that buffers characters read from
     TEXTUAL-INPUT-PORT.

 -- procedure: substring->parser-buffer string start end
     Returns a parser buffer that buffers the characters in the argument
     substring.  This is equivalent to creating a string input port and
     calling 'textual-input-port->parser-buffer', but it runs faster and
     uses less memory.

 -- procedure: string->parser-buffer string
     Like 'substring->parser-buffer' but buffers the entire string.

 -- procedure: source->parser-buffer source
     Returns a parser buffer that buffers the characters returned by
     calling SOURCE.  SOURCE is a procedure of three arguments: a
     string, a start index, and an end index (in other words, a
     substring specifier).  Each time SOURCE is called, it writes some
     characters in the substring, and returns the number of characters
     written.  When there are no more characters available, it returns
     zero.  It must not return zero in any other circumstance.

   Parser buffers and parser-buffer pointers may be distinguished from
other objects:

 -- procedure: parser-buffer? object
     Returns '#t' if OBJECT is a parser buffer, otherwise returns '#f'.

 -- procedure: parser-buffer-pointer? object
     Returns '#t' if OBJECT is a parser-buffer pointer, otherwise
     returns '#f'.

   Characters can be read from a parser buffer much as they can be read
from an input port.  The parser buffer maintains an internal pointer
indicating its current position in the input stream.  Additionally, the
buffer remembers all characters that were previously read, and can look
at characters arbitrarily far ahead in the stream.  It is this buffering
capability that facilitates complex matching and backtracking.

 -- procedure: read-parser-buffer-char buffer
     Returns the next character in BUFFER, advancing the internal
     pointer past that character.  If there are no more characters
     available, returns '#f' and leaves the internal pointer unchanged.

 -- procedure: peek-parser-buffer-char buffer
     Returns the next character in BUFFER, or '#f' if no characters are
     available.  Leaves the internal pointer unchanged.

 -- procedure: parser-buffer-ref buffer index
     Returns a character in BUFFER.  INDEX is a non-negative integer
     specifying the character to be returned.  If INDEX is zero, returns
     the next available character; if it is one, returns the character
     after that, and so on.  If INDEX specifies a position after the
     last character in BUFFER, returns '#f'.  Leaves the internal
     pointer unchanged.

   The internal pointer of a parser buffer can be read or written:

 -- procedure: get-parser-buffer-pointer buffer
     Returns a parser-buffer pointer object corresponding to the
     internal pointer of BUFFER.

 -- procedure: set-parser-buffer-pointer! buffer pointer
     Sets the internal pointer of BUFFER to the position specified by
     POINTER.  POINTER must have been returned from a previous call of
     'get-parser-buffer-pointer' on BUFFER.  Additionally, if some of
     BUFFER's characters have been discarded by
     'discard-parser-buffer-head!', POINTER must be outside the range
     that was discarded.

 -- procedure: get-parser-buffer-tail buffer pointer
     Returns a newly-allocated string consisting of all of the
     characters in BUFFER that fall between POINTER and BUFFER's
     internal pointer.  POINTER must have been returned from a previous
     call of 'get-parser-buffer-pointer' on BUFFER.  Additionally, if
     some of BUFFER's characters have been discarded by
     'discard-parser-buffer-head!', POINTER must be outside the range
     that was discarded.

 -- procedure: discard-parser-buffer-head! buffer
     Discards all characters in BUFFER that have already been read; in
     other words, all characters prior to the internal pointer.  After
     this operation has completed, it is no longer possible to move the
     internal pointer backwards past the current position by calling
     'set-parser-buffer-pointer!'.

   The next rather large set of procedures does conditional matching
against the contents of a parser buffer.  All matching is performed
relative to the buffer's internal pointer, so the first character to be
matched against is the next character that would be returned by
'peek-parser-buffer-char'.  The returned value is always '#t' for a
successful match, and '#f' otherwise.  For procedures whose names do not
end in '-no-advance', a successful match also moves the internal pointer
of the buffer forward to the end of the matched text; otherwise the
internal pointer is unchanged.

 -- procedure: match-parser-buffer-char buffer char
 -- procedure: match-parser-buffer-char-ci buffer char
 -- procedure: match-parser-buffer-not-char buffer char
 -- procedure: match-parser-buffer-not-char-ci buffer char
 -- procedure: match-parser-buffer-char-no-advance buffer char
 -- procedure: match-parser-buffer-char-ci-no-advance buffer char
 -- procedure: match-parser-buffer-not-char-no-advance buffer char
 -- procedure: match-parser-buffer-not-char-ci-no-advance buffer char
     Each of these procedures compares a single character in BUFFER to
     CHAR.  The basic comparison 'match-parser-buffer-char' compares the
     character to CHAR using 'char=?'.  The procedures whose names
     contain the '-ci' modifier do case-insensitive comparison (i.e.
     they use 'char-ci=?').  The procedures whose names contain the
     'not-' modifier are successful if the character _doesn't_ match
     CHAR.

 -- procedure: match-parser-buffer-char-in-set buffer char-set
 -- procedure: match-parser-buffer-char-in-set-no-advance buffer
          char-set
     These procedures compare the next character in BUFFER against
     CHAR-SET using 'char-in-set?'.

 -- procedure: match-parser-buffer-string buffer string
 -- procedure: match-parser-buffer-string-ci buffer string
 -- procedure: match-parser-buffer-string-no-advance buffer string
 -- procedure: match-parser-buffer-string-ci-no-advance buffer string
     These procedures match STRING against BUFFER's contents.  The '-ci'
     procedures do case-insensitive matching.

 -- procedure: match-parser-buffer-substring buffer string start end
 -- procedure: match-parser-buffer-substring-ci buffer string start end
 -- procedure: match-parser-buffer-substring-no-advance buffer string
          start end
 -- procedure: match-parser-buffer-substring-ci-no-advance buffer string
          start end
     These procedures match the specified substring against BUFFER's
     contents.  The '-ci' procedures do case-insensitive matching.

   The remaining procedures provide information that can be used to
identify locations in a parser buffer's stream.

 -- procedure: parser-buffer-position-string pointer
     Returns a string describing the location of POINTER in terms of its
     character and line indexes.  This resulting string is meant to be
     presented to an end user in order to direct their attention to a
     feature in the input stream.  In this string, the indexes are
     presented as one-based numbers.

     POINTER may alternatively be a parser buffer, in which case it is
     equivalent to having specified the buffer's internal pointer.

 -- procedure: parser-buffer-pointer-index pointer
 -- procedure: parser-buffer-pointer-line pointer
     Returns the character or line index, respectively, of POINTER.
     Both indexes are zero-based.


File: mit-scheme-ref.info,  Node: Parser Language,  Next: XML Support,  Prev: Parser Buffers,  Up: Input/Output

14.14 Parser Language
=====================

Although it is possible to write parsers using the parser-buffer
abstraction (*note Parser Buffers::), it is tedious.  The problem is
that the abstraction isn't closely matched to the way that people think
about syntactic structures.  In this section, we introduce a
higher-level mechanism that greatly simplifies the implementation of a
parser.

   The "parser language" described here allows the programmer to write
BNF-like specifications that are translated into efficient Scheme code
at compile time.  The language is declarative, but it can be freely
mixed with Scheme code; this allows the parsing of grammars that aren't
conveniently described in the language.

   The language also provides backtracking.  For example, this
expression matches any sequence of alphanumeric characters followed by a
single alphabetic character:

     (*matcher
      (seq (* (char-set char-set:alphanumeric))
           (char-set char-set:alphabetic)))

The way that this works is that the matcher matches alphanumeric
characters in the input stream until it finds a non-alphanumeric
character.  It then tries to match an alphabetic character, which of
course fails.  At this point, if it matched at least one alphanumeric
character, it _backtracks_: the last matched alphanumeric is
"unmatched", and it again attempts to match an alphabetic character.
The backtracking can be arbitrarily deep; the matcher will continue to
back up until it finds a way to match the remainder of the expression.

   So far, this sounds a lot like regular-expression matching (*note
Regular Expressions::).  However, there are some important differences.

   * The parser language uses a Scheme-like syntax that is easier to
     read and write than regular-expression notation.

   * The language provides macros so that common syntactic constructs
     can be abstracted.

   * The language mixes easily with Scheme code, allowing the full power
     of Scheme to be applied to program around limitations in the parser
     language.

   * The language provides expressive facilities for converting syntax
     into parsed structure.  It also makes it easy to convert parsed
     strings into meaningful objects (e.g. numbers).

   * The language is compiled into machine language; regular expressions
     are usually interpreted.

   Here is an example that shows off several of the features of the
parser language.  The example is a parser for XML start tags:

     (*parser
      (with-pointer p
        (seq "<"
             parse-name
             parse-attribute-list
             (alt (match ">")
                  (match "/>")
                  (sexp
                   (lambda (b)
                     (error
                      (string-append
                       "Unterminated start tag at "
                       (parser-buffer-position-string p)))))))))

This shows that the basic description of a start tag is very similar to
its BNF.  Non-terminal symbols 'parse-name' and 'parse-attribute-list'
do most of the work, and the noise strings '"<"' and '">"' are the
syntactic markers delimiting the form.  There are two alternate endings
for start tags, and if the parser doesn't find either of the endings,
the Scheme code (wrapped in 'sexp') is run to signal an error.  The
error procedure 'perror' takes a pointer 'p', which it uses to indicate
the position in the input stream at which the error occurred.  In this
case, that is the beginning of the start tag, i.e. the position of the
leading '"<"' marker.

   This example still looks pretty complicated, mostly due to the
error-signalling code.  In practice, this is abstracted into a macro,
after which the expression is quite succinct:

     (*parser
      (bracket "start tag"
          (seq (noise (string "<")) parse-name)
          (match (alt (string ">") (string "/>")))
        parse-attribute-list))

The 'bracket' macro captures the pattern of a bracketed item, and hides
much of the detail.

   The parser language actually consists of two languages: one for
defining matchers, and one for defining parsers.  The languages are
intentionally very similar, and are meant to be used together.  Each
sub-language is described below in its own section.

   The parser language is a run-time-loadable option; to use it, execute

     (load-option '*parser)

once before compiling any code that uses the language.

* Menu:

* *Matcher::
* *Parser::
* Parser-language Macros::


File: mit-scheme-ref.info,  Node: *Matcher,  Next: *Parser,  Prev: Parser Language,  Up: Parser Language

14.14.1 *Matcher
----------------

The "matcher language" is a declarative language for specifying a
"matcher procedure".  A matcher procedure is a procedure that accepts a
single parser-buffer argument and returns a boolean value indicating
whether the match it performs was successful.  If the match succeeds,
the internal pointer of the parser buffer is moved forward over the
matched text.  If the match fails, the internal pointer is unchanged.

   For example, here is a matcher procedure that matches the character
'a':

     (lambda (b) (match-parser-buffer-char b #\a))

Here is another example that matches two given characters, C1 and C2, in
sequence:

     (lambda (b)
       (let ((p (get-parser-buffer-pointer b)))
         (if (match-parser-buffer-char b C1)
             (if (match-parser-buffer-char b C2)
                 #t
                 (begin
                   (set-parser-buffer-pointer! b p)
                   #f))
             #f)))

This is code is clear, but has lots of details that get in the way of
understanding what it is doing.  Here is the same example in the matcher
language:

     (*matcher (seq (char C1) (char C2)))

This is much simpler and more intuitive.  And it generates virtually the
same code:

     (pp (*matcher (seq (char c1) (char c2))))
     -| (lambda (#[b1])
     -|   (let ((#[p1] (get-parser-buffer-pointer #[b1])))
     -|     (and (match-parser-buffer-char #[b1] c1)
     -|          (if (match-parser-buffer-char #[b1] c2)
     -|              #t
     -|              (begin
     -|                (set-parser-buffer-pointer! #[b1] #[p1])
     -|                #f)))))

   Now that we have seen an example of the language, it's time to look
at the detail.  The '*matcher' special form is the interface between the
matcher language and Scheme.

 -- special form: *matcher mexp
     The operand MEXP is an expression in the matcher language.  The
     '*matcher' expression expands into Scheme code that implements a
     matcher procedure.

   Here are the predefined matcher expressions.  New matcher expressions
can be defined using the macro facility (*note Parser-language
Macros::).  We will start with the primitive expressions.

 -- matcher expression: char expression
 -- matcher expression: char-ci expression
 -- matcher expression: not-char expression
 -- matcher expression: not-char-ci expression
     These expressions match a given character.  In each case, the
     EXPRESSION operand is a Scheme expression that must evaluate to a
     character at run time.  The '-ci' expressions do case-insensitive
     matching.  The 'not-' expressions match any character other than
     the given one.

 -- matcher expression: string expression
 -- matcher expression: string-ci expression
     These expressions match a given string.  The EXPRESSION operand is
     a Scheme expression that must evaluate to a string at run time.
     The 'string-ci' expression does case-insensitive matching.

 -- matcher expression: char-set expression
     These expressions match a single character that is a member of a
     given character set.  The EXPRESSION operand is a Scheme expression
     that must evaluate to a character set at run time.

 -- matcher expression: end-of-input
     The 'end-of-input' expression is successful only when there are no
     more characters available to be matched.

 -- matcher expression: discard-matched
     The 'discard-matched' expression always successfully matches the
     null string.  However, it isn't meant to be used as a matching
     expression; it is used for its effect.  'discard-matched' causes
     all of the buffered text prior to this point to be discarded (i.e.
     it calls 'discard-parser-buffer-head!' on the parser buffer).

     Note that 'discard-matched' may not be used in certain places in a
     matcher expression.  The reason for this is that it deliberately
     discards information needed for backtracking, so it may not be used
     in a place where subsequent backtracking will need to back over it.
     As a rule of thumb, use 'discard-matched' only in the last operand
     of a 'seq' or 'alt' expression (including any 'seq' or 'alt'
     expressions in which it is indirectly contained).

   In addition to the above primitive expressions, there are two
convenient abbreviations.  A character literal (e.g. '#\A') is a legal
primitive expression, and is equivalent to a 'char' expression with that
literal as its operand (e.g. '(char #\A)').  Likewise, a string literal
is equivalent to a 'string' expression (e.g. '(string "abc")').

   Next there are several combinator expressions.  These closely
correspond to similar combinators in regular expressions.  Parameters
named MEXP are arbitrary expressions in the matcher language.

 -- matcher expression: seq mexp ...
     This matches each MEXP operand in sequence.  For example,

          (seq (char-set char-set:alphabetic)
               (char-set char-set:numeric))

     matches an alphabetic character followed by a numeric character,
     such as 'H4'.

     Note that if there are no MEXP operands, the 'seq' expression
     successfully matches the null string.

 -- matcher expression: alt mexp ...
     This attempts to match each MEXP operand in order from left to
     right.  The first one that successfully matches becomes the match
     for the entire 'alt' expression.

     The 'alt' expression participates in backtracking.  If one of the
     MEXP operands matches, but the overall match in which this
     expression is embedded fails, the backtracking mechanism will cause
     the 'alt' expression to try the remaining MEXP operands.  For
     example, if the expression

          (seq (alt "ab" "a") "b")

     is matched against the text 'abc', the 'alt' expression will
     initially match its first operand.  But it will then fail to match
     the second operand of the 'seq' expression.  This will cause the
     'alt' to be restarted, at which time it will match 'a', and the
     overall match will succeed.

     Note that if there are no MEXP operands, the 'alt' match will
     always fail.

 -- matcher expression: * mexp
     This matches zero or more occurrences of the MEXP operand.
     (Consequently this match always succeeds.)

     The '*' expression participates in backtracking; if it matches N
     occurrences of MEXP, but the overall match fails, it will backtrack
     to N-1 occurrences and continue.  If the overall match continues to
     fail, the '*' expression will continue to backtrack until there are
     no occurrences left.

 -- matcher expression: + mexp
     This matches one or more occurrences of the MEXP operand.  It is
     equivalent to

          (seq MEXP (* MEXP))

 -- matcher expression: ? mexp
     This matches zero or one occurrences of the MEXP operand.  It is
     equivalent to

          (alt MEXP (seq))

 -- matcher expression: sexp expression
     The 'sexp' expression allows arbitrary Scheme code to be embedded
     inside a matcher.  The EXPRESSION operand must evaluate to a
     matcher procedure at run time; the procedure is called to match the
     parser buffer.  For example,

          (*matcher
           (seq "a"
                (sexp parse-foo)
                "b"))

     expands to

          (lambda (#[b1])
            (let ((#[p1] (get-parser-buffer-pointer #[b1])))
              (and (match-parser-buffer-char #[b1] #\a)
                   (if (parse-foo #[b1])
                       (if (match-parser-buffer-char #[b1] #\b)
                           #t
                           (begin
                             (set-parser-buffer-pointer! #[b1] #[p1])
                             #f))
                       (begin
                         (set-parser-buffer-pointer! #[b1] #[p1])
                         #f)))))

     The case in which EXPRESSION is a symbol is so common that it has
     an abbreviation: '(sexp SYMBOL)' may be abbreviated as just SYMBOL.

 -- matcher expression: with-pointer identifier mexp
     The 'with-pointer' expression fetches the parser buffer's internal
     pointer (using 'get-parser-buffer-pointer'), binds it to
     IDENTIFIER, and then matches the pattern specified by MEXP.
     IDENTIFIER must be a symbol.

     This is meant to be used on conjunction with 'sexp', as a way to
     capture a pointer to a part of the input stream that is outside the
     'sexp' expression.  An example of the use of 'with-pointer' appears
     above (*note with-pointer example::).


File: mit-scheme-ref.info,  Node: *Parser,  Next: Parser-language Macros,  Prev: *Matcher,  Up: Parser Language

14.14.2 *Parser
---------------

The "parser language" is a declarative language for specifying a "parser
procedure".  A parser procedure is a procedure that accepts a single
parser-buffer argument and parses some of the input from the buffer.  If
the parse is successful, the procedure returns a vector of objects that
are the result of the parse, and the internal pointer of the parser
buffer is advanced past the input that was parsed.  If the parse fails,
the procedure returns '#f' and the internal pointer is unchanged.  This
interface is much like that of a matcher procedure, except that on
success the parser procedure returns a vector of values rather than
'#t'.

   The '*parser' special form is the interface between the parser
language and Scheme.

 -- special form: *parser pexp
     The operand PEXP is an expression in the parser language.  The
     '*parser' expression expands into Scheme code that implements a
     parser procedure.

   There are several primitive expressions in the parser language.  The
first two provide a bridge to the matcher language (*note *Matcher::):

 -- parser expression: match mexp
     The 'match' expression performs a match on the parser buffer.  The
     match to be performed is specified by MEXP, which is an expression
     in the matcher language.  If the match is successful, the result of
     the 'match' expression is a vector of one element: a string
     containing that text.

 -- parser expression: noise mexp
     The 'noise' expression performs a match on the parser buffer.  The
     match to be performed is specified by MEXP, which is an expression
     in the matcher language.  If the match is successful, the result of
     the 'noise' expression is a vector of zero elements.  (In other
     words, the text is matched and then thrown away.)

     The MEXP operand is often a known character or string, so in the
     case that MEXP is a character or string literal, the 'noise'
     expression can be abbreviated as the literal.  In other words,
     '(noise "foo")' can be abbreviated just '"foo"'.

 -- parser expression: values expression ...
     Sometimes it is useful to be able to insert arbitrary values into
     the parser result.  The 'values' expression supports this.  The
     EXPRESSION arguments are arbitrary Scheme expressions that are
     evaluated at run time and returned in a vector.  The 'values'
     expression always succeeds and never modifies the internal pointer
     of the parser buffer.

 -- parser expression: discard-matched
     The 'discard-matched' expression always succeeds, returning a
     vector of zero elements.  In all other respects it is identical to
     the 'discard-matched' expression in the matcher language.

   Next there are several combinator expressions.  Parameters named PEXP
are arbitrary expressions in the parser language.  The first few
combinators are direct equivalents of those in the matcher language.

 -- parser expression: seq pexp ...
     The 'seq' expression parses each of the PEXP operands in order.  If
     all of the PEXP operands successfully match, the result is the
     concatenation of their values (by 'vector-append').

 -- parser expression: alt pexp ...
     The 'alt' expression attempts to parse each PEXP operand in order
     from left to right.  The first one that successfully parses
     produces the result for the entire 'alt' expression.

     Like the 'alt' expression in the matcher language, this expression
     participates in backtracking.

 -- parser expression: * pexp
     The '*' expression parses zero or more occurrences of PEXP.  The
     results of the parsed occurrences are concatenated together (by
     'vector-append') to produce the expression's result.

     Like the '*' expression in the matcher language, this expression
     participates in backtracking.

 -- parser expression: + pexp
     The '*' expression parses one or more occurrences of PEXP.  It is
     equivalent to

          (seq PEXP (* PEXP))

 -- parser expression: ? pexp
     The '*' expression parses zero or one occurrences of PEXP.  It is
     equivalent to

          (alt PEXP (seq))

   The next three expressions do not have equivalents in the matcher
language.  Each accepts a single PEXP argument, which is parsed in the
usual way.  These expressions perform transformations on the returned
values of a successful match.

 -- parser expression: transform expression pexp
     The 'transform' expression performs an arbitrary transformation of
     the values returned by parsing PEXP.  EXPRESSION is a Scheme
     expression that must evaluate to a procedure at run time.  If PEXP
     is successfully parsed, the procedure is called with the vector of
     values as its argument, and must return a vector or '#f'.  If it
     returns a vector, the parse is successful, and those are the
     resulting values.  If it returns '#f', the parse fails and the
     internal pointer of the parser buffer is returned to what it was
     before PEXP was parsed.

     For example:

          (transform (lambda (v) (if (= 0 (vector-length v)) #f v)) ...)

 -- parser expression: encapsulate expression pexp
     The 'encapsulate' expression transforms the values returned by
     parsing PEXP into a single value.  EXPRESSION is a Scheme
     expression that must evaluate to a procedure at run time.  If PEXP
     is successfully parsed, the procedure is called with the vector of
     values as its argument, and may return any Scheme object.  The
     result of the 'encapsulate' expression is a vector of length one
     containing that object.  (And consequently 'encapsulate' doesn't
     change the success or failure of PEXP, only its value.)

     For example:

          (encapsulate vector->list ...)

 -- parser expression: map expression pexp
     The 'map' expression performs a per-element transform on the values
     returned by parsing PEXP.  EXPRESSION is a Scheme expression that
     must evaluate to a procedure at run time.  If PEXP is successfully
     parsed, the procedure is mapped (by 'vector-map') over the values
     returned from the parse.  The mapped values are returned as the
     result of the 'map' expression.  (And consequently 'map' doesn't
     change the success or failure of PEXP, nor the number of values
     returned.)

     For example:

          (map string->symbol ...)

   Finally, as in the matcher language, we have 'sexp' and
'with-pointer' to support embedding Scheme code in the parser.

 -- parser expression: sexp expression
     The 'sexp' expression allows arbitrary Scheme code to be embedded
     inside a parser.  The EXPRESSION operand must evaluate to a parser
     procedure at run time; the procedure is called to parse the parser
     buffer.  This is the parser-language equivalent of the 'sexp'
     expression in the matcher language.

     The case in which EXPRESSION is a symbol is so common that it has
     an abbreviation: '(sexp SYMBOL)' may be abbreviated as just SYMBOL.

 -- parser expression: with-pointer identifier pexp
     The 'with-pointer' expression fetches the parser buffer's internal
     pointer (using 'get-parser-buffer-pointer'), binds it to
     IDENTIFIER, and then parses the pattern specified by PEXP.
     IDENTIFIER must be a symbol.  This is the parser-language
     equivalent of the 'with-pointer' expression in the matcher
     language.


File: mit-scheme-ref.info,  Node: Parser-language Macros,  Prev: *Parser,  Up: Parser Language

14.14.3 Parser-language Macros
------------------------------

The parser and matcher languages provide a macro facility so that common
patterns can be abstracted.  The macro facility allows new expression
types to be independently defined in the two languages.  The macros are
defined in hierarchically organized tables, so that different
applications can have private macro bindings.

 -- special form: define-*matcher-macro formals expression
 -- special form: define-*parser-macro formals expression
     These special forms are used to define macros in the matcher and
     parser language, respectively.  FORMALS is like the FORMALS list of
     a 'define' special form, and EXPRESSION is a Scheme expression.

     If FORMALS is a list (or improper list) of symbols, the first
     symbol in the list is the name of the macro, and the remaining
     symbols are interpreted as the FORMALS of a lambda expression.  A
     lambda expression is formed by combining the latter FORMALS with
     the EXPRESSION, and this lambda expression, when evaluated, becomes
     the "expander".  The defined macro accepts the same number of
     operands as the expander.  A macro instance is expanded by applying
     the expander to the list of operands; the result of the application
     is interpreted as a replacement expression for the macro instance.

     If FORMALS is a symbol, it is the name of the macro.  In this case,
     the expander is a procedure of no arguments whose body is
     EXPRESSION.  When the FORMALS symbol appears by itself as an
     expression in the language, the expander is called with no
     arguments, and the result is interpreted as a replacement
     expression for the symbol.

 -- procedure: define-*matcher-expander identifier expander
 -- procedure: define-*parser-expander identifier expander
     These procedures provide a procedural interface to the
     macro-definition mechanism.  IDENTIFIER must be a symbol, and
     EXPANDER must be an expander procedure, as defined above.
     Instances of the 'define-*matcher-macro' and 'define-*parser-macro'
     special forms expand into calls to these procedures.

   The remaining procedures define the interface to the parser-macros
table abstraction.  Each parser-macro table has a separate binding space
for macros in the matcher and parser languages.  However, the table
inherits bindings from one specified table; it's not possible to inherit
matcher-language bindings from one table and parser-language bindings
from another.

 -- procedure: make-parser-macros parent-table
     Create and return a new parser-macro table that inherits from
     PARENT-TABLE.  PARENT-TABLE must be either a parser-macro table, or
     '#f'; usually it is specified as the value of
     'global-parser-macros'.

 -- procedure: parser-macros? object
     This is a predicate for parser-macro tables.

 -- procedure: global-parser-macros
     Return the global parser-macro table.  This table is predefined and
     contains all of the bindings documented here.

   There is a "current" table at all times, and macro definitions are
always placed in this table.  By default, the current table is the
global macro table, but the following procedures allow this to be
changed.

 -- procedure: current-parser-macros
     Return the current parser-macro table.

 -- procedure: set-current-parser-macros! table
     Change the current parser-macro table to TABLE, which must satisfy
     'parser-macros?'.

 -- procedure: with-current-parser-macros table thunk
     Bind the current parser-macro table to TABLE, call THUNK with no
     arguments, then restore the original table binding.  The value
     returned by THUNK is the returned as the value of this procedure.
     TABLE must satisfy 'parser-macros?', and THUNK must be a procedure
     of no arguments.


File: mit-scheme-ref.info,  Node: XML Support,  Prev: Parser Language,  Up: Input/Output

14.15 XML Support
=================

MIT/GNU Scheme provides a simple non-validating XML parser.  This parser
is believed to be conformant with XML 1.0.  It passes all of the tests
in the "xmltest" directory of the XML conformance tests (dated
2001-03-15).  The parser supports XML namespaces; it doesn't support
external document type declarations (DTDs), and it doesn't yet support
XML 1.1.  The output of the parser is a record tree that closely
reflects the structure of the XML document.

   MIT/GNU Scheme also provides support for writing an XML record tree
to an output port.  There is no guarantee that parsing an XML document
and writing it back out will make a verbatim copy of the document.  The
output will be semantically identical but may have small syntactic
differences.  For example, entities are substituted during the parsing
process.

   The purpose of the XML support is to provide a mechanism for reading
and writing simple XML documents.  In the future this support may be
further developed to support a standard interface such as DOM or SAX.

   The XML support is a run-time-loadable option; to use it, execute

     (load-option 'xml)

once before running any code that uses it.

* Menu:

* XML Input::
* XML Output::
* XML Names::
* XML Structure::


File: mit-scheme-ref.info,  Node: XML Input,  Next: XML Output,  Prev: XML Support,  Up: XML Support

14.15.1 XML Input
-----------------

The primary entry point for the XML parser is 'read-xml', which reads
characters from a port and returns an XML document record.  The
character coding of the input is determined by reading some of the input
stream and looking for a byte order mark and/or an encoding in the XML
declaration.  We support all ISO 8859 codings, as well as UTF-8, UTF-16,
and UTF-32.

   When an XHTML document is read, the parser provides entity
definitions for all of the named XHTML characters; for example, it
defines '&nbsp;' and '&copy;'.  In order for a document to be recognized
as XHTML, it must contain an XHTML DTD, such as this:

     <!DOCTYPE html
               PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
               "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

At present the parser recognizes XHTML Strict 1.0 and XHTML 1.1
documents.

 -- procedure: read-xml port [pi-handlers]
     Read an XML document from PORT and return the corresponding XML
     document record.

     PI-HANDLERS, if specified, must be an association list.  Each
     element of PI-HANDLERS must be a list of two elements: a symbol and
     a procedure.  When the parser encounters processing instructions
     with a name that appears in PI-HANDLERS, the procedure is called
     with one argument, which is the text of the processing
     instructions.  The procedure must return a list of XML structure
     records that are legal for the context of the processing
     instructions.

 -- procedure: read-xml-file pathname [pi-handlers]
     This convenience procedure simplifies reading XML from a file.  It
     is roughly equivalent to

          (define (read-xml-file pathname #!optional pi-handlers)
            (call-with-input-file pathname
              (lambda (port)
                (read-xml port pi-handlers))))

 -- procedure: string->xml string [start [end [pi-handlers]]]
     This convenience procedure simplifies reading XML from a string.
     The STRING argument may be a string or a wide string.  It is
     roughly equivalent to

          (define (string->xml string #!optional start end pi-handlers)
            (read-xml (open-input-string string start end)
                      pi-handlers))


File: mit-scheme-ref.info,  Node: XML Output,  Next: XML Names,  Prev: XML Input,  Up: XML Support

14.15.2 XML Output
------------------

The following procedures serialize XML document records into character
sequences.  All are virtually identical except for the way that the
character sequence is represented.

   Each procedure will accept either an 'xml-document' record or any of
the other XML record types.  This makes it possible to write fragments
of XML documents, although you should keep in mind that such fragments
aren't documents and won't generally be accepted by any XML parser.

   If the XML being written is an 'xml-document' record, the procedures
'write-xml' and 'write-xml-file' will look for a contained
'xml-declaration' record and its 'encoding' attribute.  If the
'encoding' is a supported value, the output will be encoded as
specified; otherwise it will be encoded as UTF-8.

   When an XHTML document record is written, named XHTML characters are
translated into their corresponding entities.  For example, the
character '#\U+00A0' is written as '&nbsp;'.  In order for an XML
document record to be recognized as XHTML, it must have a DTD record
that satisfies the predicate 'html-dtd?'.

 -- procedure: write-xml xml port
     Write XML to PORT.  Note that character encoding will only be done
     if PORT supports it.

 -- procedure: write-xml-file xml pathname
     Write XML to the file specified by PATHNAME.  Roughly equivalent to

          (define (write-xml-file xml pathname)
            (call-with-output-file pathname
              (lambda (port)
                (write-xml xml port))))

 -- procedure: xml->wide-string xml
     Convert XML to a wide string.  No character encoding is used, since
     wide strings can represent all characters without encoding.
     Roughly equivalent to

          (define (xml->wide-string xml)
            (call-with-wide-output-string
             (lambda (port)
               (write-xml xml port))))

 -- procedure: xml->string xml
     Convert XML to a character string encoded as UTF-8.  Roughly
     equivalent to

          (define (xml->string xml)
            (wide-string->utf8-string (xml->wide-string xml)))


File: mit-scheme-ref.info,  Node: XML Names,  Next: XML Structure,  Prev: XML Output,  Up: XML Support

14.15.3 XML Names
-----------------

MIT/GNU Scheme implements XML names in a slightly complex way.
Unfortunately, this complexity is a direct consequence of the definition
of XML names rather than a mis-feature of this implementation.

   The reason that XML names are complex is that XML namespace support,
which was added after XML was standardized, is not very well integrated
with the core XML definition.  The most obvious problem is that names
can't have associated namespaces when they appear in the DTD of a
document, even if the body of the document uses them.  Consequently, it
must be possible to compare non-associated names with associated names.

   An XML name consists of two parts: the "qname", which is a symbol,
possibly including a namespace prefix; and the "Uniform Resource
Identifier" (URI), which identifies an optional namespace.

 -- procedure: make-xml-name qname uri
     Creates and returns an XML name.  QNAME must be a symbol whose name
     satisfies 'string-is-xml-name?'.  URI must satisfy either
     'absolute-uri?' or 'null-xml-namespace-uri?'.  The returned value
     is an XML name that satisfies 'xml-name?'.

     If URI is the "null" namespace (satisfies
     'null-xml-namespace-uri?'), the returned value is a symbol
     equivalent to QNAME.  This means that an ordinary symbol can be
     used as an XML name when there is no namespace associated with the
     name.

     For convenience, QNAME may be a string, in which case it is
     converted to a symbol using 'make-xml-qname'.

     For convenience, URI may be any object that '->uri' is able to
     convert to a URI record, provided the resulting URI meets the above
     restrictions.

 -- procedure: xml-name? object
     Returns '#t' if OBJECT is an XML name, and '#f' otherwise.

 -- procedure: xml-name->symbol xml-name
     Returns the symbol part of XML-NAME.

 -- procedure: xml-name-uri xml-name
     Returns the "URI" of XML-NAME.  The result always satisfies
     'absolute-uri?' or 'null-xml-namespace-uri?'.

 -- procedure: xml-name-string xml-name
     Returns the "qname" of XML-NAME as a string.  Equivalent to

          (symbol->string (xml-name->symbol XML-NAME))

   The next two procedures get the "prefix" and "local part" of an XML
name, respectively.  The prefix of an XML name is the part of the qname
to the left of the colon, while the local part is the part of the qname
to the right of the colon.  If there is no colon in the qname, the local
part is the entire qname, and the prefix is the null symbol (i.e. '||').

 -- procedure: xml-name-prefix xml-name
     Returns the "prefix" of XML-NAME as a symbol.

 -- procedure: xml-name-local xml-name
     Returns the "local part" of XML-NAME as a symbol.

   The next procedure compares two XML names for equality.  The rules
for equality are slightly complex, in order to permit comparing names in
the DTD with names in the document body.  So, if both of the names have
non-null namespace URIs, then the names are equal if and only if their
local parts are equal and their URIs are equal.  (The prefixes of the
names are not considered in this case.)  Otherwise, the names are equal
if and only if their qnames are equal.

 -- procedure: xml-name=? xml-name-1 xml-name-2
     Returns '#t' if XML-NAME-1 and XML-NAME-2 are the same name, and
     '#f' otherwise.

   These next procedures define the data abstraction for qnames.  While
qnames are represented as symbols, only symbols whose names satisfy
'string-is-xml-name?' are qnames.

 -- procedure: make-xml-qname string
     STRING must satisfy 'string-is-xml-name?'.  Returns the qname
     corresponding to STRING (the symbol whose name is STRING).

 -- procedure: xml-qname? object
     Returns '#t' if OBJECT is a qname, otherwise returns '#f'.

 -- procedure: xml-qname-prefix qname
     Returns the prefix of QNAME as a symbol.

 -- procedure: xml-qname-local qname
     Returns the local part of QNAME as a symbol.

   The prefix of a qname or XML name may be absent if there is no colon
in the name.  The absent, or null, prefix is abstracted by the next two
procedures.  Note that the null prefix is a symbol, just like non-null
prefixes.

 -- procedure: null-xml-name-prefix
     Returns the null prefix.

 -- procedure: null-xml-name-prefix? object
     Returns '#t' if OBJECT is the null prefix, otherwise returns '#f'.

   The namespace URI of an XML name may be null, meaning that there is
no namespace associated with the name.  This namespace is represented by
a relative URI record whose string representation is the null string.

 -- procedure: null-xml-namespace-uri
     Returns the null namespace URI record.

 -- procedure: null-xml-namespace-uri? object
     Returns '#t' if OBJECT is the null namespace URI record, otherwise
     returns '#f'.

   The following values are two distinguished URI records.

 -- variable: xml-uri
     'xml-uri' is the URI reserved for use by the XML recommendation.
     This URI must be used with the 'xml' prefix.

 -- variable: xmlns-uri
     'xmlns-uri' is the URI reserved for use by the XML namespace
     recommendation.  This URI must be used with the 'xmlns' prefix.

 -- procedure: make-xml-nmtoken string

 -- procedure: xml-nmtoken? object

 -- procedure: string-is-xml-name? string

 -- procedure: string-is-xml-nmtoken? string


File: mit-scheme-ref.info,  Node: XML Structure,  Prev: XML Names,  Up: XML Support

14.15.4 XML Structure
---------------------

The output from the XML parser and the input to the XML output procedure
is a complex data structure composed of a hierarchy of typed components.
Each component is a record whose fields correspond to parts of the XML
structure that the record represents.  There are no special operations
on these records; each is a tuple with named subparts.  The root record
type is 'xml-document', which represents a complete XML document.

   Each record type TYPE has the following associated bindings:

'<TYPE>'
     is a variable bound to the record-type descriptor for TYPE.  The
     record-type descriptor may be used as a specializer in SOS method
     definitions, which greatly simplifies code to dispatch on these
     types.

'TYPE?'
     is a predicate for records of type TYPE.  It accepts one argument,
     which can be any object, and returns '#t' if the object is a record
     of this type, or '#f' otherwise.

'make-TYPE'
     is a constructor for records of type TYPE.  It accepts one argument
     for each field of TYPE, in the same order that they are written in
     the type description, and returns a newly-allocated record of that
     type.

'TYPE-FIELD'
     is an accessor procedure for the field FIELD in records of type
     TYPE.  It accepts one argument, which must be a record of that
     type, and returns the contents of the corresponding field in the
     record.

'set-TYPE-FIELD!'
     is a modifier procedure for the field FIELD in records of type
     TYPE.  It accepts two arguments: the first must be a record of that
     type, and the second is a new value for the corresponding field.
     The record's field is modified to have the new value.

 -- record type: xml-document declaration misc-1 dtd misc-2 root misc-3
     The 'xml-document' record is the top-level record representing a
     complete XML document.  DECLARATION is either an 'xml-declaration'
     object or '#f'.  DTD is either an 'xml-dtd' object or '#f'.  ROOT
     is an 'xml-element' object.  MISC-1, MISC-2, and MISC-3 are lists
     of miscellaneous items; a miscellaneous item is either an
     'xml-comment' object, an 'xml-processing-instructions' object, or a
     string of whitespace.

 -- record type: xml-declaration version encoding standalone
     The 'xml-declaration' record represents the '<?xml ... ?>'
     declaration that optionally appears at the beginning of an XML
     document.  VERSION is a version string, typically '"1.0"'.
     ENCODING is either an encoding string or '#f'.  STANDALONE is
     either '"yes"', '"no"', or '#f'.

 -- record type: xml-element name attributes contents
     The 'xml-element' record represents general XML elements; the bulk
     of a typical XML document consists of these elements.  NAME is the
     element name (an XML name).  ATTRIBUTES is a list of XML attribute
     objects.  CONTENTS is a list of the contents of the element.  Each
     element of this list is either a string, an 'xml-element' record or
     an 'xml-processing-instructions' record.

 -- record type: xml-processing-instructions name text
     The 'xml-processing-instructions' record represents processing
     instructions, which have the form '<?NAME ... ?>'.  These
     instructions are intended to contain non-XML data that will be
     processed by another interpreter; for example they might contain
     PHP programs.  The NAME field is the processor name (a symbol), and
     the TEXT field is the body of the instructions (a string).

 -- record type: xml-dtd root external internal
     The 'xml-dtd' record represents a document type declaration.  The
     ROOT field is an XML name for the root element of the document.
     EXTERNAL is either an 'xml-external-id' record or '#f'.  INTERNAL
     is a list of DTD element records (e.g. 'xml-!element',
     'xml-!attlist', etc.).

   The remaining record types are valid only within a DTD.

 -- record type: xml-!element name content-type
     The 'xml-!element' record represents an element-type declaration.
     NAME is the XML name of the type being declared (a symbol).
     CONTENT-TYPE describes the type and can have several different
     values, as follows:

        * The XML names 'EMPTY' and 'ANY' correspond to the XML keywords
          of the same name.

        * A list '(MIX TYPE ...)' corresponds to the '(#PCDATA | TYPE |
          ...)' syntax.

 -- record type: xml-!attlist name definitions
     The 'xml-!attlist' record represents an attribute-list declaration.
     NAME is the XML name of the type for which attributes are being
     declared (a symbol).  DEFINITIONS is a list of attribute
     definitions, each of which is a list of three elements '(NAME TYPE
     DEFAULT)'.  NAME is an XML name for the name of the attribute (a
     symbol).  TYPE describes the attribute type, and can have one of
     the following values:

        * The XML names 'CDATA', 'IDREFS', 'IDREF', 'ID', 'ENTITY',
          'ENTITIES', 'NMTOKENS', and 'NMTOKEN' correspond to the XML
          keywords of the same names.

        * A list '(NOTATION NAME1 NAME2 ...)' corresponds to the
          'NOTATION (NAME1 | NAME2 ...)' syntax.

        * A list '(ENUMERATED NAME1 NAME2 ...)' corresponds to the
          '(NAME1 | NAME2 ...)' syntax.

     DEFAULT describes the default value for the attribute, and can have
     one of the following values:

        * The XML names '#REQUIRED' and '#IMPLIED' correspond to the XML
          keywords of the same names.

        * A list '(#FIXED VALUE)' corresponds to the '#FIXED "VALUE"'
          syntax.  VALUE is represented as a string.

        * A list '(DEFAULT VALUE)' corresponds to the '"VALUE"' syntax.
          VALUE is represented as a string.

 -- record type: xml-!entity name value
     The 'xml-!entity' record represents a general entity declaration.
     NAME is an XML name for the entity.  VALUE is the entity's value,
     either a string or an 'xml-external-id' record.

 -- record type: xml-parameter-!entity name value
     The 'xml-parameter-!entity' record represents a parameter entity
     declaration.  NAME is an XML name for the entity.  VALUE is the
     entity's value, either a string or an 'xml-external-id' record.

 -- record type: xml-unparsed-!entity name id notation
     The 'xml-unparsed-!entity' record represents an unparsed entity
     declaration.  'Name' is an XML name for the entity.  ID is an
     'xml-external-id' record.  NOTATION is an XML name for the
     notation.

 -- record type: xml-!notation name id
     The 'xml-!notation' record represents a notation declaration.
     'Name' is an XML name for the notation.  ID is an 'xml-external-id'
     record.

 -- record type: xml-external-id id uri
     The 'xml-external-id' record is a reference to an external DTD.
     This reference consists of two parts: ID is a public ID literal,
     corresponding to the 'PUBLIC' keyword, while URI is a system
     literal, corresponding to the 'SYSTEM' keyword.  Either or both may
     be present, depending on the context.  ID is represented as a
     string, while URI is represented as a URI record.


File: mit-scheme-ref.info,  Node: Operating-System Interface,  Next: Error System,  Prev: Input/Output,  Up: Top

15 Operating-System Interface
*****************************

The Scheme standard provides a simple mechanism for reading and writing
files: file ports.  MIT/GNU Scheme provides additional tools for dealing
with other aspects of the operating system:

   * "Pathnames" are a reasonably operating-system independent tool for
     manipulating the component parts of file names.  This can be useful
     for implementing defaulting of file name components.

   * Control over the "current working directory": the place in the file
     system from which relative file names are interpreted.

   * Procedures that rename, copy, delete, and test for the existence of
     files.  Also, procedures that return detailed information about a
     particular file, such as its type (directory, link, etc.)  or
     length.

   * Procedures for reading the contents of a directory.

   * Procedures for obtaining times in various formats, converting
     between the formats, and generating human-readable time strings.

   * Procedures to run other programs as subprocesses of Scheme, to read
     their output, and write input to them.

   * A means to determine the operating system Scheme is running under.

* Menu:

* Pathnames::
* Working Directory::
* File Manipulation::
* Directory Reader::
* Date and Time::
* Machine Time::
* Subprocesses::
* TCP Sockets::
* Miscellaneous OS Facilities::


File: mit-scheme-ref.info,  Node: Pathnames,  Next: Working Directory,  Prev: Operating-System Interface,  Up: Operating-System Interface

15.1 Pathnames
==============

MIT/GNU Scheme programs need to use names to designate files.  The main
difficulty in dealing with names of files is that different file systems
have different naming formats for files.  For example, here is a table
of several file systems (actually, operating systems that provide file
systems) and what equivalent file names might look like for each one:

     System          File Name
     ------          ---------
     TOPS-20         <LISPIO>FORMAT.FASL.13
     TOPS-10         FORMAT.FAS[1,4]
     ITS             LISPIO;FORMAT FASL
     MULTICS         >udd>LispIO>format.fasl
     TENEX           <LISPIO>FORMAT.FASL;13
     VAX/VMS         [LISPIO]FORMAT.FAS;13
     UNIX            /usr/lispio/format.fasl
     DOS             C:\USR\LISPIO\FORMAT.FAS

   It would be impossible for each program that deals with file names to
know about each different file name format that exists; a new operating
system to which Scheme was ported might use a format different from any
of its predecessors.  Therefore, MIT/GNU Scheme provides _two_ ways to
represent file names: "filenames" (also called "namestrings"), which are
strings in the implementation-dependent form customary for the file
system, and "pathnames", which are special abstract data objects that
represent file names in an implementation-independent way.  Procedures
are provided to convert between these two representations, and all
manipulations of files can be expressed in machine-independent terms by
using pathnames.

   In order to allow MIT/GNU Scheme programs to operate in a network
environment that may have more than one kind of file system, the
pathname facility allows a file name to specify which file system is to
be used.  In this context, each file system is called a "host", in
keeping with the usual networking terminology.(1)

   Note that the examples given in this section are specific to unix
pathnames.  Pathnames for other operating systems have different
external representations.

* Menu:

* Filenames and Pathnames::
* Components of Pathnames::
* Operations on Pathnames::
* Miscellaneous Pathnames::

   ---------- Footnotes ----------

   (1) This introduction is adapted from 'Common Lisp, The Language',
second edition, section 23.1.


File: mit-scheme-ref.info,  Node: Filenames and Pathnames,  Next: Components of Pathnames,  Prev: Pathnames,  Up: Pathnames

15.1.1 Filenames and Pathnames
------------------------------

Pathname objects are usually created by parsing filenames (character
strings) into component parts.  MIT/GNU Scheme provides operations that
convert filenames into pathnames and vice versa.

 -- procedure: ->pathname object
     Returns a pathname that is the equivalent of OBJECT.  OBJECT must
     be a pathname or a string.  If OBJECT is a pathname, it is
     returned.  If OBJECT is a string, this procedure returns the
     pathname that corresponds to the string; in this case it is
     equivalent to '(parse-namestring OBJECT #f #f)'.

          (->pathname "foo")          =>  #[pathname 65 "foo"]
          (->pathname "/usr/morris")  =>  #[pathname 66 "/usr/morris"]

 -- procedure: parse-namestring thing [host [defaults]]
     This turns THING into a pathname.  THING must be a pathname or a
     string.  If THING is a pathname, it is returned.  If THING is a
     string, this procedure returns the pathname that corresponds to the
     string, parsed according to the syntax of the file system specified
     by HOST.

     This procedure _does not_ do defaulting of pathname components.

     The optional arguments are used to determine what syntax should be
     used for parsing the string.  In general this is only really useful
     if your implementation of MIT/GNU Scheme supports more than one
     file system, otherwise you would use '->pathname'.  If given, HOST
     must be a host object or '#f', and DEFAULTS must be a pathname.
     HOST specifies the syntax used to parse the string.  If HOST is not
     given or '#f', the host component from DEFAULTS is used instead; if
     DEFAULTS is not given, the host component from
     'param:default-pathname-defaults' is used.

 -- procedure: ->namestring pathname
     '->namestring' returns a newly allocated string that is the
     filename corresponding to PATHNAME.
          (->namestring (->pathname "/usr/morris/minor.van"))
               =>  "/usr/morris/minor.van"

 -- procedure: pathname-simplify pathname
     Returns a pathname that locates the same file or directory as
     PATHNAME, but is in some sense simpler.  Note that
     'pathname-simplify' might not always be able to simplify the
     pathname, e.g. on unix with symbolic links the directory
     '/usr/morris/../' need not be the same as '/usr/'.  In cases of
     uncertainty the behavior is conservative, returning the original or
     a partly simplified pathname.

          (pathname-simplify "/usr/morris/../morris/dance")
               =>  #[pathname "/usr/morris/dance"]


File: mit-scheme-ref.info,  Node: Components of Pathnames,  Next: Operations on Pathnames,  Prev: Filenames and Pathnames,  Up: Pathnames

15.1.2 Components of Pathnames
------------------------------

A pathname object always has six components, described below.  These
components are the common interface that allows programs to work the
same way with different file systems; the mapping of the pathname
components into the concepts peculiar to each file system is taken care
of by the Scheme implementation.

HOST
     The name of the file system on which the file resides.  In the
     current implementation, this component is always a host object that
     is filled in automatically by the runtime system.  When specifying
     the host component, use either '#f' or the value of the variable
     'local-host'.

DEVICE
     Corresponds to the "device" or "file structure" concept in many
     host file systems: the name of a (logical or physical) device
     containing files.  This component is the drive letter for PC file
     systems, and is unused for unix file systems.

DIRECTORY
     Corresponds to the "directory" concept in many host file systems:
     the name of a group of related files (typically those belonging to
     a single user or project).  This component is always used for all
     file systems.

NAME
     The name of a group of files that can be thought of as conceptually
     the "same" file.  This component is always used for all file
     systems.

TYPE
     Corresponds to the "filetype" or "extension" concept in many host
     file systems.  This says what kind of file this is.  Files with the
     same name but different type are usually related in some specific
     way, such as one being a source file, another the compiled form of
     that source, and a third the listing of error messages from the
     compiler.  This component is currently used for all file systems,
     and is formed by taking the characters that follow the last dot in
     the namestring.

VERSION
     Corresponds to the "version number" concept in many host file
     systems.  Typically this is a number that is incremented every time
     the file is modified.  This component is currently unused for all
     file systems.

   Note that a pathname is not necessarily the name of a specific file.
Rather, it is a specification (possibly only a partial specification) of
how to access a file.  A pathname need not correspond to any file that
actually exists, and more than one pathname can refer to the same file.
For example, the pathname with a version of 'newest' may refer to the
same file as a pathname with the same components except a certain number
as the version.  Indeed, a pathname with version 'newest' may refer to
different files as time passes, because the meaning of such a pathname
depends on the state of the file system.  In file systems with such
facilities as "links", multiple file names, logical devices, and so on,
two pathnames that look quite different may turn out to address the same
file.  To access a file given a pathname, one must do a file-system
operation such as 'open-input-file'.

   Two important operations involving pathnames are "parsing" and
"merging".  Parsing is the conversion of a filename (which might be
something supplied interactively by the users when asked to supply the
name of a file) into a pathname object.  This operation is
implementation-dependent, because the format of filenames is
implementation-dependent.  Merging takes a pathname with missing
components and supplies values for those components from a source of
default values.

   Not all of the components of a pathname need to be specified.  If a
component of a pathname is missing, its value is '#f'.  Before the file
system interface can do anything interesting with a file, such as
opening the file, all the missing components of a pathname must be
filled in.  Pathnames with missing components are used internally for
various purposes; in particular, parsing a namestring that does not
specify certain components will result in a pathname with missing
components.

   Any component of a pathname may be the symbol 'unspecific', meaning
that the component simply does not exist, for file systems in which such
a value makes no sense.  For example, unix and Windows file systems
usually do not support version numbers, so the version component for
such a host might be 'unspecific'.(1)

   In addition to '#f' and 'unspecific', the components of a pathname
may take on the following meaningful values:

HOST
     An implementation-defined type which may be tested for using the
     'host?' predicate.

DEVICE
     On systems that support this component (Windows), it may be
     specified as a string containing a single alphabetic character, for
     which the alphabetic case is ignored.

DIRECTORY
     A non-empty list, which represents a "directory path": a sequence
     of directories, each of which has a name in the previous directory,
     the last of which is the directory specified by the entire path.
     Each element in such a path specifies the name of the directory
     relative to the directory specified by the elements to its left.
     The first element of the list is either the symbol 'absolute' or
     the symbol 'relative'.  If the first element in the list is the
     symbol 'absolute', then the directory component (and subsequently
     the pathname) is "absolute"; the first component in the sequence is
     to be found at the "root" of the file system.  If the directory is
     "relative" then the first component is to be found in some as yet
     unspecified directory; typically this is later specified to be the
     "current working directory".

     Aside from 'absolute' and 'relative', which may only appear as the
     first element of the list, each subsequent element in the list is
     either: a string, which is a literal component; the symbol 'wild',
     meaningful only when used in conjunction with the directory reader;
     or the symbol 'up', meaning the next directory is the "parent" of
     the previous one.  'up' corresponds to the file '..' in unix and PC
     file systems.

     (The following note does not refer to any file system currently
     supported by MIT/GNU Scheme, but is included for completeness.)  In
     file systems that do not have "hierarchical" structure, a specified
     directory component will always be a list whose first element is
     'absolute'.  If the system does not support directories other than
     a single global directory, the list will have no other elements.
     If the system supports "flat" directories, i.e. a global set of
     directories with no subdirectories, then the list will contain a
     second element, which is either a string or 'wild'.  In other
     words, a non-hierarchical file system is treated as if it were
     hierarchical, but the hierarchical features are unused.  This
     representation is somewhat inconvenient for such file systems, but
     it discourages programmers from making code depend on the lack of a
     file hierarchy.

NAME
     A string, which is a literal component; or the symbol 'wild',
     meaningful only when used in conjunction with the directory reader.

TYPE
     A string, which is a literal component; or the symbol 'wild',
     meaningful only when used in conjunction with the directory reader.

VERSION
     An exact positive integer, which is a literal component; the symbol
     'newest', which means to choose the largest available version
     number for that file; the symbol 'oldest', which means to choose
     the smallest version number; or the symbol 'wild', meaningful only
     when used in conjunction with the directory reader.  In the future
     some other possible values may be added, e.g. 'installed'.  Note
     that currently no file systems support version numbers; thus this
     component is not used and should be specified as '#f'.

 -- procedure: make-pathname host device directory name type version
     Returns a pathname object whose components are the respective
     arguments.  Each argument must satisfy the restrictions for the
     corresponding component, which were outlined above.

          (make-pathname #f
                         #f
                         '(absolute "usr" "morris")
                         "foo"
                         "scm"
                         #f)
               =>  #[pathname 67 "/usr/morris/foo.scm"]

 -- procedure: pathname-host pathname
 -- procedure: pathname-device pathname
 -- procedure: pathname-directory pathname
 -- procedure: pathname-name pathname
 -- procedure: pathname-type pathname
 -- procedure: pathname-version pathname
     Returns a particular component of PATHNAME.

          (define x (->pathname "/usr/morris/foo.scm"))
          (pathname-host x)       =>  #[host 1]
          (pathname-device x)     =>  unspecific
          (pathname-directory x)  =>  (absolute "usr" "morris")
          (pathname-name x)       =>  "foo"
          (pathname-type x)       =>  "scm"
          (pathname-version x)    =>  unspecific

 -- procedure: pathname-new-device pathname device
 -- procedure: pathname-new-directory pathname directory
 -- procedure: pathname-new-name pathname name
 -- procedure: pathname-new-type pathname type
 -- procedure: pathname-new-version pathname version
     Returns a new copy of PATHNAME with the respective component
     replaced by the second argument.  PATHNAME is unchanged.  Portable
     programs should not explicitly replace a component with
     'unspecific' because this might not be permitted in some
     situations.

          (define p (->pathname "/usr/blisp/rel15"))
          p
               =>  #[pathname 71 "/usr/blisp/rel15"]
          (pathname-new-name p "rel100")
               =>  #[pathname 72 "/usr/blisp/rel100"]
          (pathname-new-directory p '(relative "test" "morris"))
               =>  #[pathname 73 "test/morris/rel15"]
          p
               =>  #[pathname 71 "/usr/blisp/rel15"]

 -- procedure: pathname-default-device pathname device
 -- procedure: pathname-default-directory pathname directory
 -- procedure: pathname-default-name pathname name
 -- procedure: pathname-default-type pathname type
 -- procedure: pathname-default-version pathname version
     These operations are similar to the 'pathname-new-COMPONENT'
     operations, except that they only change the specified COMPONENT if
     it has the value '#f' in PATHNAME.

   ---------- Footnotes ----------

   (1) This description is adapted from 'Common Lisp, The Language',
second edition, section 23.1.1.


File: mit-scheme-ref.info,  Node: Operations on Pathnames,  Next: Miscellaneous Pathnames,  Prev: Components of Pathnames,  Up: Pathnames

15.1.3 Operations on Pathnames
------------------------------

 -- procedure: pathname? object
     Returns '#t' if OBJECT is a pathname; otherwise returns '#f'.

 -- procedure: pathname=? pathname1 pathname2
     Returns '#t' if PATHNAME1 is equivalent to PATHNAME2; otherwise
     returns '#f'.  Pathnames are equivalent if all of their components
     are equivalent, hence two pathnames that are equivalent must
     identify the same file or equivalent partial pathnames.  However,
     the converse is not true: non-equivalent pathnames may specify the
     same file (e.g. via absolute and relative directory components),
     and pathnames that specify no file at all (e.g. name and directory
     components unspecified) may be equivalent.

 -- procedure: pathname-absolute? pathname
     Returns '#t' if PATHNAME is an absolute rather than relative
     pathname object; otherwise returns '#f'.  Specifically, this
     procedure returns '#t' when the directory component of PATHNAME is
     a list starting with the symbol 'absolute', and returns '#f' in all
     other cases.  All pathnames are either absolute or relative, so if
     this procedure returns '#f', the argument is a relative pathname.

 -- procedure: directory-pathname? pathname
     Returns '#t' if PATHNAME has only directory components and no file
     components.  This is roughly equivalent to

          (define (directory-pathname? pathname)
            (string-null? (file-namestring pathname)))

     except that it is faster.

 -- procedure: pathname-wild? pathname
     Returns '#t' if PATHNAME contains any wildcard components;
     otherwise returns '#f'.

 -- procedure: merge-pathnames pathname [defaults [default-version]]
     Returns a pathname whose components are obtained by combining those
     of PATHNAME and DEFAULTS.  DEFAULTS defaults to the value of
     'param:default-pathname-defaults' and DEFAULT-VERSION defaults to
     'newest'.

     The pathnames are combined by components: if PATHNAME has a
     non-missing component, that is the resulting component, otherwise
     the component from DEFAULTS is used.  The default version can be
     '#f' to preserve the information that the component was missing
     from PATHNAME.  The directory component is handled specially: if
     both pathnames have directory components that are lists, and the
     directory component from PATHNAME is relative (i.e. starts with
     'relative'), then the resulting directory component is formed by
     appending PATHNAME's component to DEFAULTS's component.  For
     example:

          (define path1 (->pathname "scheme/foo.scm"))
          (define path2 (->pathname "/usr/morris"))
          path1
               =>  #[pathname 74 "scheme/foo.scm"]
          path2
               =>  #[pathname 75 "/usr/morris"]
          (merge-pathnames path1 path2)
               =>  #[pathname 76 "/usr/scheme/foo.scm"]
          (merge-pathnames path2 path1)
               =>  #[pathname 77 "/usr/morris.scm"]

     The merging rules for the version are more complex and depend on
     whether PATHNAME specifies a name.  If PATHNAME does not specify a
     name, then the version, if not provided, will come from DEFAULTS.
     However, if PATHNAME does specify a name then the version is not
     affected by DEFAULTS.  The reason is that the version "belongs to"
     some other file name and is unlikely to have anything to do with
     the new one.  Finally, if this process leaves the version missing,
     then DEFAULT-VERSION is used.

     The net effect is that if the user supplies just a name, then the
     host, device, directory and type will come from DEFAULTS, but the
     version will come from DEFAULT-VERSION.  If the user supplies
     nothing, or just a directory, the name, type and version will come
     over from DEFAULTS together.

 -- parameter: param:default-pathname-defaults
     The value of this parameter (*note Parameters::) is the default
     pathname-defaults pathname; if any pathname primitive that needs a
     set of defaults is not given one, it uses this one.  Modifying the
     'working-directory-pathname' parameter also changes this parameter
     to the same value, computed by merging the new working directory
     with the parameter's old value.

 -- variable: *default-pathname-defaults*
     This variable is *deprecated*; use
     'param:default-pathname-defaults' instead.

 -- procedure: pathname-default pathname device directory name type
          version
     This procedure defaults all of the components of PATHNAME
     simultaneously.  It could have been defined by:

          (define (pathname-default pathname
                                    device directory name type version)
            (make-pathname (pathname-host pathname)
                           (or (pathname-device pathname) device)
                           (or (pathname-directory pathname) directory)
                           (or (pathname-name pathname) name)
                           (or (pathname-type pathname) type)
                           (or (pathname-version pathname) version)))

 -- procedure: file-namestring pathname
 -- procedure: directory-namestring pathname
 -- procedure: host-namestring pathname
 -- procedure: enough-namestring pathname [defaults]
     These procedures return a string corresponding to a subset of the
     PATHNAME information.  'file-namestring' returns a string
     representing just the NAME, TYPE and VERSION components of
     PATHNAME; the result of 'directory-namestring' represents just the
     HOST, DEVICE, and DIRECTORY components; and 'host-namestring'
     returns a string for just the HOST portion.

     'enough-namestring' takes another argument, DEFAULTS.  It returns
     an abbreviated namestring that is just sufficient to identify the
     file named by PATHNAME when considered relative to the DEFAULTS
     (which defaults to the value of 'param:default-pathname-defaults').

          (file-namestring "/usr/morris/minor.van")
               =>  "minor.van"
          (directory-namestring "/usr/morris/minor.van")
               =>  "/usr/morris/"
          (enough-namestring "/usr/morris/men")
               =>  "men"      ;perhaps

 -- procedure: file-pathname pathname
 -- procedure: directory-pathname pathname
 -- procedure: enough-pathname pathname [defaults]
     These procedures return a pathname corresponding to a subset of the
     PATHNAME information.  'file-pathname' returns a pathname with just
     the NAME, TYPE and VERSION components of PATHNAME.  The result of
     'directory-pathname' is a pathname containing the HOST, DEVICE and
     DIRECTORY components of PATHNAME.

     'enough-pathname' takes another argument, DEFAULTS.  It returns an
     abbreviated pathname that is just sufficient to identify the file
     named by PATHNAME when considered relative to the DEFAULTS (which
     defaults to the value of 'param:default-pathname-defaults').

     These procedures are similar to 'file-namestring',
     'directory-namestring' and 'enough-namestring', but they return
     pathnames instead of strings.

 -- procedure: directory-pathname-as-file pathname
     Returns a pathname that is equivalent to PATHNAME, but in which the
     directory component is represented as a file.  The last directory
     is removed from the directory component and converted into name and
     type components.  This is the inverse operation to
     'pathname-as-directory'.

          (directory-pathname-as-file (->pathname "/usr/blisp/"))
               =>  #[pathname "/usr/blisp"]

 -- procedure: pathname-as-directory pathname
     Returns a pathname that is equivalent to PATHNAME, but in which any
     file components have been converted to a directory component.  If
     PATHNAME does not have name, type, or version components, it is
     returned without modification.  Otherwise, these file components
     are converted into a string, and the string is added to the end of
     the list of directory components.  This is the inverse operation to
     'directory-pathname-as-file'.

          (pathname-as-directory (->pathname "/usr/blisp/rel5"))
               =>  #[pathname "/usr/blisp/rel5/"]


File: mit-scheme-ref.info,  Node: Miscellaneous Pathnames,  Prev: Operations on Pathnames,  Up: Pathnames

15.1.4 Miscellaneous Pathname Procedures
----------------------------------------

This section gives some standard operations on host objects, and some
procedures that return some useful pathnames.

 -- variable: local-host
     This variable has as its value the host object that describes the
     local host's file system.

 -- procedure: host? object
     Returns '#t' if OBJECT is a pathname host; otherwise returns '#f'.

 -- procedure: host=? host1 host2
     Returns '#t' if HOST1 and HOST2 denote the same pathname host;
     otherwise returns '#f'.

 -- procedure: init-file-pathname [host]
     Returns a pathname for the user's initialization file on HOST.  The
     HOST argument defaults to the value of 'local-host'.  If the
     initialization file does not exist this procedure returns '#f'.

     Under unix, the init file is called '.scheme.init'; under Windows,
     the init file is called 'scheme.ini'.  In either case, it is
     located in the user's home directory, which is computed by
     'user-homedir-pathname'.

 -- procedure: user-homedir-pathname [host]
     Returns a pathname for the user's "home directory" on HOST.  The
     HOST argument defaults to the value of 'local-host'.  The concept
     of a "home directory" is itself somewhat implementation-dependent,
     but it should be the place where the user keeps personal files,
     such as initialization files and mail.

     Under unix, the user's home directory is specified by the 'HOME'
     environment variable.  If this variable is undefined, the user name
     is computed using the 'getlogin' system call, or if that fails, the
     'getuid' system call.  The resulting user name is passed to the
     'getpwnam' system call to obtain the home directory.

     Under Windows, several heuristics are tried to find the user's home
     directory.  The user's home directory is computed by examining
     several environment variables, in the following order:

        * 'HOMEDRIVE' and 'HOMEPATH' are both defined and
          '%HOMEDRIVE%%HOMEPATH%' is an existing directory.  (These
          variables are automatically defined by Windows NT.)

        * 'HOME' is defined and '%HOME%' is an existing directory.

        * 'USERDIR' and 'USERNAME' are defined and
          '%USERDIR%\%USERNAME%' is an existing directory.

        * 'USERDIR' and 'USER' are defined and '%USERDIR%\%USER%' is an
          existing directory.

        * 'USERNAME' is defined and '%USERNAME%' is an existing
          directory on the Windows system drive.

        * 'USER' is defined and '%USER%' is an existing directory on the
          Windows system drive.

        * Finally, if all else fails, the Windows system drive is used
          as the home directory.

 -- procedure: system-library-pathname pathname
     Locates PATHNAME in MIT/GNU Scheme's system library directory.  An
     error of type 'condition-type:file-operation-error' is signalled if
     PATHNAME cannot be located on the library search path.

          (system-library-pathname "compiler.com")
            => #[pathname 45 "/usr/local/lib/mit-scheme/compiler.com"]

 -- procedure: system-library-directory-pathname pathname
     Locates the pathname of an MIT/GNU Scheme system library directory.
     An error of type 'condition-type:file-operation-error' is signalled
     if PATHNAME cannot be located on the library search path.

          (system-library-directory-pathname "options")
               => #[pathname 44 "/usr/local/lib/mit-scheme/options/"]


File: mit-scheme-ref.info,  Node: Working Directory,  Next: File Manipulation,  Prev: Pathnames,  Up: Operating-System Interface

15.2 Working Directory
======================

When MIT/GNU Scheme is started, the "current working directory" (or
simply, "working directory") is initialized in an operating-system
dependent manner; usually, it is the directory in which Scheme was
invoked.  The working directory can be determined from within Scheme by
calling the 'pwd' procedure, and changed by calling the 'cd' procedure.
Each REP loop has its own working directory, and inferior REP loops
initialize their working directory from the value in effect in their
superior at the time they are created.

 -- parameter: working-directory-pathname
 -- parameter: pwd
     Returns the current working directory as a pathname that has no
     name, type, or version components, just host, device, and directory
     components.  'pwd' is an alias for 'working-directory-pathname';
     the long name is intended for programs and the short name for
     interactive use.

     This parameter may be called with an argument to set its value, in
     which case it also modifies the value of
     'param:default-pathname-defaults' by merging the new working
     directory into it.

 -- procedure: set-working-directory-pathname! filename
 -- procedure: cd filename
     This procedure is *deprecated*; instead call
     'working-directory-pathname' with an argument.

     Makes FILENAME the current working directory and returns the new
     current working directory as a pathname.  FILENAME is coerced to a
     pathname using 'pathname-as-directory'.  'cd' is an alias for
     'set-working-directory-pathname!'; the long name is intended for
     programs and the short name for interactive use.

     Additionally, 'set-working-directory-pathname!' modifies the value
     of 'param:default-pathname-defaults' by merging the new working
     directory into it.

     When this procedure is executed in the top-level REP loop, it
     changes the working directory of the running Scheme executable.

          (set-working-directory-pathname! "/usr/morris/blisp")
               =>  #[pathname "/usr/morris/blisp/"]
          (set-working-directory-pathname! "~")
               =>  #[pathname "/usr/morris/"]

     This procedure signals an error if FILENAME does not refer to an
     existing directory.

     If FILENAME describes a relative rather than absolute pathname,
     this procedure interprets it as relative to the current working
     directory, before changing the working directory.

          (working-directory-pathname)
               =>  #[pathname "/usr/morris/"]
          (set-working-directory-pathname! "foo")
               =>  #[pathname "/usr/morris/foo/"]

 -- procedure: with-working-directory-pathname filename thunk
     This procedure is *deprecated*; instead bind
     'working-directory-pathname' using 'parameterize'.

     This procedure dynamically binds the current working directory to
     FILENAME and returns the value of THUNK (a procedure of no
     arguments).  FILENAME is coerced to a pathname using
     'pathname-as-directory'.  In addition to binding the working
     directory, 'with-working-directory-pathname' also dynamically binds
     the 'param:default-pathname-defaults' parameter, merging the old
     value with the new working directory pathname.


File: mit-scheme-ref.info,  Node: File Manipulation,  Next: Directory Reader,  Prev: Working Directory,  Up: Operating-System Interface

15.3 File Manipulation
======================

This section describes procedures that manipulate files and directories.
Any of these procedures can signal a number of errors for many reasons.
The specifics of these errors are much too operating-system dependent to
document here.  However, if such an error is signalled by one of these
procedures, it will be of type 'condition-type:file-operation-error'.

 -- procedure: file-exists? filename
 -- procedure: file-exists-direct? filename
 -- procedure: file-exists-indirect? filename
     These procedures return '#t' if FILENAME is an existing file or
     directory; otherwise they return '#f'.  In operating systems that
     support symbolic links, if the file is a symbolic link,
     'file-exists-direct?' tests for the existence of the link, while
     'file-exists-indirect?' and 'file-exists?' test for the existence
     of the file pointed to by the link.

 -- procedure: copy-file source-filename target-filename
     Makes a copy of the file named by SOURCE-FILENAME.  The copy is
     performed by creating a new file called TARGET-FILENAME, and
     filling it with the same data as SOURCE-FILENAME.

 -- procedure: rename-file source-filename target-filename
     Changes the name of SOURCE-FILENAME to be TARGET-FILENAME.  In the
     unix implementation, this will not rename across file systems.

 -- procedure: delete-file filename
     Deletes the file named FILENAME.

 -- procedure: delete-file-no-errors filename
     Like 'delete-file', but returns a boolean value indicating whether
     an error occurred during the deletion.  If no errors occurred, '#t'
     is returned.  If an error of type 'condition-type:file-error' or
     'condition-type:port-error' is signalled, '#f' is returned.

 -- procedure: hard-link-file source-filename target-filename
     Makes a hard link from SOURCE-FILENAME to TARGET-FILENAME.  This
     operation gives the file specified by SOURCE-FILENAME a new name,
     in addition to the old name.

     This currently works only on unix systems.  It is further
     restricted to work only when SOURCE-FILENAME and TARGET-FILENAME
     refer to names in the same file system.

 -- procedure: soft-link-file source-filename target-filename
     Creates a new soft link called TARGET-FILENAME that points at the
     file SOURCE-FILENAME.  (Soft links are also sometimes called
     "symbolic" links.)  Note that SOURCE-FILENAME will be interpreted
     as a string (although you may specify it as a pathname object, if
     you wish).  The contents of this string will be stored in the file
     system as the soft link.  When a file operation attempts to open
     the link, the contents of the link are interpreted relative to the
     link's location at that time.

     This currently works only on unix systems.

 -- procedure: make-directory filename
     Creates a new directory named FILENAME.  Signals an error if
     FILENAME already exists, or if the directory cannot be created.

 -- procedure: delete-directory filename
     Deletes the directory named FILENAME.  Signals an error if the
     directory does not exist, is not a directory, or contains any files
     or subdirectories.

 -- procedure: ->truename filename
     This procedure attempts to discover and return the "true name" of
     the file associated with FILENAME within the file system.  An error
     of type 'condition-type:file-operation-error' is signalled if the
     appropriate file cannot be located within the file system.

 -- procedure: call-with-temporary-file-pathname procedure
     Calls 'temporary-file-pathname' to create a temporary file, then
     calls PROCEDURE with one argument, the pathname referring to that
     file.  When PROCEDURE returns, if the temporary file still exists,
     it is deleted; then, the value yielded by PROCEDURE is returned.
     If PROCEDURE escapes from its continuation, and the file still
     exists, it is deleted.

 -- procedure: temporary-file-pathname [directory]
     Creates a new empty temporary file and returns a pathname referring
     to it.  The temporary file is created with Scheme's default
     permissions, so barring unusual circumstances it can be opened for
     input and/or output without error.  The temporary file will remain
     in existence until explicitly deleted.  If the file still exists
     when the Scheme process terminates, it will be deleted.

     If DIRECTORY is specified, the temporary file will be stored there.
     If it is not specified, or if it is '#f', the temporary file will
     be stored in the directory returned by
     'temporary-directory-pathname'.

 -- procedure: temporary-directory-pathname
     Returns the pathname of an existing directory that can be used to
     store temporary files.  These directory names are tried, in order,
     until a writeable directory is found:

        * The directories specified by the environment variables
          'TMPDIR', 'TEMP', or 'TMP'.

        * Under unix, the directories '/var/tmp', '/usr/tmp', or '/tmp'.

        * Under Windows, the following directories on the system drive:
          '\temp', '\tmp', or '\'.

        * Under Windows, the current directory, as specified by
          'param:default-pathname-defaults'.

 -- procedure: file-directory? filename
     Returns '#t' if the file named FILENAME exists and is a directory.
     Otherwise returns '#f'.  In operating systems that support symbolic
     links, if FILENAME names a symbolic link, this examines the file
     linked to, not the link itself.

     This is equivalent to

          (eq? 'directory (file-type-indirect FILENAME))

 -- procedure: file-regular? filename
     Returns '#t' if the file named FILENAME exists and is a regular
     file (i.e. not a directory, symbolic link, device file, etc.).
     Otherwise returns '#f'.  In operating systems that support symbolic
     links, if FILENAME names a symbolic link, this examines the file
     linked to, not the link itself.

     This is equivalent to

          (eq? 'regular (file-type-indirect FILENAME))

 -- procedure: file-symbolic-link? filename
     In operating systems that support symbolic links, if the file named
     FILENAME exists and is a symbolic link, this procedure returns the
     contents of the symbolic link as a newly allocated string.  The
     returned value is the name of the file that the symbolic link
     points to and must be interpreted relative to the directory of
     FILENAME.  If FILENAME either does not exist or is not a symbolic
     link, or if the operating system does not support symbolic links,
     this procedure returns '#f'.

 -- procedure: file-type-direct filename
 -- procedure: file-type-indirect filename
     If the file named FILENAME exists, 'file-type-direct' returns a
     symbol specifying what type of file it is.  For example, if
     FILENAME refers to a directory, the symbol 'directory' is returned.
     If FILENAME doesn't refer to an existing file, '#f' is returned.

     If FILENAME refers to a symbolic link, 'file-type-direct' returns
     the type of the link itself, while 'file-type-indirect' returns the
     type of the file linked to.

     At this time, the symbols that can be returned are the following.
     The names are intended to be self-explanatory.  Most of these names
     can only be returned on particular operating systems, and so the
     operating-system name is prefixed to the name.

          regular
          directory
          unix-symbolic-link
          unix-character-device
          unix-block-device
          unix-named-pipe
          unix-socket
          win32-named-pipe

 -- procedure: file-readable? filename
     Returns '#t' if FILENAME names a file that can be opened for input;
     i.e. a "readable" file.  Otherwise returns '#f'.

 -- procedure: file-writeable? filename
     Returns '#t' if FILENAME names a file that can be opened for
     output; i.e. a "writeable" file.  Otherwise returns '#f'.

 -- procedure: file-executable? filename
     Returns '#t' if FILENAME names a file that can be executed.
     Otherwise returns '#f'.  Under unix, an executable file is
     identified by its mode bits.  Under Windows, an executable file has
     one of the file extensions '.exe', '.com', or '.bat'.

 -- procedure: file-access filename mode
     MODE must be an exact integer between '0' and '7' inclusive; it is
     a bitwise-encoded predicate selector with '1' meaning "executable",
     '2' meaning "writeable", and '4' meaning "readable".  'file-access'
     returns '#t' if FILENAME exists and satisfies the predicates
     selected by MODE.  For example, if MODE is '5', then FILENAME must
     be both readable and executable.  If FILENAME doesn't exist, or if
     it does not satisfy the selected predicates, '#f' is returned.

 -- procedure: file-eq? filename1 filename2
     Determines whether FILENAME1 and FILENAME2 refer to the same file.
     Under unix, this is done by comparing the inodes and devices of the
     two files.  Under Windows, this is done by comparing the filename
     strings.

 -- procedure: file-modes filename
     If FILENAME names an existing file, 'file-modes' returns an exact
     non-negative integer encoding the file's permissions.  The encoding
     of this integer is operating-system dependent.  Under unix, it is
     the least-significant 12 bits of the 'st_mode' element of the
     'struct stat' structure.  Under Windows, it is the file attribute
     bits, which are described below.  If FILENAME does not name an
     existing file, '#f' is returned.

 -- procedure: set-file-modes! filename modes
     FILENAME must name an existing file.  MODES must be an exact
     non-negative integer that could have been returned by a call to
     'file-modes'.  'set-file-modes!' modifies the file's permissions to
     be those encoded by MODES.

 -- variable: nt-file-mode/read-only
 -- variable: nt-file-mode/hidden
 -- variable: nt-file-mode/system
 -- variable: nt-file-mode/directory
 -- variable: nt-file-mode/archive
 -- variable: nt-file-mode/normal
 -- variable: nt-file-mode/temporary
 -- variable: nt-file-mode/compressed
     The values of these variables are the "mode bits" that comprise the
     value returned by 'file-modes' under Windows.  These bits are small
     integers that are combined by adding to form a complete set of
     modes.  The integer zero represents a set of modes in which none of
     these bits are set.

 -- procedure: file-modification-time filename
     Returns the modification time of FILENAME as an exact non-negative
     integer.  The result may be compared to other file times using
     ordinary integer arithmetic.  If FILENAME names a file that does
     not exist, 'file-modification-time' returns '#f'.

     In operating systems that support symbolic links, if FILENAME names
     a symbolic link, 'file-modification-time' returns the modification
     time of the file linked to.  An alternate procedure,
     'file-modification-time-direct', returns the modification time of
     the link itself; in all other respects it is identical to
     'file-modification-time'.  For symmetry,
     'file-modification-time-indirect' is a synonym of
     'file-modification-time'.

 -- procedure: file-access-time filename
     Returns the access time of FILENAME as an exact non-negative
     integer.  The result may be compared to other file times using
     ordinary integer arithmetic.  If FILENAME names a file that does
     not exist, 'file-access-time' returns '#f'.

     In operating systems that support symbolic links, if FILENAME names
     a symbolic link, 'file-access-time' returns the access time of the
     file linked to.  An alternate procedure, 'file-access-time-direct',
     returns the access time of the link itself; in all other respects
     it is identical to 'file-access-time'.  For symmetry,
     'file-access-time-indirect' is a synonym of 'file-access-time'.

 -- procedure: set-file-times! filename access-time modification-time
     FILENAME must name an existing file, while ACCESS-TIME and
     MODIFICATION-TIME must be valid file times that might have been
     returned by 'file-access-time' and 'file-modification-time',
     respectively.  'set-file-times!' alters the access and modification
     times of the file specified by FILENAME to the values given by
     ACCESS-TIME and MODIFICATION-TIME, respectively.  For convenience,
     either of the time arguments may be specified as '#f'; in this case
     the corresponding time is not changed.  'set-file-times!' returns
     an unspecified value.

 -- procedure: current-file-time
     Returns the current time as an exact non-negative integer, in the
     same format used by the above file-time procedures.  This number
     can be compared to other file times using ordinary arithmetic
     operations.

 -- procedure: file-touch filename
     "Touches" the file named FILENAME.  If the file already exists, its
     modification time is set to the current file time and '#f' is
     returned.  Otherwise, the file is created and '#t' is returned.
     This is an atomic test-and-set operation, so it is useful as a
     synchronization mechanism.

 -- procedure: file-length filename
     Returns the length, in bytes, of the file named FILENAME as an
     exact non-negative integer.

 -- procedure: file-attributes filename
     This procedure determines if the file named FILENAME exists, and
     returns information about it if so; if the file does not exist, it
     returns '#f'.

     In operating systems that support symbolic links, if FILENAME names
     a symbolic link, 'file-attributes' returns the attributes of the
     link itself.  An alternate procedure, 'file-attributes-indirect',
     returns the attributes of the file linked to; in all other respects
     it is identical to 'file-attributes'.  For symmetry,
     'file-attributes-direct' is a synonym of 'file-attributes'.

   The information returned by 'file-attributes' is decoded by accessor
procedures.  The following accessors are defined in all operating
systems:

 -- procedure: file-attributes/type attributes
     The file type: '#t' if the file is a directory, a character string
     (the name linked to) if a symbolic link, or '#f' for all other
     types of file.

 -- procedure: file-attributes/access-time attributes
     The last access time of the file, an exact non-negative integer.

 -- procedure: file-attributes/modification-time attributes
     The last modification time of the file, an exact non-negative
     integer.

 -- procedure: file-attributes/change-time attributes
     The last change time of the file, an exact non-negative integer.

 -- procedure: file-attributes/length attributes
     The length of the file in bytes.

 -- procedure: file-attributes/mode-string attributes
     The mode string of the file, a newly allocated string showing the
     file's mode bits.  Under unix, this string is in unix format.
     Under Windows, this string shows the standard "DOS" attributes in
     their usual format.

 -- procedure: file-attributes/n-links attributes
     The number of links to the file, an exact positive integer.  Under
     Windows, this is always '1'.

   The following additional accessors are defined under unix:

 -- procedure: file-attributes/uid attributes
     The user id of the file's owner, an exact non-negative integer.

 -- procedure: file-attributes/gid attributes
     The group id of the file's group, an exact non-negative integer.

 -- procedure: file-attributes/inode-number attributes
     The inode number of the file, an exact non-negative integer.

   The following additional accessor is defined under Windows:

 -- procedure: file-attributes/modes attributes
     The attribute bits of the file.  This is an exact non-negative
     integer containing the file's attribute bits, exactly as specified
     by the operating system's API.


File: mit-scheme-ref.info,  Node: Directory Reader,  Next: Date and Time,  Prev: File Manipulation,  Up: Operating-System Interface

15.4 Directory Reader
=====================

 -- procedure: directory-read directory [sort?]
     DIRECTORY must be an object that can be converted into a pathname
     by
     '->pathname'.  The directory specified by DIRECTORY is read, and
     the contents of the directory is returned as a newly allocated list
     of absolute pathnames.  The result is sorted according to the usual
     sorting conventions for directories, unless SORT? is specified as
     '#f'.  If DIRECTORY has name, type, or version components, the
     returned list contains only those pathnames whose name, type, and
     version components match those of DIRECTORY; 'wild' or '#f' as one
     of these components means "match anything".

     The Windows implementation supports "globbing", in which the
     characters '*' and '?' are interpreted to mean "match anything" and
     "match any character", respectively.  This "globbing" is supported
     only in the file part of DIRECTORY.


File: mit-scheme-ref.info,  Node: Date and Time,  Next: Machine Time,  Prev: Directory Reader,  Up: Operating-System Interface

15.5 Date and Time
==================

MIT/GNU Scheme provides a simple set of procedures for manipulating date
and time information.  There are four time representations, each of
which serves a different purpose.  Each representation may be converted
to any of the others.

   The primary time representation, "universal time", is an exact
non-negative integer counting the number of seconds that have elapsed
since midnight January 1, 1900 UTC. (UTC stands for "Coordinated
Universal Time", and is the modern name for Greenwich Mean Time.)  This
format is produced by 'get-universal-time' and
'decoded-time->universal-time'.

   The second representation, "decoded time", is a record structure in
which the time is broken down into components, such as month, minute,
etc.  Decoded time is always relative to a particular time zone, which
is a component of the structure.  This format is produced by
'global-decoded-time' and 'local-decoded-time'.

   The third representation, "file time", is an exact non-negative
integer that is larger for increasing time.  Unlike universal time, this
representation is operating-system dependent.  This format is produced
by all of the file-attribute procedures, for example
'file-modification-time' and 'file-attributes'.

   The fourth representation, the "time string", is an external
representation for time.  This format is defined by RFC-822, 'Standard
for the format of ARPA Internet text messages', with the modification
that years are represented as four-digit numbers rather than two-digit
numbers.  This format is the standard format for Internet email and
numerous other network protocols.

   Within this section, argument variables named UNIVERSAL-TIME,
DECODED-TIME, FILE-TIME, and TIME-STRING are respectively required to be
of the corresponding format.

* Menu:

* Universal Time::
* Decoded Time::
* File Time::
* Time-Format Conversion::
* External Representation of Time::


File: mit-scheme-ref.info,  Node: Universal Time,  Next: Decoded Time,  Prev: Date and Time,  Up: Date and Time

15.5.1 Universal Time
---------------------

 -- procedure: get-universal-time
     Return the current time in universal format.

          (get-universal-time) => 3131453078

 -- variable: epoch
     'epoch' is the representation of midnight January 1, 1970 UTC in
     universal-time format.

          epoch => 2208988800


File: mit-scheme-ref.info,  Node: Decoded Time,  Next: File Time,  Prev: Universal Time,  Up: Date and Time

15.5.2 Decoded Time
-------------------

Objects representing standard time components, such as seconds and
minutes, are required to be exact non-negative integers.  Seconds and
minutes must be inclusively between '0' and '59'; hours between '0' and
'23'; days between '1' and '31'; months between '1' and '12'; years are
represented in "four-digit" form, in which 1999 is represented as '1999'
-- _not_ '99'.

 -- procedure: local-decoded-time
     Return the current time in decoded format.  The decoded time is
     represented in the local time zone.

          (pp (local-decoded-time))
          -| #[decoded-time 76]
          -| (second 2)
          -| (minute 12)
          -| (hour 11)
          -| (day 27)
          -| (month 4)
          -| (year 1999)
          -| (day-of-week 1)
          -| (daylight-savings-time 1)
          -| (zone 5)

 -- procedure: global-decoded-time
     Return the current time in decoded format.  The decoded time is
     represented in UTC.

          (pp (global-decoded-time))
          -| #[decoded-time 77]
          -| (second 8)
          -| (minute 12)
          -| (hour 15)
          -| (day 27)
          -| (month 4)
          -| (year 1999)
          -| (day-of-week 1)
          -| (daylight-savings-time 0)
          -| (zone 0)

 -- procedure: make-decoded-time second minute hour day month year
          [zone]
     Return a new decoded-time object representing the given time.  The
     arguments must be valid components according to the above rules,
     and must form a valid date.

     If ZONE is not supplied or is '#f', the resulting decoded time will
     be represented in the local time zone.  Otherwise, ZONE must be a
     valid time zone, and the result will be represented in that zone.

     *Warning*: because this procedure depends on the operating system's
     runtime library, it is not capable of representing all dates.  In
     particular, on most unix systems, it is not possible to encode
     dates that occur prior to midnight, January 1, 1970 UTC. Attempting
     to do this will signal an error.

          (pp (make-decoded-time 0 9 11 26 3 1999))
          -| #[decoded-time 19]
          -| (second 0)
          -| (minute 9)
          -| (hour 11)
          -| (day 26)
          -| (month 3)
          -| (year 1999)
          -| (day-of-week 4)
          -| (daylight-savings-time 0)
          -| (zone 5)

          (pp (make-decoded-time 0 9 11 26 3 1999 3))
          -| #[decoded-time 80]
          -| (second 0)
          -| (minute 9)
          -| (hour 11)
          -| (day 26)
          -| (month 3)
          -| (year 1999)
          -| (day-of-week 4)
          -| (daylight-savings-time 0)
          -| (zone 3)

 -- procedure: decoded-time/second decoded-time
 -- procedure: decoded-time/minute decoded-time
 -- procedure: decoded-time/hour decoded-time
 -- procedure: decoded-time/day decoded-time
 -- procedure: decoded-time/month decoded-time
 -- procedure: decoded-time/year decoded-time
     Return the corresponding component of DECODED-TIME.

          (decoded-time/second (local-decoded-time)) => 17
          (decoded-time/year (local-decoded-time)) => 1999
          (decoded-time/day (local-decoded-time)) => 26

 -- procedure: decoded-time/day-of-week decoded-time
     Return the day of the week on which DECODED-TIME falls, encoded as
     an exact integer between '0' (Monday) and '6' (Sunday), inclusive.

          (decoded-time/day-of-week (local-decoded-time)) => 4

 -- procedure: decoded-time/daylight-savings-time? decoded-time
     Return '#t' if DECODED-TIME is represented using daylight savings
     time.  Otherwise return '#f'.

          (decoded-time/daylight-savings-time? (local-decoded-time))
                            => #f

 -- procedure: decoded-time/zone decoded-time
     Return the time zone in which DECODED-TIME is represented.  This is
     an exact rational number between '-24' and '+24' inclusive, that
     when multiplied by '3600' is an integer.  The value is the number
     of hours west of UTC.

          (decoded-time/zone (local-decoded-time)) => 5

 -- procedure: time-zone? object
     Returns '#t' if OBJECT is an exact number between '-24' and '+24'
     inclusive, that when multiplied by '3600' is an integer.

          (time-zone? -5)   => #t
          (time-zone? 11/2) => #t
          (time-zone? 11/7) => #f

 -- procedure: month/max-days month
     Returns the maximum number of days possible in MONTH.  MONTH must
     be an exact integer between '1' and '12' inclusive.

          (month/max-days 2) => 29
          (month/max-days 3) => 31
          (month/max-days 4) => 30


File: mit-scheme-ref.info,  Node: File Time,  Next: Time-Format Conversion,  Prev: Decoded Time,  Up: Date and Time

15.5.3 File Time
----------------

As stated above, file time is operating-system dependent.  As of this
writing, two formats are used.  For unix and Windows systems, file time
is the number of seconds since midnight January 1, 1970 UTC (the
standard unix time convention).

   The following procedures generate their results in file-time format:

     file-access-time
     file-access-time-direct
     file-access-time-indirect
     file-modification-time
     file-modification-time-direct
     file-modification-time-indirect
     file-attributes/access-time
     file-attributes/modification-time
     file-attributes/change-time

Additionally, 'set-file-times!' accepts its time arguments in file-time
format.


File: mit-scheme-ref.info,  Node: Time-Format Conversion,  Next: External Representation of Time,  Prev: File Time,  Up: Date and Time

15.5.4 Time-Format Conversion
-----------------------------

The procedures described in this section convert times from one format
to another.

 -- procedure: universal-time->local-decoded-time universal-time
 -- procedure: universal-time->global-decoded-time universal-time
     Converts an argument in universal-time format to decoded-time
     format.  The result is in the local time zone or UTC, respectively.

          (pp (universal-time->local-decoded-time (get-universal-time)))
          -| #[decoded-time 21]
          -| (second 23)
          -| (minute 57)
          -| (hour 17)
          -| (day 29)
          -| (month 4)
          -| (year 1999)
          -| (day-of-week 3)
          -| (daylight-savings-time 1)
          -| (zone 5)

          (pp (universal-time->global-decoded-time
               (get-universal-time)))
          -| #[decoded-time 22]
          -| (second 27)
          -| (minute 57)
          -| (hour 21)
          -| (day 29)
          -| (month 4)
          -| (year 1999)
          -| (day-of-week 3)
          -| (daylight-savings-time 0)
          -| (zone 0)

 -- procedure: universal-time->file-time universal-time
     Converts an argument in universal-time format to file-time format.

          (universal-time->file-time (get-universal-time))
              => 925422988

 -- procedure: universal-time->local-time-string universal-time
 -- procedure: universal-time->global-time-string universal-time
     Converts an argument in universal-time format to a time string.
     The result is in the local time zone or UTC, respectively.

          (universal-time->local-time-string (get-universal-time))
              => "Thu, 29 Apr 1999 17:55:31 -0400"
          (universal-time->global-time-string (get-universal-time))
              => "Thu, 29 Apr 1999 21:55:51 +0000"

 -- procedure: decoded-time->universal-time decoded-time
     Converts an argument in decoded-time format to universal-time
     format.

          (decoded-time->universal-time (local-decoded-time))
              => 3134411942
          (decoded-time->universal-time (global-decoded-time))
              => 3134411947

 -- procedure: decoded-time->file-time decoded-time
     Converts an argument in decoded-time format to file-time format.

          (decoded-time->file-time (local-decoded-time))
              => 925423191
          (decoded-time->file-time (global-decoded-time))
              => 925423195

 -- procedure: decoded-time->string decoded-time
     Convert an argument in decoded-time format to a time string.

          (decoded-time->string (local-decoded-time))
              => "Thu, 29 Apr 1999 18:00:43 -0400"
          (decoded-time->string (global-decoded-time))
              => "Thu, 29 Apr 1999 22:00:46 +0000"

 -- procedure: file-time->universal-time file-time
     Converts an argument in universal-time format to file-time format.

          (file-time->universal-time (file-modification-time "/"))
              => 3133891907

 -- procedure: file-time->local-decoded-time file-time
 -- procedure: file-time->global-decoded-time file-time
     Converts an argument in file-time format to decoded-time format.
     The result is in the local time zone or UTC, respectively.

          (pp (file-time->local-decoded-time
               (file-modification-time "/")))
          -| #[decoded-time 26]
          -| (second 47)
          -| (minute 31)
          -| (hour 17)
          -| (day 23)
          -| (month 4)
          -| (year 1999)
          -| (day-of-week 4)
          -| (daylight-savings-time 1)
          -| (zone 5)

          (pp (file-time->global-decoded-time
               (file-modification-time "/")))
          -| #[decoded-time 27]
          -| (second 47)
          -| (minute 31)
          -| (hour 21)
          -| (day 23)
          -| (month 4)
          -| (year 1999)
          -| (day-of-week 4)
          -| (daylight-savings-time 0)
          -| (zone 0)

 -- procedure: file-time->local-time-string file-time
 -- procedure: file-time->global-time-string file-time
     Converts an argument in file-time format to a time string.  The
     result is in the local time zone or UTC, respectively.

          (file-time->local-time-string (file-modification-time "/"))
              => "Fri, 23 Apr 1999 17:31:47 -0400"
          (file-time->global-time-string (file-modification-time "/"))
              => "Fri, 23 Apr 1999 21:31:47 +0000"

 -- procedure: string->universal-time time-string
     Converts a time-string argument to universal-time format.

          (string->universal-time "Fri, 23 Apr 1999 21:31:47 +0000")
              => 3133888307
          (string->universal-time "Fri, 23 Apr 1999 17:31:47 -0400")
              => 3133888307

 -- procedure: string->decoded-time time-string
     Converts a time-string argument to decoded-time format.

          (pp (string->decoded-time "Fri, 23 Apr 1999 17:31:47 -0400"))
          -| #[decoded-time 30]
          -| (second 47)
          -| (minute 31)
          -| (hour 17)
          -| (day 23)
          -| (month 4)
          -| (year 1999)
          -| (day-of-week 4)
          -| (daylight-savings-time 0)
          -| (zone 4)

 -- procedure: string->file-time time-string
     Converts a time-string argument to file-time format.

          (string->file-time "Fri, 23 Apr 1999 17:31:47 -0400")
              => 924899507


File: mit-scheme-ref.info,  Node: External Representation of Time,  Prev: Time-Format Conversion,  Up: Date and Time

15.5.5 External Representation of Time
--------------------------------------

The normal external representation for time is the time string, as
described above.  The procedures in this section generate alternate
external representations of time which are more verbose and may be more
suitable for presentation to human readers.

 -- procedure: decoded-time/date-string decoded-time
 -- procedure: decoded-time/time-string decoded-time
     These procedures return strings containing external representations
     of the date and time, respectively, represented by DECODED-TIME.
     The results are implicitly in local time.

          (decoded-time/date-string (local-decoded-time))
              => "Tuesday March 30, 1999"
          (decoded-time/time-string (local-decoded-time))
              => "11:22:38 AM"

 -- procedure: day-of-week/long-string day-of-week
 -- procedure: day-of-week/short-string day-of-week
     Returns a string representing the given DAY-OF-WEEK.  The argument
     must be an exact non-negative integer between '0' and '6'
     inclusive.  'day-of-week/long-string' returns a long string that
     fully spells out the name of the day.  'day-of-week/short-string'
     returns a shortened string that abbreviates the day to three
     letters.

          (day-of-week/long-string 0)  => "Monday"
          (day-of-week/short-string 0) => "Mon"
          (day-of-week/short-string 3) => "Thu"

 -- procedure: month/long-string month
 -- procedure: month/short-string month
     Returns a string representing the given MONTH.  The argument must
     be an exact non-negative integer between '1' and '12' inclusive.
     'month/long-string' returns a long string that fully spells out the
     name of the month.  'month/short-string' returns a shortened string
     that abbreviates the month to three letters.

          (month/long-string 1)   => "January"
          (month/short-string 1)  => "Jan"
          (month/short-string 10) => "Oct"

 -- procedure: time-zone->string
     Returns a string corresponding to the given time zone.  This string
     is the same string that is used to generate RFC-822 time strings.

          (time-zone->string 5)    => "-0500"
          (time-zone->string -4)   => "+0400"
          (time-zone->string 11/2) => "-0530"


File: mit-scheme-ref.info,  Node: Machine Time,  Next: Subprocesses,  Prev: Date and Time,  Up: Operating-System Interface

15.6 Machine Time
=================

The previous section dealt with procedures that manipulate clock time.
This section describes procedures that deal with computer time: elapsed
CPU time, elapsed real time, and so forth.  These procedures are useful
for measuring the amount of time it takes to execute code.

   Some of the procedures in this section manipulate a time
representation called "ticks".  A tick is a unit of time that is
unspecified here but can be converted to and from seconds by supplied
procedures.  A count in ticks is represented as an exact integer.  At
present each tick is one millisecond, but this may change in the future.

 -- procedure: process-time-clock
     Returns the amount of process time, in ticks, that has elapsed
     since Scheme was started.  Process time is measured by the
     operating system and is time during which the Scheme process is
     computing.  It does not include time in system calls, but depending
     on the operating system it may include time used by subprocesses.

          (process-time-clock) => 21290

 -- procedure: real-time-clock
     Returns the amount of real time, in ticks, that has elapsed since
     Scheme was started.  Real time is the time measured by an ordinary
     clock.

          (real-time-clock) => 33474836

 -- procedure: internal-time/ticks->seconds ticks
     Returns the number of seconds corresponding to TICKS.  The result
     is always a real number.

          (internal-time/ticks->seconds 21290) => 21.29
          (internal-time/ticks->seconds 33474836) => 33474.836

 -- procedure: internal-time/seconds->ticks seconds
     Returns the number of ticks corresponding to SECONDS.  SECONDS must
     be a real number.

          (internal-time/seconds->ticks 20.88) => 20880
          (internal-time/seconds->ticks 20.83) => 20830

 -- procedure: system-clock
     Returns the amount of process time, in seconds, that has elapsed
     since Scheme was started.  Roughly equivalent to:

          (internal-time/ticks->seconds (process-time-clock))

     Example:

          (system-clock) => 20.88

 -- procedure: runtime
     Returns the amount of process time, in seconds, that has elapsed
     since Scheme was started.  However, it does not include time spent
     in garbage collection.

          (runtime) => 20.83

 -- procedure: with-timings thunk receiver
     Calls THUNK with no arguments.  After THUNK returns, RECEIVER is
     called with three arguments describing the time spent while
     computing THUNK: the elapsed run time, the amount of time spent in
     the garbage collector, and the elapsed real time.  All three times
     are in ticks.

     This procedure is most useful for doing performance measurements,
     and is designed to have relatively low overhead.

          (with-timings
           (lambda () ... hairy computation ...)
           (lambda (run-time gc-time real-time)
             (write (internal-time/ticks->seconds run-time))
             (write-char #\space)
             (write (internal-time/ticks->seconds gc-time))
             (write-char #\space)
             (write (internal-time/ticks->seconds real-time))
             (newline)))

 -- procedure: measure-interval runtime? procedure
     Calls PROCEDURE, passing it the current process time, in seconds,
     as an argument.  The result of this call must be another procedure.
     When PROCEDURE returns, the resulting procedure is tail-recursively
     called with the ending time, in seconds, as an argument.

     If RUNTIME? is '#f', the elapsed time is deducted from the elapsed
     system time returned by 'runtime'.

     While this procedure can be used for time measurement, its
     interface is somewhat clumsy for that purpose.  We recommend that
     you use 'with-timings' instead, because it is more convenient and
     has lower overhead.

          (measure-interval #t
                            (lambda (start-time)
                              (let ((v ... hairy computation ...))
                                (lambda (end-time)
                                  (write (- end-time start-time))
                                  (newline)
                                  v))))


File: mit-scheme-ref.info,  Node: Subprocesses,  Next: TCP Sockets,  Prev: Machine Time,  Up: Operating-System Interface

15.7 Subprocesses
=================

MIT/GNU Scheme provides the ability to run and control subprocesses.
This support is divided into two parts: a low-level set of primitives
that maps onto the underlying operating system's process-control
primitives, and a high-level set of procedures for starting a subprocess
and running it to completion in a single call.  Subprocesses that are
run in the latter fashion are referred to as "synchronous", because they
are started and stopped in synchrony with a Scheme procedure call.

   This chapter documents Scheme's high-level synchronous-subprocess
support.  The low-level support is not documented but is available for
those who are willing to read the source code.

   Synchronous-subprocess support is a run-time-loadable option.  To use
it, execute

     (load-option 'synchronous-subprocess)

once before calling it.

* Menu:

* Subprocess Procedures::
* Subprocess Conditions::
* Subprocess Options::


File: mit-scheme-ref.info,  Node: Subprocess Procedures,  Next: Subprocess Conditions,  Prev: Subprocesses,  Up: Subprocesses

15.7.1 Subprocess Procedures
----------------------------

There are two commands for running synchronous subprocesses under
Scheme.  'run-shell-command' is very simple to use, provides access to
all shell features, and is to be preferred in most situations.
'run-synchronous-subprocess' allows direct execution of a program and
precise control of the command-line arguments passed to the program, but
does not provide file globbing, I/O redirection, or other shell
features.

 -- procedure: run-shell-command command option ...
     Runs COMMAND, which must be a string.  COMMAND is passed to a
     command shell for interpretation; how the shell is chosen is
     detailed below.

     The OPTIONs are a sequence of keyword/value pairs that specify
     optional behavior.  *Note Subprocess Options::.

     'run-shell-command' waits until the subprocess completes its
     execution and returns the exit code from the subprocess.  If the
     subprocess is killed or stopped, an error is signalled and the
     procedure does not return.

 -- procedure: run-synchronous-subprocess program arguments option ...
     Runs PROGRAM, passing it the given command-line ARGUMENTS.  PROGRAM
     must be either the name of a program on the path, or else a
     pathname to a specific program.  ARGUMENTS must be a list of
     strings; each string is a single command-line argument to the
     program.

     The OPTIONs are a sequence of keyword/value pairs that specify
     optional behavior.  *Note Subprocess Options::.

     'run-synchronous-subprocess' waits until the subprocess completes
     its execution and returns the exit code from the subprocess.  If
     the subprocess is killed or stopped, an error is signalled and the
     procedure does not return.


File: mit-scheme-ref.info,  Node: Subprocess Conditions,  Next: Subprocess Options,  Prev: Subprocess Procedures,  Up: Subprocesses

15.7.2 Subprocess Conditions
----------------------------

If a subprocess spawned by one of the above procedures is killed or
suspended, then one of the following errors will be signalled.

 -- condition type: condition-type:subprocess-signalled subprocess
          reason
     This condition type is a subtype of
     'condition-type:subprocess-abnormal-termination'.  It is signalled
     when the subprocess is killed.

     SUBPROCESS is an object that represents the subprocess involved.
     The internals of this object can be accessed but the interface is
     not documented at this time; see the source code for details.

     REASON is interesting only on unix systems, where it is the signal
     that killed the process.  On other systems it has a fixed value
     that conveys no useful information.

 -- condition type: condition-type:subprocess-stopped subprocess reason
     This condition type is a subtype of
     'condition-type:subprocess-abnormal-termination'.  It is signalled
     when the subprocess is stopped or suspended.

     SUBPROCESS is an object that represents the subprocess involved.
     The internals of this object can be accessed but the interface is
     not documented at this time; see the source code for details.

     REASON is interesting only on unix systems, where it is the signal
     that stopped the process.  On other systems it has a fixed value
     that conveys no useful information.

 -- condition type: condition-type:subprocess-abnormal-termination
          subprocess reason
     This condition type is a subtype of 'condition-type:error'.  This
     is an abstract type that is never signalled.  It is provided so
     that condition handlers can be bound to it.


File: mit-scheme-ref.info,  Node: Subprocess Options,  Prev: Subprocess Conditions,  Up: Subprocesses

15.7.3 Subprocess Options
-------------------------

The following subprocess options may be passed to 'run-shell-command' or
'run-synchronous-subprocess'.  These options are passed as alternating
keyword/value pairs, for example:

     (run-shell-command "ls /"
                        'output my-output-port
                        'output-buffer-size 8192)

The example shows a shell command being run with two options specified:
'output' and 'output-buffer-size'.

 -- subprocess option: input port
     Specifies the standard input of the subprocess.  PORT may be an
     input port, in which case characters are read from PORT and fed to
     the subprocess until PORT reaches end-of-file.  Alternatively, PORT
     may be '#f', indicating that the subprocess has no standard input.

     The default value of this option is '#f'.

          (call-with-input-file "foo.in"
            (lambda (port)
              (run-shell-command "cat > /dev/null" 'input port)))

 -- subprocess option: input-line-translation line-ending
     Specifies how line-endings should be translated when writing
     characters to the subprocess.  Ignored if the 'input' option is
     '#f'.  LINE-ENDING must be either a string specifying the line
     ending, or the symbol 'default', meaning to use the operating
     system's standard line ending.  In either case, newline characters
     to be written to the 'input' port are translated to the specified
     line ending before being written.

     The default value of this option is 'default'.

          (call-with-input-file "foo.in"
            (lambda (port)
              (run-shell-command "cat > /dev/null"
                                 'input port
                                 'input-line-translation "\r\n")))

 -- subprocess option: input-buffer-size n
     Specifies the size of the input buffer for the standard input of
     the subprocess.  (This is the buffer on the Scheme side, and has
     nothing to do with any buffering done on the subprocess side.)
     Ignored if the 'input' option is '#f'.  N must be an exact positive
     integer specifying the number of characters the buffer can hold.

     The default value of this option is '512'.

          (call-with-input-file "foo.in"
            (lambda (port)
              (run-shell-command "cat > /dev/null"
                                 'input port
                                 'input-buffer-size 4096)))

 -- subprocess option: output port
     Specifies the standard output and standard error of the subprocess.
     PORT may be an output port, in which case characters are read from
     the subprocess and fed to PORT until the subprocess finishes.
     Alternatively, PORT may be '#f', indicating that the subprocess has
     no standard output or standard error.

     The default value of this option is the value of
     '(current-output-port)'.

          (call-with-output-file "foo.out"
            (lambda (port)
              (run-shell-command "ls -la /etc" 'output port)))

 -- subprocess option: output-line-translation line-ending
     Specifies how line-endings should be translated when reading
     characters from the standard output of the subprocess.  Ignored if
     the 'output' option is '#f'.  LINE-ENDING must be either a string
     specifying the line ending, or the symbol 'default', meaning to use
     the operating system's standard line ending.  In either case,
     newline characters read from the subprocess port are translated to
     the specified line ending.

     The default value of this option is 'default'.

          (call-with-output-file "foo.out"
            (lambda (port)
              (run-shell-command "ls -la /etc"
                                 'output port
                                 'output-line-translation "\r\n")))

 -- subprocess option: output-buffer-size n
     Specifies the size of the output buffer for the standard output of
     the subprocess.  (This is the buffer on the Scheme side, and has
     nothing to do with any buffering done on the subprocess side.)
     Ignored if the 'output' option is '#f'.  N must be an exact
     positive integer specifying the number of characters the buffer can
     hold.

     The default value of this option is '512'.

          (call-with-output-file "foo.out"
            (lambda (port)
              (run-shell-command "ls -la /etc"
                                 'output port
                                 'output-buffer-size 4096)))

 -- subprocess option: redisplay-hook thunk
     Specifies that THUNK is to be run periodically when output from the
     subprocess is available.  THUNK must be a procedure of no
     arguments, or '#f' indicating that no hook is supplied.  This
     option is mostly useful for interactive systems.  For example, the
     Edwin text editor uses this to update output buffers when running
     some subprocesses.

     The default value of this option is '#f'.

          (run-shell-command "ls -la /etc"
                             'redisplay-hook
                             (lambda ()
                               (update-buffer-contents buffer)))

 -- subprocess option: environment environment
     Specifies the environment variables that are to be used for the
     subprocess.  ENVIRONMENT must be either a vector of strings or '#f'
     indicating the default environment.  If it is a vector of strings,
     each string must be a name/value pair where the name and value are
     separated by an equal sign, for example, '"foo=bar"'.  To define a
     variable with no value, just omit the value, as in '"foo="'.

     Note that the variable 'scheme-subprocess-environment' is bound to
     the default subprocess environment.

     The default value of this option is '#f'.

          (run-shell-command "ls -la /etc"
                             'environment
                             (let* ((v scheme-subprocess-environment)
                                    (n (vector-length v))
                                    (v (vector-grow v (+ n 1))))
                               (vector-set! v n "TERM=none")
                               v))

 -- subprocess option: working-directory pathname
     Specifies the working directory in which the subprocess will run.

     The default value of this option is '(working-directory-pathname)'.

          (run-shell-command "ls -la" 'working-directory "/etc/")

 -- subprocess option: use-pty? boolean
     This option is meaningful only on unix systems; on other systems it
     is ignored.  Specifies whether to communicate with the subprocess
     using PTY devices; if true, PTYs will be used, otherwise pipes will
     be used.

     The default value of this option is '#f'.

          (run-shell-command "ls -la /etc" 'use-pty? #t)

 -- subprocess option: shell-file-name pathname
     Specifies the shell program to use for 'run-shell-command'.

     The default value of this option is '(os/shell-file-name)'.  This
     is the value of the environment variable 'SHELL', or if 'SHELL' is
     not set, the value is operating-system dependent as follows:

        * On unix systems, '/bin/sh' is used.

        * On Windows systems, the value of the environment variable
          'COMSPEC' is used.  If that is not set, 'cmd.exe' is used for
          Windows NT, or 'command.com' is used for Windows 9x; in each
          case the shell is found by searching the path.

          (run-shell-command "ls -la /etc"
                             'shell-file-name "/usr/local/bin/bash")


File: mit-scheme-ref.info,  Node: TCP Sockets,  Next: Miscellaneous OS Facilities,  Prev: Subprocesses,  Up: Operating-System Interface

15.8 TCP Sockets
================

MIT/GNU Scheme provides access to "sockets", which are a mechanism for
inter-process communication.  TCP stream sockets are supported, which
communicate between computers over a TCP/IP network.  TCP sockets are
supported on all operating systems.

   TCP sockets have two distinct interfaces: one interface to implement
a "client" and another to implement a "server".  The basic protocol is
that servers set up a listening port and wait for connections from
clients.  Implementation of clients is simpler and will be treated
first.

   The socket procedures accept two special arguments, called HOST-NAME
and SERVICE.  HOST-NAME is a string which must be the name of an
internet host.  It is looked up using the ordinary lookup rules for your
computer.  For example, if your host is 'foo.mit.edu' and HOST-NAME is
'"bar"', then it specifies 'bar.mit.edu'.

   SERVICE specifies the service to which you will connect.  A networked
computer normally provides several different services, such as telnet or
FTP.  Each service is associated with a unique "port number"; for
example, the '"www"' service is associated with port '80'.  The SERVICE
argument specifies the port number, either as a string, or directly as
an exact non-negative integer.  Port strings are decoded by the
operating system using a table; for example, on unix the table is in
'/etc/services'.  Usually you will use a port string rather than a
number.

 -- procedure: open-tcp-stream-socket host-name service
     'open-tcp-stream-socket' opens a connection to the host specified
     by HOST-NAME.  HOST-NAME is looked up using the ordinary lookup
     rules for your computer.  The connection is established to the
     service specified by SERVICE.  The returned value is an I/O port,
     to which you can read and write characters using ordinary Scheme
     I/O procedures such as 'read-char' and 'write-char'.

     When you wish to close the connection, just use 'close-port'.

     As an example, here is how you can open a connection to a web
     server:

          (open-tcp-stream-socket "web.mit.edu" "www")

   Next we will treat setting up a TCP server, which is slightly more
complicated.  Creating a server is a two-part process.  First, you must
open a "server socket", which causes the operating system to listen to
the network on a port that you specify.  Once the server socket is
opened, the operating system will allow clients to connect to your
computer on that port.

   In the second step of the process, you "accept" the connection, which
completes the connection initiated by the client, and allows you to
communicate with the client.  Accepting a connection does not affect the
server socket; it continues to listen for additional client connections.
You can have multiple client connections to the same server socket open
simultaneously.

 -- procedure: open-tcp-server-socket service [address]
     This procedure opens a server socket that listens for connections
     to SERVICE; the socket will continue to listen until you close it.
     The returned value is a server socket object.

     An error is signalled if another process is already listening on
     the service.  Additionally, ports whose number is less than '1024'
     are privileged on many operating systems, and cannot be used by
     non-privileged processes; if SERVICE specifies such a port and you
     do not have administrative privileges, an error may be signalled.

     The optional argument ADDRESS specifies the IP address on which the
     socket will listen.  If this argument is not supplied or is given
     as '#f', then the socket listens on all IP addresses for this
     machine.  (This is equivalent to passing the result of calling
     'host-address-any'.)

 -- procedure: tcp-server-connection-accept server-socket block?
          peer-address [line-translation]
     Checks to see if a client has connected to SERVER-SOCKET.  If so,
     an I/O port is returned.  The returned port can be read and written
     using ordinary Scheme I/O procedures such as 'read-char' and
     'write-char'.

     The argument BLOCK? says what to do if no client has connected at
     the time of the call.  If '#f', it says to return immediately with
     two values of '#f'.  Otherwise, the call waits until a client
     connects.

     The argument PEER-ADDRESS is either '#f' or an IP address as
     allocated by 'allocate-host-address'.  If it is an IP address, the
     address is modified to be the address of the client making the
     connection.

     The optional argument LINE-TRANSLATION specifies how end-of-line
     characters will be translated when reading or writing to the
     returned socket.  If this is unspecified or '#f', then lines will
     be terminated by CR-LF, which is the standard for most internet
     protocols.  Otherwise, it must be a string, which specifies the
     line-ending character sequence to use.

     Note that closing the port returned by this procedure does not
     affect SERVER-SOCKET; it just closes the particular client
     connection that was opened by the call.  To close SERVER-SOCKET,
     use 'close-tcp-server-socket'.

 -- procedure: close-tcp-server-socket server-socket
     Closes the server socket SERVER-SOCKET.  The operating system will
     cease listening for network connections to that service.  Client
     connections to SERVER-SOCKET that have already been accepted will
     not be affected.


File: mit-scheme-ref.info,  Node: Miscellaneous OS Facilities,  Prev: TCP Sockets,  Up: Operating-System Interface

15.9 Miscellaneous OS Facilities
================================

This section contains assorted operating-system facilities that don't
fit into other categories.

 -- variable: microcode-id/operating-system
 -- obsolete variable: microcode-id/operating-system-name
     'microcode-id/operating-system' is bound to a symbol that specifies
     the type of operating system that Scheme is running under.  There
     are two possible values: 'unix' or 'nt'.

     The *deprecated* variable 'microcode-id/operating-system-name' is a
     string that's equivalent to 'microcode-id/operating-system'.

 -- variable: microcode-id/operating-system-variant
     This variable is a string that identifies the particular variant of
     the operating system that Scheme is running under.  Here are some
     of the possible values:

          "GNU/Linux"
          "MacOSX"
          "Microsoft Windows NT 4.0 (Build 1381; Service Pack 3)"

     For Windows systems, it is recommended that you match on the prefix
     of this string and ignore the '"Build"' suffix.  This is because
     the suffix may contain information about service packs or fixes,
     while the prefix will be constant for a particular version of
     Windows.

   The next few procedures provide access to the "domain name service"
(DNS), which maintains associations between internet host names such as
'"www.swiss.ai.mit.edu"' and IP addresses, such as '18.23.0.16'.  In
MIT/GNU Scheme, we represent an internet host name as a string, and an
IP address as a byte vector of length 4 (byte vectors are just character
strings that are accessed using 'vector-8b-ref' rather than
'string-ref').  The bytes in an IP address read in the same order as
they do when written out:

     (get-host-by-name "www.swiss") => #("\022\027\000\020")

 -- procedure: get-host-by-name host-name
     Looks up the internet host name HOST-NAME using the DNS, returning
     a vector of IP addresses for the corresponding host, or '#f' if
     there is no such host.  Usually the returned vector has only one
     element, but if a host has more than one network interface, the
     vector might have more than one element.

          (get-host-by-name "www.swiss") => #("\022\027\000\020")

 -- procedure: get-host-by-address ip-address
     Does a reverse DNS lookup on IP-ADDRESS, returning the internet
     host name corresponding to that address, or '#f' if there is no
     such host.

          (get-host-by-address "\022\027\000\020") => "swissnet.ai.mit.edu"

 -- procedure: canonical-host-name host-name
     Finds the "canonical" internet host name for HOST-NAME.  For
     example:

          (canonical-host-name "zurich")    => "zurich.ai.mit.edu"
          (canonical-host-name "www.swiss") => "swissnet.ai.mit.edu"

     In both examples, the default internet domain 'ai.mit.edu' is added
     to HOST-NAME.  In the second example, '"www.swiss"' is an alias for
     another computer named '"swissnet"'.

 -- procedure: get-host-name
     Returns the string that identifies the computer that MIT/GNU Scheme
     is running on.  Usually this is an unqualified internet host name,
     i.e. the host name without the domain suffix:

          (get-host-name) => "aarau"

 -- procedure: os/hostname
     Returns the canonical internet host name of the computer that
     MIT/GNU Scheme is running on.  So, in contrast to the example for
     'get-host-name':

          (os/hostname) => "aarau.ai.mit.edu"

 -- procedure: allocate-host-address
     Allocates and returns an IP address object.  This is just a string
     of a fixed length (current 4 bytes) into which an IP address may be
     stored.  This procedure is used to generate an appropriate argument
     to be passed to 'tcp-server-connection-accept'.

          (allocate-host-address) => "Xe\034\241"

 -- procedure: host-address-any
     Return an IP address object that specifies "any host".  This object
     is useful only when passed as the ADDRESS argument to
     'open-tcp-server-socket'.

          (host-address-any) => "\000\000\000\000"

 -- procedure: host-address-loopback
     Return an IP address object that specifies the local "loopback"
     network interface.  The loopback interface is a software network
     interface that can be used only for communicating between processes
     on the same computer.  This address object is useful only when
     passed as the ADDRESS argument to 'open-tcp-server-socket'.

          (host-address-loopback) => "\177\000\000\001"


File: mit-scheme-ref.info,  Node: Error System,  Next: Graphics,  Prev: Operating-System Interface,  Up: Top

16 Error System
***************

The MIT/GNU Scheme error system provides a uniform mechanism for the
signalling of errors and other exceptional conditions.  The simplest and
most generally useful procedures in the error system are:

'error'
     is used to signal simple errors, specifying a message and some
     irritant objects (*note Condition Signalling::).  Errors are
     usually handled by stopping the computation and putting the user in
     an error REPL.

'warn'
     is used to signal warnings (*note Condition Signalling::).
     Warnings are usually handled by printing a message on the console
     and continuing the computation normally.

'ignore-errors'
     is used to suppress the normal handling of errors within a given
     dynamic extent (*note Condition Handling::).  Any error that occurs
     within the extent is trapped, returning immediately to the caller
     of 'ignore-errors'.

   More demanding applications require more powerful facilities.  To
give a concrete example, suppose you want floating-point division to
return a very large number whenever the denominator is zero.  This
behavior can be implemented using the error system.

   The Scheme arithmetic system can signal many different kinds of
errors, including floating-point divide by zero.  In our example, we
would like to handle this particular condition specially, allowing the
system to handle other arithmetic errors in its usual way.

   The error system supports this kind of application by providing
mechanisms for distinguishing different types of error conditions and
for specifying where control should be transferred should a given
condition arise.  In this example, there is a specific object that
represents the "floating-point divide by zero" condition type, and it is
possible to dynamically specify an arbitrary Scheme procedure to be
executed when a condition of that type is signalled.  This procedure
then finds the stack frame containing the call to the division operator,
and returns the appropriate value from that frame.

   Another useful kind of behavior is the ability to specify uniform
handling for related classes of conditions.  For example, it might be
desirable, when opening a file for input, to gracefully handle a variety
of different conditions associated with the file system.  One such
condition might be that the file does not exist, in which case the
program will try some other action, perhaps opening a different file
instead.  Another related condition is that the file exists, but is read
protected, so it cannot be opened for input.  If these or any other
related conditions occur, the program would like to skip this operation
and move on to something else.

   At the same time, errors unrelated to the file system should be
treated in their usual way.  For example, calling 'car' on the argument
'3' should signal an error.  Or perhaps the name given for the file is
syntactically incorrect, a condition that probably wants to be handled
differently from the case of the file not existing.

   To facilitate the handling of classes of conditions, the error system
taxonomically organizes all condition types.  The types are related to
one another by "taxonomical links", which specify that one type is a
"kind of" another type.  If two types are linked this way, one is
considered to be a "specialization" of the other; or vice-versa, the
second is a "generalization" of the first.  In our example, all of the
errors associated with opening an input file would be specializations of
the condition type "cannot open input file".

   The taxonomy of condition types permits any condition type to have no
more than one immediate generalization.  Thus, the condition types form
a forest (set of trees).  While users can create new trees, the standard
taxonomy (*note Taxonomy::) is rooted at
'condition-type:serious-condition', 'condition-type:warning',
'condition-type:simple-condition', and 'condition-type:breakpoint';
users are encouraged to add new subtypes to these condition types rather
than create new trees in the forest.

   To summarize, the error system provides facilities for the following
tasks.  The sections that follow will describe these facilities in more
detail.

Signalling a condition
     A condition may be signalled in a number of different ways.  Simple
     errors may be signalled, without explicitly defining a condition
     type, using 'error'.  The 'signal-condition' procedure provides the
     most general signalling mechanism.

Handling a condition
     The programmer can dynamically specify handlers for particular
     condition types or for classes of condition types, by means of the
     'bind-condition-handler' procedure.  Individual handlers have
     complete control over the handling of a condition, and additionally
     may decide not to handle a particular condition, passing it on to
     previously bound handlers.

Restarting from a handler
     The 'with-restart' procedure provides a means for
     condition-signalling code to communicate to condition-handling code
     what must be done to proceed past the condition.  Handlers can
     examine the restarts in effect when a condition was signalled,
     allowing a structured way to continue an interrupted computation.

Packaging condition state
     Each condition is represented by an explicit object.  Condition
     objects contain information about the nature of the condition,
     information that describes the state of the computation from which
     the condition arose, and information about the ways the computation
     can be restarted.

Classification of conditions
     Each condition has a type, represented by a condition type object.
     Each condition type may be a specialization of some other condition
     types.  A group of types that share a common generalization can be
     handled uniformly by specifying a handler for the generalization.

* Menu:

* Condition Signalling::
* Error Messages::
* Condition Handling::
* Restarts::
* Condition Instances::
* Condition Types::
* Taxonomy::


File: mit-scheme-ref.info,  Node: Condition Signalling,  Next: Error Messages,  Prev: Error System,  Up: Error System

16.1 Condition Signalling
=========================

Once a condition instance has been created using 'make-condition' (or
any condition constructor), it can be "signalled".  The act of
signalling a condition is separated from the act of creating the
condition to allow more flexibility in how conditions are handled.  For
example, a condition instance could be returned as the value of a
procedure, indicating that something unusual has happened, to allow the
caller to clean up some state.  The caller could then signal the
condition once it is ready.

   A more important reason for having a separate condition-signalling
mechanism is that it allows _resignalling_.  When a signalled condition
has been caught by a particular handler, and the handler decides that it
doesn't want to process that particular condition, it can signal the
condition again.  This is one way to allow other handlers to get a
chance to see the condition.

 -- procedure: error reason argument ...
     This is the simplest and most common way to signal a condition that
     requires intervention before a computation can proceed (when
     intervention is not required, 'warn' is more appropriate).  'error'
     signals a condition (using 'signal-condition'), and if no handler
     for that condition alters the flow of control (by invoking a
     restart, for example) it calls the procedure
     'standard-error-handler', which normally prints an error message
     and stops the computation, entering an error REPL.  Under normal
     circumstances 'error' will not return a value (although an
     interactive debugger can be used to force this to occur).

     Precisely what condition is signalled depends on the first argument
     to 'error'.  If REASON is a condition, then that condition is
     signalled and the ARGUMENTs are ignored.  If REASON is a condition
     type, then a new instance of this type is generated and signalled;
     the ARGUMENTs are used to generate the values of the fields for
     this condition type (they are passed as the FIELD-PLIST argument to
     'make-condition').  In the most common case, however, REASON is
     neither a condition nor a condition type, but rather a string or
     symbol.  In this case a condition of type
     'condition-type:simple-error' is created with the MESSAGE field
     containing the REASON and the IRRITANTS field containing the
     ARGUMENTs.

 -- procedure: warn reason argument ...
     When a condition is not severe enough to warrant intervention, it
     is appropriate to signal the condition with 'warn' rather than
     'error'.  As with 'error', 'warn' first calls 'signal-condition';
     the condition that is signalled is chosen exactly as in 'error'
     except that a condition of type 'condition-type:simple-warning' is
     signalled if REASON is neither a condition nor a condition type.
     If the condition is not handled, 'warn' calls the procedure
     'standard-warning-handler', which normally prints a warning message
     and continues the computation by returning from 'warn'.

     'warn' establishes a restart named 'muffle-warning' before calling
     'signal-condition'.  This allows a signal handler to prevent the
     generation of the warning message by calling 'muffle-warning'.  The
     value of a call to 'warn' is unspecified.

 -- procedure: signal-condition condition
     This is the fundamental operation for signalling a condition.  The
     precise operation of 'signal-condition' depends on the condition
     type of which CONDITION is an instance, the condition types set by
     'break-on-signals', and the handlers established by
     'bind-condition-handler' and 'bind-default-condition-handler'.

     If the CONDITION is an instance of a type that is a specialization
     of any of the types specified by 'break-on-signals', then a
     breakpoint REPL is initiated.  Otherwise (or when that REPL
     returns), the handlers established by 'bind-condition-handler' are
     checked, most recent first.  Each applicable handler is invoked,
     and the search for a handler continues if the handler returns
     normally.  If all applicable handlers return, then the applicable
     handlers established by 'bind-default-condition-handler' are
     checked, again most recent first.  Finally, if no handlers apply
     (or all return in a normal manner), 'signal-condition' returns an
     unspecified value.

     _Note:_ unlike many other systems, the MIT/GNU Scheme runtime
     library does _not_ establish handlers of any kind.  (However, the
     Edwin text editor uses condition handlers extensively.)  Thus,
     calls to 'signal-condition' will return to the caller unless there
     are user supplied condition handlers, as the following example
     shows:

          (signal-condition
           (make-condition
            condition-type:error
            (call-with-current-continuation (lambda (x) x))
            '()    ; no restarts
            '()))  ; no fields
          =>  unspecified


File: mit-scheme-ref.info,  Node: Error Messages,  Next: Condition Handling,  Prev: Condition Signalling,  Up: Error System

16.2 Error Messages
===================

By convention, error messages (and in general, the reports generated by
'write-condition-report') should consist of one or more complete
sentences.  The usual rules for sentences should be followed: the first
word of the sentence should be capitalized, and the sentence should be
terminated by a period.  The message should not contain extraneous
whitespace such as line breaks or indentation.

   The error system provides a simple formatting language that allows
the programmer to have some control over the printing of error messages.
This formatting language will probably be redesigned in a future
release.

   Error messages typically consist of a string describing the error,
followed by some irritant objects.  The string is printed using
'display', and the irritants are printed using 'write', typically with a
space between each irritant.  To allow simple formatting, we introduce a
"noise" object, printed using 'display'.  The irritant list may contain
ordinary objects interspersed with noise objects.  Each noise object is
printed using 'display', with no extra whitespace, while each normal
object is printed using 'write', prefixed by a single space character.

   Here is an example:

     (define (error-within-procedure message irritant procedure)
       (error message
              irritant
              (error-irritant/noise "within procedure")
              procedure
              (error-irritant/noise ".")))

This would format as follows:

     (error-within-procedure "Bad widget" 'widget-32 'invert-widget) error->

     Bad widget widget-32 within procedure invert-widget.

   Here are the operations supporting error messages:

 -- procedure: format-error-message message irritants port
     MESSAGE is typically a string (although this is not required),
     IRRITANTS a list of irritant objects, and PORT an output port.
     Formats MESSAGE and IRRITANTS to PORT in the standard way.  Note
     that, during the formatting process, the depth and breadth to which
     lists are printed are each limited to small numbers, to guarantee
     that the output from each irritant is not arbitrarily large.

 -- procedure: error-irritant/noise value
     Creates and returns a noise object whose value is VALUE.


File: mit-scheme-ref.info,  Node: Condition Handling,  Next: Restarts,  Prev: Error Messages,  Up: Error System

16.3 Condition Handling
=======================

The occurrence of a condition is signalled using 'signal-condition'.
'signal-condition' attempts to locate and invoke a "condition handler"
that is prepared to deal with the type of condition that has occurred.
A condition handler is a procedure of one parameter, the condition that
is being signalled.  A procedure is installed as a condition handler by
calling 'bind-condition-handler' (to establish a handler that is in
effect only while a particular thunk is executing) or
'bind-default-condition-handler' (to establish a handler that is in
effect permanently).  As implied by the name, handlers created by
'bind-default-condition-handler' are invoked only after all other
applicable handlers have been invoked.

   A HANDLER may process a signal in any way it deems appropriate, but
the common patterns are:

Ignore the condition.
     By returning from the handler in the usual manner.

Handle the condition.
     By doing some processing and then invoking a restart (or, less
     preferably, a continuation) that was established at some point
     prior to the call to 'signal-condition'.

Resignal a condition.
     By doing some processing and calling 'signal-condition' with either
     the same condition or a newly created one.  In order to support
     this, 'signal-condition' runs HANDLER in such a way that a
     subsequent call to 'signal-condition' sees only the handlers that
     were established prior to this one.

   As an aid to debugging condition handlers, Scheme maintains a set of
condition types that will cause an interactive breakpoint to occur prior
to normal condition signalling.  That is, 'signal-condition' creates a
new REPL prior to its normal operation when its argument is a condition
that is a specialization of any of these types.  The procedure
'break-on-signals' establishes this set of condition types.

 -- procedure: ignore-errors thunk
     Executes THUNK with a condition handler that intercepts the
     signalling of any specialization of 'condition-type:error'
     (including those produced by calls to 'error') and immediately
     terminates the execution of THUNK and returns from the call to
     'ignore-errors' with the signalled condition as its value.  If
     THUNK returns normally, its value is returned from 'ignore-errors'.

     Notice that 'ignore-errors' does not "turn off signalling" or
     condition handling.  Condition handling takes place in the normal
     manner but conditions specialized from 'condition-type:error' are
     trapped rather than propogated as they would be by default.

 -- procedure: bind-condition-handler condition-types handler thunk
     Invokes THUNK after adding HANDLER as a condition handler for the
     conditions specified by CONDITION-TYPES.  CONDITION-TYPES must be a
     list of condition types; signalling a condition whose type is a
     specialization of any of these types will cause the HANDLER to be
     invoked.  See 'signal-condition' for a description of the mechanism
     used to invoke handlers.

     By special extension, if CONDITION-TYPES is the empty list then the
     HANDLER is called for all conditions.

 -- procedure: bind-default-condition-handler condition-types handler
     Installs HANDLER as a (permanent) condition handler for the
     conditions specified by CONDITION-TYPES.  CONDITION-TYPES must be a
     list of condition types; signalling a condition whose type is a
     specialization of any of these types will cause the HANDLER to be
     invoked.  See 'signal-condition' for a description of the mechanism
     used to invoke handlers.

     By special extension, if CONDITION-TYPES is the empty list then the
     HANDLER is called for all conditions.

 -- procedure: break-on-signals condition-types
     Arranges for 'signal-condition' to create an interactive REPL
     before it signals a condition that is a specialization of any of
     the types in the list of CONDITION-TYPES.  This can be extremely
     helpful when trying to debug code that uses custom condition
     handlers.  In order to create a REPL when _any_ condition type is
     signalled it is best to actually put a breakpoint on entry to
     'signal-condition'.

 -- procedure: standard-error-handler condition
     Called internally by 'error' after it calls 'signal-condition'.
     Normally creates a new REPL with the prompt '"error>"' (but see
     'standard-error-hook').  In order to simulate the effect of calling
     'error', code may call 'signal-condition' directly and then call
     'standard-error-handler' if 'signal-condition' returns.

 -- parameter: standard-error-hook
     This parameter controls the behavior of the procedure
     'standard-error-handler', and hence 'error'.  It is intended to be
     bound with 'parameterize' and is normally '#f'.  It may be changed
     to a procedure of one argument and will then be invoked (with
     'standard-error-hook' rebound to '#f') by 'standard-error-handler'
     just prior to starting the error REPL.  It is passed one argument,
     the condition being signalled.

 -- procedure: standard-warning-handler condition
     This is the procedure called internally by 'warn' after it calls
     'signal-condition'.  The normal behavior of
     'standard-warning-handler' is to print a message (but see
     'standard-warning-hook').  More precisely, the message is printed
     to the port returned by 'notification-output-port'.  The message is
     formed by first printing the string '"Warning: "' to this port, and
     then calling 'write-condition-report' on CONDITION and the port.

     In order to simulate the effect of calling 'warn', code may call
     'signal-condition' directly and then call
     'standard-warning-handler' if 'signal-condition' returns.  (This is
     not sufficient to implement the 'muffle-warning' protocol, however.
     For that purpose an explicit restart must be provided.)

 -- parameter: standard-warning-hook
     This parameter controls the behavior of the procedure
     'standard-warning-handler', and hence 'warn'.  It is intended to be
     bound with 'parameterize' and is normally '#f'.  It may be changed
     to a procedure of one argument and will then be invoked (with
     'standard-warning-hook' rebound to '#f') by
     'standard-warning-handler' in lieu of writing the warning message.
     It is passed one argument, the condition being signalled.


File: mit-scheme-ref.info,  Node: Restarts,  Next: Condition Instances,  Prev: Condition Handling,  Up: Error System

16.4 Restarts
=============

The Scheme error system provides a mechanism, known as "restarts", that
helps coordinate condition-signalling code with condition-handling code.
A module of code that detects and signals conditions can provide
procedures (using 'with-simple-restart' or 'with-restart') to be invoked
by handlers that wish to continue, abort, or restart the computation.
These procedures, called "restart effectors", are encapsulated in
restart objects.

   When a condition object is created, it contains a set of restart
objects, each of which contains a restart effector.  Condition handlers
can inspect the condition they are handling (using 'find-restart' to
find restarts by name, or 'condition/restarts' to see the entire set),
and they can invoke the associated effectors (using 'invoke-restart' or
'invoke-restart-interactively').  Effectors can take arguments, and
these may be computed directly by the condition-handling code or by
gathering them interactively from the user.

   The names of restarts can be chosen arbitrarily, but the choice of
name is significant.  These names are used to coordinate between the
signalling code (which supplies names for restarts) and the handling
code (which typically chooses a restart effector by the name of its
restart).  Thus, the names specify the "restart protocol" implemented by
the signalling code and invoked by the handling code.  The protocol
indicates the number of arguments required by the effector code as well
as the semantics of the arguments.

   Scheme provides a conventional set of names (hence, protocols) for
common use.  By choosing the names of restarts from this set, signalling
code can indicate that it is able to perform a small set of fairly
common actions ('abort', 'continue', 'muffle-warning', 'retry',
'store-value', 'use-value').  In turn, simple condition-handling code
can look for the kind of action it wishes to perform and simply invoke
it by name.  All of Scheme's conventional names are symbols, although in
general restart names are not restricted to any particular data type.
In addition, the object '#f' is reserved to indicate the "not for
automated use" protocol: these restarts should be activated only under
human control.

   Restarts themselves are first-class objects.  They encapsulate their
name, a procedure (known as the EFFECTOR) to be executed if they are
invoked, and a thunk (known as the REPORTER) that can be invoked to
display a description of the restart (used, for example, by the
interactive debugger).  Invoking a restart is an indication that a
handler has chosen to accept control for a condition; as a consequence,
the EFFECTOR of the restart should not return, since this would indicate
that the handler declined to handle the condition.  Thus, the EFFECTOR
should call a continuation captured before the condition-signalling
process began.  The most common pattern of usage by signalling code is
encapsulated in 'with-simple-restart'.

   Within this chapter, a parameter named RESTARTS will accept any of
the following values:

   * A list of restart objects.

   * A condition.  The procedure 'condition/restarts' is called on the
     condition, and the resulting list of restarts is used in place of
     the condition.

   * The symbol 'bound-restarts'.  The procedure 'bound-restarts' is
     called (with no arguments), and the resulting list of restarts is
     used in place of the symbol.

   * If the RESTARTS parameter is optional and is not supplied, it is
     equivalent to having specified the symbol 'bound-restarts'.

* Menu:

* Establishing Restart Code::
* Invoking Standard Restart Code::
* Finding and Invoking General Restart Code::
* The Named Restart Abstraction::


File: mit-scheme-ref.info,  Node: Establishing Restart Code,  Next: Invoking Standard Restart Code,  Prev: Restarts,  Up: Restarts

16.4.1 Establishing Restart Code
--------------------------------

 -- procedure: with-simple-restart name reporter thunk
     Invokes THUNK in a dynamic environment created by adding a restart
     named NAME to the existing named restarts.  REPORTER may be used
     during the execution of THUNK to produce a description of the newly
     created restart; it must either be a procedure of one argument (a
     port) or a string.  By convention, the description generated by
     REPORTER should be a short complete sentence, with first word
     capitalized and terminated by a period.  The sentence should fit on
     one line with a little room to spare (see the examples below);
     usually this means that the sentence should be 70 characters or
     less in length.

     If the restart created by 'with-simple-restart' is invoked it
     simply aborts the computation in progress by returning an
     unspecified value from the call to 'with-simple-restart'.
     Otherwise 'with-simple-restart' returns the value computed by
     THUNK.

     (with-simple-restart 'george "This restart is named george."
       (lambda () 3)) => 3

     (with-simple-restart 'george "This restart is named george."
       (lambda ()
         (invoke-restart (find-restart 'george)))) => unspecific

     (with-simple-restart 'george "This restart is named george."
       (lambda () (car 3)))
     ;The object 3, passed as the first argument to car,
     ; is not the correct type.
     ;To continue, call RESTART with an option number:
     ; (RESTART 3) => Specify an argument to use in its place.
     ; (RESTART 2) => This restart is named george.
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- procedure: with-restart name reporter effector interactor thunk
     Invokes THUNK in a dynamic environment created by adding a restart
     named NAME to the existing named restarts.  REPORTER may be used
     during the execution of THUNK to produce a description of the newly
     created restart; it must either be a procedure of one argument (a
     port) or a string.  EFFECTOR is a procedure which will be called
     when the restart is invoked by 'invoke-restart'.  INTERACTOR
     specifies the arguments that are to be passed to EFFECTOR when it
     is invoked interactively; it may be either a procedure of no
     arguments, or '#f'.  If INTERACTOR is '#f', this restart is not
     meant to be invoked interactively.

     The value returned by 'with-restart' is the value returned by
     THUNK.  Should the restart be invoked by a condition handler,
     however, the EFFECTOR will not return back to the handler that
     invoked it.  Instead, the EFFECTOR should call a continuation
     created before the condition-signalling process began, and
     'with-restart' will therefore not return in the normal manner.

     (define (by-george! thunk)
       ; This code handles conditions that arise while executing THUNK
       ; by invoking the GEORGE restart, passing 1 and 2 to the restart's
       ; EFFECTOR code.
       (bind-condition-handler '() ; All conditions
        (lambda (condition)
          (invoke-restart (find-restart 'george) 1 2))
        thunk))

     (define (can-george! thunk)
       ; This code provides a way of handling errors: the GEORGE restart.
       ; In order to GEORGE you must supply two values.
       (lambda ()
         (call-with-current-continuation
          (lambda (kappa)
            (with-restart
             'george                         ; Name
             "This restart is named george." ; Reporter
             (lambda (a b)                   ; Effector
               (kappa (list 'george a b)))
             values                          ; Interactor
             thunk)))))                      ; Thunk

     (by-george! (can-george! (lambda () -3))        => -3
     (by-george! (can-george! (lambda () (car 'x)))) => (george 1 2)


File: mit-scheme-ref.info,  Node: Invoking Standard Restart Code,  Next: Finding and Invoking General Restart Code,  Prev: Establishing Restart Code,  Up: Restarts

16.4.2 Invoking Standard Restart Code
-------------------------------------

Scheme supports six standard protocols for restarting from a condition,
each encapsulated using a named restart (for use by condition-signalling
code) and a simple procedure (for use by condition-handling code).
Unless otherwise specified, if one of these procedures is unable to find
its corresponding restart, it returns immediately with an unspecified
value.

   Each of these procedures accepts an optional argument RESTARTS, which
is described above in *note Restarts::.

 -- procedure: abort [restarts]
     Abort the computation, using the restart named 'abort'.  The
     corresponding effector takes no arguments and abandons the current
     line of computation.  This is the restart provided by Scheme's
     REPL.

     If there is no restart named 'abort', this procedure signals an
     error of type 'condition-type:no-such-restart'.

 -- procedure: continue [restarts]
     Continue the current computation, using the restart named
     'continue'.  The corresponding effector takes no arguments and
     continues the computation beyond the point at which the condition
     was signalled.

 -- procedure: muffle-warning [restarts]
     Continue the current computation, using the restart named
     'muffle-warning'.  The corresponding effector takes no arguments
     and continues the computation beyond the point at which any warning
     message resulting from the condition would be presented to the
     user.  The procedure 'warn' establishes a 'muffle-warning' restart
     for this purpose.

     If there is no restart named 'muffle-warning', this procedure
     signals an error of type 'condition-type:no-such-restart'.

 -- procedure: retry [restarts]
     Retry the current computation, using the restart named 'retry'.
     The corresponding effector takes no arguments and simply retries
     the same computation that triggered the condition.  The condition
     may reoccur, of course, if the root cause has not been eliminated.
     The code that signals a "file does not exist" error can be expected
     to supply a 'retry' restart.  The restart would be invoked after
     first creating the missing file, since the computation is then
     likely to succeed if it is simply retried.

 -- procedure: store-value new-value [restarts]
     Retry the current computation, using the restart named
     'store-value', after first storing NEW-VALUE.  The corresponding
     effector takes one argument, NEW-VALUE, and stores it away in a
     restart-dependent location, then retries the same computation that
     triggered the condition.  The condition may reoccur, of course, if
     the root cause has not been eliminated.  The code that signals an
     "unassigned variable" error can be expected to supply a
     'store-value' restart; this would store the value in the variable
     and continue the computation.

 -- procedure: use-value new-value [restarts]
     Retry the current computation, using the restart named 'use-value',
     but substituting NEW-VALUE for a value that previously caused a
     failure.  The corresponding effector takes one argument, NEW-VALUE,
     and retries the same computation that triggered the condition with
     the new value substituted for the failing value.  The condition may
     reoccur, of course, if the new value also induces the condition.

     The code that signals an "unassigned variable" error can be
     expected to supply a 'use-value' restart; this would simply
     continue the computation with NEW-VALUE instead of the value of the
     variable.  Contrast this with the 'retry' and 'store-value'
     restarts.  If the 'retry' restart is used it will fail because the
     variable still has no value.  The 'store-value' restart could be
     used, but it would alter the value of the variable, so that future
     references to the variable would not be detected.


File: mit-scheme-ref.info,  Node: Finding and Invoking General Restart Code,  Next: The Named Restart Abstraction,  Prev: Invoking Standard Restart Code,  Up: Restarts

16.4.3 Finding and Invoking General Restart Code
------------------------------------------------

Restarts are a general mechanism for establishing a protocol between
condition-signalling and condition-handling code.  The Scheme error
system provides "packaging" for a number of common protocols.  It also
provides lower-level hooks that are intended for implementing customized
protocols.  The mechanism used by signalling code ('with-restart' and
'with-simple-restart') is used for both purposes.

   Four additional operations are provided for the use of
condition-handling code.  Two operations ('bound-restarts' and
'find-restart') allow condition-handling code to locate active restarts.
The other two operations ('invoke-restart' and
'invoke-restart-interactively') allow restart effectors to be invoked
once the restart object has been located.

   In addition, there is a data abstraction that provides access to the
information encapsulated in restart objects.

 -- procedure: bound-restarts
     Returns a list of all currently active restart objects, most
     recently installed first.  'bound-restarts' should be used with
     caution by condition-handling code, since it reveals all restarts
     that are active at the time it is called, rather than at the time
     the condition was signalled.  It is useful, however, for collecting
     the list of restarts for inclusion in newly generated condition
     objects or for inspecting the current state of the system.

 -- procedure: find-restart name [restarts]
     Returns the first restart object named NAME in the list of RESTARTS
     (permissible values for RESTARTS are described above in *note
     Restarts::).  When used in a condition handler, 'find-restart' is
     usually passed the name of a particular restart _and_ the condition
     object that has been signalled.  In this way the handler finds only
     restarts that were available when the condition was created
     (usually the same as when it was signalled).  If RESTARTS is
     omitted, the currently active restarts would be used, and these
     often include restarts added after the condition ocurred.

 -- procedure: invoke-restart restart argument ...
     Calls the restart effector encapsulated in RESTART, passing the
     specified ARGUMENTs to it.  'invoke-restart' is intended for use by
     condition-handling code that understands the protocol implemented
     by RESTART, and can therefore calculate and pass an appropriate set
     of arguments.

     If a condition handler needs to interact with a user to gather the
     arguments for an effector (e.g. if it does not understand the
     protocol implemented by RESTART) 'invoke-restart-interactively'
     should be used instead of 'invoke-restart'.

 -- procedure: invoke-restart-interactively restart
     First calls the interactor encapsulated in RESTART to interactively
     gather the arguments needed for RESTART's effector.  It then calls
     the effector, passing these arguments to it.

     'invoke-restart-interactively' is intended for calling interactive
     restarts (those for which 'restart/interactor' is not '#f').  For
     convenience, 'invoke-restart-interactively' will call the restart's
     effector with no arguments if the restart has no interactor; this
     behavior may change in the future.


File: mit-scheme-ref.info,  Node: The Named Restart Abstraction,  Prev: Finding and Invoking General Restart Code,  Up: Restarts

16.4.4 The Named Restart Abstraction
------------------------------------

A restart object is very simple, since it encapsulates only a name,
effector, interactor, and description.

 -- procedure: restart? object
     Returns '#f' if and only if OBJECT is not a restart.

 -- procedure: restart/name restart
     Returns the name of RESTART.  While the Scheme error system uses
     only symbols and the object '#f' for its predefined names, programs
     may use arbitrary objects (name equivalence is tested using 'eq?').

 -- procedure: restart/effector restart
     Returns the effector encapsulated in RESTART.  Normally this
     procedure is not used since 'invoke-restart' and
     'invoke-restart-interactively' capture the most common invocation
     patterns.

 -- procedure: restart/interactor restart
     Returns the interactor encapsulated in RESTART.  This is either a
     procedure of no arguments or the object '#f'.  Normally this
     procedure is not used since 'invoke-restart-interactively' captures
     the most common usage.  Thus 'restart/interactor' is most useful as
     a predicate to determine if RESTART is intended to be invoked
     interactively.

 -- procedure: write-restart-report restart port
     Writes a description of RESTART to PORT.  This works by either
     displaying (if it is a string) or calling (if it is a procedure)
     the REPORTER that was supplied when the restart was created.


File: mit-scheme-ref.info,  Node: Condition Instances,  Next: Condition Types,  Prev: Restarts,  Up: Error System

16.5 Condition Instances
========================

A "condition", in addition to the information associated with its type,
usually contains other information that is not shared with other
conditions of the same type.  For example, the condition type associated
with "unbound variable" errors does not specify the name of the variable
that was unbound.  The additional information is captured in a
"condition" object, also called a "condition instance".

   In addition to information that is specific to a given type of
condition (such as the variable name for "unbound variable" conditions),
every condition instance also contains a continuation that encapsulates
the state of the computation in which the condition occurred.  This
continuation is used for analyzing the computation to learn more about
the context in which the condition occurred.  It is _not_ intended to
provide a mechanism for continuing the computation; that mechanism is
provided by restarts.

* Menu:

* Generating Operations on Conditions::
* Condition State::
* Simple Condition Instance Operations::


File: mit-scheme-ref.info,  Node: Generating Operations on Conditions,  Next: Condition State,  Prev: Condition Instances,  Up: Condition Instances

16.5.1 Generating Operations on Conditions
------------------------------------------

Scheme provides four procedures that take a condition type as input and
produce operations on the corresponding condition object.  These are
reminiscent of the operations on record types that produce record
operators (*note Records::).  Given a condition type it is possible to
generate: a constructor for instances of the type (using
'condition-constructor'); an accessor to extract the contents of a field
in instances of the type (using 'condition-accessor'); a predicate to
test for instances of the type (using 'condition-predicate'); and a
procedure to create and signal an instance of the type (using
'condition-signaller').

   Notice that the creation of a condition object is distinct from
signalling an occurrence of the condition.  Condition objects are
first-class; they may be created and never signalled, or they may be
signalled more than once.  Further notice that there are no procedures
for modifying conditions; once created, a condition cannot be altered.

 -- procedure: condition-constructor condition-type field-names
     Returns a constructor procedure that takes as arguments values for
     the fields specified in FIELD-NAMES and creates a condition of type
     CONDITION-TYPE.  FIELD-NAMES must be a list of symbols that is a
     subset of the FIELD-NAMES in CONDITION-TYPE.  The constructor
     procedure returned by 'condition-constructor' has signature

          (lambda (CONTINUATION RESTARTS . FIELD-VALUES) ...)

     where the FIELD-NAMES correspond to the FIELD-VALUES.  The
     constructor argument RESTARTS is described in *note Restarts::.
     Conditions created by the constructor procedure have '#f' for the
     values of all fields other than those specified by FIELD-NAMES.

     For example, the following procedure 'make-simple-warning'
     constructs a condition of type 'condition-type:simple-warning'
     given a continuation (where the condition occurred), a description
     of the restarts to be made available, a warning message, and a list
     of irritants that caused the warning:

          (define make-simple-warning
            (condition-constructor condition-type:simple-warning
                                   '(message irritants)))

 -- procedure: condition-accessor condition-type field-name
     Returns a procedure that takes as input a condition object of type
     CONDITION-TYPE and extracts the contents of the specified
     FIELD-NAME.  'condition-accessor' signals
     'error:bad-range-argument' if the FIELD-NAME isn't one of the named
     fields of CONDITION-TYPE; the returned procedure will signal
     'error:wrong-type-argument' if passed an object other than a
     condition of type CONDITION-TYPE or one of its specializations.

     If it is known in advance that a particular field of a condition
     will be accessed repeatedly it is worth constructing an accessor
     for the field using 'condition-accessor' rather than using the
     (possibly more convenient, but slower) 'access-condition'
     procedure.

 -- procedure: condition-predicate condition-type
     Returns a predicate procedure for testing whether an object is a
     condition of type CONDITION-TYPE or one of its specializations
     (there is no predefined way to test for a condition of a given type
     but _not_ a specialization of that type).

 -- procedure: condition-signaller condition-type field-names
          default-handler
     Returns a signalling procedure with parameters FIELD-NAMES.  When
     the signalling procedure is called it creates and signals a
     condition of type CONDITION-TYPE.  If the condition isn't handled
     (i.e. if no handler is invoked that causes an escape from the
     current continuation) the signalling procedure reduces to a call to
     DEFAULT-HANDLER with the condition as its argument.

     There are several standard procedures that are conventionally used
     for DEFAULT-HANDLER.  If CONDITION-TYPE is a specialization of
     'condition-type:error', DEFAULT-HANDLER should be the procedure
     'standard-error-handler'.  If CONDITION-TYPE is a specialization of
     'condition-type:warning', DEFAULT-HANDLER should be the procedure
     'standard-warning-handler'.  If CONDITION-TYPE is a specialization
     of 'condition-type:breakpoint', DEFAULT-HANDLER should be the
     procedure 'standard-breakpoint-handler'.


File: mit-scheme-ref.info,  Node: Condition State,  Next: Simple Condition Instance Operations,  Prev: Generating Operations on Conditions,  Up: Condition Instances

16.5.2 Condition Abstraction
----------------------------

The condition data type is abstracted through a predicate 'condition?'
and a set of accessor procedures.

 -- procedure: condition? object
     Returns '#f' if and only if OBJECT is not a condition.

 -- procedure: condition/type condition
     Returns the condition type of which CONDITION is an instance.

 -- procedure: condition/error? condition
     Returns '#t' if the CONDITION is an instance of condition type
     'condition-type:error' or a specialization of it, '#f' otherwise.

 -- procedure: condition/restarts condition
     Returns the list of restarts specified when CONDITION was created.

 -- procedure: condition/continuation condition
     Returns the continuation specified when CONDITION was created.
     This is provided for inspecting the state of the system when the
     condition occurred, _not_ for continuing or restarting the
     computation.

 -- procedure: write-condition-report condition port
     Writes a description of CONDITION to PORT, using the reporter
     function from the condition type associated with CONDITION.  See
     also 'condition/report-string'.


File: mit-scheme-ref.info,  Node: Simple Condition Instance Operations,  Prev: Condition State,  Up: Condition Instances

16.5.3 Simple Operations on Condition Instances
-----------------------------------------------

The simple procedures described in this section are built on top of the
more detailed abstraction of condition objects described above.  While
these procedures are sometimes easier to use, they are often less
efficient.

 -- procedure: make-condition condition-type continuation restarts
          field-plist
     Create a new condition object as an instance of CONDITION-TYPE,
     associated with CONTINUATION.  The CONTINUATION is provided for
     inspection purposes only, _not_ for restarting the computation.
     The RESTARTS argument is described in *note Restarts::.  The
     FIELD-PLIST is an alternating list of field names and values for
     those fields, where the field names are those that would be
     returned by '(condition-type/field-names CONDITION-TYPE)'.  It is
     used to provide values for fields in the condition object; fields
     with no value specified are set to '#f'.  Once a condition object
     has been created there is no way to alter the values of these
     fields.

 -- procedure: access-condition condition field-name
     Returns the value stored in the field FIELD-NAME within CONDITION.
     FIELD-NAME must be one of the names returned by
     '(condition-type/field-names (condition/type CONDITION))'.
     'access-condition' looks up the FIELD-NAME at runtime, so it is
     more efficient to use 'condition-accessor' to create an access
     function if the same field is to be extracted from several
     instances of the same condition type.

 -- procedure: condition/report-string condition
     Returns a string containing a report of the CONDITION.  This is
     generated by calling 'write-condition-report' on CONDITION and a
     string output port, and returning the output collected by the port
     as a string.


File: mit-scheme-ref.info,  Node: Condition Types,  Next: Taxonomy,  Prev: Condition Instances,  Up: Error System

16.6 Condition Types
====================

Each condition has a "condition type" object associated with it.  These
objects are used as a means of focusing on related classes of
conditions, first by concentrating all of the information about a
specific class of condition in a single place, and second by specifying
an inheritance relationship between types.  This inheritance
relationship forms the taxonomic structure of the condition hierarchy
(*note Taxonomy::).

   The following procedures consititute the abstraction for condition
types.

 -- procedure: make-condition-type name generalization field-names
          reporter
     Creates and returns a (new) condition type that is a specialization
     of GENERALIZATION (if it is a condition type) or is the root of a
     new tree of condition types (if GENERALIZATION is '#f').  For
     debugging purposes, the condition type has a NAME, and instances of
     this type contain storage for the fields specified by FIELD-NAMES
     (a list of symbols) in addition to the fields common to all
     conditions (TYPE, CONTINUATION and RESTARTS).

     REPORTER is used to produce a description of a particular condition
     of this type.  It may be a string describing the condition, a
     procedure of arity two (the first argument will be a condition of
     this type and the second a port) that will 'write' the message to
     the given port, or '#f' to specify that the reporter should be
     taken from the condition type GENERALIZATION (or produce an
     "undocumented condition of type ..." message if GENERALIZATION is
     '#f').  The conventions used to form descriptions are spelled out
     in *note Error Messages::.

 -- procedure: condition-type/error? condition-type
     Returns '#t' if the CONDITION-TYPE is 'condition-type:error' or a
     specialization of it, '#f' otherwise.

 -- procedure: condition-type/field-names condition-type
     Returns a list of all of the field names for a condition of type
     CONDITION-TYPE.  This is the set union of the fields specified when
     this CONDITION-TYPE was created with the
     'condition-type/field-names' of the generalization of this
     CONDITION-TYPE.

 -- procedure: condition-type/generalizations condition-type
     Returns a list of all of the generalizations of CONDITION-TYPE.
     Notice that every condition type is considered a generalization of
     itself.

 -- procedure: condition-type? object
     Returns '#f' if and only if OBJECT is not a condition type.


File: mit-scheme-ref.info,  Node: Taxonomy,  Prev: Condition Types,  Up: Error System

16.7 Condition-Type Taxonomy
============================

The MIT/GNU Scheme error system provides a rich set of predefined
condition types.  These are organized into a forest through taxonomic
links providing the relationships for "specializes" and "generalizes".
The chart appearing below shows these relationships by indenting all the
specializations of a given type relative to the type.  Note that the
variables that are bound to these condition types are prefixed by
'condition-type:'; for example, the type appearing in the following
table as 'simple-error' is stored in the variable
'condition-type:simple-error'.  Users are encouraged to add new
condition types by creating specializations of existing ones.

   Following the chart are detailed descriptions of the predefined
condition types.  Some of these types are marked as "abstract" types.
Abstract types are not intended to be used directly as the type of a
condition; they are to be used as generalizations of other types, and
for binding condition handlers.  Types that are not marked as abstract
are "concrete"; they are intended to be explicitly used as a condition's
type.

     serious-condition
         error
             simple-error
             illegal-datum
                 wrong-type-datum
                     wrong-type-argument
                     wrong-number-of-arguments
                 datum-out-of-range
                     bad-range-argument
                 inapplicable-object
             file-error
                 file-operation-error
                 derived-file-error
             port-error
                 derived-port-error
             variable-error
                 unbound-variable
                 unassigned-variable
             arithmetic-error
                 divide-by-zero
                 floating-point-overflow
                 floating-point-underflow
             control-error
                 no-such-restart
             not-loading
             primitive-procedure-error
                 system-call-error
     warning
         simple-warning
     simple-condition
     breakpoint

 -- condition type: condition-type:serious-condition
     This is an abstract type.  All serious conditions that require some
     form of intervention should inherit from this type.  In particular,
     all errors inherit from this type.

 -- condition type: condition-type:error
     This is an abstract type.  All errors should inherit from this
     type.

 -- condition type: condition-type:simple-error message irritants
     This is the condition generated by the 'error' procedure when its
     first argument is not a condition or condition type.  The fields
     MESSAGE and IRRITANTS are taken directly from the arguments to
     'error'; MESSAGE contains an object (usually a string) and
     IRRITANTS contains a list of objects.  The reporter for this type
     uses 'format-error-message' to generate its output from MESSAGE and
     IRRITANTS.

 -- condition type: condition-type:illegal-datum datum
     This is an abstract type.  This type indicates the class of errors
     in which a program discovers an object that lacks specific required
     properties.  Most commonly, the object is of the wrong type or is
     outside a specific range.  The DATUM field contains the offending
     object.

 -- condition type: condition-type:wrong-type-datum datum type
     This type indicates the class of errors in which a program
     discovers an object that is of the wrong type.  The TYPE field
     contains a string describing the type that was expected, and the
     DATUM field contains the object that is of the wrong type.

     (error:wrong-type-datum 3.4 "integer")  error->
     ;The object 3.4 is not an integer.
     ;To continue, call RESTART with an option number:
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- procedure: error:wrong-type-datum datum type
     This procedure signals a condition of type
     'condition-type:wrong-type-datum'.  The DATUM and TYPE fields of
     the condition are filled in from the corresponding arguments to the
     procedure.

 -- condition type: condition-type:wrong-type-argument datum type
          operator operand
     This type indicates that a procedure was passed an argument of the
     wrong type.  The OPERATOR field contains the procedure (or a symbol
     naming the procedure), the OPERAND field indicates the argument
     position that was involved (this field contains either a symbol, a
     non-negative integer, or '#f'), the TYPE field contains a string
     describing the type that was expected, and the DATUM field contains
     the offending argument.

     (+ 'a 3)                                error->
     ;The object a, passed as the first argument to integer-add,
     ; is not the correct type.
     ;To continue, call RESTART with an option number:
     ; (RESTART 2) => Specify an argument to use in its place.
     ; (RESTART 1) => Return to read-eval-print level 1.

     (list-copy 3)
     ;The object 3, passed as an argument to list-copy, is not a list.
     ;To continue, call RESTART with an option number:
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- procedure: error:wrong-type-argument datum type operator
     This procedure signals a condition of type
     'condition-type:wrong-type-argument'.  The DATUM, TYPE and OPERATOR
     fields of the condition are filled in from the corresponding
     arguments to the procedure; the OPERAND field of the condition is
     set to '#f'.

 -- condition type: condition-type:wrong-number-of-arguments datum type
          operands
     This type indicates that a procedure was called with the wrong
     number of arguments.  The DATUM field contains the procedure being
     called, the TYPE field contains the number of arguments that the
     procedure accepts, and the OPERANDS field contains a list of the
     arguments that were passed to the procedure.

     (car 3 4)                               error->
     ;The procedure car has been called with 2 arguments;
     ; it requires exactly 1 argument.
     ;To continue, call RESTART with an option number:
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- procedure: error:wrong-number-of-arguments datum type operands
     This procedure signals a condition of type
     'condition-type:wrong-number-of-arguments'.  The DATUM, TYPE and
     OPERANDS fields of the condition are filled in from the
     corresponding arguments to the procedure.

 -- condition type: condition-type:datum-out-of-range datum
     This type indicates the class of errors in which a program
     discovers an object that is of the correct type but is otherwise
     out of range.  Most often, this type indicates that an index to
     some data structure is outside of the range of indices for that
     structure.  The DATUM field contains the offending object.

     (error:datum-out-of-range 3)            error->
     ;The object 3 is not in the correct range.
     ;To continue, call RESTART with an option number:
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- procedure: error:datum-out-of-range datum
     This procedure signals a condition of type
     'condition-type:datum-out-of-range'.  The DATUM field of the
     condition is filled in from the corresponding argument to the
     procedure.

 -- condition type: condition-type:bad-range-argument datum operator
          operand
     This type indicates that a procedure was passed an argument that is
     of the correct type but is otherwise out of range.  Most often,
     this type indicates that an index to some data structure is outside
     of the range of indices for that structure.  The OPERATOR field
     contains the procedure (or a symbol naming the procedure), the
     OPERAND field indicates the argument position that was involved
     (this field contains either a symbol, a non-negative integer, or
     '#f'), and the DATUM field is the offending argument.

     (string-ref "abc" 3)                    error->
     ;The object 3, passed as the second argument to string-ref,
     ; is not in the correct range.
     ;To continue, call RESTART with an option number:
     ; (RESTART 2) => Specify an argument to use in its place.
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- procedure: error:bad-range-argument datum operator
     This procedure signals a condition of type
     'condition-type:bad-range-argument'.  The DATUM and OPERATOR fields
     of the condition are filled in from the corresponding arguments to
     the procedure; the OPERAND field of the condition is set to '#f'.

 -- condition type: condition-type:inapplicable-object datum operands
     This type indicates an error in which a program attempted to apply
     an object that is not a procedure.  The object being applied is
     saved in the DATUM field, and the arguments being passed to the
     object are saved as a list in the OPERANDS field.

     (3 4)                                   error->
     ;The object 3 is not applicable.
     ;To continue, call RESTART with an option number:
     ; (RESTART 2) => Specify a procedure to use in its place.
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- condition type: condition-type:file-error filename
     This is an abstract type.  It indicates that an error associated
     with a file has occurred.  For example, attempting to delete a
     nonexistent file will signal an error.  The FILENAME field contains
     a filename or pathname associated with the operation that failed.

 -- condition type: condition-type:file-operation-error filename verb
          noun reason operator operands
     This is the most common condition type for file system errors.  The
     FILENAME field contains the filename or pathname that was being
     operated on.  The VERB field contains a string which is the verb or
     verb phrase describing the operation being performed, and the NOUN
     field contains a string which is a noun or noun phrase describing
     the object being operated on.  The REASON field contains a string
     describing the error that occurred.  The OPERATOR field contains
     the procedure performing the operation (or a symbol naming that
     procedure), and the OPERANDS field contains a list of the arguments
     that were passed to that procedure.  For example, an attempt to
     delete a nonexistent file would have the following field values:

          filename        "/zu/cph/tmp/no-such-file"
          verb            "delete"
          noun            "file"
          reason          "no such file or directory"
          operator        file-remove
          operands        ("/zu/cph/tmp/no-such-file")

     and would generate a message like this:

          (delete-file "/zu/cph/tmp/no-such-file") error->
          ;Unable to delete file "/zu/cph/tmp/no-such-file" because:
          ; No such file or directory.
          ;To continue, call RESTART with an option number:
          ; (RESTART 3) => Try to delete the same file again.
          ; (RESTART 2) => Try to delete a different file.
          ; (RESTART 1) => Return to read-eval-print level 1.

 -- procedure: error:file-operation index verb noun reason operator
          operands
     This procedure signals a condition of type
     'condition-type:file-operation-error'.  The fields of the condition
     are filled in from the corresponding arguments to the procedure,
     except that the filename is taken as the INDEXth element of
     OPERANDS.

 -- condition type: condition-type:derived-file-error filename condition
     This is another kind of file error, which is generated by obscure
     file-system errors that do not fit into the standard categories.
     The FILENAME field contains the filename or pathname that was being
     operated on, and the CONDITION field contains a condition
     describing the error in more detail.  Usually the CONDITION field
     contains a condition of type 'condition-type:system-call-error'.

 -- procedure: error:derived-file filename condition
     This procedure signals a condition of type
     'condition-type:derived-file-error'.  The FILENAME and CONDITION
     fields of the condition are filled in from the corresponding
     arguments to the procedure.

 -- condition type: condition-type:port-error port
     This is an abstract type.  It indicates that an error associated
     with a I/O port has occurred.  For example, writing output to a
     file port can signal an error if the disk containing the file is
     full; that error would be signalled as a port error.  The PORT
     field contains the associated port.

 -- condition type: condition-type:derived-port-error port condition
     This is a concrete type that is signalled when port errors occur.
     The PORT field contains the port associated with the error, and the
     CONDITION field contains a condition object that describes the
     error in more detail.  Usually the CONDITION field contains a
     condition of type 'condition-type:system-call-error'.

 -- procedure: error:derived-port port condition
     This procedure signals a condition of type
     'condition-type:derived-port-error'.  The PORT and CONDITION fields
     of the condition are filled in from the corresponding arguments to
     the procedure.

 -- condition type: condition-type:variable-error location environment
     This is an abstract type.  It indicates that an error associated
     with a variable has occurred.  The LOCATION field contains the name
     of the variable, and the ENVIRONMENT field contains the environment
     in which the variable was referenced.

 -- condition type: condition-type:unbound-variable location environment
     This type is generated when a program attempts to access or modify
     a variable that is not bound.  The LOCATION field contains the name
     of the variable, and the ENVIRONMENT field contains the environment
     in which the reference occurred.

     foo                                     error->
     ;Unbound variable: foo
     ;To continue, call RESTART with an option number:
     ; (RESTART 3) => Specify a value to use instead of foo.
     ; (RESTART 2) => Define foo to a given value.
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- condition type: condition-type:unassigned-variable location
          environment
     This type is generated when a program attempts to access a variable
     that is not assigned.  The LOCATION field contains the name of the
     variable, and the ENVIRONMENT field contains the environment in
     which the reference occurred.

     foo                                     error->
     ;Unassigned variable: foo
     ;To continue, call RESTART with an option number:
     ; (RESTART 3) => Specify a value to use instead of foo.
     ; (RESTART 2) => Set foo to a given value.
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- condition type: condition-type:arithmetic-error operator operands
     This is an abstract type.  It indicates that a numerical operation
     was unable to complete because of an arithmetic error.  (For
     example, division by zero.)  The OPERATOR field contains the
     procedure that implements the operation (or a symbol naming the
     procedure), and the OPERANDS field contains a list of the arguments
     that were passed to the procedure.

 -- condition type: condition-type:divide-by-zero operator operands
     This type is generated when a program attempts to divide by zero.
     The OPERATOR field contains the procedure that implements the
     failing operation (or a symbol naming the procedure), and the
     OPERANDS field contains a list of the arguments that were passed to
     the procedure.

     (/ 1 0)
     ;Division by zero signalled by /.
     ;To continue, call RESTART with an option number:
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- procedure: error:divide-by-zero operator operands
     This procedure signals a condition of type
     'condition-type:divide-by-zero'.  The OPERATOR and OPERANDS fields
     of the condition are filled in from the corresponding arguments to
     the procedure.

 -- condition type: condition-type:floating-point-overflow operator
          operands
     This type is generated when a program performs an arithmetic
     operation that results in a floating-point overflow.  The OPERATOR
     field contains the procedure that implements the operation (or a
     symbol naming the procedure), and the OPERANDS field contains a
     list of the arguments that were passed to the procedure.

 -- condition type: condition-type:floating-point-underflow operator
          operands
     This type is generated when a program performs an arithmetic
     operation that results in a floating-point underflow.  The OPERATOR
     field contains the procedure that implements the operation (or a
     symbol naming the procedure), and the OPERANDS field contains a
     list of the arguments that were passed to the procedure.

 -- condition type: condition-type:primitive-procedure-error operator
          operands
     This is an abstract type.  It indicates that an error was generated
     by a primitive procedure call.  Primitive procedures are
     distinguished from ordinary procedures in that they are not written
     in Scheme but instead in the underlying language of the Scheme
     implementation.  The OPERATOR field contains the procedure that
     implements the operation (or a symbol naming the procedure), and
     the OPERANDS field contains a list of the arguments that were
     passed to the procedure.

 -- condition type: condition-type:system-call-error operator operands
          system-call error-type
     This is the most common condition type generated by primitive
     procedures.  A condition of this type indicates that the primitive
     made a system call to the operating system, and that the system
     call signalled an error.  The system-call error is reflected back
     to Scheme as a condition of this type, except that many common
     system-call errors are automatically translated by the Scheme
     implementation into more useful forms; for example, a system-call
     error that occurs while trying to delete a file will be translated
     into a condition of type 'condition-type:file-operation-error'.
     The OPERATOR field contains the procedure that implements the
     operation (or a symbol naming the procedure), and the OPERANDS
     field contains a list of the arguments that were passed to the
     procedure.  The SYSTEM-CALL and ERROR-TYPE fields contain symbols
     that describe the specific system call that was being made and the
     error that occurred, respectively; these symbols are completely
     operating-system dependent.

 -- condition type: condition-type:control-error
     This is an abstract type.  It describes a class of errors relating
     to program control flow.

 -- condition type: condition-type:no-such-restart name
     This type indicates that a named restart was not active when it was
     expected to be.  Conditions of this type are signalled by several
     procedures that look for particular named restarts, for example
     'muffle-warning'.  The NAME field contains the name that was being
     searched for.

     (muffle-warning)                        error->
     ;The restart named muffle-warning is not bound.
     ;To continue, call RESTART with an option number:
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- procedure: error:no-such-restart name
     This procedure signals a condition of type
     'condition-type:no-such-restart'.  The NAME field of the condition
     is filled in from the corresponding argument to the procedure.

 -- condition type: condition-type:not-loading
     A condition of this type is generated when the procedure
     'current-load-pathname' is called from somewhere other than inside
     a file being loaded.

     (current-load-pathname)                 error->
     ;No file being loaded.
     ;To continue, call RESTART with an option number:
     ; (RESTART 1) => Return to read-eval-print level 1.

 -- condition type: condition-type:warning
     This is an abstract type.  All warnings should inherit from this
     type.  Warnings are a class of conditions that are usually handled
     by informing the user of the condition and proceeding the
     computation normally.

 -- condition type: condition-type:simple-warning message irritants
     This is the condition generated by the 'warn' procedure.  The
     fields MESSAGE and IRRITANTS are taken directly from the arguments
     to 'warn'; MESSAGE contains an object (usually a string) and
     IRRITANTS contains a list of objects.  The reporter for this type
     uses 'format-error-message' to generate its output from MESSAGE and
     IRRITANTS.

 -- condition type: condition-type:simple-condition message irritants
     This is an unspecialized condition that does not fall into any of
     the standard condition classes.  The MESSAGE field contains an
     object (usually a string) and IRRITANTS contains a list of objects.
     The reporter for this type uses 'format-error-message' to generate
     its output from MESSAGE and IRRITANTS.

 -- condition type: condition-type:breakpoint environment message prompt
     A condition of this type is generated by the breakpoint mechanism.
     The contents of its fields are beyond the scope of this document.


File: mit-scheme-ref.info,  Node: Graphics,  Next: Win32 Package Reference,  Prev: Error System,  Up: Top

17 Graphics
***********

MIT/GNU Scheme has a simple two-dimensional line-graphics interface that
is suitable for many graphics applications.  In particular it is often
used for plotting data points from experiments.  The interface is
generic in that it can support different types of graphics devices in a
uniform manner.  At the present time only one type of graphics device is
implemented on each operating system.

   Procedures are available for drawing points, lines, and text;
defining the coordinate system; clipping graphics output; controlling
some of the drawing characteristics; and controlling the output buffer
(for devices that perform buffering).  Additionally, devices may support
custom operations, such as control of colors.

   There are some constraints on the arguments to the procedures
described in this chapter.  Any argument named GRAPHICS-DEVICE must be a
graphics device object that was returned from a call to
'make-graphics-device'.  Any argument that is a coordinate must be
either an exact integer or an inexact real.

* Menu:

* Opening and Closing of Graphics Devices::
* Coordinates for Graphics::
* Drawing Graphics::
* Characteristics of Graphics Output::
* Buffering of Graphics Output::
* Clipping of Graphics Output::
* Custom Graphics Operations::
* Images::
* X Graphics::                  Graphics on the X Window System
* Win32 Graphics::              Graphics on Microsoft Windows and Windows NT


File: mit-scheme-ref.info,  Node: Opening and Closing of Graphics Devices,  Next: Coordinates for Graphics,  Prev: Graphics,  Up: Graphics

17.1 Opening and Closing of Graphics Devices
============================================

 -- procedure: graphics-type-available? graphics-device-type
     This predicate returns '#t' if the graphics system named by the
     symbol GRAPHICS-DEVICE-TYPE is implemented by the Scheme system.
     Otherwise it returns '#f', in which case it is an error to attempt
     to make a graphics device using GRAPHICS-DEVICE-TYPE.

 -- procedure: enumerate-graphics-types
     This procedure returns a list of symbols which are the names of all
     the graphics device types that are supported by the Scheme system.
     The result is useful in deciding what additional arguments to
     supply to 'make-graphics-device', as each device type typically has
     a unique way of specifying the initial size, shape and other
     attributes.

 -- procedure: make-graphics-device graphics-device-type object ...
     This operation creates and returns a graphics device object.
     GRAPHICS-DEVICE-TYPE is a symbol naming a graphics device type, and
     both the number and the meaning of the remaining arguments is
     determined by that type (see the description of each device type
     for details); GRAPHICS-DEVICE-TYPE must satisfy
     'graphics-type-available?'.  GRAPHICS-DEVICE-TYPE may also be '#f',
     in which case the graphics device type is chosen by the system from
     what is available.  This allows completely portable graphics
     programs to be written provided no custom graphics operations are
     used.  When GRAPHICS-DEVICE-TYPE is '#f' no further arguments may
     be given; each graphics device type will use some "sensible"
     defaults.  If more control is required then the program should use
     one of the two procedures above to dispatch on the available types.

     This procedure opens and initializes the device, which remains
     valid until explicitly closed by the procedure 'graphics-close'.
     Depending on the implementation of the graphics device, if this
     object is reclaimed by the garbage collector, the graphics device
     may remain open or it may be automatically closed.  While a
     graphics device remains open the resources associated with it are
     not released.

 -- procedure: graphics-close graphics-device
     Closes GRAPHICS-DEVICE, releasing its resources.  Subsequently it
     is an error to use GRAPHICS-DEVICE.


File: mit-scheme-ref.info,  Node: Coordinates for Graphics,  Next: Drawing Graphics,  Prev: Opening and Closing of Graphics Devices,  Up: Graphics

17.2 Coordinates for Graphics
=============================

Each graphics device has two different coordinate systems associated
with it: "device coordinates" and "virtual coordinates".  Device
coordinates are generally defined by low-level characteristics of the
device itself, and often cannot be changed.  Most device coordinate
systems are defined in terms of pixels, and usually the upper-left-hand
corner is the origin of the coordinate system, with X coordinates
increasing to the right and Y coordinates increasing downwards.

   In contrast, virtual coordinates are more flexible in the units
employed, the position of the origin, and even the direction in which
the coordinates increase.  A virtual coordinate system is defined by
assigning coordinates to the edges of a device.  Because these edge
coordinates are arbitrary real numbers, any Cartesian coordinate system
can be defined.

   All graphics procedures that use coordinates are defined on virtual
coordinates.  For example, to draw a line at a particular place on a
device, the virtual coordinates for the endpoints of that line are
given.

   When a graphics device is initialized, its virtual coordinate system
is reset so that the left edge corresponds to an x-coordinate of '-1',
the right edge to x-coordinate '1', the bottom edge to y-coordinate
'-1', and the top edge to y-coordinate '1'.

 -- procedure: graphics-device-coordinate-limits graphics-device
     Returns (as multiple values) the device coordinate limits for
     GRAPHICS-DEVICE.  The values, which are exact non-negative
     integers, are: X-LEFT, Y-BOTTOM, X-RIGHT, and Y-TOP.

 -- procedure: graphics-coordinate-limits graphics-device
     Returns (as multiple values) the virtual coordinate limits for
     GRAPHICS-DEVICE.  The values, which are real numbers, are: X-LEFT,
     Y-BOTTOM, X-RIGHT, and Y-TOP.

 -- procedure: graphics-set-coordinate-limits graphics-device x-left
          y-bottom x-right y-top
     Changes the virtual coordinate limits of GRAPHICS-DEVICE to the
     given arguments.  X-LEFT, Y-BOTTOM, X-RIGHT, and Y-TOP must be real
     numbers.  Subsequent calls to 'graphics-coordinate-limits' will
     return the new limits.  This operation has no effect on the
     device's displayed contents.

     Note: This operation usually resets the clip rectangle, although it
     is not guaranteed to do so.  If a clip rectangle is in effect when
     this procedure is called, it is necessary to redefine the clip
     rectangle afterwards.


File: mit-scheme-ref.info,  Node: Drawing Graphics,  Next: Characteristics of Graphics Output,  Prev: Coordinates for Graphics,  Up: Graphics

17.3 Drawing Graphics
=====================

The procedures in this section provide the basic drawing capabilities of
Scheme's graphics system.

 -- procedure: graphics-clear graphics-device
     Clears the display of GRAPHICS-DEVICE.  Unaffected by the current
     drawing mode.

 -- procedure: graphics-draw-point graphics-device x y
     Draws a single point on GRAPHICS-DEVICE at the virtual coordinates
     given by X and Y, using the current drawing mode.

 -- procedure: graphics-erase-point graphics-device x y
     Erases a single point on GRAPHICS-DEVICE at the virtual coordinates
     given by X and Y.  This procedure is unaffected by the current
     drawing mode.

This is equivalent to

     (lambda (device x y)
       (graphics-bind-drawing-mode device 0
         (lambda ()
           (graphics-draw-point device x y))))

 -- procedure: graphics-draw-line graphics-device x-start y-start x-end
          y-end
     X-START, Y-START, X-END, and Y-END must be real numbers.  Draws a
     line on GRAPHICS-DEVICE that connects the points (X-START, Y-START)
     and (X-END, Y-END).  The line is drawn using the current drawing
     mode and line style.

 -- procedure: graphics-draw-text graphics-device x y string
     Draws the characters of STRING at the point (X, Y) on
     GRAPHICS-DEVICE, using the current drawing mode.  The
     characteristics of the characters drawn are device-dependent, but
     all devices are initialized so that the characters are drawn
     upright, from left to right, with the leftmost edge of the leftmost
     character at X, and the baseline of the characters at Y.

   The following two procedures provide an alternate mechanism for
drawing lines, which is more akin to using a plotter.  They maintain a
"cursor", which can be positioned to a particular point and then dragged
to another point, producing a line.  Sequences of connected line
segments can be drawn by dragging the cursor from point to point.

   Many graphics operations have an unspecified effect on the cursor.
The following exceptions are guaranteed to leave the cursor unaffected:

     graphics-device-coordinate-limits
     graphics-coordinate-limits
     graphics-enable-buffering
     graphics-disable-buffering
     graphics-flush
     graphics-bind-drawing-mode
     graphics-set-drawing-mode
     graphics-bind-line-style
     graphics-set-line-style

   The initial state of the cursor is unspecified.

 -- procedure: graphics-move-cursor graphics-device x y
     Moves the cursor for GRAPHICS-DEVICE to the point (X, Y).  The
     contents of the device's display are unchanged.

 -- procedure: graphics-drag-cursor graphics-device x y
     Draws a line from GRAPHICS-DEVICE's cursor to the point (X, Y),
     simultaneously moving the cursor to that point.  The line is drawn
     using the current drawing mode and line style.


File: mit-scheme-ref.info,  Node: Characteristics of Graphics Output,  Next: Buffering of Graphics Output,  Prev: Drawing Graphics,  Up: Graphics

17.4 Characteristics of Graphics Output
=======================================

Two characteristics of graphics output are so useful that they are
supported uniformly by all graphics devices: "drawing mode" and "line
style".  A third characteristic, "color", is equally useful (if not more
so), but implementation restrictions prohibit a uniform interface.

   The "drawing mode", an exact integer in the range '0' to '15'
inclusive, determines how the figure being drawn is combined with the
background over which it is drawn to generate the final result.
Initially the drawing mode is set to "source", so that the new output
overwrites whatever appears in that place.  Useful alternative drawing
modes can, for example, erase what was already there, or invert it.

   Altogether 16 boolean operations are available for combining the
source (what is being drawn) and the destination (what is being drawn
over).  The source and destination are combined by the device on a
pixel-by-pixel basis as follows:

     Mode    Meaning
     ----    -------
     0       ZERO [erase; use background color]
     1       source AND destination
     2       source AND (NOT destination)
     3       source
     4       (NOT source) AND destination
     5       destination
     6       source XOR destination
     7       source OR destination
     8       NOT (source OR destination)
     9       NOT (source XOR destination)
     10      NOT destination
     11      source OR (NOT destination)
     12      NOT source
     13      (NOT source) OR destination
     14      (NOT source) OR (NOT destination)
     15      ONE [use foreground color]

   The "line style", an exact integer in the range '0' to '7' inclusive,
determines which parts of a line are drawn in the foreground color, and
which in the background color.  The default line style, "solid", draws
the entire line in the foreground color.  Alternatively, the "dash"
style alternates between foreground and background colors to generate a
dashed line.  This capability is useful for plotting several things on
the same graph.

   Here is a table showing the name and approximate pattern of the
different styles.  A '1' in the pattern represents a foreground pixel,
while a '-' represents a background pixel.  Note that the precise output
for each style will vary from device to device.  The only style that is
guaranteed to be the same for every device is "solid".

     Style   Name                    Pattern
     -----   -------                 -------
     0       solid                   1111111111111111
     1       dash                    11111111--------
     2       dot                     1-1-1-1-1-1-1-1-
     3       dash dot                1111111111111-1-
     4       dash dot dot            11111111111-1-1-
     5       long dash               11111111111-----
     6       center dash             111111111111-11-
     7       center dash dash        111111111-11-11-

 -- procedure: graphics-bind-drawing-mode graphics-device drawing-mode
          thunk
 -- procedure: graphics-bind-line-style graphics-device line-style thunk
     These procedures bind the drawing mode or line style, respectively,
     of GRAPHICS-DEVICE, invoke the procedure THUNK with no arguments,
     then undo the binding when THUNK returns.  The value of each
     procedure is the value returned by THUNK.  Graphics operations
     performed during THUNK's dynamic extent will see the newly bound
     mode or style as current.

 -- procedure: graphics-set-drawing-mode graphics-device drawing-mode
 -- procedure: graphics-set-line-style graphics-device line-style
     These procedures change the drawing mode or line style,
     respectively, of GRAPHICS-DEVICE.  The mode or style will remain in
     effect until subsequent changes or bindings.


File: mit-scheme-ref.info,  Node: Buffering of Graphics Output,  Next: Clipping of Graphics Output,  Prev: Characteristics of Graphics Output,  Up: Graphics

17.5 Buffering of Graphics Output
=================================

To improve performance of graphics output, most graphics devices provide
some form of buffering.  By default, Scheme's graphics procedures flush
this buffer after every drawing operation.  The procedures in this
section allow the user to control the flushing of the output buffer.

 -- procedure: graphics-enable-buffering graphics-device
     Enables buffering for GRAPHICS-DEVICE.  In other words, after this
     procedure is called, graphics operations are permitted to buffer
     their drawing requests.  This usually means that the drawing is
     delayed until the buffer is flushed explicitly by the user, or
     until it fills up and is flushed by the system.

 -- procedure: graphics-disable-buffering graphics-device
     Disables buffering for GRAPHICS-DEVICE.  By default, all graphics
     devices are initialized with buffering disabled.  After this
     procedure is called, all drawing operations perform their output
     immediately, before returning.

     Note: 'graphics-disable-buffering' flushes the output buffer if
     necessary.

 -- procedure: graphics-flush graphics-device
     Flushes the graphics output buffer for GRAPHICS-DEVICE.  This
     operation has no effect for devices that do not support buffering,
     or if buffering is disabled for the device.


File: mit-scheme-ref.info,  Node: Clipping of Graphics Output,  Next: Custom Graphics Operations,  Prev: Buffering of Graphics Output,  Up: Graphics

17.6 Clipping of Graphics Output
================================

Scheme provides a rudimentary mechanism for restricting graphics output
to a given rectangular subsection of a graphics device.  By default,
graphics output that is drawn anywhere within the device's virtual
coordinate limits will appear on the device.  When a "clip rectangle" is
specified, however, output that would have appeared outside the clip
rectangle is not drawn.

   Note that changing the virtual coordinate limits for a device will
usually reset the clip rectangle for that device, as will any operation
that affects the size of the device (such as a window resizing
operation).  However, programs should not depend on this.

 -- procedure: graphics-set-clip-rectangle graphics-device x-left
          y-bottom x-right y-top
     Specifies the clip rectangle for GRAPHICS-DEVICE in virtual
     coordinates.  X-LEFT, Y-BOTTOM, X-RIGHT, and Y-TOP must be real
     numbers.  Subsequent graphics output is clipped to the intersection
     of this rectangle and the device's virtual coordinate limits.

 -- procedure: graphics-reset-clip-rectangle graphics-device
     Eliminates the clip rectangle for GRAPHICS-DEVICE.  Subsequent
     graphics output is clipped to the virtual coordinate limits of the
     device.


File: mit-scheme-ref.info,  Node: Custom Graphics Operations,  Next: Images,  Prev: Clipping of Graphics Output,  Up: Graphics

17.7 Custom Graphics Operations
===============================

In addition to the standard operations, a graphics device may support
"custom operations".  For example, most devices have custom operations
to control color.  'graphics-operation' is used to invoke custom
operations.

 -- procedure: graphics-operation graphics-device name object ...
     Invokes the graphics operation on GRAPHICS-DEVICE whose name is the
     symbol NAME, passing it the remaining arguments.  This procedure
     can be used to invoke the standard operations, as well as custom
     operations that are specific to a particular graphics device type.
     The names of the standard graphics operations are formed by
     removing the 'graphics-' prefix from the corresponding procedure.
     For example, the following are equivalent:

          (graphics-draw-point device x y)
          (graphics-operation device 'draw-point x y)

     For information on the custom operations for a particular device,
     see the documentation for its type.


File: mit-scheme-ref.info,  Node: Images,  Next: X Graphics,  Prev: Custom Graphics Operations,  Up: Graphics

17.8 Images
===========

Some graphics device types support images, which are rectangular pieces
of picture that may be drawn into a graphics device.  Images are often
called something else in the host graphics system, such as bitmaps or
pixmaps.  The operations supported vary between devices, so look under
the different device types to see what operations are available.  All
devices that support images support the following operations.

 -- operation on graphics-device: create-image width height
     Images are created using the 'create-image' graphics operation,
     specifying the WIDTH and HEIGHT of the image in device coordinates
     (pixels).

          (graphics-operation device 'create-image 200 100)

     The initial contents of an image are unspecified.

     'create-image' is a graphics operation rather than a procedure
     because the kind of image returned depends on the kind of graphics
     device used and the options specified in its creation.  The image
     may be used freely with other graphics devices created with the
     same attributes, but the effects of using an image with a graphics
     device with different attributes (for example, different colors) is
     undefined.  Under X, the image is display dependent.

 -- operation on graphics-device: draw-image x y image
     The image is copied into the graphics device at the specified
     position.

 -- operation on graphics-device: draw-subimage x y image im-x im-y w h
     Part of the image is copied into the graphics device at the
     specified (X, Y) position.  The part of the image that is copied is
     the rectangular region at IM-X and IM-Y and of width W and height
     H.  These four numbers are given in device coordinates (pixels).

 -- procedure: image? object
     Returns '#t' if OBJECT is an image, otherwise returns '#f'.

 -- procedure: image/destroy image
     This procedure destroys IMAGE, returning storage to the system.
     Programs should destroy images after they have been used because
     even modest images may use large amounts of memory.  Images are
     reclaimed by the garbage collector, but they may be implemented
     using memory outside of Scheme's heap.  If an image is reclaimed
     before being destroyed, the implementation might not deallocate
     that non-heap memory, which can cause a subsequent call to
     'create-image' to fail because it is unable to allocate enough
     memory.

 -- procedure: image/height image
     Returns the height of the image in device coordinates.

 -- procedure: image/width image
     Returns the width of the image in device coordinates.

 -- procedure: image/fill-from-byte-vector image bytes
     The contents of IMAGE are set in a device-dependent way, using one
     byte per pixel from BYTES (a string).  Pixels are filled row by row
     from the top of the image to the bottom, with each row being filled
     from left to right.  There must be at least '(* (image/height
     IMAGE) (image/width IMAGE))' bytes in BYTES.


File: mit-scheme-ref.info,  Node: X Graphics,  Next: Win32 Graphics,  Prev: Images,  Up: Graphics

17.9 X Graphics
===============

MIT/GNU Scheme supports graphics in the X window system (version 11).
Arbitrary numbers of displays may be opened, and arbitrary numbers of
graphics windows may be created for each display.  A variety of
operations is available to manipulate various aspects of the windows, to
control their size, position, colors, and mapping.  The X graphics
device type supports images, which are implemented as Xlib 'XImage'
objects.  X display, window, and image objects are automatically closed
if they are reclaimed by the garbage collector.

* Menu:

* X Graphics Type::
* Utilities for X Graphics::
* Custom Operations on X Graphics Devices::


File: mit-scheme-ref.info,  Node: X Graphics Type,  Next: Utilities for X Graphics,  Prev: X Graphics,  Up: X Graphics

17.9.1 X Graphics Type
----------------------

A graphics device for X windows is created by passing the symbol 'x' as
the graphics device type name to 'make-graphics-device':

     (make-graphics-device 'x #!optional DISPLAY GEOMETRY SUPPRESS-MAP?)

where DISPLAY is either a display object, '#f', or a string; GEOMETRY is
either '#f' or a string; and SUPPRESS-MAP? is a boolean or a vector (see
below).  A new window is created on the appropriate display, and a
graphics device representing that window is returned.

   DISPLAY specifies which X display the window is to be opened on; if
it is '#f' or a string, it is passed as an argument to 'x-open-display',
and the value returned by that procedure is used in place of the
original argument.  GEOMETRY is an X geometry string, or '#f' which
means to use the default geometry (which is specified as a resource).

   SUPPRESS-MAP?, if given, may take two forms.  First, it may be a
boolean: if '#f' (the default), the window is automatically mapped after
it is created; otherwise, '#t' means to suppress this automatic mapping.
The second form is a vector of three elements.  The first element is a
boolean with the same meaning as the boolean form of SUPPRESS-MAP?.  The
second element is a string, which specifies an alternative resource name
to be used for looking up the window's resources.  The third element is
also a string, which specifies a class name for looking up the window's
resources.  The default value for SUPPRESS-MAP? is '#f'.

   The default resource and class names are '"schemeGraphics"' and
'"SchemeGraphics"' respectively.

   The window is initialized using the resource and class names
specified by SUPPRESS-MAP?, and is sensitive to the following resource
properties:

     Property        Class           Default
     --------        -----           -------
     geometry        Geometry        512x384+0+0
     font            Font            fixed
     borderWidth     BorderWidth     2
     internalBorder  BorderWidth     [border width]
     background      Background      white
     foreground      Foreground      black
     borderColor     BorderColor     [foreground color]
     cursorColor     Foreground      [foreground color]
     pointerColor    Foreground      [foreground color]

   The window is created with a 'backing_store' attribute of 'Always'.
The window's name and icon name are initialized to '"scheme-graphics"'.


File: mit-scheme-ref.info,  Node: Utilities for X Graphics,  Next: Custom Operations on X Graphics Devices,  Prev: X Graphics Type,  Up: X Graphics

17.9.2 Utilities for X Graphics
-------------------------------

 -- procedure: x-graphics/open-display display-name
     Opens a connection to the display whose name is DISPLAY-NAME,
     returning a display object.  If unable to open a connection, '#f'
     is returned.  DISPLAY-NAME is normally a string, which is an X
     display name in the usual form; however, '#f' is also allowed,
     meaning to use the value of the unix environment variable
     'DISPLAY'.

 -- procedure: x-graphics/close-display display
     Closes DISPLAY; after calling this procedure, it is an error to use
     DISPLAY for any purpose.  Any windows that were previously opened
     on DISPLAY are destroyed and their resources returned to the
     operating system.

 -- procedure: x-close-all-displays
     Closes all open connections to X displays.  Equivalent to calling
     'x-close-display' on all open displays.

 -- procedure: x-geometry-string x y width height
     This procedure creates and returns a standard X geometry string
     from the given arguments.  X and Y must be either exact integers or
     '#f', while WIDTH and HEIGHT must be either exact non-negative
     integers or '#f'.  Usually either X and Y are both specified or
     both '#f'; similarly for WIDTH and HEIGHT.  If only one of the
     elements of such a pair is specified, it is ignored.

     Examples:

          (x-geometry-string #f #f 100 200) => "100x200"
          (x-geometry-string 2 -3 100 200) => "100x200+2-3"
          (x-geometry-string 2 -3 #f #f) => "+2-3"

     Note that the X and Y arguments cannot distinguish between '+0' and
     '-0', even though these have different meanings in X. If either of
     those arguments is '0', it means '+0' in X terminology.  If you
     need to distinguish these two cases you must create your own
     geometry string using Scheme's string and number primitives.


File: mit-scheme-ref.info,  Node: Custom Operations on X Graphics Devices,  Prev: Utilities for X Graphics,  Up: X Graphics

17.9.3 Custom Operations on X Graphics Devices
----------------------------------------------

Custom operations are invoked using the procedure 'graphics-operation'.
For example,

     (graphics-operation device 'set-foreground-color "blue")

 -- operation on x-graphics-device: set-background-color color-name
 -- operation on x-graphics-device: set-foreground-color color-name
 -- operation on x-graphics-device: set-border-color color-name
 -- operation on x-graphics-device: set-mouse-color color-name
     These operations change the colors associated with a window.
     COLOR-NAME must be a string, which is the X server's name for the
     desired color.  'set-border-color' and 'set-mouse-color'
     immediately change the border and mouse-cursor colors.
     'set-background-color' and 'set-foreground-color' change the colors
     to be used when drawing, but have no effect on anything drawn prior
     to their invocation.  Because changing the background color affects
     the entire window, we recommend calling 'graphics-clear' on the
     window's device afterwards.  Color names include both mnemonic
     names, like '"red"', and intensity names specified in the
     '"#RRGGBB"' notation.

 -- operation on x-graphics-device: draw-arc x y radius-x radius-y
          angle-start angle-sweep fill?

     Operation 'draw-arc' draws or fills an arc.  An arc is a segment of
     a circle, which may have been stretched along the x- or y- axis to
     form an ellipse.

     The parameters X, Y, RADIUS-X and RADIUS-Y describe the circle and
     ANGLE-START and ANGLE-SWEEP choose which part of the circle is
     drawn.  The arc is drawn on the graphics device with the center of
     the circle at the virtual coordinates given by X and Y.  RADIUS-X
     and RADIUS-Y determine the size of the circle in virtual coordinate
     units.

     The parameter ANGLE-START determines where the arc starts.  It is
     measured in degrees in an anti-clockwise direction, starting at 3
     o'clock.  ANGLE-SWEEP determines how much of the circle is drawn.
     It too is measured anti-clockwise in degrees.  A negative value
     means the measurement is in a clockwise direction.

     Note that the angles are determined on a unit circle before it is
     stretched into an ellipse, so the actual angles that you will see
     on the computer screen depends on all of: RADIUS-X and RADIUS-Y,
     the window size, and the virtual coordinates.

     If FILL? is '#f' then just the segment of the circle is drawn,
     otherwise the arc is filled in a pie-slice fashion.

     This draws a quarter circle pie slice, standing on its point, with
     point at virtual coordinates (3,5):

          (graphics-operation g 'draw-arc 3 5 .5 .5 45 90 #t)

 -- operation on x-graphics-device: draw-circle x y radius
 -- operation on x-graphics-device: fill-circle x y radius
     These operations draw a circle (outline) or a filled circle (solid)
     at on the graphics device at the virtual coordinates given by X and
     Y.  These operations could be implemented trivially interms of the
     'draw-arc' operation.

 -- operation on x-graphics-device: set-border-width width
 -- operation on x-graphics-device: set-internal-border-width width
     These operations change the external and internal border widths of
     a window.  WIDTH must be an exact non-negative integer, specified
     in pixels.  The change takes place immediately.  Note that changing
     the internal border width can cause displayed graphics to be
     garbled; we recommend calling 'graphics-clear' on the window's
     device after doing so.

 -- operation on x-graphics-device: set-font font-name
     Changes the font used when drawing text in a window.  FONT-NAME
     must be a string that is a font name known to the X server.  This
     operation does not affect text drawn prior to its invocation.

 -- operation on x-graphics-device: set-mouse-shape shape-number
     Changes the shape of the mouse cursor.  SHAPE-NUMBER is an exact
     non-negative integer that is used as an index into the mouse-shape
     font; when multiplied by 2 this number corresponds to an index in
     the file
     '/usr/include/X11/cursorfont.h'.

 -- operation on x-graphics-device: map-window
 -- operation on x-graphics-device: withdraw-window
     These operations control the mapping of windows.  They correspond
     directly to Xlib's 'XMapWindow' and 'XWithdrawWindow'.

 -- operation on x-graphics-device: resize-window width height
     Changes the size of a window.  WIDTH and HEIGHT must be exact
     non-negative integers.  The operation corresponds directly to
     Xlib's 'XResizeWindow'.

     This operation resets the virtual coordinate system and the clip
     rectangle.

 -- operation on x-graphics-device: move-window x y
     Changes the position of a window on the display.  X and Y must be
     exact integers.  The operation corresponds directly to Xlib's
     'XMoveWindow'.  Note that the coordinates X and Y do not take the
     external border into account, and therefore will not position the
     window as you might like.  The only reliable way to position a
     window is to ask a window manager to do it for you.

 -- operation on x-graphics-device: get-default resource property
     This operation corresponds directly to Xlib's 'XGetDefault'.
     RESOURCE and PROPERTY must be strings.  The operation returns the
     character string corresponding to the association of RESOURCE and
     PROPERTY; if no such association exists, '#f' is returned.

 -- operation on x-graphics-device: copy-area source-x-left source-y-top
          width height destination-x-left destination-y-top
     This operation copies the contents of the rectangle specified by
     SOURCE-X-LEFT, SOURCE-Y-TOP, WIDTH, and HEIGHT to the rectangle of
     the same dimensions at DESTINATION-X-LEFT and DESTINATION-Y-TOP.

 -- operation on x-graphics-device: font-structure font-name
     Returns a Scheme equivalent of the X font structure for the font
     named FONT-NAME.  If the string FONT-NAME does not name a font
     known to the X server, or names a 16-bit font, '#f' is returned.

 -- procedure: x-font-structure/name font-structure
 -- procedure: x-font-structure/direction font-structure
 -- procedure: x-font-structure/all-chars-exist font-structure
 -- procedure: x-font-structure/default-char font-structure
 -- procedure: x-font-structure/min-bounds font-structure
 -- procedure: x-font-structure/max-bounds font-structure
 -- procedure: x-font-structure/start-index font-structure
 -- procedure: x-font-structure/character-bounds font-structure
 -- procedure: x-font-structure/max-ascent font-structure
 -- procedure: x-font-structure/max-descent font-structure
     These procedures extract the components of the font description
     structure returned by the X graphics operation 'font-structure'.  A
     more complete description of these components appears in
     documentation of the 'XLoadQueryFont' Xlib call.  'start-index' is
     the index of the first character available in the font.  The
     'min-bounds' and 'max-bounds' components are structures of type
     'x-character-bounds', and the 'character-bounds' component is a
     vector of the same type.

 -- procedure: x-character-bounds/lbearing character-bounds
 -- procedure: x-character-bounds/rbearing character-bounds
 -- procedure: x-character-bounds/width character-bounds
 -- procedure: x-character-bounds/ascent character-bounds
 -- procedure: x-character-bounds/descent character-bounds
     These procedures extract components of objects of type
     'x-character-bounds'.  A more complete description of them appears
     in documentation of the
     'XLoadQueryFont' Xlib call.


File: mit-scheme-ref.info,  Node: Win32 Graphics,  Prev: X Graphics,  Up: Graphics

17.10 Win32 Graphics
====================

MIT/GNU Scheme supports graphics on Microsoft Windows 95, Windows 98,
and Windows NT. In addition to the usual operations, there are
operations to control the size, position and colors of a graphics
window.  Win32 devices support images, which are implemented as device
independent bitmaps (DIBs).

   The Win32 graphics device type is implemented as a top level window.
'graphics-enable-buffering' is implemented and gives a 2x to 4x speedup
on many graphics operations.  As a convenience, when buffering is
enabled clicking on the graphics window's title bar effects a
'graphics-flush' operation.  The user has the benefit of the increased
performance and the ability to view the progress in drawing at the click
of a mouse button.

* Menu:

* Win32 Graphics Type::
* Custom Operations for Win32 Graphics::  Custom Operations for Win32 Graphics Devices


File: mit-scheme-ref.info,  Node: Win32 Graphics Type,  Next: Custom Operations for Win32 Graphics,  Prev: Win32 Graphics,  Up: Win32 Graphics

17.10.1 Win32 Graphics Type
---------------------------

Win32 graphics devices are created by specifying the symbol 'win32' as
the GRAPHICS-DEVICE-TYPE argument to 'make-graphics-device'.  The Win32
graphics device type is implemented as a top-level window and supports
color drawing in addition to the standard Scheme graphics operations.

   Graphics devices are opened as follows:

     (make-graphics-device 'win32 #!optional WIDTH HEIGHT PALETTE)

where WIDTH and HEIGHT specify the size, in pixels, of the drawing area
in the graphics window (i.e. excluding the frame).  PALETTE determines
the colors available for drawing in the window.

   When a color is specified for drawing, the nearest color available in
the palette is used.  Permitted values for PALETTE are

''grayscale'
     The window allocates colors from a grayscale palette of
     approximately 236 shades of gray.

''grayscale-128'
     The window allocates colors from a grayscale palette of 128 shades
     of gray.

''standard'
     The standard palette has good selection of colors and grays.

'#f' or ''system'
     The colors available are those in the system palette.  There are
     usually 16 to 20 colors in the system palette and these are usually
     sufficent for simple applications like line drawings and x-vs-y
     graphs of mathematical functions.  Drawing with the system palette
     can be more efficient.

If PALETTE is not specified then the 'standard' palette is used.


File: mit-scheme-ref.info,  Node: Custom Operations for Win32 Graphics,  Prev: Win32 Graphics Type,  Up: Win32 Graphics

17.10.2 Custom Operations for Win32 Graphics
--------------------------------------------

Custom operations are invoked using the procedure 'graphics-operation'.
For example,

     (graphics-operation device 'set-foreground-color "blue")

 -- operation on win32-graphics-device: set-background-color color-name
 -- operation on win32-graphics-device: set-foreground-color color-name
     These operations change the colors associated with a window.
     COLOR-NAME must be of one of the valid color specification forms
     listed below.  'set-background-color' and 'set-foreground-color'
     change the colors to be used when drawing, but have no effect on
     anything drawn prior to their invocation.  Because changing the
     background color affects the entire window, we recommend calling
     'graphics-clear' on the window's device afterwards.

     The foreground color affects the drawing of text, points, lines,
     ellipses and filled polygons.

     Colors are specified in one of three ways:

     An integer
          This is the Win32 internal RGB value.

     By name
          A limited number of names are understood by the system.  Names
          are strings, e.g. '"red"', '"blue"', '"black"'.  More names
          can be registered with the 'define-color' operation.

     RGB (Red-Green-Blue) triples
          A triple is either a vector or list of three integers in the
          range 0-255 inclusive which specify the intensity of the red,
          green and blue components of the color.  Thus '#(0 0 0)' is
          black, '(0 0 128)' is dark blue and '#(255 255 255)' is white.

     If the color is not available in the graphics device then the
     nearest available color is used instead.

 -- operation on win32-graphics-device: define-color name spec
     Define the string NAME to be the color specified by SPEC.  SPEC may
     be any acceptable color specification.  Note that the color names
     defined this way are available to any Win32 graphics device, and
     the names do _not_ have to be defined for each device.

     Color names defined by this interface may also be used when setting
     the colors of the Scheme console window, or the colors of Edwin
     editor windows.

 -- operation on win32-graphics-device: find-color name
     Looks up a color previously defined by 'define-color'.  This
     returns the color in its most efficient form for operations
     'set-foreground-color' or 'set-background-color'.

 -- operation on win32-graphics-device: draw-ellipse left top right
          bottom
     Draw an ellipse.  LEFT, TOP, RIGHT and BOTTOM indicate the
     coordinates of the bounding rectangle of the ellipse.  Circles are
     merely ellipses with equal width and height.  Note that the
     bounding rectangle has horizontal and vertical sides.  Ellipses
     with rotated axes cannot be drawn.  The rectangle applies to the
     center of the line used to draw the ellipse; if the line width has
     been set to greater than 1 then the ellipse will spill outside the
     bounding rectange by half of the line width.

 -- operation on win32-graphics-device: fill-polygon points
     Draws a filled polygon using the current foreground color.  POINTS
     is a vector of real numbers.  The numbers are in the order x1 y1 x2
     y2 ... xn yn.  For example,

          (graphics-operation device 'fill-polygon #(0 0 0 1 1 0))

     draws a solid triangular region between the points (0, 0), (0, 1)
     and (1, 0).

 -- operation on win32-graphics-device: load-bitmap pathname
     The graphics device contents and size are initialized from the
     windows bitmap file specified by PATHNAME.  If no file type is
     supplied then a '".BMP"' extension is added.  If a clip rectangle
     is in effect when this procedure is called, it is necessary to
     redefine the clip rectangle afterwards.

 -- operation on win32-graphics-device: save-bitmap pathname
     The graphics device contents are saved as a bitmap to the file
     specified by PATHNAME.  If no file type is supplied then a '".BMP"'
     extension is added.  The saved bitmap may be incorporated into
     documents or printed.

 -- operation on win32-graphics-device: move-window x y
     The graphics device window is moved to the screen position
     specified by X and Y.

 -- operation on win32-graphics-device: resize-window width height
     The graphics device window is resized to the specified WIDTH and
     HEIGHT in device coordinates (pixels).  If a clip rectangle is in
     effect when this procedure is called, it is necessary to redefine
     the clip rectangle afterwards.

 -- operation on win32-graphics-device: set-line-width width
     This operation sets the line width for future drawing of lines,
     points and ellipses.  It does not affect existing lines and has no
     effect on filled polygons.  The line width is specified in device
     units.  The default and initial value of this parameter is 1 pixel.

 -- operation on win32-graphics-device: set-window-name name
     This sets the window title to the string NAME.  The window is given
     the name '"Scheme Graphics"' at creation.

 -- operation on win32-graphics-device: set-font handle
     Sets the font for drawing text.  Currently not well supported.  If
     you can get a Win32 font handle it can be used here.

 -- operation on win32-graphics-device: copy-area source-x-left
          source-y-top width height destination-x-left destination-y-top
     This operation copies the contents of the rectangle specified by
     SOURCE-X-LEFT, SOURCE-Y-TOP, WIDTH, and HEIGHT to the rectangle of
     the same dimensions at DESTINATION-X-LEFT and DESTINATION-Y-TOP.
