Go to the first, previous, next, last section, table of contents.


Textual Conversion Packages

Precedence Parsing

(require 'precedence-parse) or (require 'parse)

This package implements:

Precedence Parsing Overview

This package offers improvements over previous parsers.

Here are the higher-level syntax types and an example of each. Precedence considerations are omitted for clarity. See section Grammar Rule Definition for full details.

Grammar: nofix bye exit
bye

calls the function exit with no arguments.

Grammar: prefix - negate
- 42

Calls the function negate with the argument 42.

Grammar: infix - difference
x - y

Calls the function difference with arguments x and y.

Grammar: nary + sum
x + y + z

Calls the function sum with arguments x, y, and y.

Grammar: postfix ! factorial
5 !

Calls the function factorial with the argument 5.

Grammar: prestfix set set!
set foo bar

Calls the function set! with the arguments foo and bar.

Grammar: commentfix /* */
/* almost any text here */

Ignores the comment delimited by /* and */.

Grammar: matchfix { list }
{0, 1, 2}

Calls the function list with the arguments 0, 1, and 2.

Grammar: inmatchfix ( funcall )
f(x, y)

Calls the function funcall with the arguments f, x, and y.

Grammar: delim ;
set foo bar;

delimits the extent of the restfix operator set.

Ruleset Definition and Use

Variable: *syn-defs*
A grammar is built by one or more calls to prec:define-grammar. The rules are appended to *syn-defs*. The value of *syn-defs* is the grammar suitable for passing as an argument to prec:parse.

Constant: *syn-ignore-whitespace*
Is a nearly empty grammar with whitespace characters set to group 0, which means they will not be made into tokens. Most rulesets will want to start with *syn-ignore-whitespace*

In order to start defining a grammar, either

(set! *syn-defs* '())

or

(set! *syn-defs* *syn-ignore-whitespace*)

Function: prec:define-grammar rule1 ...
Appends rule1 ... to *syn-defs*. prec:define-grammar is used to define both the character classes and rules for tokens.

Once your grammar is defined, save the value of *syn-defs* in a variable (for use when calling prec:parse).

(define my-ruleset *syn-defs*)

Function: prec:parse ruleset delim
Function: prec:parse ruleset delim port
The ruleset argument must be a list of rules as constructed by prec:define-grammar and extracted from *syn-defs*.

The token delim may be a character, symbol, or string. A character delim argument will match only a character token; i.e. a character for which no token-group is assigned. A symbols or string will match only a token string; i.e. a token resulting from a token group.

prec:parse reads a ruleset grammar expression delimited by delim from the given input port. prec:parse returns the next object parsable from the given input port, updating port to point to the first character past the end of the external representation of the object.

If an end of file is encountered in the input before any characters are found that can begin an object, then an end of file object is returned. If a delimiter (such as delim) is found before any characters are found that can begin an object, then #f is returned.

The port argument may be omitted, in which case it defaults to the value returned by current-input-port. It is an error to parse from a closed port.

Token definition

Function: tok:char-group group chars chars-proc
The argument chars may be a single character, a list of characters, or a string. Each character in chars is treated as though tok:char-group was called with that character alone.

The argument chars-proc must be a procedure of one argument, a list of characters. After tokenize has finished accumulating the characters for a token, it calls chars-proc with the list of characters. The value returned is the token which tokenize returns.

The argument group may be an exact integer or a procedure of one character argument. The following discussion concerns the treatment which the tokenizing routine, tokenize, will accord to characters on the basis of their groups.

When group is a non-zero integer, characters whose group number is equal to or exactly one less than group will continue to accumulate. Any other character causes the accumulation to stop (until a new token is to be read).

The group of zero is special. These characters are ignored when parsed pending a token, and stop the accumulation of token characters when the accumulation has already begun. Whitespace characters are usually put in group 0.

If group is a procedure, then, when triggerd by the occurence of an initial (no accumulation) chars character, this procedure will be repeatedly called with each successive character from the input stream until the group procedure returns a non-false value.

The following convenient constants are provided for use with tok:char-group.

Constant: tok:decimal-digits
Is the string "0123456789".
Constant: tok:upper-case
Is the string consisting of all upper-case letters ("ABCDEFGHIJKLMNOPQRSTUVWXYZ").
Constant: tok:lower-case
Is the string consisting of all lower-case letters ("abcdefghijklmnopqrstuvwxyz").
Constant: tok:whitespaces
Is the string consisting of all characters between 0 and 255 for which char-whitespace? returns true.

Nud and Led Definition

This section describes advanced features. You can skip this section on first reading.

The Null Denotation (or nud) of a token is the procedure and arguments applying for that token when Left, an unclaimed parsed expression is not extant.

The Left Denotation (or led) of a token is the procedure, arguments, and lbp applying for that token when there is a Left, an unclaimed parsed expression.

In his paper,

Pratt, V. R. Top Down Operator Precendence. SIGACT/SIGPLAN Symposium on Principles of Programming Languages, Boston, 1973, pages 41-51

the left binding power (or lbp) was an independent property of tokens. I think this was done in order to allow tokens with NUDs but not LEDs to also be used as delimiters, which was a problem for statically defined syntaxes. It turns out that dynamically binding NUDs and LEDs allows them independence.

For the rule-defining procedures that follow, the variable tk may be a character, string, or symbol, or a list composed of characters, strings, and symbols. Each element of tk is treated as though the procedure were called for each element.

Character tk arguments will match only character tokens; i.e. characters for which no token-group is assigned. Symbols and strings will both match token strings; i.e. tokens resulting from token groups.

Function: prec:make-nud tk sop arg1 ...
Returns a rule specifying that sop be called when tk is parsed. If sop is a procedure, it is called with tk and arg1 ... as its arguments; the resulting value is incorporated into the expression being built. Otherwise, (list sop arg1 ...) is incorporated.

If no NUD has been defined for a token; then if that token is a string, it is converted to a symbol and returned; if not a string, the token is returned.

Function: prec:make-led tk sop arg1 ...
Returns a rule specifying that sop be called when tk is parsed and left has an unclaimed parsed expression. If sop is a procedure, it is called with left, tk, and arg1 ... as its arguments; the resulting value is incorporated into the expression being built. Otherwise, left is incorporated.

If no LED has been defined for a token, and left is set, the parser issues a warning.

Grammar Rule Definition

Here are procedures for defining rules for the syntax types introduced in section Precedence Parsing Overview.

For the rule-defining procedures that follow, the variable tk may be a character, string, or symbol, or a list composed of characters, strings, and symbols. Each element of tk is treated as though the procedure were called for each element.

For procedures prec:delim, ..., prec:prestfix, if the sop argument is #f, then the token which triggered this rule is converted to a symbol and returned. A false sop argument to the procedures prec:commentfix, prec:matchfix, or prec:inmatchfix has a different meaning.

Character tk arguments will match only character tokens; i.e. characters for which no token-group is assigned. Symbols and strings will both match token strings; i.e. tokens resulting from token groups.

Function: prec:delim tk
Returns a rule specifying that tk should not be returned from parsing; i.e. tk's function is purely syntactic. The end-of-file is always treated as a delimiter.

Function: prec:nofix tk sop
Returns a rule specifying the following actions take place when tk is parsed:

Function: prec:prefix tk sop bp rule1 ...
Returns a rule specifying the following actions take place when tk is parsed:

Function: prec:infix tk sop lbp bp rule1 ...
Returns a rule declaring the left-binding-precedence of the token tk is lbp and specifying the following actions take place when tk is parsed:

Function: prec:nary tk sop bp
Returns a rule declaring the left-binding-precedence of the token tk is bp and specifying the following actions take place when tk is parsed:

Function: prec:postfix tk sop lbp
Returns a rule declaring the left-binding-precedence of the token tk is lbp and specifying the following actions take place when tk is parsed:

Function: prec:prestfix tk sop bp rule1 ...
Returns a rule specifying the following actions take place when tk is parsed:

Function: prec:commentfix tk stp match rule1 ...
Returns rules specifying the following actions take place when tk is parsed:

Parsing of commentfix syntax differs from the others in several ways. It reads directly from input without tokenizing; It calls stp but does not return its value; nay any value. I added the stp argument so that comment text could be echoed.

Function: prec:matchfix tk sop sep match rule1 ...
Returns a rule specifying the following actions take place when tk is parsed:

Function: prec:inmatchfix tk sop sep match lbp rule1 ...
Returns a rule declaring the left-binding-precedence of the token tk is lbp and specifying the following actions take place when tk is parsed:

Format (version 3.0)

(require 'format)

Format Interface

Function: format destination format-string . arguments
An almost complete implementation of Common LISP format description according to the CL reference book Common LISP from Guy L. Steele, Digital Press. Backward compatible to most of the available Scheme format implementations.

Returns #t, #f or a string; has side effect of printing according to format-string. If destination is #t, the output is to the current output port and #t is returned. If destination is #f, a formatted string is returned as the result of the call. NEW: If destination is a string, destination is regarded as the format string; format-string is then the first argument and the output is returned as a string. If destination is a number, the output is to the current error port if available by the implementation. Otherwise destination must be an output port and #t is returned.

format-string must be a string. In case of a formatting error format returns #f and prints a message on the current output or error port. Characters are output as if the string were output by the display function with the exception of those prefixed by a tilde (~). For a detailed description of the format-string syntax please consult a Common LISP format reference manual. For a test suite to verify this format implementation load `formatst.scm'. Please send bug reports to lutzeb@cs.tu-berlin.de.

Note: format is not reentrant, i.e. only one format-call may be executed at a time.

Format Specification (Format version 3.0)

Please consult a Common LISP format reference manual for a detailed description of the format string syntax. For a demonstration of the implemented directives see `formatst.scm'.

This implementation supports directive parameters and modifiers (: and @ characters). Multiple parameters must be separated by a comma (,). Parameters can be numerical parameters (positive or negative), character parameters (prefixed by a quote character ('), variable parameters (v), number of rest arguments parameter (#), empty and default parameters. Directive characters are case independent. The general form of a directive is:

directive ::= ~{directive-parameter,}[:][@]directive-character

directive-parameter ::= [ [-|+]{0-9}+ | 'character | v | # ]

Implemented CL Format Control Directives

Documentation syntax: Uppercase characters represent the corresponding control directive characters. Lowercase characters represent control directive parameter descriptions.

~A
Any (print as display does).
~@A
left pad.
~mincol,colinc,minpad,padcharA
full padding.
~S
S-expression (print as write does).
~@S
left pad.
~mincol,colinc,minpad,padcharS
full padding.
~D
Decimal.
~@D
print number sign always.
~:D
print comma separated.
~mincol,padchar,commacharD
padding.
~X
Hexadecimal.
~@X
print number sign always.
~:X
print comma separated.
~mincol,padchar,commacharX
padding.
~O
Octal.
~@O
print number sign always.
~:O
print comma separated.
~mincol,padchar,commacharO
padding.
~B
Binary.
~@B
print number sign always.
~:B
print comma separated.
~mincol,padchar,commacharB
padding.
~nR
Radix n.
~n,mincol,padchar,commacharR
padding.
~@R
print a number as a Roman numeral.
~:@R
print a number as an "old fashioned" Roman numeral.
~:R
print a number as an ordinal English number.
~:@R
print a number as a cardinal English number.
~P
Plural.
~@P
prints y and ies.
~:P
as ~P but jumps 1 argument backward.
~:@P
as ~@P but jumps 1 argument backward.
~C
Character.
~@C
prints a character as the reader can understand it (i.e. #\ prefixing).
~:C
prints a character as emacs does (eg. ^C for ASCII 03).
~F
Fixed-format floating-point (prints a flonum like mmm.nnn).
~width,digits,scale,overflowchar,padcharF
~@F
If the number is positive a plus sign is printed.
~E
Exponential floating-point (prints a flonum like mmm.nnnEee).
~width,digits,exponentdigits,scale,overflowchar,padchar,exponentcharE
~@E
If the number is positive a plus sign is printed.
~G
General floating-point (prints a flonum either fixed or exponential).
~width,digits,exponentdigits,scale,overflowchar,padchar,exponentcharG
~@G
If the number is positive a plus sign is printed.
~$
Dollars floating-point (prints a flonum in fixed with signs separated).
~digits,scale,width,padchar$
~@$
If the number is positive a plus sign is printed.
~:@$
A sign is always printed and appears before the padding.
~:$
The sign appears before the padding.
~%
Newline.
~n%
print n newlines.
~&
print newline if not at the beginning of the output line.
~n&
prints ~& and then n-1 newlines.
~|
Page Separator.
~n|
print n page separators.
~~
Tilde.
~n~
print n tildes.
~<newline>
Continuation Line.
~:<newline>
newline is ignored, white space left.
~@<newline>
newline is left, white space ignored.
~T
Tabulation.
~@T
relative tabulation.
~colnum,colincT
full tabulation.
~?
Indirection (expects indirect arguments as a list).
~@?
extracts indirect arguments from format arguments.
~(str~)
Case conversion (converts by string-downcase).
~:(str~)
converts by string-capitalize.
~@(str~)
converts by string-capitalize-first.
~:@(str~)
converts by string-upcase.
~*
Argument Jumping (jumps 1 argument forward).
~n*
jumps n arguments forward.
~:*
jumps 1 argument backward.
~n:*
jumps n arguments backward.
~@*
jumps to the 0th argument.
~n@*
jumps to the nth argument (beginning from 0)
~[str0~;str1~;...~;strn~]
Conditional Expression (numerical clause conditional).
~n[
take argument from n.
~@[
true test conditional.
~:[
if-else-then conditional.
~;
clause separator.
~:;
default clause follows.
~{str~}
Iteration (args come from the next argument (a list)).
~n{
at most n iterations.
~:{
args from next arg (a list of lists).
~@{
args from the rest of arguments.
~:@{
args from the rest args (lists).
~^
Up and out.
~n^
aborts if n = 0
~n,m^
aborts if n = m
~n,m,k^
aborts if n <= m <= k

Not Implemented CL Format Control Directives

~:A
print #f as an empty list (see below).
~:S
print #f as an empty list (see below).
~<~>
Justification.
~:^
(sorry I don't understand its semantics completely)

Extended, Replaced and Additional Control Directives

~mincol,padchar,commachar,commawidthD
~mincol,padchar,commachar,commawidthX
~mincol,padchar,commachar,commawidthO
~mincol,padchar,commachar,commawidthB
~n,mincol,padchar,commachar,commawidthR
commawidth is the number of characters between two comma characters.
~I
print a R4RS complex number as ~F~@Fi with passed parameters for ~F.
~Y
Pretty print formatting of an argument for scheme code lists.
~K
Same as ~?.
~!
Flushes the output if format destination is a port.
~_
Print a #\space character
~n_
print n #\space characters.
~/
Print a #\tab character
~n/
print n #\tab characters.
~nC
Takes n as an integer representation for a character. No arguments are consumed. n is converted to a character by integer->char. n must be a positive decimal number.
~:S
Print out readproof. Prints out internal objects represented as #<...> as strings "#<...>" so that the format output can always be processed by read.
~:A
Print out readproof. Prints out internal objects represented as #<...> as strings "#<...>" so that the format output can always be processed by read.
~Q
Prints information and a copyright notice on the format implementation.
~:Q
prints format version.
~F, ~E, ~G, ~$
may also print number strings, i.e. passing a number as a string and format it accordingly.

Configuration Variables

Format has some configuration variables at the beginning of `format.scm' to suit the systems and users needs. There should be no modification necessary for the configuration that comes with SLIB. If modification is desired the variable should be set after the format code is loaded. Format detects automatically if the running scheme system implements floating point numbers and complex numbers.

format:symbol-case-conv
Symbols are converted by symbol->string so the case type of the printed symbols is implementation dependent. format:symbol-case-conv is a one arg closure which is either #f (no conversion), string-upcase, string-downcase or string-capitalize. (default #f)
format:iobj-case-conv
As format:symbol-case-conv but applies for the representation of implementation internal objects. (default #f)
format:expch
The character prefixing the exponent value in ~E printing. (default #\E)

Compatibility With Other Format Implementations

SLIB format 2.x:
See `format.doc'.
SLIB format 1.4:
Downward compatible except for padding support and ~A, ~S, ~P, ~X uppercase printing. SLIB format 1.4 uses C-style printf padding support which is completely replaced by the CL format padding style.
MIT C-Scheme 7.1:
Downward compatible except for ~, which is not documented (ignores all characters inside the format string up to a newline character). (7.1 implements ~a, ~s, ~newline, ~~, ~%, numerical and variable parameters and :/@ modifiers in the CL sense).
Elk 1.5/2.0:
Downward compatible except for ~A and ~S which print in uppercase. (Elk implements ~a, ~s, ~~, and ~% (no directive parameters or modifiers)).
Scheme->C 01nov91:
Downward compatible except for an optional destination parameter: S2C accepts a format call without a destination which returns a formatted string. This is equivalent to a #f destination in S2C. (S2C implements ~a, ~s, ~c, ~%, and ~~ (no directive parameters or modifiers)).

This implementation of format is solely useful in the SLIB context because it requires other components provided by SLIB.

Standard Formatted I/O

stdio

(require 'stdio)

requires printf and scanf and additionally defines the symbols:

Variable: stdin
Defined to be (current-input-port).
Variable: stdout
Defined to be (current-output-port).
Variable: stderr
Defined to be (current-error-port).

Standard Formatted Output

(require 'printf)

Procedure: printf format arg1 ...
Procedure: fprintf port format arg1 ...
Procedure: sprintf str format arg1 ...
Procedure: sprintf #f format arg1 ...
Procedure: sprintf k format arg1 ...

Each function converts, formats, and outputs its arg1 ... arguments according to the control string format argument and returns the number of characters output.

printf sends its output to the port (current-output-port). fprintf sends its output to the port port. sprintf string-set!s locations of the non-constant string argument str to the output characters.

Two extensions of sprintf return new strings. If the first argument is #f, then the returned string's length is as many characters as specified by the format and data; if the first argument is a non-negative integer k, then the length of the returned string is also bounded by k.

The string format contains plain characters which are copied to the output stream, and conversion specifications, each of which results in fetching zero or more of the arguments arg1 .... The results are undefined if there are an insufficient number of arguments for the format. If format is exhausted while some of the arg1 ... arguments remain unused, the excess arg1 ... arguments are ignored.

The conversion specifications in a format string have the form:

% [ flags ] [ width ] [ . precision ] [ type ] conversion

An output conversion specifications consist of an initial `%' character followed in sequence by:

Exact Conversions

`d', `i'
Print an integer as a signed decimal number. `%d' and `%i' are synonymous for output, but are different when used with scanf for input (see section Standard Formatted Input).
`o'
Print an integer as an unsigned octal number.
`u'
Print an integer as an unsigned decimal number.
`x', `X'
Print an integer as an unsigned hexadecimal number. `%x' prints using the digits `0123456789abcdef'. `%X' prints using the digits `0123456789ABCDEF'.

Inexact Conversions

`f'
Print a floating-point number in fixed-point notation.
`e', `E'
Print a floating-point number in exponential notation. `%e' prints `e' between mantissa and exponont. `%E' prints `E' between mantissa and exponont.
`g', `G'
Print a floating-point number in either normal or exponential notation, whichever is more appropriate for its magnitude. Unless an `#' flag has been supplied trailing zeros after a decimal point will be stripped off. `%g' prints `e' between mantissa and exponont. `%G' prints `E' between mantissa and exponent.

Other Conversions

`c'
Print a single character. The `-' flag is the only one which can be specified. It is an error to specify a precision.
`s'
Print a string. The `-' flag is the only one which can be specified. A precision specifies the maximum number of characters to output; otherwise all characters in the string are output.
`a', `A'
Print a scheme expression. The `-' flag left-justifies the output. The `#' flag specifies that strings and characters should be quoted as by write (which can be read using read); otherwise, output is as display prints. A precision specifies the maximum number of characters to output; otherwise as many characters as needed are output. Note: `%a' and `%A' are SLIB extensions.
`%'
Print a literal `%' character. No argument is consumed. It is an error to specifiy flags, field width, precision, or type modifiers with `%%'.

Standard Formatted Input

(require 'scanf)

Function: scanf-read-list format
Function: scanf-read-list format port
Function: scanf-read-list format string

Macro: scanf format arg1 ...
Macro: fscanf port format arg1 ...
Macro: sscanf str format arg1 ...

Each function reads characters, interpreting them according to the control string format argument.

scanf-read-list returns a list of the items specified as far as the input matches format. scanf, fscanf, and sscanf return the number of items successfully matched and stored. scanf, fscanf, and sscanf also set the location corresponding to arg1 ... using the methods:

symbol
set!
car expression
set-car!
cdr expression
set-cdr!
vector-ref expression
vector-set!
substring expression
substring-move-left!

The argument to a substring expression in arg1 ... must be a non-constant string. Characters will be stored starting at the position specified by the second argument to substring. The number of characters stored will be limited by either the position specified by the third argument to substring or the length of the matched string, whichever is less.

The control string, format, contains conversion specifications and other characters used to direct interpretation of input sequences. The control string contains:

Unless the specification contains the `n' conversion character (described below), a conversion specification directs the conversion of the next input field. The result of a conversion specification is returned in the position of the corresponding argument points, unless `*' indicates assignment suppression. Assignment suppression provides a way to describe an input field to be skipped. An input field is defined as a string of characters; it extends to the next inappropriate character or until the field width, if specified, is exhausted.

Note: This specification of format strings differs from the ANSI C and POSIX specifications. In SLIB, white space before an input field is not skipped unless white space appears before the conversion specification in the format string. In order to write format strings which work identically with ANSI C and SLIB, prepend whitespace to all conversion specifications except `[' and `c'.

The conversion code indicates the interpretation of the input field; For a suppressed field, no value is returned. The following conversion codes are legal:

`%'
A single % is expected in the input at this point; no value is returned.
`d', `D'
A decimal integer is expected.
`u', `U'
An unsigned decimal integer is expected.
`o', `O'
An octal integer is expected.
`x', `X'
A hexadecimal integer is expected.
`i'
An integer is expected. Returns the value of the next input item, interpreted according to C conventions; a leading `0' implies octal, a leading `0x' implies hexadecimal; otherwise, decimal is assumed.
`n'
Returns the total number of bytes (including white space) read by scanf. No input is consumed by %n.
`f', `F', `e', `E', `g', `G'
A floating-point number is expected. The input format for floating-point numbers is an optionally signed string of digits, possibly containing a radix character `.', followed by an optional exponent field consisting of an `E' or an `e', followed by an optional `+', `-', or space, followed by an integer.
`c', `C'
Width characters are expected. The normal skip-over-white-space is suppressed in this case; to read the next non-space character, use `%1s'. If a field width is given, a string is returned; up to the indicated number of characters is read.
`s', `S'
A character string is expected The input field is terminated by a white-space character. scanf cannot read a null string.
`['
Indicates string data and the normal skip-over-leading-white-space is suppressed. The left bracket is followed by a set of characters, called the scanset, and a right bracket; the input field is the maximal sequence of input characters consisting entirely of characters in the scanset. `^', when it appears as the first character in the scanset, serves as a complement operator and redefines the scanset as the set of all characters not contained in the remainder of the scanset string. Construction of the scanset follows certain conventions. A range of characters may be represented by the construct first-last, enabling `[0123456789]' to be expressed `[0-9]'. Using this convention, first must be lexically less than or equal to last; otherwise, the dash stands for itself. The dash also stands for itself when it is the first or the last character in the scanset. To include the right square bracket as an element of the scanset, it must appear as the first character (possibly preceded by a `^') of the scanset, in which case it will not be interpreted syntactically as the closing bracket. At least one character must match for this conversion to succeed.

The scanf functions terminate their conversions at end-of-file, at the end of the control string, or when an input character conflicts with the control string. In the latter case, the offending character is left unread in the input stream.

Program and Arguments

Getopt

(require 'getopt)

This routine implements Posix command line argument parsing. Notice that returning values through global variables means that getopt is not reentrant.

Variable: *optind*
Is the index of the current element of the command line. It is initially one. In order to parse a new command line or reparse an old one, *opting* must be reset.

Variable: *optarg*
Is set by getopt to the (string) option-argument of the current option.

Procedure: getopt argc argv optstring
Returns the next option letter in argv (starting from (vector-ref argv *optind*)) that matches a letter in optstring. argv is a vector or list of strings, the 0th of which getopt usually ignores. argc is the argument count, usually the length of argv. optstring is a string of recognized option characters; if a character is followed by a colon, the option takes an argument which may be immediately following it in the string or in the next element of argv.

*optind* is the index of the next element of the argv vector to be processed. It is initialized to 1 by `getopt.scm', and getopt updates it when it finishes with each element of argv.

getopt returns the next option character from argv that matches a character in optstring, if there is one that matches. If the option takes an argument, getopt sets the variable *optarg* to the option-argument as follows:

If, when getopt is called, the string (vector-ref argv *optind*) either does not begin with the character #\- or is just "-", getopt returns #f without changing *optind*. If (vector-ref argv *optind*) is the string "--", getopt returns #f after incrementing *optind*.

If getopt encounters an option character that is not contained in optstring, it returns the question-mark #\? character. If it detects a missing option argument, it returns the colon character #\: if the first character of optstring was a colon, or a question-mark character otherwise. In either case, getopt sets the variable getopt:opt to the option character that caused the error.

The special option "--" can be used to delimit the end of the options; #f is returned, and "--" is skipped.

RETURN VALUE

getopt returns the next option character specified on the command line. A colon #\: is returned if getopt detects a missing argument and the first character of optstring was a colon #\:.

A question-mark #\? is returned if getopt encounters an option character not in optstring or detects a missing argument and the first character of optstring was not a colon #\:.

Otherwise, getopt returns #f when all command line options have been parsed.

Example:

#! /usr/local/bin/scm
;;;This code is SCM specific.
(define argv (program-arguments))
(require 'getopt)

(define opts ":a:b:cd")
(let loop ((opt (getopt (length argv) argv opts)))
  (case opt
    ((#\a) (print "option a: " *optarg*))
    ((#\b) (print "option b: " *optarg*))
    ((#\c) (print "option c"))
    ((#\d) (print "option d"))
    ((#\?) (print "error" getopt:opt))
    ((#\:) (print "missing arg" getopt:opt))
    ((#f) (if (< *optind* (length argv))
              (print "argv[" *optind* "]="
                     (list-ref argv *optind*)))
          (set! *optind* (+ *optind* 1))))
  (if (< *optind* (length argv))
      (loop (getopt (length argv) argv opts))))

(slib:exit)

Getopt--

Function: getopt-- argc argv optstring
The procedure getopt-- is an extended version of getopt which parses long option names of the form `--hold-the-onions' and `--verbosity-level=extreme'. Getopt-- behaves as getopt except for non-empty options beginning with `--'.

Options beginning with `--' are returned as strings rather than characters. If a value is assigned (using `=') to a long option, *optarg* is set to the value. The `=' and value are not returned as part of the option string.

No information is passed to getopt-- concerning which long options should be accepted or whether such options can take arguments. If a long option did not have an argument, *optarg will be set to #f. The caller is responsible for detecting and reporting errors.

(define opts ":-:b:")
(define argc 5)
(define argv '("foo" "-b9" "--f1" "--2=" "--g3=35234.342" "--"))
(define *optind* 1)
(define *optarg* #f)
(require 'qp)
(do ((i 5 (+ -1 i)))
    ((zero? i))
  (define opt (getopt-- argc argv opts))
  (print *optind* opt *optarg*)))
-|
2 #\b "9" 
3 "f1" #f 
4 "2" "" 
5 "g3" "35234.342" 
5 #f "35234.342" 

Command Line

(require 'read-command)

Function: read-command port
Function: read-command
read-command converts a command line into a list of strings suitable for parsing by getopt. The syntax of command lines supported resembles that of popular shells. read-command updates port to point to the first character past the command delimiter.

If an end of file is encountered in the input before any characters are found that can begin an object or comment, then an end of file object is returned.

The port argument may be omitted, in which case it defaults to the value returned by current-input-port.

The fields into which the command line is split are delimited by whitespace as defined by char-whitespace?. The end of a command is delimited by end-of-file or unescaped semicolon (;) or newline. Any character can be literally included in a field by escaping it with a backslach (\).

The initial character and types of fields recognized are:

`\'
The next character has is taken literally and not interpreted as a field delimiter. If \ is the last character before a newline, that newline is just ignored. Processing continues from the characters after the newline as though the backslash and newline were not there.
`"'
The characters up to the next unescaped " are taken literally, according to [R4RS] rules for literal strings (see section `Strings' in Revised(4) Scheme).
`(', `%''
One scheme expression is read starting with this character. The read expression is evaluated, converted to a string (using display), and replaces the expression in the returned field.
`;'
Semicolon delimits a command. Using semicolons more than one command can appear on a line. Escaped semicolons and semicolons inside strings do not delimit commands.

The comment field differs from the previous fields in that it must be the first character of a command or appear after whitespace in order to be recognized. # can be part of fields if these conditions are not met. For instance, ab#c is just the field ab#c.

`#'
Introduces a comment. The comment continues to the end of the line on which the semicolon appears. Comments are treated as whitespace by read-dommand-line and backslashes before newlines in comments are also ignored.

Function: read-options-file filename
read-options-file converts an options file into a list of strings suitable for parsing by getopt. The syntax of options files is the same as the syntax for command lines, except that newlines do not terminate reading (only ; or end of file).

If an end of file is encountered before any characters are found that can begin an object or comment, then an end of file object is returned.

Parameter lists

(require 'parameters)

Arguments to procedures in scheme are distinguished from each other by their position in the procedure call. This can be confusing when a procedure takes many arguments, many of which are not often used.

A parameter-list is a way of passing named information to a procedure. Procedures are also defined to set unused parameters to default values, check parameters, and combine parameter lists.

A parameter has the form (parameter-name value1 ...). This format allows for more than one value per parameter-name.

A parameter-list is a list of parameters, each with a different parameter-name.

Function: make-parameter-list parameter-names
Returns an empty parameter-list with slots for parameter-names.

Function: parameter-list-ref parameter-list parameter-name
parameter-name must name a valid slot of parameter-list. parameter-list-ref returns the value of parameter parameter-name of parameter-list.

Procedure: adjoin-parameters! parameter-list parameter1 ...
Returns parameter-list with parameter1 ... merged in.

Procedure: parameter-list-expand expanders parameter-list
expanders is a list of procedures whose order matches the order of the parameter-names in the call to make-parameter-list which created parameter-list. For each non-false element of expanders that procedure is mapped over the corresponding parameter value and the returned parameter lists are merged into parameter-list.

This process is repeated until parameter-list stops growing. The value returned from parameter-list-expand is unspecified.

Function: fill-empty-parameters defaulters parameter-list
defaulters is a list of procedures whose order matches the order of the parameter-names in the call to make-parameter-list which created parameter-list. fill-empty-parameters returns a new parameter-list with each empty parameter replaced with the list returned by calling the corresponding defaulter with parameter-list as its argument.

Function: check-parameters checks parameter-list
checks is a list of procedures whose order matches the order of the parameter-names in the call to make-parameter-list which created parameter-list.

check-parameters returns parameter-list if each check of the corresponding parameter-list returns non-false. If some check returns #f an error is signaled.

In the following procedures arities is a list of symbols. The elements of arities can be:

single
Requires a single parameter.
optional
A single parameter or no parameter is acceptable.
boolean
A single boolean parameter or zero parameters is acceptable.
nary
Any number of parameters are acceptable.
nary1
One or more of parameters are acceptable.

Function: parameter-list->arglist positions arities types parameter-list
Returns parameter-list converted to an argument list. Parameters of arity type single and boolean are converted to the single value associated with them. The other arity types are converted to lists of the value(s) of type types.

positions is a list of positive integers whose order matches the order of the parameter-names in the call to make-parameter-list which created parameter-list. The integers specify in which argument position the corresponding parameter should appear.

Getopt Parameter lists

(require 'getopt-parameters)

Function: getopt->parameter-list argc argv optnames arities types aliases
Returns argv converted to a parameter-list. optnames are the parameter-names. aliases is a list of lists of strings and elements of optnames. Each of these strings which have length of 1 will be treated as a single - option by getopt. Longer strings will be treated as long-named options (see section Getopt).

Function: getopt->arglist argc argv optnames positions arities types defaulters checks aliases
Like getopt->parameter-list, but converts argv to an argument-list as specified by optnames, positions, arities, types, defaulters, checks, and aliases.

These getopt functions can be used with SLIB relational databases. For an example, See section Database Utilities.

If errors are encountered while processing options, directions for using the options are printed to current-error-port.

(begin
  (set! *optind* 1)
  (getopt->parameter-list
   2
   '("cmd" "-?")
   '(flag number symbols symbols string flag2 flag3 num2 num3)
   '(boolean optional nary1 nary single boolean boolean nary nary)
   '(boolean integer symbol symbol string boolean boolean integer integer)
   '(("flag" flag)
     ("f" flag)
     ("Flag" flag2)
     ("B" flag3)
     ("optional" number)
     ("o" number)
     ("nary1" symbols)
     ("N" symbols)
     ("nary" symbols)
     ("n" symbols)
     ("single" string)
     ("s" string)
     ("a" num2)
     ("Abs" num3))))
-|
Usage: cmd [OPTION ARGUMENT ...] ...

  -f, --flag 
  -o, --optional=<number> 
  -n, --nary=<symbols> ...
  -N, --nary1=<symbols> ...
  -s, --single=<string> 
      --Flag 
  -B        
  -a        <num2> ...
      --Abs=<num3> ...

ERROR: getopt->parameter-list "unrecognized option" "-?"

Filenames

(require 'filename) or (require 'glob)

Function: filename:match?? pattern
Function: filename:match-ci?? pattern
Returns a predicate which returns true if its string argument matches (the string) pattern, false otherwise. Filename matching is like glob expansion described the bash manpage, except that names beginning with `.' are matched and `/' characters are not treated specially.

These functions interpret the following characters specially in pattern strings:

`*'
Matches any string, including the null string.
`?'
Matches any single character.
`[...]'
Matches any one of the enclosed characters. A pair of characters separated by a minus sign (-) denotes a range; any character lexically between those two characters, inclusive, is matched. If the first character following the `[' is a `!' or a `^' then any character not enclosed is matched. A `-' or `]' may be matched by including it as the first or last character in the set.


Function: replace-suffix str old new
str can be a string or a list of strings. Returns a new string (or strings) similar to str but with the suffix string old removed and the suffix string new appended. If the end of str does not match old, an error is signaled.

(replace-suffix "/usr/local/lib/slib/batch.scm" ".scm" ".c")
=> "/usr/local/lib/slib/batch.c"

Batch

(require 'batch)

The batch procedures provide a way to write and execute portable scripts for a variety of operating systems. Each batch: procedure takes as its first argument a parameter-list (see section Parameter lists). This parameter-list argument parms contains named associations. Batch currently uses 2 of these:

batch-port
The port on which to write lines of the batch file.
batch-dialect
The syntax of batch file to generate. Currently supported are:

`batch.scm' uses 2 enhanced relational tables (see section Database Utilities) to store information linking the names of operating-systems to batch-dialectes.

Function: batch:initialize! database
Defines operating-system and batch-dialect tables and adds the domain operating-system to the enhanced relational database database.

Variable: batch:platform
Is batch's best guess as to which operating-system it is running under. batch:platform is set to (software-type) (see section Configuration) unless (software-type) is unix, in which case finer distinctions are made.

Function: batch:call-with-output-script parms file proc
proc should be a procedure of one argument. If file is an output-port, batch:call-with-output-script writes an appropriate header to file and then calls proc with file as the only argument. If file is a string, batch:call-with-output-script opens a output-file of name file, writes an appropriate header to file, and then calls proc with the newly opened port as the only argument. Otherwise, batch:call-with-output-script acts as if it was called with the result of (current-output-port) as its third argument.

Function: batch:apply-chop-to-fit proc arg1 arg2 ... list
The procedure proc must accept at least one argument and return #t if successful, #f if not. batch:apply-chop-to-fit calls proc with arg1, arg2, ..., and chunk, where chunk is a subset of list. batch:apply-chop-to-fit tries proc with successively smaller subsets of list until either proc returns non-false, or the chunks become empty.

The rest of the batch: procedures write (or execute if batch-dialect is system) commands to the batch port which has been added to parms or (copy-tree parms) by the code:

(adjoin-parameters! parms (list 'batch-port port))

Function: batch:system parms string1 string2 ...
Calls batch:try-system (below) with arguments, but signals an error if batch:try-system returns #f.

These functions return a non-false value if the command was successfully translated into the batch dialect and #f if not. In the case of the system dialect, the value is non-false if the operation suceeded.

Function: batch:try-system parms string1 string2 ...
Writes a command to the batch-port in parms which executes the program named string1 with arguments string2 ....

Function: batch:run-script parms string1 string2 ...
Writes a command to the batch-port in parms which executes the batch script named string1 with arguments string2 ....

Note: batch:run-script and batch:try-system are not the same for some operating systems (VMS).

Function: batch:comment parms line1 ...
Writes comment lines line1 ... to the batch-port in parms.

Function: batch:lines->file parms file line1 ...
Writes commands to the batch-port in parms which create a file named file with contents line1 ....

Function: batch:delete-file parms file
Writes a command to the batch-port in parms which deletes the file named file.

Function: batch:rename-file parms old-name new-name
Writes a command to the batch-port in parms which renames the file old-name to new-name.

In addition, batch provides some small utilities very useful for writing scripts:

Function: truncate-up-to path char
Function: truncate-up-to path string
Function: truncate-up-to path charlist
path can be a string or a list of strings. Returns path sans any prefixes ending with a character of the second argument. This can be used to derive a filename moved locally from elsewhere.

(truncate-up-to "/usr/local/lib/slib/batch.scm" "/")
=> "batch.scm"

Function: string-join joiner string1 ...
Returns a new string consisting of all the strings string1 ... in order appended together with the string joiner between each adjacent pair.

Function: must-be-first list1 list2
Returns a new list consisting of the elements of list2 ordered so that if some elements of list1 are equal? to elements of list2, then those elements will appear first and in the order of list1.

Function: must-be-last list1 list2
Returns a new list consisting of the elements of list1 ordered so that if some elements of list2 are equal? to elements of list1, then those elements will appear last and in the order of list2.

Function: os->batch-dialect osname
Returns its best guess for the batch-dialect to be used for the operating-system named osname. os->batch-dialect uses the tables added to database by batch:initialize!.

Here is an example of the use of most of batch's procedures:

(require 'database-utilities)
(require 'parameters)
(require 'batch)
(require 'glob)

(define batch (create-database #f 'alist-table))
(batch:initialize! batch)

(define my-parameters
  (list (list 'batch-dialect (os->batch-dialect batch:platform))
        (list 'platform batch:platform)
        (list 'batch-port (current-output-port)))) ;gets filled in later

(batch:call-with-output-script
 my-parameters
 "my-batch"
 (lambda (batch-port)
   (adjoin-parameters! my-parameters (list 'batch-port batch-port))
   (and
    (batch:comment my-parameters
                   "================ Write file with C program.")
    (batch:rename-file my-parameters "hello.c" "hello.c~")
    (batch:lines->file my-parameters "hello.c"
                       "#include <stdio.h>"
                       "int main(int argc, char **argv)"
                       "{"
                       "  printf(\"hello world\\n\");"
                       "  return 0;"
                       "}" )
    (batch:system my-parameters "cc" "-c" "hello.c")
    (batch:system my-parameters "cc" "-o" "hello"
                  (replace-suffix "hello.c" ".c" ".o"))
    (batch:system my-parameters "hello")
    (batch:delete-file my-parameters "hello")
    (batch:delete-file my-parameters "hello.c")
    (batch:delete-file my-parameters "hello.o")
    (batch:delete-file my-parameters "my-batch")
    )))

Produces the file `my-batch':

#!/bin/sh
# "my-batch" build script created Sat Jun 10 21:20:37 1995
# ================ Write file with C program.
mv -f hello.c hello.c~
rm -f hello.c
echo '#include <stdio.h>'>>hello.c
echo 'int main(int argc, char **argv)'>>hello.c
echo '{'>>hello.c
echo '  printf("hello world\n");'>>hello.c
echo '  return 0;'>>hello.c
echo '}'>>hello.c
cc -c hello.c
cc -o hello hello.o
hello
rm -f hello
rm -f hello.c
rm -f hello.o
rm -f my-batch

When run, `my-batch' prints:

bash$ my-batch
mv: hello.c: No such file or directory
hello world

HTML Forms

(require 'html-form)

Variable: *html:output-port*
Procedure names starting with `html:' send their output to the port *html:output-port*. *html:output-port* is initially the current output port.

Function: html:atval txt
Returns a string with character substitutions appropriate to send txt as an attribute-value.

Function: html:plain txt
Returns a string with character substitutions appropriate to send txt as an plain-text.

Function: html:comment line ...
Writes (using html:printf) the strings lines as HTML comments.

Function: html:start-form method action
The symbol method is either get, head, post, put, or delete. html:start-form prints the header for an HTML form.

Function: html:end-form pname submit-label
html:end-form prints the footer for an HTML form. The string submit-label appears on the button which submits the form.

Function: html:start-page title
Outputs headers for an HTML page named title.

Function: html:end-page
Outputs HTML codes to end a page.

Function: command->html rdb command-table command method action
The symbol command-table names a command table in the rdb relational database.

command->html writes an HTML-2.0 form for command command to the current-output-port. The `SUBMIT' button, which is labeled command, invokes the URI action with method method with a hidden attribute *command* bound to the command symbol submitted.

An action may invoke a CGI script (`http://www.my-site.edu/cgi-bin/search.cgi') or HTTP daemon (`http://www.my-site.edu:8001').

This example demonstrates how to create a HTML-form for the `build' command.

(require (in-vicinity (implementation-vicinity) "build.scm"))
(call-with-output-file "buildscm.html"
  (lambda (port)
    (fluid-let ((*html:output-port* port))
      (html:start-page 'commands)
      (command->html
       build '*commands* 'build 'post
       (or "/cgi-bin/build.cgi"
           "http://localhost:8081/buildscm"))
      html:end-page)))

HTTP and CGI service

(require 'html-form)

Function: cgi:serve-command rdb command-table
Reads a `"POST"' or `"GET"' query from (current-input-port) and executes the encoded command from command-table in relational-database rdb.

This example puts up a plain-text page in response to a CGI query.

(display "Content-Type: text/plain") (newline) (newline)
(require 'html-form)
(load (in-vicinity (implementation-vicinity) "build.scm"))
(cgi:serve-command build '*commands*)

Function: serve-urlencoded-command rdb command-table urlencoded
Reads attribute-value pairs from urlencoded, converts them to parameters and invokes the rdb command named by the parameter *command*.

Function: http:serve-query input-port output-port serve-proc
reads the query-string from input-port. If this is a valid `"POST"' or `"GET"' query, then http:serve-query calls serve-proc with two arguments, the query-string and the header-alist.

Otherwise, http:serve-query replies (to output-port) with appropriate HTML describing the problem.

This example services HTTP queries from port 8081:

(define socket (make-stream-socket AF_INET 0))
(socket:bind socket 8081)
(socket:listen socket 10)
(dynamic-wind
 (lambda () #f)
 (lambda ()
   (do ((port (socket:accept socket)
              (socket:accept socket)))
       (#f)
     (dynamic-wind
      (lambda () #f)
      (lambda ()
        (fluid-let ((*html:output-port* port))
          (http:serve-query
           port port
           (lambda (query-string header)
             (http:send-header
              '(("Content-Type" . "text/plain")))
             (with-output-to-port port
               (lambda ()
                 (serve-urlencoded-command
                  build '*commands* query-string)))))))
      (lambda () (close-port port)))))
 (lambda () (close-port socket)))

Function: http:read-request-line port
Reads the first non-blank line from port and, if successful, returns a list of three itmes from the request-line:

  1. Method Either one of the symbols options, get, head, post, put, delete, or trace; Or a string.
  2. Request-URI A string. At the minimum, it will be the string `"/"'.
  3. HTTP-Version A string. For example, `HTTP/1.0'.

Function: cgi:read-query-string
Reads the query-string from (current-input-port). cgi:read-query-string reads a `"POST"' or `"GET"' queries, depending on the value of (getenv "REQUEST_METHOD").

Printing Scheme

Generic-Write

(require 'generic-write)

generic-write is a procedure that transforms a Scheme data value (or Scheme program expression) into its textual representation and prints it. The interface to the procedure is sufficiently general to easily implement other useful formatting procedures such as pretty printing, output to a string and truncated output.

Procedure: generic-write obj display? width output
obj
Scheme data value to transform.
display?
Boolean, controls whether characters and strings are quoted.
width
Extended boolean, selects format:
#f
single line format
integer > 0
pretty-print (value = max nb of chars per line)
output
Procedure of 1 argument of string type, called repeatedly with successive substrings of the textual representation. This procedure can return #f to stop the transformation.

The value returned by generic-write is undefined.

Examples:

(write obj) == (generic-write obj #f #f display-string)
(display obj) == (generic-write obj #t #f display-string)

where

display-string ==
(lambda (s) (for-each write-char (string->list s)) #t)

Object-To-String

(require 'object->string)

Function: object->string obj
Returns the textual representation of obj as a string.

Function: object->limited-string obj limit
Returns the textual representation of obj as a string of length at most limit.

Pretty-Print

(require 'pretty-print)

Procedure: pretty-print obj
Procedure: pretty-print obj port

pretty-prints obj on port. If port is not specified, current-output-port is used.

Example:

(pretty-print '((1 2 3 4 5) (6 7 8 9 10) (11 12 13 14 15)
                (16 17 18 19 20) (21 22 23 24 25)))
   -| ((1 2 3 4 5)
   -|  (6 7 8 9 10)
   -|  (11 12 13 14 15)
   -|  (16 17 18 19 20)
   -|  (21 22 23 24 25))

(require 'pprint-file)

Procedure: pprint-file infile
Procedure: pprint-file infile outfile
Pretty-prints all the code in infile. If outfile is specified, the output goes to outfile, otherwise it goes to (current-output-port).

Function: pprint-filter-file infile proc outfile
Function: pprint-filter-file infile proc
infile is a port or a string naming an existing file. Scheme source code expressions and definitions are read from the port (or file) and proc is applied to them sequentially.

outfile is a port or a string. If no outfile is specified then current-output-port is assumed. These expanded expressions are then pretty-printed to this port.

Whitepsace and comments (introduced by ;) which are not part of scheme expressions are reproduced in the output. This procedure does not affect the values returned by current-input-port and current-output-port.

pprint-filter-file can be used to pre-compile macro-expansion and thus can reduce loading time. The following will write into `exp-code.scm' the result of expanding all defmacros in `code.scm'.

(require 'pprint-file)
(require 'defmacroexpand)
(defmacro:load "my-macros.scm")
(pprint-filter-file "code.scm" defmacro:expand* "exp-code.scm")

Time and Date

If (provided? 'current-time):

The procedures current-time, difftime, and offset-time deal with a calendar time datatype which may or may not be disjoint from other Scheme datatypes.

Function: current-time
Returns the time since 00:00:00 GMT, January 1, 1970, measured in seconds. Note that the reference time is different from the reference time for get-universal-time in section Common-Lisp Time.

Function: difftime caltime1 caltime0
Returns the difference (number of seconds) between twe calendar times: caltime1 - caltime0. caltime0 may also be a number.

Function: offset-time caltime offset
Returns the calendar time of caltime offset by offset number of seconds (+ caltime offset).

Time Zone

(require 'time-zone)

Data Format: TZ-string

POSIX standards specify several formats for encoding time-zone rules.

:<pathname>
If the first character of <pathname> is `/', then <pathname> specifies the absolute pathname of a tzfile(5) format time-zone file. Otherwise, <pathname> is interpreted as a pathname within tzfile:vicinity (/usr/lib/zoneinfo/) naming a tzfile(5) format time-zone file.
<std><offset>
The string <std> consists of 3 or more alphabetic characters. <offset> specifies the time difference from GMT. The <offset> is positive if the local time zone is west of the Prime Meridian and negative if it is east. <offset> can be the number of hours or hours and minutes (and optionally seconds) separated by `:'. For example, -4:30.
<std><offset><dst>
<dst> is the at least 3 alphabetic characters naming the local daylight-savings-time.
<std><offset><dst><doffset>
<doffset> specifies the offset from the Prime Meridian when daylight-savings-time is in effect.

The non-tzfile formats can optionally be followed by transition times specifying the day and time when a zone changes from standard to daylight-savings and back again.

,<date>/<time>,<date>/<time>
The <time>s are specified like the <offset>s above, except that leading `+' and `-' are not allowed. Each <date> has one of the formats:
J<day>
specifies the Julian day with <day> between 1 and 365. February 29 is never counted and cannot be referenced.
<day>
This specifies the Julian day with n between 0 and 365. February 29 is counted in leap years and can be specified.
M<month>.<week>.<day>
This specifies day <day> (0 <= <day> <= 6) of week <week> (1 <= <week> <= 5) of month <month> (1 <= <month> <= 12). Week 1 is the first week in which day d occurs and week 5 is the last week in which day <day> occurs. Day 0 is a Sunday.

Data Type: time-zone
is a datatype encoding how many hours from Greenwich Mean Time the local time is, and the Daylight Savings Time rules for changing it.

Function: time-zone TZ-string
Creates and returns a time-zone object specified by the string TZ-string. If time-zone cannot interpret TZ-string, #f is returned.

Function: tz:params caltime tz
tz is a time-zone object. tz:params returns a list of three items:
  1. An integer. 0 if standard time is in effect for timezone tz at caltime; 1 if daylight savings time is in effect for timezone tz at caltime.
  2. The number of seconds west of the Prime Meridian timezone tz is at caltime.
  3. The name for timezone tz at caltime.

tz:params is unaffected by the default timezone; inquiries can be made of any timezone at any calendar time.

The rest of these procedures and variables are provided for POSIX compatability. Because of shared state they are not thread-safe.

Function: tzset
Returns the default time-zone.

Function: tzset tz
Sets (and returns) the default time-zone to tz.

Function: tzset TZ-string
Sets (and returns) the default time-zone to that specified by TZ-string.

tzset also sets the variables *timezone*, daylight?, and tzname. This function is automatically called by the time conversion procedures which depend on the time zone (see section Time and Date).

Variable: *timezone*
Contains the difference, in seconds, between Greenwich Mean Time and local standard time (for example, in the U.S. Eastern time zone (EST), timezone is 5*60*60). *timezone* is initialized by tzset.

Variable: daylight?
is #t if the default timezone has rules for Daylight Savings Time. Note: daylight? does not tell you when Daylight Savings Time is in effect, just that the default zone sometimes has Daylight Savings Time.

Variable: tzname
is a vector of strings. Index 0 has the abbreviation for the standard timezone; If daylight?, then index 1 has the abbreviation for the Daylight Savings timezone.

Posix Time

(require 'posix-time)

Data Type: Calendar-Time
is a datatype encapsulating time.

Data Type: Coordinated Universal Time
(abbreviated UTC) is a vector of integers representing time:

  1. seconds (0 - 61)
  2. minutes (0 - 59)
  3. hours since midnight (0 - 23)
  4. day of month (1 - 31)
  5. month (0 - 11). Note difference from decode-universal-time.
  6. the number of years since 1900. Note difference from decode-universal-time.
  7. day of week (0 - 6)
  8. day of year (0 - 365)
  9. 1 for daylight savings, 0 for regular time

Function: gmtime caltime
Converts the calendar time caltime to UTC and returns it.

Function: localtime caltime tz
Returns caltime converted to UTC relative to timezone tz.

Function: localtime caltime
converts the calendar time caltime to a vector of integers expressed relative to the user's time zone. localtime sets the variable *timezone* with the difference between Coordinated Universal Time (UTC) and local standard time in seconds (see section Time Zone).

Function: gmktime univtime
Converts a vector of integers in GMT Coordinated Universal Time (UTC) format to a calendar time.

Function: mktime univtime
Converts a vector of integers in local Coordinated Universal Time (UTC) format to a calendar time.

Function: mktime univtime tz
Converts a vector of integers in Coordinated Universal Time (UTC) format (relative to time-zone tz) to calendar time.

Function: asctime univtime
Converts the vector of integers caltime in Coordinated Universal Time (UTC) format into a string of the form "Wed Jun 30 21:49:08 1993".

Function: gtime caltime
Function: ctime caltime
Function: ctime caltime tz
Equivalent to (asctime (gmtime caltime)), (asctime (localtime caltime)), and (asctime (localtime caltime tz)), respectively.

Common-Lisp Time

Function: get-decoded-time
Equivalent to (decode-universal-time (get-universal-time)).

Function: get-universal-time
Returns the current time as Universal Time, number of seconds since 00:00:00 Jan 1, 1900 GMT. Note that the reference time is different from current-time.

Function: decode-universal-time univtime
Converts univtime to Decoded Time format. Nine values are returned:
  1. seconds (0 - 61)
  2. minutes (0 - 59)
  3. hours since midnight
  4. day of month
  5. month (1 - 12). Note difference from gmtime and localtime.
  6. year (A.D.). Note difference from gmtime and localtime.
  7. day of week (0 - 6)
  8. #t for daylight savings, #f otherwise
  9. hours west of GMT (-24 - +24)

Notice that the values returned by decode-universal-time do not match the arguments to encode-universal-time.

Function: encode-universal-time second minute hour date month year
Function: encode-universal-time second minute hour date month year time-zone
Converts the arguments in Decoded Time format to Universal Time format. If time-zone is not specified, the returned time is adjusted for daylight saving time. Otherwise, no adjustment is performed.

Notice that the values returned by decode-universal-time do not match the arguments to encode-universal-time.

Vector Graphics

Tektronix Graphics Support

Note: The Tektronix graphics support files need more work, and are not complete.

Tektronix 4000 Series Graphics

The Tektronix 4000 series graphics protocol gives the user a 1024 by 1024 square drawing area. The origin is in the lower left corner of the screen. Increasing y is up and increasing x is to the right.

The graphics control codes are sent over the current-output-port and can be mixed with regular text and ANSI or other terminal control sequences.

Procedure: tek40:init

Procedure: tek40:graphics

Procedure: tek40:text

Procedure: tek40:linetype linetype

Procedure: tek40:move x y

Procedure: tek40:draw x y

Procedure: tek40:put-text x y str

Procedure: tek40:reset

Tektronix 4100 Series Graphics

The graphics control codes are sent over the current-output-port and can be mixed with regular text and ANSI or other terminal control sequences.

Procedure: tek41:init

Procedure: tek41:reset

Procedure: tek41:graphics

Procedure: tek41:move x y

Procedure: tek41:draw x y

Procedure: tek41:point x y number

Procedure: tek41:encode-x-y x y

Procedure: tek41:encode-int number

Schmooz

Schmooz is a simple, lightweight markup language for interspersing Texinfo documentation with Scheme source code. Schmooz does not create the top level Texinfo file; it creates `txi' files which can be imported into the documentation using the Texinfo command `@include'.

(require 'schmooz) defines the function schmooz, which is used to process files. Files containing schmooz documentation should not contain (require 'schmooz).

Procedure: schmooz filenamescm ...
Filenamescm should be a string ending with `scm' naming an existing file containing Scheme source code. schmooz extracts top-level comments containing schmooz commands from filenamescm and writes the converted Texinfo source to a file named filenametxi.

Procedure: schmooz filenametexi ...
Procedure: schmooz filenametex ...
Procedure: schmooz filenametxi ...
Filename should be a string naming an existing file containing Texinfo source code. For every occurrence of the string `@include filenametxi' within that file, schmooz calls itself with the argument `filenamescm'.

Schmooz comments are distinguished (from non-schmooz comments) by their first line, which must start with an at-sign (@) preceded by one or more semicolons (;). A schmooz comment ends at the first subsequent line which does not start with a semicolon. Currently schmooz comments are recognized only at top level.

Schmooz comments are copied to the Texinfo output file with the leading contiguous semicolons removed. Certain character sequences starting with at-sign are treated specially. Others are copied unchanged.

A schmooz comment starting with `@body' must be followed by a Scheme definition. All comments between the `@body' line and the definition will be included in a Texinfo definition, either a `@defun' or a `@defvar', depending on whether a procedure or a variable is being defined.

Within the text of that schmooz comment, at-sign followed by `0' will be replaced by @code{procedure-name} if the following definition is of a procedure; or @var{variable} if defining a variable.

An at-sign followed by a non-zero digit will expand to the variable citation of that numbered argument: `@var{argument-name}'.

If more than one definition follows a `@body' comment line without an intervening blank or comment line, then those definitions will be included in the same Texinfo definition using `@defvarx' or `@defunx', depending on whether the first definition is of a variable or of a procedure.

Schmooz can figure out whether a definition is of a procedure if it is of the form:

`(define (<identifier> <arg> ...) <expression>)'

or if the left hand side of the definition is some form ending in a lambda expression. Obviously, it can be fooled. In order to force recognition of a procedure definition, start the documentation with `@args' instead of `@body'. `@args' should be followed by the argument list of the function being defined, which may be enclosed in parentheses and delimited by whitespace, (as in Scheme), enclosed in braces and separated by commas, (as in Texinfo), or consist of the remainder of the line, separated by whitespace.

For example:

;;@args arg1 args ...
;;@0 takes argument @1 and any number of @2
(define myfun (some-function-returning-magic))

Will result in:

@defun myfun arg1 args @dots{}

@code{myfun} takes argument @var{arg1} and any number of @var{args}
@end defun

`@args' may also be useful for indicating optional arguments by name. If `@args' occurs inside a schmooz comment section, rather than at the beginning, then it will generate a `@defunx' line with the arguments supplied.

If the first at-sign in a schmooz comment is immediately followed by whitespace, then the comment will be expanded to whatever follows that whitespace. If the at-sign is followed by a non-whitespace character then the at-sign will be included as the first character of the expansion. This feature is intended to make it easy to include Texinfo directives in schmooz comments.


Go to the first, previous, next, last section, table of contents.