This is guile.info, produced by makeinfo version 4.3 from guile.texi.

INFO-DIR-SECTION The Algorithmic Language Scheme
START-INFO-DIR-ENTRY
* Guile Reference: (guile).     The Guile reference manual.
END-INFO-DIR-ENTRY

   Guile Reference Manual Copyright (C) 1996 Free Software Foundation
Copyright (C) 1997 Free Software Foundation
Copyright (C) 2000 Free Software Foundation
Copyright (C) 2001 Free Software Foundation
Copyright (C) 2002 Free Software Foundation

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that
the entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the Free Software Foundation.


File: guile.info,  Node: Throw,  Next: Lazy Catch,  Prev: Catch,  Up: Exceptions

Throwing Exceptions
-------------------

   The `throw' primitive is used to throw an exception.  One argument,
the KEY, is mandatory, and must be a symbol; it indicates the type of
exception that is being thrown.  Following the KEY, `throw' accepts any
number of additional arguments, whose meaning depends on the exception
type.  The documentation for each possible type of exception should
specify the additional arguments that are expected for that kind of
exception.

 - Scheme Procedure: throw key . args
 - C Function: scm_throw (key, args)
     Invoke the catch form matching KEY, passing ARGS to the HANDLER.

     KEY is a symbol.  It will match catches of the same symbol or of
     `#t'.

     If there is no handler at all, Guile prints an error and then
     exits.

   When an exception is thrown, it will be caught by the innermost
`catch' expression that applies to the type of the thrown exception; in
other words, the innermost `catch' whose KEY is `#t' or is the same
symbol as that used in the `throw' expression.  Once Guile has
identified the appropriate `catch', it handles the exception by
applying that `catch' expression's handler procedure to the arguments
of the `throw'.

   If there is no appropriate `catch' for a thrown exception, Guile
prints an error to the current error port indicating an uncaught
exception, and then exits.  In practice, it is quite difficult to
observe this behaviour, because Guile when used interactively installs a
top level `catch' handler that will catch all exceptions and print an
appropriate error message _without_ exiting.  For example, this is what
happens if you try to throw an unhandled exception in the standard
Guile REPL; note that Guile's command loop continues after the error
message:

     guile> (throw 'badex)
     <unnamed port>:3:1: In procedure gsubr-apply ...
     <unnamed port>:3:1: unhandled-exception: badex
     ABORT: (misc-error)
     guile>

   The default uncaught exception behaviour can be observed by
evaluating a `throw' expression from the shell command line:

     $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
     guile: uncaught throw to badex: ()
     $

That Guile exits immediately following the uncaught exception is shown
by the absence of any output from the `display' expression, because
Guile never gets to the point of evaluating that expression.


File: guile.info,  Node: Lazy Catch,  Next: Exception Implementation,  Prev: Throw,  Up: Exceptions

Catch Without Unwinding
-----------------------

   A "lazy catch" is used in the same way as a normal `catch', with
KEY, THUNK and HANDLER arguments specifying the exception type, normal
case code and handler procedure, but differs in one important respect:
the handler procedure is executed without unwinding the call stack from
the context of the `throw' expression that caused the handler to be
invoked.

 - Scheme Procedure: lazy-catch key thunk handler
 - C Function: scm_lazy_catch (key, thunk, handler)
     This behaves exactly like `catch', except that it does not unwind
     the stack before invoking HANDLER.  The HANDLER procedure is not
     allowed to return: it must throw to another catch, or otherwise
     exit non-locally.

   Typically, HANDLER should save any desired state associated with the
stack at the point where the corresponding `throw' occurred, and then
throw an exception itself -- usually the same exception as the one it
caught.  If HANDLER is invoked and does _not_ throw an exception, Guile
itself throws an exception with key `misc-error'.

   Not unwinding the stack means that throwing an exception that is
caught by a `lazy-catch' is _almost_ equivalent to calling the
`lazy-catch''s handler inline instead of each `throw', and then
omitting the surrounding `lazy-catch'.  In other words,

     (lazy-catch 'key
       (lambda () ... (throw 'key args ...) ...)
       handler)

is _almost_ equivalent to

     ((lambda () ... (handler 'key args ...) ...))

But why only _almost_?  The difference is that with `lazy-catch' (as
with normal `catch'), the dynamic context is unwound back to just
outside the `lazy-catch' expression before invoking the handler.  (For
an introduction to what is meant by dynamic context, *Note Dynamic
Wind::.)

   Then, when the handler _itself_ throws an exception, that exception
must be caught by some kind of `catch' (including perhaps another
`lazy-catch') higher up the call stack.

   The dynamic context also includes `with-fluids' blocks (REFFIXME),
so the effect of unwinding the dynamic context can also be seen in fluid
variable values.  This is illustrated by the following code, in which
the normal case thunk uses `with-fluids' to temporarily change the
value of a fluid:

     (define f (make-fluid))
     (fluid-set! f "top level value")
     
     (define (handler . args)
       (cons (fluid-ref f) args))
     
     (lazy-catch 'foo
                 (lambda ()
                   (with-fluids ((f "local value"))
                     (throw 'foo)))
                 handler)
     =>
     ("top level value" foo)
     
     ((lambda ()
        (with-fluids ((f "local value"))
          (handler 'foo))))
     =>
     ("local value" foo)

In the `lazy-catch' version, the unwinding of dynamic context restores
`f' to its value outside the `with-fluids' block before the handler is
invoked, so the handler's `(fluid-ref f)' returns the external value.

   `lazy-catch' is useful because it permits the implementation of
debuggers and other reflective programming tools that need to access the
state of the call stack at the exact point where an exception or an
error is thrown.  For an example of this, see REFFIXME:stack-catch.


File: guile.info,  Node: Exception Implementation,  Prev: Lazy Catch,  Up: Exceptions

How Guile Implements Exceptions
-------------------------------

   It is traditional in Scheme to implement exception systems using
`call-with-current-continuation'.  Continuations (*note
Continuations::) are such a powerful concept that any other control
mechanism -- including `catch' and `throw' -- can be implemented in
terms of them.

   Guile does not implement `catch' and `throw' like this, though.  Why
not?  Because Guile is specifically designed to be easy to integrate
with applications written in C.  In a mixed Scheme/C environment, the
concept of "continuation" must logically include "what happens next" in
the C parts of the application as well as the Scheme parts, and it
turns out that the only reasonable way of implementing continuations
like this is to save and restore the complete C stack.

   So Guile's implementation of `call-with-current-continuation' is a
stack copying one.  This allows it to interact well with ordinary C
code, but means that creating and calling a continuation is slowed down
by the time that it takes to copy the C stack.

   The more targeted mechanism provided by `catch' and `throw' does not
need to save and restore the C stack because the `throw' always jumps
to a location higher up the stack of the code that executes the
`throw'.  Therefore Guile implements the `catch' and `throw' primitives
independently of `call-with-current-continuation', in a way that takes
advantage of this _upwards only_ nature of exceptions.


File: guile.info,  Node: Error Reporting,  Next: Dynamic Wind,  Prev: Exceptions,  Up: Control Mechanisms

Procedures for Signaling Errors
===============================

   Guile provides a set of convenience procedures for signaling error
conditions that are implemented on top of the exception primitives just
described.

 - Scheme Procedure: error msg args ...
     Raise an error with key `misc-error' and a message constructed by
     displaying MSG and writing ARGS.

 - Scheme Procedure: scm-error key subr message args data
 - C Function: scm_error_scm (key, subr, message, args, data)
     Raise an error with key KEY.  SUBR can be a string naming the
     procedure associated with the error, or `#f'.  MESSAGE is the
     error message string, possibly containing `~S' and `~A' escapes.
     When an error is reported, these are replaced by formatting the
     corresponding members of ARGS: `~A' (was `%s' in older versions of
     Guile) formats using `display' and `~S' (was `%S') formats using
     `write'.  DATA is a list or `#f' depending on KEY: if KEY is
     `system-error' then it should be a list containing the Unix
     `errno' value; If KEY is `signal' then it should be a list
     containing the Unix signal number; otherwise it will usually be
     `#f'.

 - Scheme Procedure: strerror err
 - C Function: scm_strerror (err)
     Return the Unix error message corresponding to ERR, which must be
     an integer value.

 - syntax: false-if-exception expr
     Returns the result of evaluating its argument; however if an
     exception occurs then `#f' is returned instead.


File: guile.info,  Node: Dynamic Wind,  Next: Handling Errors,  Prev: Error Reporting,  Up: Control Mechanisms

Dynamic Wind
============

   [FIXME: this is pasted in from Tom Lord's original guile.texi and
should be reviewed]

 - Scheme Procedure: dynamic-wind in_guard thunk out_guard
 - C Function: scm_dynamic_wind (in_guard, thunk, out_guard)
     All three arguments must be 0-argument procedures.  IN_GUARD is
     called, then THUNK, then OUT_GUARD.

     If, any time during the execution of THUNK, the continuation of
     the `dynamic_wind' expression is escaped non-locally, OUT_GUARD is
     called.  If the continuation of the dynamic-wind is re-entered,
     IN_GUARD is called.  Thus IN_GUARD and OUT_GUARD may be called any
     number of times.
          (define x 'normal-binding)
          => x
          (define a-cont  (call-with-current-continuation
          		  (lambda (escape)
          		     (let ((old-x x))
          		       (dynamic-wind
          			  ;; in-guard:
          			  ;;
          			  (lambda () (set! x 'special-binding))
          
          			  ;; thunk
          			  ;;
          		 	  (lambda () (display x) (newline)
          				     (call-with-current-continuation escape)
          				     (display x) (newline)
          				     x)
          
          			  ;; out-guard:
          			  ;;
          			  (lambda () (set! x old-x)))))))
          
          ;; Prints:
          special-binding
          ;; Evaluates to:
          => a-cont
          x
          => normal-binding
          (a-cont #f)
          ;; Prints:
          special-binding
          ;; Evaluates to:
          => a-cont  ;; the value of the (define a-cont...)
          x
          => normal-binding
          a-cont
          => special-binding


File: guile.info,  Node: Handling Errors,  Prev: Dynamic Wind,  Up: Control Mechanisms

How to Handle Errors in C Code
==============================

   Error handling is based on `catch' and `throw'.  Errors are always
thrown with a KEY and four arguments:

   * KEY: a symbol which indicates the type of error.  The symbols used
     by libguile are listed below.

   * SUBR: the name of the procedure from which the error is thrown, or
     `#f'.

   * MESSAGE: a string (possibly language and system dependent)
     describing the error.  The tokens `~A' and `~S' can be embedded
     within the message: they will be replaced with members of the ARGS
     list when the message is printed.  `~A' indicates an argument
     printed using `display', while `~S' indicates an argument printed
     using `write'.  MESSAGE can also be `#f', to allow it to be
     derived from the KEY by the error handler (may be useful if the
     KEY is to be thrown from both C and Scheme).

   * ARGS: a list of arguments to be used to expand `~A' and `~S'
     tokens in MESSAGE.  Can also be `#f' if no arguments are required.

   * REST: a list of any additional objects required. e.g., when the
     key is `'system-error', this contains the C errno value.  Can also
     be `#f' if no additional objects are required.

   In addition to `catch' and `throw', the following Scheme facilities
are available:

 - Scheme Procedure: scm-error key subr message args rest
     Throw an error, with arguments as described above.

 - Scheme Procedure: error msg arg ...
     Throw an error using the key `'misc-error'.  The error message is
     created by displaying MSG and writing the ARGS.

 - Scheme Procedure: display-error stack port subr message args rest
 - C Function: scm_display_error (stack, port, subr, message, args,
          rest)
     Display an error message to the output port PORT.  STACK is the
     saved stack for the error, SUBR is the name of the procedure in
     which the error occurred and MESSAGE is the actual error message,
     which may contain formatting instructions. These will format the
     arguments in the list ARGS accordingly.  REST is currently ignored.

   The following are the error keys defined by libguile and the
situations in which they are used:

   * `error-signal': thrown after receiving an unhandled fatal signal
     such as SIGSEGV, SIGBUS, SIGFPE etc.  The REST argument in the
     throw contains the coded signal number (at present this is not the
     same as the usual Unix signal number).

   * `system-error': thrown after the operating system indicates an
     error condition.  The REST argument in the throw contains the
     errno value.

   * `numerical-overflow': numerical overflow.

   * `out-of-range': the arguments to a procedure do not fall within the
     accepted domain.

   * `wrong-type-arg': an argument to a procedure has the wrong type.

   * `wrong-number-of-args': a procedure was called with the wrong
     number of arguments.

   * `memory-allocation-error': memory allocation error.

   * `stack-overflow': stack overflow error.

   * `regex-error': errors generated by the regular expression library.

   * `misc-error': other errors.

C Support
---------

   SCM scm_error (SCM key, char *subr, char *message, SCM args, SCM
rest)

   Throws an error, after converting the char * arguments to Scheme
strings.  subr is the Scheme name of the procedure, NULL is converted
to #f.  Likewise a NULL message is converted to #f.

   The following procedures invoke scm_error with various error keys and
arguments.  The first three call scm_error with the system-error key
and automatically supply errno in the "rest" argument:  scm_syserror
generates messages using strerror,  scm_sysmissing is used when
facilities are not available.  Care should be taken that the errno
value is not reset (e.g. due to an interrupt).

   * void scm_syserror (char *subr);

   * void scm_syserror_msg (char *subr, char *message, SCM args);

   * void scm_sysmissing (char *subr);

   * void scm_num_overflow (char *subr);

   * void scm_out_of_range (char *subr, SCM bad_value);

   * void scm_wrong_num_args (SCM proc);

   * void scm_wrong_type_arg (char *subr, int pos, SCM bad_value);

   * void scm_memory_error (char *subr);

   * static void scm_regex_error (char *subr, int code); (only used in
     rgx.c).

   Exception handlers can also be installed from C, using
scm_internal_catch, scm_lazy_catch, or scm_stack_catch from
libguile/throw.c.  These have not yet been documented, however the
source contains some useful comments.


File: guile.info,  Node: Input and Output,  Next: Read/Load/Eval,  Prev: Control Mechanisms,  Up: Top

Input and Output
****************

* Menu:

* Ports::                       The idea of the port abstraction.
* Reading::                     Procedures for reading from a port.
* Writing::                     Procedures for writing to a port.
* Closing::                     Procedures to close a port.
* Random Access::               Moving around a random access port.
* Line/Delimited::              Read and write lines or delimited text.
* Block Reading and Writing::   Reading and writing blocks of text.
* Default Ports::               Defaults for input, output and errors.
* Port Types::                  Types of port and how to make them.
* I/O Extensions::              Using and extending ports in C.


File: guile.info,  Node: Ports,  Next: Reading,  Up: Input and Output

Ports
=====

   [Concept of the port abstraction.]

   Sequential input/output in Scheme is represented by operations on a
"port".  Characters can be read from an input port and written to an
output port.  This chapter explains the operations that Guile provides
for working with ports.

   The formal definition of a port is very generic: an input port is
simply "an object which can deliver characters on command," and an
output port is "an object which can accept characters."  Because this
definition is so loose, it is easy to write functions that simulate
ports in software.  "Soft ports" and "string ports" are two interesting
and powerful examples of this technique.

 - Scheme Procedure: input-port? x
 - C Function: scm_input_port_p (x)
     Return `#t' if X is an input port, otherwise return `#f'.  Any
     object satisfying this predicate also satisfies `port?'.

 - Scheme Procedure: output-port? x
 - C Function: scm_output_port_p (x)
     Return `#t' if X is an output port, otherwise return `#f'.  Any
     object satisfying this predicate also satisfies `port?'.

 - Scheme Procedure: port? x
 - C Function: scm_port_p (x)
     Return a boolean indicating whether X is a port.  Equivalent to
     `(or (input-port? X) (output-port?  X))'.


File: guile.info,  Node: Reading,  Next: Writing,  Prev: Ports,  Up: Input and Output

Reading
=======

   [Generic procedures for reading from ports.]

 - Scheme Procedure: eof-object? x
 - C Function: scm_eof_object_p (x)
     Return `#t' if X is an end-of-file object; otherwise return `#f'.

 - Scheme Procedure: char-ready? [port]
 - C Function: scm_char_ready_p (port)
     Return `#t' if a character is ready on input PORT and return `#f'
     otherwise.  If `char-ready?' returns `#t' then the next
     `read-char' operation on PORT is guaranteed not to hang.  If PORT
     is a file port at end of file then `char-ready?' returns `#t'.  (1)

 - Scheme Procedure: read-char [port]
 - C Function: scm_read_char (port)
     Return the next character available from PORT, updating PORT to
     point to the following character.  If no more characters are
     available, the end-of-file object is returned.

 - Scheme Procedure: peek-char [port]
 - C Function: scm_peek_char (port)
     Return the next character available from PORT, _without_ updating
     PORT to point to the following character.  If no more characters
     are available, the end-of-file object is returned.(2)

 - Scheme Procedure: unread-char cobj [port]
 - C Function: scm_unread_char (cobj, port)
     Place CHAR in PORT so that it will be read by the next read
     operation.  If called multiple times, the unread characters will
     be read again in last-in first-out order.  If PORT is not
     supplied, the current input port is used.

 - Scheme Procedure: unread-string str port
 - C Function: scm_unread_string (str, port)
     Place the string STR in PORT so that its characters will be read
     in subsequent read operations.  If called multiple times, the
     unread characters will be read again in last-in first-out order.
     If PORT is not supplied, the current-input-port is used.

 - Scheme Procedure: drain-input port
 - C Function: scm_drain_input (port)
     This procedure clears a port's input buffers, similar to the way
     that force-output clears the output buffer.  The contents of the
     buffers are returned as a single string, e.g.,

          (define p (open-input-file ...))
          (drain-input p) => empty string, nothing buffered yet.
          (unread-char (read-char p) p)
          (drain-input p) => initial chars from p, up to the buffer size.

     Draining the buffers may be useful for cleanly finishing buffered
     I/O so that the file descriptor can be used directly for further
     input.

 - Scheme Procedure: port-column port
 - Scheme Procedure: port-line port
 - C Function: scm_port_column (port)
 - C Function: scm_port_line (port)
     Return the current column number or line number of PORT, using the
     current input port if none is specified.  If the number is
     unknown, the result is #f.  Otherwise, the result is a 0-origin
     integer - i.e. the first character of the first line is line 0,
     column 0.  (However, when you display a file position, for example
     in an error message, we recommend you add 1 to get 1-origin
     integers.  This is because lines and column numbers traditionally
     start with 1, and that is what non-programmers will find most
     natural.)

 - Scheme Procedure: set-port-column! port column
 - Scheme Procedure: set-port-line! port line
 - C Function: scm_set_port_column_x (port, column)
 - C Function: scm_set_port_line_x (port, line)
     Set the current column or line number of PORT, using the current
     input port if none is specified.

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

   (1) `char-ready?' exists to make it possible for a program to accept
characters from interactive ports without getting stuck waiting for
input.  Any input editors associated with such ports must make sure
that characters whose existence has been asserted by `char-ready?'
cannot be rubbed out.  If `char-ready?' were to return `#f' at end of
file, a port at end of file would be indistinguishable from an
interactive port that has no ready characters.

   (2) The value returned by a call to `peek-char' is the same as the
value that would have been returned by a call to `read-char' on the same
port.  The only difference is that the very next call to `read-char' or
`peek-char' on that PORT will return the value returned by the
preceding call to `peek-char'.  In particular, a call to `peek-char' on
an interactive port will hang waiting for input whenever a call to
`read-char' would have hung.


File: guile.info,  Node: Writing,  Next: Closing,  Prev: Reading,  Up: Input and Output

Writing
=======

   [Generic procedures for writing to ports.]

 - Scheme Procedure: get-print-state port
 - C Function: scm_get_print_state (port)
     Return the print state of the port PORT. If PORT has no associated
     print state, `#f' is returned.

 - Scheme Procedure: display obj [port]
     Send a representation of OBJ to CURRENT-OUTPUT-PORT.  Optional
     second arg PORT specifies an alternative output port.  The
     representation is similar to that produced by `write' (REFFIXME),
     the differences being strings are not quoted (and their characters
     are not escaped), and characters are rendered as if with
     `write-char'.

 - Scheme Procedure: newline [port]
 - C Function: scm_newline (port)
     Send a newline to PORT.  If PORT is omitted, send to the current
     output port.

 - Scheme Procedure: port-with-print-state port pstate
 - C Function: scm_port_with_print_state (port, pstate)
     Create a new port which behaves like PORT, but with an included
     print state PSTATE.

 - Scheme Procedure: print-options-interface [setting]
 - C Function: scm_print_options (setting)
     Option interface for the print options. Instead of using this
     procedure directly, use the procedures `print-enable',
     `print-disable', `print-set!' and `print-options'.

 - Scheme Procedure: simple-format destination message . args
 - C Function: scm_simple_format (destination, message, args)
     Write MESSAGE to DESTINATION, defaulting to the current output
     port.  MESSAGE can contain `~A' (was `%s') and `~S' (was `%S')
     escapes.  When printed, the escapes are replaced with
     corresponding members of ARGS: `~A' formats using `display' and
     `~S' formats using `write'.  If DESTINATION is `#t', then use the
     current output port, if DESTINATION is `#f', then return a string
     containing the formatted text. Does not add a trailing newline.

 - Scheme Procedure: write-char chr [port]
 - C Function: scm_write_char (chr, port)
     Send character CHR to PORT.

 - Scheme Procedure: force-output [port]
 - C Function: scm_force_output (port)
     Flush the specified output port, or the current output port if PORT
     is omitted.  The current output buffer contents are passed to the
     underlying port implementation (e.g., in the case of fports, the
     data will be written to the file and the output buffer will be
     cleared.)  It has no effect on an unbuffered port.

     The return value is unspecified.

 - Scheme Procedure: flush-all-ports
 - C Function: scm_flush_all_ports ()
     Equivalent to calling `force-output' on all open output ports.
     The return value is unspecified.


File: guile.info,  Node: Closing,  Next: Random Access,  Prev: Writing,  Up: Input and Output

Closing
=======

 - Scheme Procedure: close-port port
 - C Function: scm_close_port (port)
     Close the specified port object.  Return `#t' if it successfully
     closes a port or `#f' if it was already closed.  An exception may
     be raised if an error occurs, for example when flushing buffered
     output.  See also *Note close: Ports and File Descriptors, for a
     procedure which can close file descriptors.

 - Scheme Procedure: close-input-port port
 - C Function: scm_close_input_port (port)
     Close the specified input port object.  The routine has no effect
     if the file has already been closed.  An exception may be raised
     if an error occurs.  The value returned is unspecified.

     See also *Note close: Ports and File Descriptors, for a procedure
     which can close file descriptors.

 - Scheme Procedure: close-output-port port
 - C Function: scm_close_output_port (port)
     Close the specified output port object.  The routine has no effect
     if the file has already been closed.  An exception may be raised
     if an error occurs.  The value returned is unspecified.

     See also *Note close: Ports and File Descriptors, for a procedure
     which can close file descriptors.

 - Scheme Procedure: port-closed? port
 - C Function: scm_port_closed_p (port)
     Return `#t' if PORT is closed or `#f' if it is open.


File: guile.info,  Node: Random Access,  Next: Line/Delimited,  Prev: Closing,  Up: Input and Output

Random Access
=============

 - Scheme Procedure: seek fd_port offset whence
 - C Function: scm_seek (fd_port, offset, whence)
     Sets the current position of FD/PORT to the integer OFFSET, which
     is interpreted according to the value of WHENCE.

     One of the following variables should be supplied for WHENCE:

      - Variable: SEEK_SET
          Seek from the beginning of the file.

      - Variable: SEEK_CUR
          Seek from the current position.

      - Variable: SEEK_END
          Seek from the end of the file.
     If FD/PORT is a file descriptor, the underlying system call is
     `lseek'.  PORT may be a string port.

     The value returned is the new position in the file.  This means
     that the current position of a port can be obtained using:
          (seek port 0 SEEK_CUR)

 - Scheme Procedure: ftell fd_port
 - C Function: scm_ftell (fd_port)
     Return an integer representing the current position of FD/PORT,
     measured from the beginning.  Equivalent to:

          (seek port 0 SEEK_CUR)

 - Scheme Procedure: truncate-file object [length]
 - C Function: scm_truncate_file (object, length)
     Truncates the object referred to by OBJECT to at most LENGTH
     bytes.  OBJECT can be a string containing a file name or an
     integer file descriptor or a port.  LENGTH may be omitted if
     OBJECT is not a file name, in which case the truncation occurs at
     the current port.  position.  The return value is unspecified.


File: guile.info,  Node: Line/Delimited,  Next: Block Reading and Writing,  Prev: Random Access,  Up: Input and Output

Line Oriented and Delimited Text
================================

   The delimited-I/O module can be accessed with:

     (use-modules (ice-9 rdelim))

   It can be used to read or write lines of text, or read text
delimited by a specified set of characters.  It's similar to the `(scsh
rdelim)' module from guile-scsh, but does not use multiple values or
character sets and has an extra procedure `write-line'.

 - Scheme Procedure: read-line [port] [handle-delim]
     Return a line of text from PORT if specified, otherwise from the
     value returned by `(current-input-port)'.  Under Unix, a line of
     text is terminated by the first end-of-line character or by
     end-of-file.

     If HANDLE-DELIM is specified, it should be one of the following
     symbols:
    `trim'
          Discard the terminating delimiter.  This is the default, but
          it will be impossible to tell whether the read terminated
          with a delimiter or end-of-file.

    `concat'
          Append the terminating delimiter (if any) to the returned
          string.

    `peek'
          Push the terminating delimiter (if any) back on to the port.

    `split'
          Return a pair containing the string read from the port and the
          terminating delimiter or end-of-file object.

 - Scheme Procedure: read-line! buf [port]
     Read a line of text into the supplied string BUF and return the
     number of characters added to BUF.  If BUF is filled, then `#f' is
     returned.  Read from PORT if specified, otherwise from the value
     returned by `(current-input-port)'.

 - Scheme Procedure: read-delimited delims [port] [handle-delim]
     Read text until one of the characters in the string DELIMS is found
     or end-of-file is reached.  Read from PORT if supplied, otherwise
     from the value returned by `(current-input-port)'.  HANDLE-DELIM
     takes the same values as described for `read-line'.

 - Scheme Procedure: read-delimited! delims buf [port] [handle-delim]
          [start] [end]
     Read text into the supplied string BUF and return the number of
     characters added to BUF (subject to HANDLE-DELIM, which takes the
     same values specified for `read-line'.  If BUF is filled, `#f' is
     returned for both the number of characters read and the delimiter.
     Also terminates if one of the characters in the string DELIMS is
     found or end-of-file is reached.  Read from PORT if supplied,
     otherwise from the value returned by `(current-input-port)'.

 - Scheme Procedure: write-line obj [port]
 - C Function: scm_write_line (obj, port)
     Display OBJ and a newline character to PORT.  If PORT is not
     specified, `(current-output-port)' is used.  This function is
     equivalent to:
          (display obj [port])
          (newline [port])

   Some of the abovementioned I/O functions rely on the following C
primitives.  These will mainly be of interest to people hacking Guile
internals.

 - Scheme Procedure: %read-delimited! delims str gobble [port [start
          [end]]]
 - C Function: scm_read_delimited_x (delims, str, gobble, port, start,
          end)
     Read characters from PORT into STR until one of the characters in
     the DELIMS string is encountered.  If GOBBLE is true, discard the
     delimiter character; otherwise, leave it in the input stream for
     the next read.  If PORT is not specified, use the value of
     `(current-input-port)'.  If START or END are specified, store data
     only into the substring of STR bounded by START and END (which
     default to the beginning and end of the string, respectively).

     Return a pair consisting of the delimiter that terminated the
     string and the number of characters read.  If reading stopped at
     the end of file, the delimiter returned is the EOF-OBJECT; if the
     string was filled without encountering a delimiter, this value is
     `#f'.

 - Scheme Procedure: %read-line [port]
 - C Function: scm_read_line (port)
     Read a newline-terminated line from PORT, allocating storage as
     necessary.  The newline terminator (if any) is removed from the
     string, and a pair consisting of the line and its delimiter is
     returned.  The delimiter may be either a newline or the
     EOF-OBJECT; if `%read-line' is called at the end of file, it
     returns the pair `(#<eof> . #<eof>)'.


File: guile.info,  Node: Block Reading and Writing,  Next: Default Ports,  Prev: Line/Delimited,  Up: Input and Output

Block reading and writing
=========================

   The Block-string-I/O module can be accessed with:

     (use-modules (ice-9 rw))

   It currently contains procedures that help to implement the `(scsh
rw)' module in guile-scsh.

 - Scheme Procedure: read-string!/partial str [port_or_fdes [start
          [end]]]
 - C Function: scm_read_string_x_partial (str, port_or_fdes, start, end)
     Read characters from a port or file descriptor into a string STR.
     A port must have an underlying file descriptor -- a so-called
     fport.  This procedure is scsh-compatible and can efficiently read
     large strings.  It will:

        * attempt to fill the entire string, unless the START and/or
          END arguments are supplied.  i.e., START defaults to 0 and
          END defaults to `(string-length str)'

        * use the current input port if PORT_OR_FDES is not supplied.

        * return fewer than the requested number of characters in some
          cases, e.g., on end of file, if interrupted by a signal, or if
          not all the characters are immediately available.

        * wait indefinitely for some input if no characters are
          currently available, unless the port is in non-blocking mode.

        * read characters from the port's input buffers if available,
          instead from the underlying file descriptor.

        * return `#f' if end-of-file is encountered before reading any
          characters, otherwise return the number of characters read.

        * return 0 if the port is in non-blocking mode and no characters
          are immediately available.

        * return 0 if the request is for 0 bytes, with no end-of-file
          check.

 - Scheme Procedure: write-string/partial str [port_or_fdes [start
          [end]]]
 - C Function: scm_write_string_partial (str, port_or_fdes, start, end)
     Write characters from a string STR to a port or file descriptor.
     A port must have an underlying file descriptor -- a so-called
     fport.  This procedure is scsh-compatible and can efficiently
     write large strings.  It will:

        * attempt to write the entire string, unless the START and/or
          END arguments are supplied.  i.e., START defaults to 0 and
          END defaults to `(string-length str)'

        * use the current output port if PORT_OF_FDES is not supplied.

        * in the case of a buffered port, store the characters in the
          port's output buffer, if all will fit.  If they will not fit
          then any existing buffered characters will be flushed before
          attempting to write the new characters directly to the
          underlying file descriptor.  If the port is in non-blocking
          mode and buffered characters can not be flushed immediately,
          then an `EAGAIN' system-error exception will be raised (Note:
          scsh does not support the use of non-blocking buffered ports.)

        * write fewer than the requested number of characters in some
          cases, e.g., if interrupted by a signal or if not all of the
          output can be accepted immediately.

        * wait indefinitely for at least one character from STR to be
          accepted by the port, unless the port is in non-blocking mode.

        * return the number of characters accepted by the port.

        * return 0 if the port is in non-blocking mode and can not
          accept at least one character from STR immediately

        * return 0 immediately if the request size is 0 bytes.


File: guile.info,  Node: Default Ports,  Next: Port Types,  Prev: Block Reading and Writing,  Up: Input and Output

Default Ports for Input, Output and Errors
==========================================

 - Scheme Procedure: current-input-port
 - C Function: scm_current_input_port ()
     Return the current input port.  This is the default port used by
     many input procedures.  Initially, `current-input-port' returns
     the "standard input" in Unix and C terminology.

 - Scheme Procedure: current-output-port
 - C Function: scm_current_output_port ()
     Return the current output port.  This is the default port used by
     many output procedures.  Initially, `current-output-port' returns
     the "standard output" in Unix and C terminology.

 - Scheme Procedure: current-error-port
 - C Function: scm_current_error_port ()
     Return the port to which errors and warnings should be sent (the
     "standard error" in Unix and C terminology).

 - Scheme Procedure: set-current-input-port port
 - Scheme Procedure: set-current-output-port port
 - Scheme Procedure: set-current-error-port port
 - C Function: scm_set_current_input_port (port)
 - C Function: scm_set_current_output_port (port)
 - C Function: scm_set_current_error_port (port)
     Change the ports returned by `current-input-port',
     `current-output-port' and `current-error-port', respectively, so
     that they use the supplied PORT for input or output.

 - Scheme Procedure: set-current-output-port port
     Set the current default output port to PORT.

 - Scheme Procedure: set-current-error-port port
     Set the current default error port to PORT.


File: guile.info,  Node: Port Types,  Next: I/O Extensions,  Prev: Default Ports,  Up: Input and Output

Types of Port
=============

   [Types of port; how to make them.]

* Menu:

* File Ports:: Ports on an operating system file.
* String Ports:: Ports on a Scheme string.
* Soft Ports:: Ports on arbitrary Scheme procedures.
* Void Ports:: Ports on nothing at all.


File: guile.info,  Node: File Ports,  Next: String Ports,  Up: Port Types

File Ports
----------

   The following procedures are used to open file ports.  See also
*Note open: Ports and File Descriptors, for an interface to the Unix
`open' system call.

 - Scheme Procedure: open-file filename mode
 - C Function: scm_open_file (filename, mode)
     Open the file whose name is FILENAME, and return a port
     representing that file.  The attributes of the port are determined
     by the MODE string.  The way in which this is interpreted is
     similar to C stdio.  The first character must be one of the
     following:
    `r'
          Open an existing file for input.

    `w'
          Open a file for output, creating it if it doesn't already
          exist or removing its contents if it does.

    `a'
          Open a file for output, creating it if it doesn't already
          exist.  All writes to the port will go to the end of the file.
          The "append mode" can be turned off while the port is in use
          *note fcntl: Ports and File Descriptors.  The following
     additional characters can be appended:
    `+'
          Open the port for both input and output.  E.g., `r+': open an
          existing file for both input and output.

    `0'
          Create an "unbuffered" port.  In this case input and output
          operations are passed directly to the underlying port
          implementation without additional buffering.  This is likely
          to slow down I/O operations.  The buffering mode can be
          changed while a port is in use *note setvbuf: Ports and File
          Descriptors.

    `l'
          Add line-buffering to the port.  The port output buffer will
          be automatically flushed whenever a newline character is
          written.  In theory we could create read/write ports which
     were buffered in one direction only.  However this isn't included
     in the current interfaces.  If a file cannot be opened with the
     access requested, `open-file' throws an exception.

 - Scheme Procedure: open-input-file filename
     Open FILENAME for input.  Equivalent to
          (open-file FILENAME "r")

 - Scheme Procedure: open-output-file filename
     Open FILENAME for output.  Equivalent to
          (open-file FILENAME "w")

 - Scheme Procedure: call-with-input-file file proc
     PROC should be a procedure of one argument, and FILE should be a
     string naming a file.  The file must already exist. These
     procedures call PROC with one argument: the port obtained by
     opening the named file for input or output.  If the file cannot be
     opened, an error is signalled.  If the procedure returns, then the
     port is closed automatically and the value yielded by the
     procedure is returned.  If the procedure does not return, then the
     port will not be closed automatically unless it is possible to
     prove that the port will never again be used for a read or write
     operation.

 - Scheme Procedure: call-with-output-file file proc
     PROC should be a procedure of one argument, and FILE should be a
     string naming a file.  The behaviour is unspecified if the file
     already exists. These procedures call PROC with one argument: the
     port obtained by opening the named file for input or output.  If
     the file cannot be opened, an error is signalled.  If the
     procedure returns, then the port is closed automatically and the
     value yielded by the procedure is returned.  If the procedure does
     not return, then the port will not be closed automatically unless
     it is possible to prove that the port will never again be used for
     a read or write operation.

 - Scheme Procedure: with-input-from-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a
     string naming a file.  The file must already exist. The file is
     opened for input, an input port connected to it is made the
     default value returned by `current-input-port', and the THUNK is
     called with no arguments.  When the THUNK returns, the port is
     closed and the previous default is restored.  Returns the value
     yielded by THUNK.  If an escape procedure is used to escape from
     the continuation of these procedures, their behavior is
     implementation dependent.

 - Scheme Procedure: with-output-to-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a
     string naming a file.  The effect is unspecified if the file
     already exists.  The file is opened for output, an output port
     connected to it is made the default value returned by
     `current-output-port', and the THUNK is called with no arguments.
     When the THUNK returns, the port is closed and the previous
     default is restored.  Returns the value yielded by THUNK.  If an
     escape procedure is used to escape from the continuation of these
     procedures, their behavior is implementation dependent.

 - Scheme Procedure: with-error-to-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a
     string naming a file.  The effect is unspecified if the file
     already exists.  The file is opened for output, an output port
     connected to it is made the default value returned by
     `current-error-port', and the THUNK is called with no arguments.
     When the THUNK returns, the port is closed and the previous
     default is restored.  Returns the value yielded by THUNK.  If an
     escape procedure is used to escape from the continuation of these
     procedures, their behavior is implementation dependent.

 - Scheme Procedure: port-mode port
 - C Function: scm_port_mode (port)
     Return the port modes associated with the open port PORT.  These
     will not necessarily be identical to the modes used when the port
     was opened, since modes such as "append" which are used only
     during port creation are not retained.

 - Scheme Procedure: port-filename port
 - C Function: scm_port_filename (port)
     Return the filename associated with PORT.  This function returns
     the strings "standard input", "standard output" and "standard
     error" when called on the current input, output and error ports
     respectively.

 - Scheme Procedure: set-port-filename! port filename
 - C Function: scm_set_port_filename_x (port, filename)
     Change the filename associated with PORT, using the current input
     port if none is specified.  Note that this does not change the
     port's source of data, but only the value that is returned by
     `port-filename' and reported in diagnostic output.

 - Scheme Procedure: file-port? obj
 - C Function: scm_file_port_p (obj)
     Determine whether OBJ is a port that is related to a file.


File: guile.info,  Node: String Ports,  Next: Soft Ports,  Prev: File Ports,  Up: Port Types

String Ports
------------

   The following allow string ports to be opened by analogy to R4R*
file port facilities:

 - Scheme Procedure: call-with-output-string proc
 - C Function: scm_call_with_output_string (proc)
     Calls the one-argument procedure PROC with a newly created output
     port.  When the function returns, the string composed of the
     characters written into the port is returned.

 - Scheme Procedure: call-with-input-string string proc
 - C Function: scm_call_with_input_string (string, proc)
     Calls the one-argument procedure PROC with a newly created input
     port from which STRING's contents may be read.  The value yielded
     by the PROC is returned.

 - Scheme Procedure: with-output-to-string thunk
     Calls the zero-argument procedure THUNK with the current output
     port set temporarily to a new string port.  It returns a string
     composed of the characters written to the current output.

 - Scheme Procedure: with-input-from-string string thunk
     Calls the zero-argument procedure THUNK with the current input
     port set temporarily to a string port opened on the specified
     STRING.  The value yielded by THUNK is returned.

 - Scheme Procedure: open-input-string str
 - C Function: scm_open_input_string (str)
     Take a string and return an input port that delivers characters
     from the string. The port can be closed by `close-input-port',
     though its storage will be reclaimed by the garbage collector if
     it becomes inaccessible.

 - Scheme Procedure: open-output-string
 - C Function: scm_open_output_string ()
     Return an output port that will accumulate characters for
     retrieval by `get-output-string'. The port can be closed by the
     procedure `close-output-port', though its storage will be
     reclaimed by the garbage collector if it becomes inaccessible.

 - Scheme Procedure: get-output-string port
 - C Function: scm_get_output_string (port)
     Given an output port created by `open-output-string', return a
     string consisting of the characters that have been output to the
     port so far.

   A string port can be used in many procedures which accept a port but
which are not dependent on implementation details of fports.  E.g.,
seeking and truncating will work on a string port, but trying to
extract the file descriptor number will fail.


File: guile.info,  Node: Soft Ports,  Next: Void Ports,  Prev: String Ports,  Up: Port Types

Soft Ports
----------

   A "soft-port" is a port based on a vector of procedures capable of
accepting or delivering characters.  It allows emulation of I/O ports.

 - Scheme Procedure: make-soft-port pv modes
 - C Function: scm_make_soft_port (pv, modes)
     Return a port capable of receiving or delivering characters as
     specified by the MODES string (*note open-file: File Ports.).  PV
     must be a vector of length 5.  Its components are as follows:

       0. procedure accepting one character for output

       1. procedure accepting a string for output

       2. thunk for flushing output

       3. thunk for getting one character

       4. thunk for closing port (not by garbage collection)

     For an output-only port only elements 0, 1, 2, and 4 need be
     procedures.  For an input-only port only elements 3 and 4 need be
     procedures.  Thunks 2 and 4 can instead be `#f' if there is no
     useful operation for them to perform.

     If thunk 3 returns `#f' or an `eof-object' (*note eof-object?:
     (r5rs)Input.) it indicates that the port has reached end-of-file.
     For example:

          (define stdout (current-output-port))
          (define p (make-soft-port
                     (vector
                      (lambda (c) (write c stdout))
                      (lambda (s) (display s stdout))
                      (lambda () (display "." stdout))
                      (lambda () (char-upcase (read-char)))
                      (lambda () (display "@" stdout)))
                     "rw"))
          
          (write p p) => #<input-output: soft 8081e20>


File: guile.info,  Node: Void Ports,  Prev: Soft Ports,  Up: Port Types

Void Ports
----------

   This kind of port causes any data to be discarded when written to,
and always returns the end-of-file object when read from.

 - Scheme Procedure: %make-void-port mode
 - C Function: scm_sys_make_void_port (mode)
     Create and return a new void port.  A void port acts like
     `/dev/null'.  The MODE argument specifies the input/output modes
     for this port: see the documentation for `open-file' in *Note File
     Ports::.


File: guile.info,  Node: I/O Extensions,  Prev: Port Types,  Up: Input and Output

Using and Extending Ports in C
==============================

* Menu:

* C Port Interface:: Using ports from C.
* Port Implementation:: How to implement a new port type in C.

