@c Copyright 1989-1992 Regents of the University of California
@c Permission to use, copy, modify, and distribute this
@c documentation for any purpose and without fee is hereby
@c granted, provided that this notice appears in all copies.
@c The University of California makes no representations about
@c the suitability of this material for any purpose.  It is
@c provided "as is" without express or implied warranty.

@node Tcl
@appendix Tcl Overview

@cindex Tcl overview
This appendix presents the same information available in the Tool
Command Language (Tcl) reference-manual entry (``man page''); we include
it in the DejaGnu manual for convenient reference.  The author of Tcl,
and of this reference, is John Ousterhout, of the University of
California at Berkeley (@code{ouster@@sprite.berkeley.edu}).

The following copyright terms apply to the documentation in this
Appendix:

@quotation
Copyright 1989--1992 Regents of the University of California.
Permission to use, copy, modify, and distribute this
documentation for any purpose and without fee is hereby
granted, provided that this notice appears in all copies.
The University of California makes no representations about
the suitability of this material for any purpose.  It is
provided ``as is'' without express or implied warranty.
@end quotation

@menu
* Tcl Introduction::
* Tcl Interpreters::
* Tcl Data Types::
* Tcl Syntax::
* Tcl Expressions::
* Tcl Lists::
* Regular Expressions::
* Results::
* Procedures::
* Variable Types::
* Tcl Commands::
* Tcl Variables::
* Thanks::
@end menu

@node Tcl Introduction
@section Introduction

@cindex tool command language (Tcl)
Tcl stands for ``tool command language'' and is pronounced ``tickle.''
It is actually two things: a language and a library.  First, Tcl is a
simple textual language, intended primarily for issuing commands to
interactive programs such as text editors, debuggers, illustrators, and
shells.  It has a simple syntax and is also programmable, so Tcl users
can write command procedures to provide more powerful commands than
those in the built-in set.

Second, Tcl is a library package that can be embedded in application
programs.  The Tcl library consists of a parser for the Tcl language,
routines to implement the Tcl built-in commands, and procedures that
allow each application to extend Tcl with additional commands specific
to that application.  The application program generates Tcl commands and
passes them to the Tcl parser for execution.  Commands may be generated
by reading characters from an input source, or by associating command
strings with elements of the application's user interface, such as menu
entries, buttons, or keystrokes.  When the Tcl library receives commands
it parses them into component fields and executes built-in commands
directly.  For commands implemented by the application, Tcl calls back
to the application to execute the commands.  In many cases commands will
invoke recursive invocations of the Tcl interpreter by passing in
additional strings to execute (procedures, looping commands, and
conditional commands all work in this way).

An application program gains three advantages by using Tcl for its
command language.  First, Tcl provides a standard syntax: once users
know Tcl, they will be able to issue commands easily to any Tcl-based
application.  Second, Tcl provides programmability.  All a Tcl
application needs to do is to implement a few application-specific
low-level commands.  Tcl provides many utility commands plus a general
programming interface for building up complex command procedures.  By
using Tcl, applications need not re-implement these features.  Third,
Tcl can be used as a common language for communicating between
applications.  Inter-application communication is not built into the Tcl
core described here, but various add-on libraries, such as the Tk
toolkit, allow applications to issue commands to each other.  This makes
it possible for applications to work together in much more powerful ways
than was previously possible.

This discussion focuses primarily on the Tcl language.  It describes the
language syntax and the built-in commands that will be available in any
application based on Tcl.  The individual library procedures are
described in detail in separate manual pages, one per procedure.

@node Tcl Interpreters
@section Tcl Interpreters

@cindex Tcl interpreters
The central data structure in Tcl is an interpreter (C type
@code{Tcl_Interp}).  An interpreter consists of a set of command
bindings, a set of variable values, and a few other miscellaneous pieces
of state.  Each Tcl command is interpreted in the context of a
particular interpreter.  Some Tcl-based applications will maintain
multiple interpreters simultaneously, each associated with a different
widget or portion of the application.  Interpreters are relatively
lightweight structures.  They can be created and deleted quickly, so
application programmers should feel free to use multiple interpreters if
that simplifies the application.  Eventually Tcl will provide a
mechanism for sending Tcl commands and results back and forth between
interpreters, even if the interpreters are managed by different
processes.

@node Tcl Data Types
@section Tcl Data Types

@cindex Tcl data type: strings
@cindex strings, Tcl data type
Tcl supports only one type of data: strings.  All commands, all
arguments to commands, all command results, and all variable values are
strings.  Where commands require numeric arguments or return numeric
results, the arguments and results are passed as strings.  Many commands
expect their string arguments to have certain formats, but this
interpretation is up to the individual commands.  For example, arguments
often contain Tcl command strings, which may get executed as part of the
commands.  The easiest way to understand the Tcl interpreter is to
remember that everything is just an operation on a string.  In many
cases Tcl constructs will look similar to more structured constructs
from other languages.  However, the Tcl constructs are not structured at
all; they are just strings of characters, and this gives them a
different behavior than the structures they may look like.

@cindex forms of Tcl commands
@cindex Tcl command forms
Although the exact interpretation of a Tcl string depends on who is
doing the interpretation, there are three common forms that strings
take: commands, expressions, and lists.  The major sections below
discuss these three forms in more detail.

@node Tcl Syntax
@section Basic Command Syntax

@cindex Tcl syntax
@cindex syntax of Tcl
The Tcl language has syntactic similarities to both the Unix shells and
Lisp.  However, the interpretation of commands is different in Tcl than
in either of those other two systems.  A Tcl command string consists of
one or more commands separated by newline characters or semicolons.
Each command consists of a collection of fields separated by white space
(spaces or tabs).  The first field must be the name of a command, and
the additional fields, if any, are arguments that will be passed to that
command.  For example, the command

@example
set a 22
@end example

@noindent
has three fields: the first, @code{set}, is the name of a Tcl command,
and the last two, @code{a} and @code{22}, will be passed as arguments to
the @code{set} command.  The command name may refer either to a built-in
Tcl command, an application-specific command bound in with the library
procedure @code{Tcl_CreateCommand}, or a command procedure defined with
the @code{proc} built-in command.

@cindex arguments to Tcl commands
@cindex Tcl command arguments
Arguments are passed literally as text strings.  Individual commands
interpret those strings in any fashion they wish.  The @code{set}
command, for example, treats its first argument as the name of a
variable and its second argument as a string value to assign to that
variable.  For other commands arguments may be interpreted as integers,
lists, file names, or Tcl commands.

Command names should normally be typed completely (e.g. no
abbreviations).  However, if the Tcl interpreter cannot locate a command
it invokes a special command named @code{unknown} which attempts to find
or create the command.  For example, at many sites @code{unknown} will
search through library directories for the desired command and create it
as a Tcl procedure if it is found.  The @code{unknown} command often
provides automatic completion of abbreviated commands, but usually only
for commands that were typed interactively.  Even if completion is
available at your site, it is probably a bad idea to use abbreviations
in command scripts and other forms that will be re-used over time:
changes to the command set may cause abbreviations to become ambiguous,
resulting in scripts that no longer work.

@menu
* Comments::
* Double Quotes::
* Braces::
* Brackets::
* Variable Substitution::
* Command Separator::
* Backslash::
* Tcl Syntax Summary::
@end menu

@node Comments
@subsection Comments

@cindex Tcl comments
@cindex comments, Tcl
If the first non-blank character in a command is @samp{#}, then
everything from the @samp{#} up through the next newline character is
treated as a comment and ignored.  When comments are embedded inside
nested commands (e.g. fields enclosed in braces) they must have
properly-matched braces (this is necessary because when Tcl parses the
top-level command it does not know yet that the nested field will be used
as a command, so it cannot process the nested comment character as a
comment).

@node Double Quotes
@subsection Grouping arguments with double-quotes

@cindex double quotes
@cindex white space in arguments
@cindex newlines in arguments
@cindex semicolons in arguments
@cindex @code{"} for grouping
Normally each argument field ends at the next white space, but
double-quotes may be used to create arguments with embedded space.  If
an argument field begins with a double-quote, then the argument isn't
terminated by white space (including newlines) or a semicolon (see
below for information on semicolons); instead it ends at the next
double-quote character.  The double-quotes are not included in the
resulting argument.  For example, the command

@example
set a "This is a single argument"
@end example

@noindent
will pass two arguments to @code{set}: @code{a} and @samp{This is a
single argument}.  Within double-quotes, command substitutions, variable
substitutions, and backslash substitutions still occur, as described
below.  If the first character of a command field is not a quote, then
quotes receive no special interpretation in the parsing of that field.

@node Braces
@subsection Grouping arguments with braces

@cindex @code{@{@}} for grouping
@cindex grouping arguments
@cindex braces, used for grouping
@cindex substitution in arguments, postponing
@cindex argument substitution, postponing
Curly braces may also be used for grouping arguments.  They are similar
to quotes except for two differences.  First, they nest; this makes them
easier to use for complicated arguments like nested Tcl command strings.
Second, the substitutions described below for commands, variables, and
backslashes do @emph{not} occur in arguments enclosed in braces, so
braces can be used to prevent substitutions where they are undesirable.
If an argument field begins with a left brace, then the argument ends at
the matching right brace.  Tcl will strip off the outermost layer of
braces and pass the information between the braces to the command
without any further modification.  For example, in the command

@example
set a @{xyz a @{b c d@}@}
@end example

@noindent
the @code{set} command will receive two arguments: @code{a} and
@samp{xyz a @{b c d@}}.

When braces or quotes are in effect, the matching brace or quote need
not be on the same line as the starting quote or brace; in this case the
newline will be included in the argument field along with any other
characters up to the matching brace or quote.  For example, the
@code{eval} command takes one argument, which is a command string;
@code{eval} invokes the Tcl interpreter to execute the command string.
The command

@example
eval @{
	set a 22
	set b 33
@}
@end example

@noindent
will assign the value @samp{22} to @code{a} and @samp{33} to @code{b}.

@cindex braces, as ordinary text
If the first character of a command field is not a left brace, then
neither left nor right braces in the field will be treated specially
(except as part of variable substitution; see below).

@node Brackets
@subsection Command substitution with brackets

@cindex @code{[]} command substitution
@cindex command substitution
@cindex brackets
@cindex square brackets
If an open bracket occurs in a field of a command, then command
substitution occurs (except for fields enclosed in braces).  All of the
text up to the matching close bracket is treated as a Tcl command and
executed immediately.  Then the result of that command is substituted
for the bracketed text.  For example, consider the command

@example
set a [set b]
@end example

When the @code{set} command has only a single argument, it is the name
of a variable and @code{set} returns the contents of that variable.  In
this case, if variable @code{b} has the value @samp{foo}, then the
command above is equivalent to the command

@example
set a foo
@end example

Brackets can be used in more complex ways.  For example, if the variable
@code{b} has the value @samp{foo} and the variable @code{c} has the
value @samp{gorp}, then the command

@example
set a xyz[set b].[set c]
@end example

@noindent
is equivalent to the command

@example
set a xyzfoo.gorp
@end example

@cindex newlines in brackets
@cindex semicolons in brackets
A bracketed command may contain multiple commands separated by newlines
or semicolons in the usual fashion.  In this case the value of the last
command is used for substitution.  For example, the command

@example
set a x[set b 22
expr $b+2]x
@end example

@noindent
is equivalent to the command

@example
set a x24x
@end example

If a field is enclosed in braces then the brackets and the characters
between them are not interpreted specially; they are passed through to
the argument verbatim.

@node Variable Substitution
@subsection Variable substitution with @code{$}

@cindex variable substitution
@cindex @code{$} variable substitution
The dollar sign (@samp{$}) may be used as a special shorthand form for
substituting variable values.  If @samp{$} appears in an argument that
isn't enclosed in braces then variable substitution will occur.  The
characters after the @samp{$}, up to the first character that isn't a
number, letter, or underscore, are taken as a variable name and the
string value of that variable is substituted for the name.  For example,
if variable @code{foo} has the value @samp{test}, then the command

@example
set a $foo.c
@end example

@noindent
is equivalent to the command

@example
set a test.c
@end example

There are two special forms for variable substitution.  If the next
character after the name of the variable is an open parenthesis, then
the variable is assumed to be an array name, and all of the characters
between the open parenthesis and the next close parenthesis are taken as
an index into the array.  Command substitutions and variable
substitutions are performed on the information between the parentheses
before it is used as an index.  For example, if the variable @code{x} is
an array with one element named @code{first} and value @samp{87} and
another element named @code{14} and value @samp{more}, then the command

@example
set a xyz$x(first)zyx
@end example

@noindent
is equivalent to the command

@example
set a xyz87zyx
@end example

If the variable @code{index} has the value @samp{14}, then the command

@example
set a xyz$x($index)zyx
@end example

@noindent
is equivalent to the command

@example
set a xyzmorezyx
@end example

@xref{Variable Types,,Variables: scalars and arrays}, for more
information on arrays.

The second special form for variables occurs when the dollar sign is
followed by an open curly brace.  In this case the variable name
consists of all the characters up to the next curly brace.  Array
references are not possible in this form: the name between braces is
assumed to refer to a scalar variable.  For example, if variable
@code{foo} has the value @samp{test}, then the command

@example
set a abc$@{foo@}bar
@end example

@noindent
is equivalent to the command

@example
set a abctestbar
@end example

Variable substitution does not occur in arguments that are enclosed in
braces: the dollar sign and variable name are passed through to the
argument verbatim.

The dollar sign abbreviation is simply a shorthand form.  @samp{$a} is
completely equivalent to @samp{[set a]}; it is provided as a convenience
to reduce typing.

@node Command Separator
@subsection Separating commands with semicolons

@cindex command separator
@cindex multiple commands on one line
@cindex @code{;} to end commands
@cindex semicolon
Normally, each command occupies one line (the command is terminated by a
newline character).  However, semicolon (@samp{;}) is treated as a
command separator character; multiple commands may be placed on one line
by separating them with a semicolon.  semicolons are not treated as
command separators if they appear within curly braces or double-quotes.

@node Backslash
@subsection Backslash substitution

@cindex backslash
@cindex @code{\@var{x}} for special chars
@cindex special characters
@cindex non-printing characters
@cindex characters, special
Backslashes may be used to insert non-printing characters into
command fields and also to insert special characters like
braces and brackets into fields
without them being interpreted specially as described above.
The backslash sequences understood by the Tcl interpreter are
listed below.  In each case, the backslash
sequence is replaced by the given character:

@table @code
@item \b
Backspace (0x8).

@item \f
Form feed (0xc).

@item \n
Newline (0xa).

@item \r
Carriage-return (0xd).

@item \t
Tab (0x9).

@item \v
Vertical tab (0xb).

@item \@{
Left brace (@samp{@{}).

@item \@}
Right brace (@samp{@}}).

@item \[
Open bracket (@samp{[}).

@item \]
Close bracket (@samp{]}).

@item \$
Dollar sign (@samp{$}).

@item \@key{sp}
Space (@w{@samp{ }}): does not terminate argument.

@item \;
Semicolon: does not terminate command.

@item \"
Double-quote.

@item \@key{nl}
@cindex multiple-line commands
@cindex commands on multiple lines
Nothing: backslash followed by newline joins two lines together into a
single line.  This backslash feature is unique in that it will be
applied even when the sequence occurs within braces.

@item \\
Backslash (@samp{\}).

@item \@var{ddd}
The digits @var{ddd} (one, two, or three of them) give the octal value of
the character.  Null characters may not be embedded in command fields;
if @var{ddd} is zero then the backslash sequence is ignored (i.e. it
maps to an empty string).
@end table

For example, in the command

@example
set a \@{x\[\\0yz\141
@end example

@noindent
the second argument to @code{set} will be @samp{@{x[\0yza}.

If a backslash is followed by something other than one of the options
described above, then the backslash is transmitted to the argument field
without any special processing, and the Tcl scanner continues normal
processing with the next character.  For example, in the command

@example
set \*a \\\@{foo
@end example

@noindent
The first argument to @code{set} will be @samp{\*a} and the second
argument will be @samp{\@{foo}.

If an argument is enclosed in braces, then backslash sequences inside
the argument are parsed but no substitution occurs (except for
backslash-newline): the backslash sequence is passed through to the
argument as is, without making any special interpretation of the
characters in the backslash sequence.  In particular, backslashed braces
are not counted in locating the matching right brace that terminates the
argument.  For example, in the command

@example
set a @{\@{abc@}
@end example

@noindent
the second argument to @code{set} is @samp{\@{abc}.

This backslash mechanism is not sufficient to generate absolutely any
argument structure; it only covers the most common cases.  To produce
particularly complicated arguments it is probably easiest to use the
@code{format} command along with command substitution.

@node Tcl Syntax Summary
@subsection Command summary

@cindex syntax summary, Tcl
@cindex Tcl syntax summary
@enumerate
@item
A command is just a string.

@item
Within a string commands are separated by newlines or semicolons
(unless the newline or semicolon is within braces or brackets or is
backslashed).

@item
A command consists of fields.  The first field is the name of the
command.  The other fields are strings that are passed to that command
as arguments.

@item
Fields are normally separated by white space.

@item
Double-quotes allow white space and semicolons to appear within a
single argument.  Command substitution, variable substitution, and
backslash substitution still occur inside quotes.

@item
Braces defer interpretation of special characters.  If a field begins
with a left brace, then it consists of everything between the left brace
and the matching right brace. The braces themselves are not included in
the argument.  No further processing is done on the information between
the braces except that backslash-newline sequences are eliminated.

@item
If a field doesn't begin with a brace then backslash, variable, and
command substitution are done on the field.  Only a single level of
processing is done: the results of one substitution are not scanned
again for further substitutions or any other special treatment.
Substitution can occur on any field of a command, including the command
name as well as the arguments.

@item
If the first non-blank character of a command is a @samp{#}, everything
from the @samp{#} up through the next newline is treated as a comment
and ignored.
@end enumerate

@node Tcl Expressions
@section Expressions

@cindex expressions, Tcl
@cindex Tcl expressions
The second major interpretation applied to strings in Tcl is as
expressions.  Several commands, such as @code{expr}, @code{for}, and
@code{if}, treat one or more of their arguments as expressions and call
the Tcl expression processors (@code{Tcl_ExprLong},
@code{Tcl_ExprBoolean}, etc.) to evaluate them.  The operators permitted
in Tcl expressions are a subset of the operators permitted in C
expressions, and they have the same meaning and precedence as the
corresponding C operators.  Expressions almost always yield numeric
results (integer or floating-point values).  For example, the expression

@example
8.2 + 6
@end example

@noindent
evaluates to 14.2.  Tcl expressions differ from C expressions in the way
that operands are specified, and in that Tcl expressions support
non-numeric operands and string comparisons.

@cindex integers, in Tcl expressions
@cindex numbers, in Tcl expressions
@cindex floating point, in Tcl
@cindex octal numbers, in Tcl
@cindex hexadecimal numbers, in Tcl
A Tcl expression consists of a combination of operands, operators, and
parentheses.  White space may be used between the operands and operators
and parentheses; it is ignored by the expression processor.  Where
possible, operands are interpreted as integer values.  Integer values
may be specified in decimal (the normal case), in octal (if the first
character of the operand is @samp{0}), or in hexadecimal (if the first
two characters of the operand are @samp{0x}).  If an operand does not
have one of the integer formats given above, then it is treated as a
floating-point number if that is possible.  Floating-point numbers may
be specified in any of the ways accepted by an @sc{ansi}-compliant C
compiler (except that the @samp{f}, @samp{F}, @samp{l}, and @samp{L}
suffixes will not be permitted in most installations).  For example, all
of the following are valid floating-point numbers: @code{2.1},
@code{3.}, @code{6e4}, @code{7.91e+16}.  If no numeric interpretation is
possible, then an operand is left as a string (and only a limited set of
operators may be applied to it).

@cindex operands, in Tcl expressions
Operands may be specified in any of the following ways:

@enumerate
@item
As an numeric value, either integer or floating-point.

@item
As a Tcl variable, using standard @samp{$} notation.  The variable's
value is used as the operand.

@item
As a string enclosed in double-quotes.  The expression parser performs
backslash, variable, and command substitutions on the information
between the quotes, and uses the resulting value as the operand.

@item
As a string enclosed in braces.  The characters between the open brace
and matching close brace are used as the operand without any
substitutions.

@item
As a Tcl command enclosed in brackets.  The command will be executed and
its result will be used as the operand.
@end enumerate

Where substitutions occur above (e.g. inside quoted strings), they are
performed by the expression processor.  However, an additional layer of
substitution may already have been performed by the command parser
before the expression processor was called.  As discussed below, it is
usually best to enclose expressions in braces to prevent the command
parser from performing substitutions on the contents.

For some examples of simple expressions, suppose the variable @code{a}
has the value @samp{3} and the variable @code{b} has the value @samp{6}.
Then the expression on the left side of each of the lines below
evaluates to the value on the right side of the line:

@example
3.1 + $a                    6.1
2 + "$a.$b"                 5.6
4*[llength "6 2"]           8
@{word one@} < "word $a"      0
@end example

@cindex operators, Tcl
@cindex arithmetic operators, Tcl
@cindex Boolean operators, Tcl
The valid operators are listed below, grouped in decreasing order
of precedence:

@table @code
@item -  ~  !
Unary minus, bit-wise NOT, logical NOT.  None of these operands
may be applied to string operands, and bit-wise NOT may be
applied only to integers.

@item *  /  %
Multiply, divide, remainder.  None of these operands may be
applied to string operands, and remainder may be applied only
to integers.

@item +  -
Add and subtract.  Valid for any numeric operands.

@item <<  >>
Left and right shift.  Valid for integer operands only.

@item <  >  <=  >=
Boolean less, greater, less than or equal, and greater than or equal.
Each operator produces 1 if the condition is true, 0 otherwise.  These
operators may be applied to strings as well as numeric operands, in
which case string comparison is used.

@item ==  !=
Boolean equal and not equal.  Each operator produces a zero/one result.
Valid for all operand types.

@item &
Bit-wise and.  Valid for integer operands only.

@item ^
Bit-wise exclusive or.  Valid for integer operands only.

@item |
Bit-wise or.  Valid for integer operands only.

@item &&
Logical and.  Produces a 1 result if both operands are non-zero, 0
otherwise.  Valid for numeric operands only (integers or
floating-point).

@item ||
Logical or.  Produces a 0 result if both operands are zero, 1 otherwise.
Valid for numeric operands only (integers or floating-point).

@item @var{x} ? @var{y} : @var{z}
@cindex if-then-else operator, Tcl
@cindex @code{?:} conditionals, Tcl
If-then-else, as in C.  If @var{x} evaluates to non-zero, then the
result is the value of @var{y}.  Otherwise the result is the value of
@var{z}.  The @var{x} operand must have a numeric value.
@end table

See the C manual for more details on the results produced by each
operator.  All of the binary operators group left-to-right within the
same precedence level.  For example, the expression @samp{4*2 < 7}
evaluates to 0.

The @code{&&}, @code{||}, and @code{?:} operators have ``lazy
evaluation'', just as in C, which means that operands are not evaluated
if they are not needed to determine the outcome.  For example, in
@samp{$v ? [a] : [b]} only one of @samp{[a]} or @samp{[b]} will actually
be evaluated, depending on the value of @samp{$v}.

All internal computations involving integers are done with the C type
@code{long}, and all internal computations involving floating-point are
done with the C type @code{double}.  When converting a string to
floating-point, exponent overflow is detected and results in a Tcl
error.  For conversion to integer from string, detection of overflow
depends on the behavior of some routines in the local C library, so it
should be regarded as unreliable.  In any case, overflow and underflow
are generally not detected reliably for intermediate results.

Conversion among internal representations for integer, floating-point,
and string operands is done automatically as needed.  For arithmetic
computations, integers are used until some floating-point number is
introduced, after which floating-point is used.  For example, @samp{5 /
4} yields the result @samp{1}, while

@example
5 / 4.0
5 / ( [string length "abcd"] + 0.0 )
@end example

@noindent
both yield the result @samp{1.25}.

String values may be used as operands of the comparison operators,
although the expression evaluator tries to do comparisons as integer or
floating-point when it can.  If one of the operands of a comparison is a
string and the other has a numeric value, the numeric operand is
converted back to a string using the C @code{sprintf} format specifier
@samp{%d} for integers and @samp{%g} for floating-point values.  For
example, the expressions

@example
"0x03" > "2"
"0y" < "0x12"
@end example

@noindent
both evaluate to @samp{1}.  The first comparison is done using integer
comparison, and the second is done using string comparison after the
second operand is converted to the string @samp{18}.

@cindex white space in expressions
@cindex expressions, white space in
@cindex substitutions in expressions
@cindex expressions, substitutions in
In general it is safest to enclose an expression in braces when entering
it in a command: otherwise, if the expression contains any white space
then the Tcl interpreter will split it among several arguments.  For
example, the command @samp{expr $a + $b} results in three arguments
being passed to @code{expr}: @samp{$a}, @samp{+}, and @samp{$b}.  In
addition, if the expression is not in braces the Tcl interpreter
performs variable and command substitution immediately (it will happen
in the command parser rather than in the expression parser).  In many
cases the expression is being passed to a command that evaluates the
expression later (or even many times if, for example, the expression is
to be used to decide when to exit a loop).  Usually the desired goal is
to re-do the variable or command substitutions each time the expression
is evaluated, rather than once and for all at the beginning.  For
example, the command

@example
for @{set i 1@} $i<=10 @{incr i@} @{...@}       ;# @emph{WRONG}
@end example

@noindent
is probably intended to iterate over all values of @code{i} from 1 to
10.  After each iteration of the body of the loop, @code{for} passes its
second argument to the expression evaluator to see whether or not to
continue processing.  Unfortunately, in this case the value of @code{i}
in the second argument is substituted once and for all when the
@code{for} command is parsed.  If @code{i} was 0 before the @code{for}
command was invoked, the second argument of @code{for} is
@samp{0<=10}---which always evaluates to @code{1}, even though the value
of @code{i} eventually becomes greater than @code{10}.  In the above
case the loop will never terminate.  Instead, the expression should be
in braces:

@example
for @{set i 1@} @{$i<=10@} @{incr i@} @{...@}     ;# @emph{RIGHT}
@end example

This delays the substitution of @code{i}; it is done again each time the
expression is evaluated, which is the desired result.

@node Tcl Lists
@section Lists

@cindex lists, Tcl
@cindex Tcl lists
The third major way that strings are interpreted in Tcl is as lists.  A
list is just a string with a list-like structure consisting of fields
separated by white space.  For example, the string @samp{Al Sue Anne
John} is a list with four elements or fields.  Lists have the same basic
structure as command strings, except that a newline character in a list
is treated as a field separator just like space or tab.  Conventions for
braces and quotes and backslashes are the same for lists as for
commands.  For example, the string

@example
a b\ c @{d e @{f g h@}@}
@end example

@noindent
is a list with three elements: @samp{a}, @samp{b c}, and @samp{d e @{f g
h@}}.  Whenever an element is extracted from a list, the same rules
about braces and quotes and backslashes are applied as for commands.
Thus in the example above when the third element is extracted from the
list, the result is @samp{d e @{f g h@}} (when the field was extracted,
all that happened was to strip off the outermost layer of braces).
Command substitution and variable substitution are never made on a list
(at least, not by the list-processing commands; the list can always be
passed to the Tcl interpreter for evaluation).

The Tcl commands @code{concat}, @code{foreach}, @code{lappend},
@code{lindex}, @code{linsert}, @code{list}, @code{llength},
@code{lrange}, @code{lreplace}, @code{lsearch}, and @code{lsort} allow
you to build lists, extract elements from them, search them, and perform
other list-related functions.

@node Regular Expressions
@section Regular expressions

@cindex regular expressions
Tcl provides two commands that support string matching using
@code{egrep}-style regular expressions: @code{regexp} and @code{regsub}.
Regular expressions are implemented using Henry Spencer's package, and
the description of regular expressions below is copied verbatim from his
manual entry.

A regular expression is zero or more @dfn{branches}, separated by
@samp{|}.  It matches anything that matches one of the branches.

A branch is zero or more @dfn{pieces}, concatenated.  It matches a match
for the first, followed by a match for the second, etc.

A piece is an @dfn{atom} possibly followed by @samp{*}, @samp{+}, or
@samp{?}.  An atom followed by @samp{*} matches a sequence of 0 or more
matches of the atom.  An atom followed by @samp{+} matches a sequence of
1 or more matches of the atom.  An atom followed by @samp{?} matches a
match of the atom, or the null string.

An atom is a regular expression in parentheses (matching a match for the
regular expression), a @dfn{range} (see below), @samp{.} (matching any
single character), @samp{^} (matching the null string at the beginning
of the input string), @samp{$} (matching the null string at the end of
the input string), a @samp{\} followed by a single character (matching
that character), or a single character with no other significance
(matching that character).

A @dfn{range} is a sequence of characters enclosed in @samp{[]}.  It
normally matches any single character from the sequence.  If the
sequence begins with @samp{^}, it matches any single character
@emph{not} from the rest of the sequence.  If two characters in the
sequence are separated by @samp{-}, this is shorthand for the full list
of @sc{ascii} characters between them (e.g. @samp{[0-9]} matches any
decimal digit).  To include a literal @samp{]} in the sequence, make it
the first character (following a possible @samp{^}).  To include a
literal @samp{-}, make it the first or last character.

If a regular expression could match two different parts of a string, it
will match the one which begins earliest.  If both begin in the same
place but match different lengths, or match the same length in different
ways, life gets messier, as follows.

In general, the possibilities in a list of branches are considered in
left-to-right order, the possibilities for @samp{*}, @samp{+}, and
@samp{?} are considered longest-first, nested constructs are considered
from the outermost in, and concatenated constructs are considered
leftmost-first.  The match that will be chosen is the one that uses the
earliest possibility in the first choice that has to be made.  If there
is more than one choice, the next will be made in the same manner
(earliest possibility) subject to the decision on the first choice.  And
so forth.

For example, @samp{(ab|a)b*c} could match @samp{abc} in one of two ways.
The first choice is between @samp{ab} and @samp{a}; since @samp{ab} is
earlier, and does lead to a successful overall match, it is chosen.
Since the @samp{b} is already spoken for, the @samp{b*} must match its
last possibility---the empty string---since it must respect the earlier
choice.

In the particular case where no @samp{|} is present and there is only
one @samp{*}, @samp{+}, or @samp{?}, the net effect is that the longest
possible match will be chosen.  So @samp{ab*}, presented with
@samp{xabbbby}, will match @samp{abbbb}.  Note that if @samp{ab*} is
tried against @samp{xabyabbbz}, it will match @samp{ab} just after
@samp{x}, due to the begins-earliest rule.  (In effect, the decision on
where to start the match is the first choice to be made, hence
subsequent choices must respect it even if this leads them to
otherwise less-preferred alternatives.)

@node Results
@section Command results

@cindex results of Tcl commands
@cindex Tcl command results
Each command produces two results:  a code and a string.  The
code indicates whether the command completed successfully or not,
and the string gives additional information.  The valid codes are
defined in @file{tcl.h}, and are:

@table @code
@item TCL_OK
This is the normal return code, and indicates that the command completed
successfully.  The string gives the command's return value.

@item TCL_ERROR
Indicates that an error occurred; the string gives a message describing
the error.  In addition, the global variable @code{errorInfo} will
contain human-readable information describing which commands and
procedures were being executed when the error occurred, and the global
variable @code{errorCode} will contain machine-readable details about
the error, if they are available.  @xref{Tcl Variables,,Built-in
variables}, for more information.

@item TCL_RETURN
Indicates that the @code{return} command has been invoked, and that the
current procedure (or top-level command or @code{source} command) should
return immediately.  The string gives the return value for the procedure
or command.

@item TCL_BREAK
Indicates that the @code{break} command has been invoked, so the
innermost loop should abort immediately.  The string should always be
empty.

@item TCL_CONTINUE
Indicates that the @code{continue} command has been invoked, so the
innermost loop should go on to the next iteration.  The string should
always be empty.
@end table

Tcl programmers do not normally need to think about return codes, since
@code{TCL_OK} is almost always returned.  If anything else is returned
by a command, then the Tcl interpreter immediately stops processing
commands and returns to its caller.  If there are several nested
invocations of the Tcl interpreter in progress, then each nested command
will usually return the error to its caller, until eventually the error
is reported to the top-level application code.  The application will
then display the error message for the user.

In a few cases, some commands will handle certain ``error'' conditions
themselves and not return them upwards.  For example, the @code{for}
command checks for the @code{TCL_BREAK} code; if it occurs, @code{for}
stops executing the body of the loop and returns @code{TCL_OK} to its
caller.  The @code{for} command also handles @code{TCL_CONTINUE} codes
and the procedure interpreter handles TCL_RETURN codes.  The
@code{catch} command allows Tcl programs to catch errors and handle them
without aborting command interpretation any further.

@node Procedures
@section Procedures

@cindex procedures, Tcl
Tcl allows you to extend the command interface by defining procedures.
A Tcl procedure can be invoked just like any other Tcl command (it has a
name and it receives one or more arguments).  The only difference is
that its body isn't a piece of C code linked into the program; it is a
string containing one or more other Tcl commands.  See the @code{proc}
description in @ref{Tcl Commands,,Built-in commands}, for information on
how to define procedures and what happens when they are invoked.

@node Variable Types
@section Variables: scalars and arrays

@cindex variable types
Tcl allows the definition of variables and the use of their values
either through @samp{$}-style variable substitution, the @code{set}
command, or a few other mechanisms.  Variables need not be declared: a
new variable will automatically be created each time a new variable name
is used.

@cindex scalar variables
@cindex array variables
@cindex indexing arrays
@cindex parentheses in variables
@cindex variable names with parens
Tcl supports two types of variables: scalars and arrays.  A scalar
variable has a single value, whereas an array variable can have any
number of elements, each with a name (called its ``index'') and a value.
Array indices may be arbitrary strings; they need not be numeric.
Parentheses are used refer to array elements in Tcl commands.  For
example, the command @samp{set x(first) 44} will modify the element of
@code{x} whose index is @code{first} so that its new value is @samp{44}.
Two-dimensional arrays can be simulated in Tcl by using indices that
contain multiple concatenated values.  For example, the commands

@example
set a(2,3) 1
set a(3,6) 2
@end example

@noindent
set the elements of @code{a} whose indices are @samp{2,3} and
@samp{3,6}.

In general, array elements may be used anywhere in Tcl that scalar
variables may be used.  If an array is defined with a particular name,
then there may not be a scalar variable with the same name.  Similarly,
if there is a scalar variable with a particular name then it is not
possible to make array references to the variable.  To convert a scalar
variable to an array or vice versa, remove the existing variable with
the @code{unset} command.

The @code{array} command provides several features for dealing with
arrays, such as querying the names of all the elements of the array and
searching through the array one element at a time.

@cindex global variables
@cindex local variables
Variables may be either global or local.  If a variable name is used
when a procedure is not being executed, then it automatically refers to
a global variable.  Variable names used within a procedure normally
refer to local variables associated with that invocation of the
procedure.  Local variables are deleted whenever a procedure exits.  The
@code{global} command may be used to request that a name refer to a
global variable for the duration of the current procedure (this is
somewhat analogous to @code{extern} in C).

@node Tcl Commands
@section Built-in commands

@cindex commands, Tcl
The Tcl library provides the following built-in commands, which will
be available in any application using Tcl.  In addition to these
built-in commands, there may be additional commands defined by each
application, plus commands defined as Tcl procedures.
In the command syntax descriptions below, words in boldface are
literals that you type verbatim to Tcl.
Words in italics are meta-symbols; they serve as names for any of
a range of values that you can type.

Ellipses (``@dots{}'') indicate that any number of additional
arguments or groups of arguments may appear, in the same format
as the preceding argument(s).

@table @code
@item append @var{varName} @var{value}
@itemx append @var{varName} @var{value} @var{value} @var{value} @dots{}
@cindex @code{append} (Tcl command)
Append all of the @var{value} arguments to the current value of variable
@var{varName}.  If @var{varName} does not exist, it is given a value
equal to the concatenation of all the @var{value} arguments.  This
command provides an efficient way to build up long variables
incrementally.  For example, @samp{append a $b} is much more efficient
than @samp{set a $a$b} if @samp{$a} is long.

@item array @var{subcommand} @var{arrayName}
@itemx array @var{subcommand} @var{arrayName} @var{arg} @dots{}
@cindex @code{array} (Tcl command)
Commands in this family perform several operations on the variable given by
@var{arrayName}.  @var{ArrayName} must be the name of an existing array
variable.

@item array anymore @var{arrayName} @var{searchId}
@cindex @code{array anymore} (Tcl command)
@cindex searching arrays
Returns 1 if there are any more elements left to be processed in an
array search, 0 if all elements have already been returned.
@var{SearchId} indicates which search on @var{arrayName} to check, and
must have been the return value from a previous invocation of
@samp{array startsearch}.  This option is particularly useful if an
array has an element with an empty name, since the return value from
@samp{array nextelement} won't indicate whether the search has been
completed.

@item array donesearch @var{arrayName} @var{searchId}
@cindex @code{array donesearch} (Tcl command)
This command terminates an array search and destroys all the state
associated with that search.  @var{SearchId} indicates which search on
@var{arrayName} to destroy, and must have been the return value from a
previous invocation of @samp{array startsearch}.  Returns an empty
string.

@item array names @var{arrayName}
@cindex @code{array names} (Tcl command)
@cindex indices to array, listing
@cindex names of array elements
Returns a list containing the names of all of the elements in the array.
If there are no elements in the array then an empty string is returned.

@item array nextelement @var{arrayName} @var{searchId}
@cindex @code{array nextelement} (Tcl command)
Returns the name of the next element in @var{arrayName}, or an empty
string if all elements of @var{arrayName} have already been returned in
this search.  The @var{searchId} argument identifies the search, and
must have been the return value of an @samp{array startsearch} command.
@emph{Warning:} if elements are added to or deleted from the array, all
searches are automatically terminated just as if @samp{array donesearch}
had been invoked; this will cause @samp{array nextelement} operations to
fail for those searches.

@item array size @var{arrayName}
@cindex @code{array size} (Tcl command)
@cindex number of elements in array
@cindex cardinality, of array
Returns a decimal string giving the number of elements in the
array.

@item array startsearch @var{arrayName}
@cindex @code{array startsearch} (Tcl command)
@cindex searching arrays
This command initializes an element-by-element search through the array
given by @var{arrayName}, such that invocations of the @samp{array
nextelement} command will return the names of the individual elements in
the array.  When the search has been completed, the @samp{array
donesearch} command should be invoked.  The return value is a search
identifier that must be used in @samp{array nextelement} and @samp{array
donesearch} commands; it allows multiple searches to be underway
simultaneously for the same array.

@item break
@cindex @code{break} (Tcl command)
@cindex loops, escaping from
@cindex exiting loops
@cindex returning from loops
This command may be invoked only inside the body of a loop command such
as @code{for} or @code{foreach} or @code{while}.  It returns a
@code{TCL_BREAK} code to signal the innermost containing loop command to
return immediately.

@item case @var{string} in @var{patList} @var{body} @dots{}
@itemx case @var{string} @var{patList} @var{body} @dots{}
@itemx case @var{string} in @{@var{patList} @var{body} @dots{}@}
@itemx case @var{string} @{@var{patList} @var{body} @dots{}@}
@cindex @code{case} (Tcl command)
@cindex multi-way branch
@cindex @code{default} pattern in @code{case}
Match @var{string} against each of the @var{patList} arguments in order.
If one matches, then evaluate the following @var{body} argument by
passing it recursively to the Tcl interpreter, and return the result of
that evaluation.  Each @var{patList} argument consists of a single
pattern or list of patterns.  Each pattern may contain any of the
wild-cards described under @samp{string match}.  If a @var{patList}
argument is @code{default}, the corresponding body will be evaluated if
no @var{patList} matches @var{string}.  If no @var{patList} argument
matches @var{string} and no default is given, then the @code{case}
command returns an empty string.

Two syntaxes are provided (each with a minor variant; you may optionally
include the separator @code{in} in either case).  The first form uses a
separate argument for each of the patterns and commands; this form is
convenient if substitutions are desired on some of the patterns or
commands.  The second form places all of the patterns and commands
together into a single argument; the argument must have proper list
structure, with the elements of the list being the patterns and
commands.  The second form makes it easy to construct multi-line case
commands, since the braces around the whole list make it unnecessary to
include a backslash at the end of each line.  Since the @var{patList}
arguments are in braces in the second form, no command or variable
substitutions are performed on them; this makes the behavior of the
second form different than the first form in some cases.

Here are some examples of @code{case} commands:

@smallexample
case abc in @{a b@} \
  @{format 1@} default @{format 2@} a* @{format 3@}
@end smallexample

@noindent
returns @samp{3}, 

@smallexample
.ta .5c 1c
case a in @{
	@{a b@} @{format 1@}
	default @{format 2@}
	a* @{format 3@}
@}
@end smallexample

@noindent
returns @samp{1}, and

@smallexample
case xyz @{
	@{a b@}
		@{format 1@}
	default
		@{format 2@}
	a*
		@{format 3@}
@}
@end smallexample

@noindent
returns @samp{2}.

@item catch @var{command}
@itemx catch @var{command} @var{varName}
@cindex @code{catch} (Tcl command)
@cindex abort, avoiding
@cindex error handling
The @code{catch} command may be used to prevent errors from aborting
command interpretation.  @code{catch} calls the Tcl interpreter
recursively to execute @var{command}, and always returns a @code{TCL_OK}
code, regardless of any errors that might occur while executing
@var{command}.  The return value from @code{catch} is a decimal string
giving the code returned by the Tcl interpreter after executing
@var{command}.  This will be @samp{0} (@code{TCL_OK}) if there were no
errors in @var{command}; otherwise it will have a non-zero value
corresponding to one of the exceptional return codes (see @file{tcl.h}
for the definitions of code values).  If the @var{varName} argument is
given, then it gives the name of a variable; @code{catch} sets the value
of the variable to the string returned from @var{command} (either a
result or an error message).

@item cd
@itemx cd @var{dirName}
@cindex @code{cd} (Tcl command)
@cindex directory, working
@cindex working directory
Change the current working directory to @var{dirName}, or to the home
directory (as specified in the @code{HOME} environment variable) if
@var{dirName} is not given.  If @var{dirName} starts with a tilde, then
tilde-expansion is done as described for @code{Tcl_TildeSubst}.  Returns
an empty string.  This command can potentially be disruptive to an
application, so it may be removed in some applications.

@item close @var{fileId}
@cindex @code{close} (Tcl command)
@cindex files, closing
@cindex pipe, closing
Closes the file given by @var{fileId}.  @var{FileId} must be the return
value from a previous invocation of the @code{open} command; after this
command, it should not be used anymore.  If @var{fileId} refers to a
command pipeline instead of a file, then @code{close} waits for the
children to complete.  The normal result of this command is an empty
string, but errors are returned if there are problems in closing the
file or waiting for children to complete.

@item concat @var{arg} @dots{}
@cindex @code{concat} (Tcl command)
@cindex catenating lists
@cindex list catenation
@cindex joining lists
@cindex lists, joining
This command treats each argument as a list and concatenates them into a
single list.  It permits any number of arguments.  For example, the
command

@example
concat a b @{c d e@} @{f @{g h@}@}
@end example

@noindent
will return @samp{a b c d e f @{g h@}}
as its result.

@item continue
@cindex @code{continue} (Tcl command)
This command may be invoked only inside the body of a loop command such
as @code{for} or @code{foreach} or @code{while}.  It returns a
@code{TCL_CONTINUE} code to signal the innermost containing loop command
to skip the remainder of the loop's body but continue with the next
iteration of the loop.

@item eof @var{fileId}
@cindex @code{eof} (Tcl command)
@cindex end of file, testing
@cindex file end, testing for
Returns @samp{1} if an end-of-file condition has occurred on
@var{fileId}, @samp{0} otherwise.  @var{fileid} must be the return value
from a previous call to @code{open}, or it may be @code{stdin},
@code{stdout}, or @code{stderr} to refer to one of the standard I/O
channels.

@item error @var{message}
@itemx error @var{message} @var{info}
@itemx error @var{message} @var{info} @var{code}
@cindex @code{error} (Tcl command)
Returns a @code{TCL_ERROR} code, which causes command interpretation to
be unwound.  @var{message} is a string that is returned to the
application to indicate what went wrong.

If the @var{info} argument is provided and is non-empty, it is used to
initialize the global variable @code{errorInfo}.  @code{errorInfo} is
used to accumulate a stack trace of what was in progress when an error
occurred; as nested commands unwind, the Tcl interpreter adds
information to @code{errorInfo}.  If the @var{info} argument is present,
it is used to initialize @code{errorInfo} and the first increment of
unwind information will not be added by the Tcl interpreter.  In other
words, the command containing the @code{error} command will not appear
in @code{errorInfo}; in its place will be @var{info}.  This feature is
most useful in conjunction with the @code{catch} command: if a caught
error cannot be handled successfully, @var{info} can be used to return a
stack trace reflecting the original point of occurrence of the error:

@example
catch @{@dots{}@} errMsg
set savedInfo $errorInfo
@dots{}
error $errMsg $savedInfo
@end example

If the @var{code} argument is present, then its value is stored in the
@code{errorCode} global variable.  This variable is intended to hold a
machine-readable description of the error in cases where such
information is available. @xref{Tcl Variables,,Built-in variables}, for
information on the proper format for the variable.  If the @var{code}
argument is not present, then @code{errorCode} is automatically reset to
@code{NONE} by the Tcl interpreter as part of processing the error
generated by the command.

@item eval @var{arg} @dots{}
@cindex @code{eval} (Tcl command)
@cindex recursive call to Tcl interpreter
@cindex executing Tcl strings
@code{eval} takes one or more arguments, which together comprise a Tcl
command (or collection of Tcl commands separated by newlines in the
usual way).  @code{eval} concatenates all its arguments in the same
fashion as the @code{concat} command, passes the concatenated string to
the Tcl interpreter recursively, and returns the result of that
evaluation (or any error generated by it).

@item exec @var{arg} @dots{}
@cindex @code{exec} (Tcl command)
@cindex shell commands
@cindex executing shell commands
This command treats its arguments as the specification of one or more
@sc{unix} commands to execute as subprocesses.  The commands take the
form of a standard shell pipeline; @samp{|} arguments separate commands
in the pipeline and cause standard output of the preceding command to be
piped into standard input of the next command.

Under normal conditions the result of the @code{exec} command consists
of the standard output produced by the last command in the pipeline.  If
any of the commands in the pipeline exit abnormally or are killed or
suspended, then @code{exec} will return an error and the error message
will include the pipeline's output followed by error messages describing
the abnormal terminations; the @code{errorCode} variable will contain
additional information about the last abnormal termination encountered.
If any of the commands writes to its standard error file, then
@code{exec} will return an error, and the error message will include the
pipeline's output, followed by messages about abnormal terminations (if
any), followed by the standard error output.

If the last character of the result or error message is a newline then
that character is deleted from the result or error message for
consistency with normal Tcl return values.

If an @var{arg} has the value @samp{>} then the following argument is
taken as the name of a file and the standard output of the last command
in the pipeline is redirected to the file.  In this situation
@code{exec} will normally return an empty string.

If an @var{arg} has the value @samp{<} then the following argument is
taken as the name of a file to use for standard input to the first
command in the pipeline.  If an argument has the value @samp{<<} then
the following argument is taken as an immediate value to be passed to
the first command as standard input.  If there is no @samp{<} or
@samp{<<} argument then the standard input for the first command in the
pipeline is taken from the application's current standard input.

If the last @var{arg} is @samp{&} then the command will be executed in
background.  In this case the standard output from the last command in
the pipeline will go to the application's standard output unless
redirected in the command, and error output from all the commands in the
pipeline will go to the application's standard error file.

Each @var{arg} becomes one word for a command, except for @samp{|},
@samp{<}, @samp{<<}, @samp{>}, and @samp{&} arguments, and the arguments
that follow @samp{<}, @samp{<<}, and @samp{>}.  The first word in each
command is taken as the command name; tilde-substitution is performed on
it, and the directories in the @code{PATH} environment variable are
searched for an executable by the given name.  No ``glob'' expansion or
other shell-like substitutions are performed on the arguments to
commands.

@item exit
@itemx exit returnCode
@cindex @code{exit} (Tcl command)
@cindex terminating a process
Terminate the process, returning @var{returnCode} to the parent as the
exit status.  If @var{returnCode} is not specified then it defaults to
@samp{0}.

@item expr @var{arg}
@cindex @code{expr} (Tcl command)
@cindex expression evaluation
@cindex evaluating expressions
Calls the expression processor to evaluate @var{arg}, and returns the
result as a string.  @xref{Tcl Expressions,,Expressions}.

@item file @var{subcommand} @var{name}
@itemx file @var{subcommand} @var{name} @var{arg} @dots{}
@cindex @code{file} (Tcl command)
Commands in this family operate on a file or a file name.  @var{name} is
the name of a file; if it starts with a tilde, then tilde substitution
is done before executing the command.

@item file atime @var{name}
@cindex @code{file atime} (Tcl command)
@cindex last-access time of file
Return a decimal string giving the time at which file @var{name} was
last accessed.  The time is measured in the standard @sc{unix} fashion
as seconds from a fixed starting time (often January 1, 1970).  If the
file does not exist or its access time cannot be queried then an error
is generated.

@item file dirname @var{name}
@cindex @code{file dirname} (Tcl command)
@cindex path, leading parts of
@cindex directory portions of filename
Return all of the characters in @var{name} up to but not including the
last slash character.  If there are no slashes in @var{name} then return
@samp{.}.  If the last slash in @var{name} is its first character, then
return @samp{/}.

@item file executable @var{name}
@cindex @code{file executable} (Tcl command)
@cindex execute permissions, testing
Return @samp{1} if file @var{name} is executable by the current user,
@samp{0} otherwise.

@item file exists @var{name}
@cindex @code{file exists} (Tcl command)
@cindex existence of file
Return @samp{1} if file @var{name} exists and the current user has
search privileges for the directories leading to it, @samp{0} otherwise.

@item file extension @var{name}
@cindex @code{file extension} (Tcl command)
@cindex extension, filename
@cindex suffix, filename
Return all of the characters in @var{name} after and including the
last dot in @var{name}.  If there is no dot in @var{name} then return
the empty string.

@item file isdirectory @var{name}
@cindex @code{file isdirectory} (Tcl command)
@cindex directory, testing
Return @samp{1} if file @var{name} is a directory, @samp{0} otherwise.

@item file isfile @var{name}
@cindex @code{file isfile} (Tcl command)
Return @samp{1} if file @var{name} is a regular file, @samp{0}
otherwise.

@item file lstat @var{name varName}
@cindex @code{file lstat} (Tcl command)
@cindex symlink, @code{stat} for
Same as @code{stat} option (see below) except uses the @var{lstat}
kernel call instead of @var{stat}.  This means that if @var{name} refers
to a symbolic link the information returned in @var{varName} is for the
link rather than the file it refers to.  On systems that do not support
symbolic links this option behaves exactly the same as the @code{stat}
option.

@item file mtime @var{name}
@cindex @code{file mtime} (Tcl command)
@cindex modification time, file
Return a decimal string giving the time at which file @var{name} was
last modified.  The time is measured in the standard @sc{unix} fashion
as seconds from a fixed starting time (often January 1, 1970).  If the
file doesn't exist or its modified time cannot be queried then an error
is generated.

@item file owned @var{name}
@cindex @code{file owned} (Tcl command)
@cindex ownership of file, testing
Return @samp{1} if file @var{name} is owned by the current user,
@samp{0} otherwise.

@item file readable @var{name}
@cindex @code{file readable} (Tcl command)
Return @samp{1} if file @var{name} is readable by the current user,
@samp{0} otherwise.

@item file readlink @var{name}
@cindex @code{file readlink} (Tcl command)
@cindex symlink, evaluating
Returns the value of the symbolic link given by @var{name} (i.e. the
name of the file it points to).  If @var{name} is not a symbolic link or
its value cannot be read, then an error is returned.  On systems that
do not support symbolic links this option is undefined.

@item file rootname @var{name}
@cindex @code{rootname} (Tcl command)
@cindex basename, file
@cindex filename excluding suffix
Return all of the characters in @var{name} up to but not including the
last @samp{.} character in the name.  If @var{name} does not contain a
dot, then return @var{name}.

@item file size @var{name}
@cindex @code{file size} (Tcl command)
@cindex size of file
Return a decimal string giving the size of file @var{name} in bytes.  If
the file does not exist or its size cannot be queried then an error is
generated.

@item file stat @var{name} @var{varName}
@cindex @code{file stat} (Tcl command)
@cindex @code{stat} information on files
Invoke the @code{stat} kernel call on @var{name}, and use the variable
given by @var{varName} to hold information returned from the kernel
call.  @var{VarName} is treated as an array variable, and the following
elements of that variable are set: @code{atime}, @code{ctime},
@code{dev}, @code{gid}, @code{ino}, @code{mode}, @code{mtime},
@code{nlink}, @code{size}, @code{type}, @code{uid}.  Each element except
@code{type} is a decimal string with the value of the corresponding
field from the @code{stat} return structure; see the manual entry for
@code{stat} for details on the meanings of the values.  The @code{type}
element gives the type of the file in the same form returned by the
command @samp{file type}.  This command returns an empty string.

@item file tail @var{name}
@cindex @code{file tail} (Tcl command)
@cindex filename excluding directories
Return all of the characters in @var{name} after the last slash.  If
@var{name} contains no slashes then return @var{name}.

@item file type @var{name}
@cindex @code{file type} (Tcl command)
@cindex type, of files
Returns a string giving the type of file @var{name}, which is one of
@code{file}, @code{directory}, @code{characterSpecial},
@code{blockSpecial}, @code{fifo}, @code{link}, or @code{socket}.

@item file writable @var{name}
@cindex @code{file writable} (Tcl command)
Return @samp{1} if file @var{name} is writable by the current user,
@samp{0} otherwise.

The @code{file} commands that return 0/1 results are often used in
conditional or looping commands, for example:

@example
if @{
  ![file exists foo]
@} then @{
  error @{bad file name@}
@} else @{
  @dots{}
@}
@end example

@item flush @var{fileId}
@cindex @code{flush} (Tcl command)
@cindex output flushing
@cindex buffered output, flushing
Flushes any output that has been buffered for @var{fileId}.
@var{FileId} must have been the return value from a previous call to
@code{open}, or it may be @code{stdout} or @code{stderr} to access one
of the standard I/O streams; it must refer to a file that was opened for
writing.  This command returns an empty string.

@item for @var{start} @var{test} @var{next} @var{body}
@cindex @code{for} (Tcl command)
@cindex looping: @code{for}
@code{for} is a looping command, similar in structure to the C
@code{for} statement.  The @var{start}, @var{next}, and @var{body}
arguments must be Tcl command strings, and @var{test} is an expression
string.

The @code{for} command first invokes the Tcl interpreter to execute
@var{start}.  Then it repeatedly evaluates @var{test} as an expression;
if the result is non-zero it invokes the Tcl interpreter on @var{body},
then invokes the Tcl interpreter on @var{next}, then repeats the loop.
The command terminates when @var{test} evaluates to @samp{0}.  If a
@code{continue} command is invoked within @var{body} then any remaining
commands in the current execution of @var{body} are skipped; processing
continues by invoking the Tcl interpreter on @var{next}, then evaluating
@var{test}, and so on.  If a @code{break} command is invoked within
@var{body} or @var{next}, then the @code{for} command will return
immediately.  The operation of @code{break} and @code{continue} are
similar to the corresponding statements in C.  @code{for} returns an
empty string.

@item foreach @var{varname} @var{list} @var{body}
@cindex @code{foreach} (Tcl command)
@cindex looping: @code{foreach}
In this command, @var{varname} is the name of a variable, @var{list} is
a list of values to assign to @var{varname}, and @var{body} is a
collection of Tcl commands.  For each field in @var{list} (in order from
left to right), @code{foreach} assigns the contents of the field to
@var{varname} (as if the @code{lindex} command had been used to extract
the field), then calls the Tcl interpreter to execute @var{body}.  The
@code{break} and @code{continue} statements may be invoked inside
@var{body}, with the same effect as in the @code{for} command.
@code{Foreach} returns an empty string.

@item format @var{formatString} 
@itemx format @var{formatString} @var{arg} @dots{}
@cindex @code{format} (Tcl command)
@cindex @code{sprintf} style output
This command generates a formatted string in the same way as the C
@code{sprintf} procedure (it uses @code{sprintf} in its implementation).
@var{FormatString} indicates how to format the result, using @samp{%}
fields as in @code{sprintf}, and the additional arguments, if any,
provide values to be substituted into the result.  All of the
@code{sprintf} options are valid; see the @code{sprintf} man page for
details.  Each @var{arg} must match the expected type from the @samp{%}
field in @var{formatString}; the @code{format} command converts each
argument to the correct type (floating, integer, etc.)  before passing
it to @code{sprintf} for formatting.  The only unusual conversion is for
@samp{%c}; in this case the argument must be a decimal string, which
will then be converted to the corresponding @sc{ascii} character value.
@code{format} does backslash substitution on its @var{formatString}
argument, so backslash sequences in @var{formatString} will be handled
correctly even if the argument is in braces.  The return value from
@code{format} is the formatted string.

@item gets @var{fileId}
@itemx gets @var{fileId} @var{varName}
@cindex @code{gets} (Tcl command)
@cindex input line, reading
@cindex line of input, reading
Reads the next line from the file given by @var{fileId} and discards the
terminating newline character.  If @var{varName} is specified, then the
line is placed in the variable by that name and the return value is a
count of the number of characters read (not including the newline).  If
the end of the file is reached before reading any characters then
@samp{-1} is returned and @var{varName} is set to an empty string.  If
@var{varName} is not specified then the return value will be the line
(minus the newline character) or an empty string if the end of the file
is reached before reading any characters.  An empty string will also be
returned if a line contains no characters except the newline, so
@code{eof} may have to be used to determine what really happened.  If
the last character in the file is not a newline character, then
@code{gets} behaves as if there were an additional newline character at
the end of the file.  @var{FileId} must be @code{stdin} or the return
value from a previous call to @code{open}; it must refer to a file that
was opened for reading.

@item glob @var{filename} @dots{}
@itemx glob -nocomplain @var{filename} @dots{}
@cindex @code{glob} (Tcl command)
@cindex file name expansion
This command performs file name expansion, using @code{csh} rules.  The
returned value from @code{glob} is the list of expanded filenames.  If
@code{-nocomplain} is specified as the first argument then an empty list
may be returned; otherwise an error is returned if the expanded list is
empty.  The @code{-nocomplain} argument must be provided exactly: an
abbreviation will not be accepted.

@item global @var{varname} @dots{}
@cindex @code{global} (Tcl command)
@cindex variable reference, global
This command is ignored unless a Tcl procedure is being interpreted.  If
so, then it declares each listed @var{varname} to be a global variable
rather than a local one.  For the duration of the current procedure (and
only while executing in the current procedure), any reference to any
such @var{varname} is bound to a global variable instead of a local one.

@item history
@itemx history @var{subcommand}
@itemx history @var{subcommand} @var{arg} @dots{}
@cindex @code{history} (Tcl command)
@emph{Note: @code{history} commands may not be available in all Tcl-based
applications.} Typically, only applications that receive command input
in a typescript form support history.  The @code{history} commands
perform several operations related to recently-executed commands
recorded in a history list.  Each of these recorded commands is referred
to as an @dfn{event}.  When specifying an event to the @code{history}
command, the following forms may be used:

@enumerate
@item
@cindex event numbers, history
A number: if positive, it refers to the event with that number (all
events are numbered starting at 1).  If the number is negative, it
selects an event relative to the current event (@code{-1} refers to the
previous event, @code{-2} to the one before that, and so on).

@item
@cindex event strings, history
A string:  selects the most recent event that matches the string.
An event is considered to match the string either if the string is
the same as the first characters of the event, or if the string
matches the event in the sense of the @samp{string match} command.
@end enumerate

@item history
Same as @samp{history info}, described below.

@item history add @var{command}
@itemx history add @var{command} exec
@cindex @code{history add} (Tcl command)
Add the @var{command} argument to the history list as a new event.  If
@code{exec} is specified (or abbreviated) then the command is also
executed and its result is returned.  If @code{exec} is not specified
then an empty string is returned as result.

@item history change @var{newValue}
@item history change @var{newValue} @var{event}
@cindex @code{history change} (Tcl command)
Replace the value recorded for an event with @var{newValue}.
@var{event} specifies the event to replace, and defaults to the
@var{current} event (not event @code{-1}).  This command is intended for
use in commands that implement new forms of history substitution and
wish to replace the current event (which invokes the substitution) with
the command created through substitution.  The return value is an empty
string.

@item history event
@item history event @var{event}
@cindex @code{history event} (Tcl command)
Returns the value of the event given by @var{event}.  @var{event}
defaults to @code{-1}.  This command causes history revision to occur:
see below for details.

@item history info
@itemx history info @var{count}
@cindex @code{history info} (Tcl command)
Returns a formatted string (intended for humans to read) giving the
event number and contents for each of the events in the history list
except the current event.  If @var{count} is specified then only the
most recent @var{count} events are returned.

@item history keep @var{count}
@cindex @code{history keep} (Tcl command)
@cindex size of event history
This command may be used to change the size of the history list to
@var{count} events.  Initially, 20 events are retained in the history
list.  This command returns an empty string.

@item history nextid
@cindex @code{history nextid} (Tcl command)
@cindex event number, for prompt
Returns the number of the next event to be recorded in the history list.
It is useful for things like printing the event number in command-line
prompts.

@item history redo
@itemx history redo @var{event}
@cindex @code{history redo} (Tcl command)
Re-execute the command indicated by @var{event} and return its result.
@var{event} defaults to @code{-1}.  This command results in history
revision: see below for details.

@item history substitute @var{old new}
@itemx history substitute @var{old new} @var{event}
@cindex @code{history substitute} (Tcl command)
Retrieve the command given by @var{event} (@code{-1} by default),
replace any occurrences of @var{old} by @var{new} in the command (only
simple character equality is supported; no wild cards), execute the
resulting command, and return the result of that execution.  This
command results in history revision: see below for details.

@item history words @var{selector}
@itemx history words @var{selector} @var{event}
@cindex @code{history words} (Tcl command)
Retrieve from the command given by @var{event} (@code{-1} by default)
the words given by @var{selector}, and return those words in a string
separated by spaces.  The @var{selector} argument has three forms.  If
it is a single number then it selects the word given by that number
(@samp{0} for the command name, @samp{1} for its first argument, and so
on).  If it consists of two numbers separated by a dash, then it selects
all the arguments between those two.  Otherwise @var{selector} is
treated as a pattern; all words matching that pattern (in the sense of
@samp{string match}) are returned.  In the numeric forms @samp{$} may be
used to select the last word of a command.  For example, suppose the
most recent command in the history list is

@smallexample
format  @{%s is %d years old@} Alice [expr $mos/12]
@end smallexample

@need 1000
Here are some @samp{history words} commands and the results they
produce:
@end table
@c table "ends" only to provide more room for example, below

@iftex
@begingroup
@c we need the space; don't narrow margins for example.
@let@nonarrowing=@comment
@end iftex

@smallexample
history words $         [expr $mos/12]
history words 1-2       @{%s is %d years  old@} Alice
history words *e*o*     @{%s is %d years old@} [expr $mos/12]
@end smallexample

@iftex
@endgroup
@end iftex

@table @code
@item @w{ }
@c resume table invisibly after wide example.
@code{history words} results in history revision.

The @code{history} options @code{event}, @code{redo}, @code{substitute},
and @code{words} result in ``history revision''.  When one of these
options is invoked then the current event is modified to eliminate the
history command and replace it with the result of the history command.
For example, suppose that the most recent command in the history list is

@example
set a [expr $b+2]
@end example

@noindent
and suppose that the next command invoked is one of the ones on
the left side of the table below.  The command actually recorded in
the history event will be the corresponding one on the right side
of the table.

@example
Command Typed               Command Recorded

history redo                set a [expr $b+2]
history s a b               set b [expr $b+2]
set c [history w 2]         set c [expr $b+2]
@end example

History revision is needed because event specifiers like @samp{-1} are
only valid at a particular time: once more events have been added to the
history list a different event specifier would be needed.  History
revision occurs even when @code{history} is invoked indirectly from the
current event (e.g. a user types a command that invokes a Tcl procedure
that invokes @code{history}): the top-level command whose execution
eventually resulted in a @code{history} command is replaced.  If you
wish to invoke commands like @samp{history words} without history
revision, you can use @samp{history event} to save the current history
event and then use @samp{history change} to restore it later.

@item if @var{test} @var{trueBody}
@itemx if @var{test} @var{trueBody} @var{falseBody}
@itemx if @var{test} then @var{trueBody}
@itemx if @var{test} then @var{trueBody} else @var{falseBody}
@cindex @code{if} (Tcl command)
@cindex @code{else} in Tcl @code{if}
@cindex conditional command
The @var{if} command evaluates @var{test} as an expression (in the same
way that @code{expr} evaluates its argument).  The value of the
expression must be numeric; if it is non-zero then @var{trueBody} is
called by passing it to the Tcl interpreter.  Otherwise @var{falseBody}
is executed by passing it to the Tcl interpreter.  The @code{then} and
@code{else} arguments are optional ``noise words'' to make the command
easier to read.  @var{falseBody} is also optional; if it is not
specified then the command does nothing if @var{test} evaluates to zero.
The return value from @code{if} is the value of the last command
executed in @var{trueBody} or @var{falseBody}, or the empty string if
@var{test} evaluates to zero and @var{falseBody} is not specified.

@item incr @var{varName}
@item incr @var{varName} @var{increment}
@cindex @code{incr} (Tcl command)
Increment the value stored in the variable whose name is @var{varName}.
The value of the variable must be integral.  If @var{increment} is
supplied then its value (which must be an integer) is added to the value
of variable @var{varName}; otherwise 1 is added to @var{varName}.  The
new value is stored as a decimal string in variable @var{varName} and
also returned as result.

@item info @var{subcommand}
@itemx info @var{subcommand} @var{arg} @dots{}
@cindex @code{info} (Tcl command)
Commands in this family provide information about various internals of
the Tcl interpreter.

@item info args @var{procname}
@cindex @code{info args} (Tcl command)
@cindex arguments to a procedure
Returns a list containing the names of the arguments to procedure
@var{procname}, in order.  @var{procname} must be the name of a
Tcl command procedure.

@item info body @var{procname}
@cindex @code{info body} (Tcl command)
@cindex procedure body
Returns the body of procedure @var{procname}.  @var{Procname} must be
the name of a Tcl command procedure.

@item info cmdcount
@cindex @code{info cmdcount} (Tcl command)
Returns a count of the total number of commands that have been invoked
in this interpreter.

@item info commands
@itemx info commands @var{pattern}
@cindex @code{info commands} (Tcl command)
@cindex commands available, listing
@cindex list of commands
If @var{pattern} is not specified, returns a list of names of all the
Tcl commands, including both the built-in commands written in C and the
command procedures defined using the @code{proc} command.  If
@var{pattern} is specified, only those names matching @var{pattern} are
returned.  Matching is determined using the same rules as for
@samp{string match}.

@item info complete @var{command}
@cindex @code{info complete} (Tcl command)
@cindex command completeness, testing
Returns @samp{1} if @var{command} is a complete Tcl command in the sense
of having no unclosed quotes, braces, brackets or array element names,
If the command does not appear to be complete, @samp{0} is returned.
This command is typically used in line-oriented input environments to
allow users to type in commands that span multiple lines; if the command
is not complete, the script can delay evaluating it until additional
lines have been typed to complete the command.

@item info default @var{procname} @var{arg} @var{varname}
@cindex @code{info default} (Tcl command)
@cindex default arguments, checking
@var{procname} must be the name of a Tcl command procedure and @var{arg}
must be the name of an argument to that procedure.  If @var{arg} does
not have a default value then the command returns @samp{0}.  Otherwise
it returns @samp{1} and places the default value of @var{arg} into
variable @var{varname}.

@item info exists @var{varName}
@cindex @code{info exists} (Tcl command)
@cindex variable existence, checking
Returns @samp{1} if the variable named @var{varName} exists in the
current context (either as a global or local variable), returns @samp{0}
otherwise.

@item info globals
@itemx info globals @var{pattern}
@cindex @code{info globals} (Tcl command)
@cindex global variables, listing
@cindex list of global variables
If @var{pattern} is not specified, returns a list of all the names of
currently-defined global variables.  If @var{pattern} is specified, only
those names matching @var{pattern} are returned.  Matching is determined
using the same rules as for @samp{string match}.

@item info level
@itemx info level @var{number}
@cindex @code{info level} (Tcl command)
If @var{number} is not specified, this command returns a number giving
the stack level of the invoking procedure, or 0 if the command is
invoked at top-level.  If @var{number} is specified, then the result is
a list consisting of the name and arguments for the procedure call at
level @var{number} on the stack.  If @var{number} is positive then it
selects a particular stack level (1 refers to the top-most active
procedure, 2 to the procedure it called, and so on); otherwise it gives
a level relative to the current level (0 refers to the current
procedure, -1 to its caller, and so on).  See the @code{uplevel} command
for more information on what stack levels mean.

@item info library
@cindex @code{info library} (Tcl command)
@cindex @code{TCL_LIBRARY} environment var
@cindex library directory, Tcl
@cindex Tcl library directory
Returns the name of the library directory in which standard Tcl scripts
are stored.  The default value for the library is compiled into Tcl, but
it may be overridden by setting the @code{TCL_LIBRARY} environment
variable.  If there is no @code{TCL_LIBRARY} variable and no compiled-in
value, an error is generated.

Normally each application will have its own application-specific script
library in addition to the Tcl script library; I suggest that each
application set a global variable with a name like
@code{@var{app}_library} (where @var{app} is the application's name) to
hold the location of that application's library directory.

@item info locals
@itemx info locals @var{pattern}
@cindex @code{info locals} (Tcl command)
@cindex local variables, listing
@cindex list of local variables
If @var{pattern} is not specified, returns a list of all the names of
currently-defined local variables, including arguments to the current
procedure, if any.  Variables defined with the @code{global} and
@code{upvar} commands will not be returned.  If @var{pattern} is
specified, only those names matching @var{pattern} are returned.
Matching is determined using the same rules as for @samp{string match}.

@item info procs
@itemx info procs @var{pattern}
@cindex @code{info procs} (Tcl command)
@cindex procedures, listing
@cindex command procedures, listing
@cindex list of procedures
If @var{pattern} is not specified, returns a list of all the names of
Tcl command procedures.  If @var{pattern} is specified, only those names
matching @var{pattern} are returned.  Matching is determined using the
same rules as for @samp{string match}.

@item info script
@cindex @code{info script} (Tcl command)
@cindex name of current Tcl script
If a Tcl script file is currently being evaluated (i.e. there is a call
to @code{Tcl_EvalFile} active or there is an active invocation of the
@code{source} command), then this command returns the name of the
innermost file being processed.  Otherwise the command returns an empty
string.

@item info tclversion
@cindex @code{info tclversion} (Tcl command)
@cindex version number, Tcl
Returns the version number for this version of Tcl in the form
@var{x.y}, where changes to @var{x} represent major changes with
probable incompatibilities and changes to @var{y} represent small
enhancements and bug fixes that retain backward compatibility.

@item info vars
@itemx info vars @var{pattern}
@cindex @code{info vars} (Tcl command)
@cindex variables, listing
@cindex list of variables
If @var{pattern} is not specified, returns a list of all the names of
currently-visible variables, including both locals and currently-visible
globals.  If @var{pattern} is specified, only those names matching
@var{pattern} are returned.  Matching is determined using the same rules
as for @samp{string match}.

@item join @var{list}
@itemx join @var{list} @var{joinString}
@cindex @code{join} (Tcl command)
@cindex converting list to string
@cindex list to string conversion
@cindex string from list, conversion
The @var{list} argument must be a valid Tcl list.  This command returns
the string formed by joining all of the elements of @var{list} together
with @var{joinString} separating each adjacent pair of elements.  The
@var{joinString} argument defaults to a space character.

@item lappend @var{varName} @var{value} @dots{}
@cindex @code{lappend} (Tcl command)
@cindex adding elements to list
@cindex list, adding elements
Treat the variable given by @var{varName} as a list and append each of
the @var{value} arguments to that list as a separate element, with
spaces between elements.  If @var{varName} does not exist, it is created
as a list with elements given by the @var{value} arguments.
@code{lappend} is similar to @code{append} except that the @var{value}s
are appended as list elements rather than raw text.  This command
provides a relatively efficient way to build up large lists.  For
example, @samp{lappend a $b} is much more efficient than @samp{set a
[concat $a [list $b]]} when @samp{$a} is long.

@item lindex @var{list} @var{index}
@cindex @code{lindex} (Tcl command)
@cindex list indexing
@cindex indexing a list
Treats @var{list} as a Tcl list and returns the @var{index}'th element
from it (0 refers to the first element of the list).  In extracting the
element, @var{lindex} observes the same rules concerning braces and
quotes and backslashes as the Tcl command interpreter; however, variable
substitution and command substitution do not occur.  If @var{index} is
negative or greater than or equal to the number of elements in
@var{value}, an empty string is returned.

@item linsert @var{list} @var{index} @var{element} @dots{}
@cindex @code{linsert} (Tcl command)
@cindex inserting elements in list
@cindex merging into a list
This command produces a new list from @var{list} by inserting all of the
@var{element} arguments just before the @var{index}th element of
@var{list}.  Each @var{element} argument will become a separate element
of the new list.  If @var{index} is less than or equal to zero, then the
new elements are inserted at the beginning of the list.  If @var{index}
is greater than or equal to the number of elements in the list, then the
new elements are appended to the list.

@item list @var{arg} @dots{}
@cindex @code{list} (Tcl command)
@cindex building list
@cindex list, building
This command returns a list comprising all the @var{arg}s.  Braces and
backslashes get added as necessary, so that the @code{index} command may
be used on the result to re-extract the original arguments, and also so
that @code{eval} may be used to execute the resulting list, with
@var{arg1} comprising the command's name and the other @var{arg}s
comprising its arguments.  @code{list} produces slightly different
results than @code{concat}: @code{concat} removes one level of grouping
before forming the list, while @code{list} works directly from the
original arguments.  For example, the command

@example
list a b @{c d e@} @{f @{g h@}@}
@end example

@noindent
will return

@example
a b @{c d e@} @{f @{g h@}@}
@end example

@noindent
while @code{concat} with the same arguments will return @samp{a b c d e
f @{g h@}}.

@item llength @var{list}
@cindex @code{llength} (Tcl command)
@cindex list length
@cindex length of list
Treats @var{list} as a list and returns a decimal string giving the
number of elements in it.

@item lrange @var{list} @var{first} @var{last}
@cindex @code{lrange} (Tcl command)
@cindex subset of list
@cindex extracting range from list
@cindex list, portion of
@var{list} must be a valid Tcl list.  This command will return a new
list consisting of elements @var{first} through @var{last}, inclusive.
@var{last} may be @code{end} (or any abbreviation of it) to refer to the
last element of the list.  If @var{first} is less than zero, it is
treated as if it were zero.  If @var{last} is greater than or equal to
the number of elements in the list, then it is treated as if it were
@code{end}.  If @var{first} is greater than @var{last} then an empty
string is returned.  Note: @samp{lrange @var{list} @var{first}
@var{first}} does not always produce the same result as @samp{\fBlindex
@var{list first}} (although it often does for simple fields that are not
enclosed in braces); it does, however, produce exactly the same results
as @samp{list [lindex @var{list first}]}.

@item lreplace @var{list first last}
@itemx lreplace @var{list first last} @var{element} @dots{}
@cindex @code{lreplace} (Tcl command)
@cindex list, replacing in
@cindex replacing list elements
Returns a new list formed by replacing one or more elements of
@var{list} with the @var{element} arguments.  @var{first} gives the
index in @var{list} of the first element to be replaced.  If @var{first}
is less than zero then it refers to the first element of @var{list}; the
element indicated by @var{first} must exist in the list.  @var{last}
gives the index in @var{list} of the last element to be replaced; it
must be greater than or equal to @var{first}.  @var{last} may be
@code{end} (or any abbreviation of it) to indicate that all elements
between @var{first} and the end of the list should be replaced.  The
@var{element} arguments specify zero or more new arguments to be added
to the list in place of those that were deleted.  Each @var{element}
argument will become a separate element of the list.  If no
@var{element} arguments are specified, then the elements between
@var{first} and @var{last} are simply deleted.

@item lsearch @var{list} @var{pattern}
@cindex @code{lsearch} (Tcl command)
@cindex searching list for pattern
@cindex list, searching for pattern
Search the elements of @var{list} to see if one of them matches
@var{pattern}.  If so, the command returns the index of the first
matching element.  If not, the command returns @samp{-1}.  Pattern
matching is done in the same way as for the @samp{string match} command.

@item lsort @var{list}
@cindex @code{lsort} (Tcl command)
@cindex sorting lists
@cindex list sort
Sort the elements of @var{list}, returning a new list in sorted order.
@sc{ascii} sorting is used, with the result in increasing order.

@item open @var{fileName}
@itemx open @var{fileName} @var{access}
@cindex @code{open} (Tcl command)
@cindex file, opening
Opens a file and returns an identifier that may be used in future
invocations of commands like @code{read}, @code{puts}, and @code{close}.
@var{fileName} gives the name of the file to open; if it starts with a
tilde then tilde substitution is performed as described for
@code{Tcl_TildeSubst}.  If the first character of @var{fileName} is
@samp{|} then the remaining characters of @var{fileName} are treated as
a command pipeline to invoke, in the same style as for @code{exec}.  In
this case, the identifier returned by @code{open} may be used to write
to the command's input pipe or read from its output pipe.  The
@var{access} argument indicates the way in which the file (or command
pipeline) is to be accessed.  It may have any of the following values:

@table @code
@item r
Open the file for reading only; the file must already exist.

@item r+
Open the file for both reading and writing; the file must
already exist.

@item w
Open the file for writing only.  Truncate it if it exists.  If it
doesn't exist, create a new file.

@item w+
Open the file for reading and writing.  Truncate it if it exists.  If it
doesn't exist, create a new file.

@item a
Open the file for writing only.  The file must already exist, and the
file is positioned so that new data is appended to the file.

@item a+
Open the file for reading and writing.  If the file doesn't exist,
create a new empty file.  Set the initial access position to the end of
the file.
@end table

@var{access} defaults to @samp{r}.  If a file is opened for both reading
and writing, then @code{seek} must be invoked between a read and a
write, or vice versa (this restriction does not apply to command
pipelines opened with @code{open}).  When @var{fileName} specifies a
command pipeline and a write-only access is used, then standard output
from the pipeline is directed to the current standard output unless
overridden by the command.  When @var{fileName} specifies a command
pipeline and a read-only access is used, then standard input from the
pipeline is taken from the current standard input unless overridden by
the command.

@item proc @var{name} @var{args} @var{body}
@cindex @code{proc} (Tcl command)
@cindex procedures, defining
@cindex command procedures, defining
@cindex defining command procedures
The @code{proc} command creates a new Tcl command procedure, @var{name},
replacing any existing command there may have been by that name.
Whenever the new command is invoked, the contents of @var{body} will be
executed by the Tcl interpreter.  @var{args} specifies the formal
arguments to the procedure.  It consists of a list, possibly empty, each
of whose elements specifies one argument.  Each argument specifier is
also a list with either one or two fields.  If there is only a single
field in the specifier, then it is the name of the argument; if there
are two fields, then the first is the argument name and the second is
its default value.  braces and backslashes may be used in the usual way
to specify complex default values.

When @var{name} is invoked, a local variable is created for each of the
formal arguments to the procedure; its value is the value of
corresponding argument in the invoking command or the argument's default
value.  Arguments with default values need not be specified in a
procedure invocation.  However, there must be enough actual arguments
for all the formal arguments that don't have defaults, and there must
not be any extra actual arguments.  There is one special case to permit
procedures with variable numbers of arguments.  If the last formal
argument has the name @code{args}, then a call to the procedure may
contain more actual arguments than the procedure has formals.  In this
case, all of the actual arguments starting at the one that would be
assigned to @code{args} are combined into a list (as if the @code{list}
command had been used); this combined value is assigned to the local
variable @code{args}.

When @var{body} is being executed, variable names normally refer to
local variables, which are created automatically when referenced and
deleted when the procedure returns.  One local variable is automatically
created for each of the procedure's arguments.  Global variables can
only be accessed by invoking the @code{global} command.

The @code{proc} command returns the null string.  When a procedure is
invoked, the procedure's return value is the value specified in a
@code{return} command.  If the procedure doesn't execute an explicit
@code{return}, then its return value is the value of the last command
executed in the procedure's body.  If an error occurs while executing
the procedure body, then the procedure-as-a-whole will return that same
error.

@item puts @var{fileId} @var{string}
@itemx puts @var{fileId} @var{string} nonewline
@cindex @code{puts} (Tcl command)
@cindex writing string in file
@cindex string, writing in file
@cindex file, writing string to
Writes the characters given by @var{string} to the file given by
@var{fileId}.  @code{puts} normally outputs a newline character after
@var{string}, but this feature may be suppressed by specifying the
@code{nonewline} argument.  Output to files is buffered internally by
Tcl; the @code{flush} command may be used to force buffered characters
to be output.  @var{fileid} must have been the return value from a
previous call to @code{open}, or it may be @code{stdout} or
@code{stderr} to refer to one of the standard I/O channels; it must
refer to a file that was opened for writing.

@item pwd
@cindex @code{pwd} (Tcl command)
@cindex current directory
@cindex directory, current
Returns the path name of the current working directory.

@item read @var{fileId}
@itemx read @var{fileId} nonewline
@itemx read @var{fileId} @var{numBytes}
@cindex @code{read} (Tcl command)
@cindex file, reading
In the first form, all of the remaining bytes are read from the file
given by @var{fileId}; they are returned as the result of the command.
If @code{nonewline} is specified as an additional argument, then the
last character of the file is discarded if it is a newline.  In the
third form, the extra argument specifies how many bytes to read; exactly
this many bytes will be read and returned, unless there are fewer than
@var{numBytes} bytes left in the file; in this case, all the remaining
bytes are returned.  @var{FileId} must be @code{stdin} or the return
value from a previous call to @code{open}; it must refer to a file that
was opened for reading.

@item regexp @var{exp} @var{string}
@itemx regexp -nocase @var{exp} @var{string}
@itemx regexp @var{exp} @var{string} @var{matchVar} @var{subMatchVar} @dots{}
@itemx regexp -indices -nocase @var{exp} @var{string} @var{matchVar} @var{subMatchVar} @dots{}
@cindex @code{regexp} (Tcl command)
@cindex regular expression matching
@cindex matching regular expressions
Determines whether the regular expression @var{exp} matches part or all
of @var{string} and returns 1 if it does, 0 if it does not.
@xref{Regular Expressions}, for complete information on the syntax of
@var{exp} and how it is matched against @var{string}.

If the @samp{-nocase} switch is specified then upper-case characters in
@var{string} are treated as lower case during the matching process.  The
@samp{-nocase} switch must be specified before @var{exp} and may not be
abbreviated.

If additional arguments are specified after @var{string} then they are
treated as the names of variables to use to return information about
which part(s) of @var{string} matched @var{exp}.  @var{matchVar} is set
to the range of @var{string} that matches all of @var{exp}.  The first
@var{subMatchVar} contains the characters in @var{string} that matched
the leftmost parenthesized subexpression within @var{exp}, the next
@var{subMatchVar} contains the characters that matched the next
parenthesized subexpression to the right in @var{exp}, and so on.

Normally, @var{matchVar} and each @var{subMatchVar} are set to hold the
matching characters from @code{string}.  However, if the @samp{-indices}
switch is specified then each variable will contain a list of two
decimal strings giving the indices in @var{string} of the first and last
characters in the matching range of characters.  The @samp{-indices}
switch must be specified before the @var{exp} argument and may not be
abbreviated.

If there are more @var{subMatchVar}s than parenthesized subexpressions
within @var{exp}, or if a particular subexpression in @var{exp} doesn't
match the string (e.g. because it was in a portion of the expression
that wasn't matched), then the corresponding @var{subMatchVar} will be
set to @samp{-1 -1} if @samp{-indices} has been specified or to an empty
string otherwise.

@item regsub @var{exp} @var{string} @var{subSpec} @var{varName}
@itemx regsub -all -nocase @var{exp} @var{string} @var{subSpec} @var{varName}
@cindex @code{regsub} (Tcl command)
@cindex regular expressions, replacement
This command matches the regular expression @var{exp} against
@var{string} using the rules described in @ref{Regular Expressions}.  If
there is no match, then the command returns 0 and does nothing else.  If
there is a match, then the command returns 1 and also copies
@var{string} to the variable whose name is given by @var{varName}.  When
copying @var{string}, the portion of @var{string} that matched @var{exp}
is replaced with @var{subSpec}.  If @var{subSpec} contains a @samp{&} or
@samp{\0}, then it is replaced in the substitution with the portion of
@var{string} that matched @var{exp}.  If @var{subSpec} contains a
@samp{\@var{n}}, where @var{n} is a digit between 1 and 9, then it is
replaced in the substitution with the portion of @var{string} that
matched the @var{n}-th parenthesized subexpression of @var{exp}.
Additional backslashes may be used in @var{subSpec} to prevent special
interpretation of @samp{&} or @samp{\0} or @samp{\@var{n}} or backslash.
The use of backslashes in @var{subSpec} tends to interact badly with the
Tcl parser's use of backslashes, so it's generally safest to enclose
@var{subSpec} in braces if it includes backslashes.

If the @samp{-all} argument is specified, then all ranges in
@var{string} that match @var{exp} are found and substitution is
performed for each of these ranges; otherwise only the first matching
range is found and substituted.  If @samp{-all} is specified, then
@samp{&} and @samp{\@var{n}} sequences are handled for each substitution
using the information from the corresponding match.

If the @samp{-nocase} argument is specified, then upper-case
characters in @var{string} are converted to lower-case before
matching against @var{exp};  however, substitutions specified
by @var{subSpec} use the original unconverted form of @var{string}.

The @samp{-all} and @samp{-nocase} arguments must be specified exactly:
no abbreviations are permitted.

@item rename @var{oldName} @var{newName}
@cindex @code{rename} (Tcl command)
@cindex command renaming
@cindex command deletion
@cindex deleting commands
@cindex renaming commands
@cindex erasing commands
Rename the command that used to be called @var{oldName} so that it is
now called @var{newName}.  If @var{newName} is an empty string (e.g.
@samp{@{@}}) then @var{oldName} is deleted.  The @code{rename} command
returns an empty string as result.

@item return
@itemx return @var{value}
@cindex @code{return} (Tcl command)
@cindex exiting a procedure
@cindex procedure, exiting
Return immediately from the current procedure (or top-level command or
@code{source} command), with @var{value} as the return value.  If
@var{value} is not specified, an empty string will be returned as
result.

@item scan @var{string} @samp{format} @var{varname} @dots{}
@cindex @code{scan} (Tcl command)
@cindex parsing input
@cindex scanning input
@cindex input scanning
This command parses fields from an input string in the same fashion as
the C @code{sscanf} procedure.  @var{string} gives the input to be
parsed and @var{format} indicates how to parse it, using @samp{%} fields
as in @code{sscanf}.  All of the @code{sscanf} options are valid; see
the @code{sscanf} documentation for details.  Each @var{varname} gives
the name of a variable; when a field is scanned from @var{string}, the
result is converted back into a string and assigned to the corresponding
@var{varname}.  The only unusual conversion is for @samp{%c}.  For
@samp{%c} conversions a single character value is converted to a decimal
string, which is then assigned to the corresponding @var{varname}; no
field width may be specified for this conversion.

@item seek @var{fileId} @var{offset}
@itemx seek @var{fileId} @var{offset} @var{origin}
@cindex @code{seek} (Tcl command)
@cindex file, position in
@cindex position in file, setting
Change the current access position for @var{fileId}.
The @var{offset} and @var{origin} arguments specify the position at
which the next read or write will occur for @var{fileId}.
@var{offset} must be a number (which may be negative) and @var{origin}
must be one of the following:

@table @code
@item start
The new access position will be @var{offset} bytes from the start
of the file.

@item current
The new access position will be @var{offset} bytes from the current
access position; a negative @var{offset} moves the access position
backwards in the file.

@item end
The new access position will be @var{offset} bytes from the end of
the file.  A negative @var{offset} places the access position before
the end-of-file, and a positive @var{offset} places the access position
after the end-of-file.
@end table

The @var{origin} argument defaults to @code{start}.  @var{fileId} must
have been the return value from a previous call to @code{open}, or it
may be @code{stdin}, @code{stdout}, or @code{stderr} to refer to one of
the standard I/O channels.  This command returns an empty string.

@item set @var{varname}
@itemx set @var{varname} @var{value}
@cindex @code{set} (Tcl command)
@cindex value of variable
@cindex variable value
@cindex defining variables
@cindex variable, defining
Returns the value of variable @var{varname}.  If @var{value} is
specified, then set the value of @var{varname} to @var{value}, creating
a new variable if one does not already exist, and return its value.  If
@var{varName} contains an open parenthesis and ends with a close
parenthesis, then it refers to an array element: the characters before
the open parenthesis are the name of the array, and the characters
between the parentheses are the index within the array.  Otherwise
@var{varName} refers to a scalar variable.  If no procedure is active,
then @var{varname} refers to a global variable.  If a procedure is
active, then @var{varname} refers to a parameter or local variable of
the procedure, unless the @code{global} command has been invoked to
declare @var{varname} to be global.

@item source @var{fileName}
@cindex @code{source} (Tcl command)
@cindex command file, reading
@cindex file of commands, reading
@cindex reading commands from file
Read file @var{fileName} and pass the contents to the Tcl interpreter as
a sequence of commands to execute in the normal fashion.  The return
value of @code{source} is the return value of the last command executed
from the file.  If an error occurs in executing the contents of the
file, then the @code{source} command will return that error.  If a
@code{return} command is invoked from within the file, the remainder of
the file will be skipped and the @code{source} command will return
normally with the result from the @code{return} command.  If
@var{fileName} starts with a tilde, then it is tilde-substituted as
described in the @code{Tcl_TildeSubst} manual entry.

@item split @var{string} 
@itemx split @var{string} @var{splitChars}
@cindex @code{split} (Tcl command)
@cindex list from string, building
@cindex building list from string
@cindex string to list conversion
Returns a list created by splitting @var{string} at each character that
is in the @var{splitChars} argument.  Each element of the result list
will consist of the characters from @var{string} between instances of
the characters in @var{splitChars}.  Empty list elements will be
generated if @var{string} contains adjacent characters in
@var{splitChars}, or if the first or last character of @var{string} is
in @var{splitChars}.  If @var{splitChars} is an empty string then each
character of @var{string} becomes a separate element of the result list.
@var{SplitChars} defaults to the standard white-space characters.  For
example,

@example
split "comp.unix.misc" .
@end example

@noindent
returns @samp{"comp unix misc"} and

@example
split "Hello world" @{@}
@end example

@noindent
returns @samp{"H e l l o @{ @} w o r l d"}.

@item string @var{subcommand} @var{arg} @dots{}
@cindex @code{string} (Tcl command)
Commands in this family perform several string operations.
The subcommands may be abbreviated.

@item string compare @var{string1} @var{string2}
@cindex @code{string compare} (Tcl command)
@cindex lexicographic comparison
Perform a character-by-character comparison of strings @var{string1} and
@var{string2} in the same way as the C @code{strcmp} procedure.  Return
-1, 0, or 1, depending on whether @var{string1} is lexicographically
less than, equal to, or greater than @var{string2}.

@item string first @var{string1} @var{string2}
@cindex @code{string first} (Tcl command)
@cindex substring search (first)
@cindex searching for substrings (first)
@cindex finding substrings (first)
Search @var{string2} for a sequence of characters that exactly match the
characters in @var{string1}.  If found, return the index of the first
character in the first such match within @var{string2}.  If not found,
return -1.

@item string index @var{string} @var{i}
@cindex @code{string index} (Tcl command)
@cindex character in string, selecting
@cindex selecting character from string
Returns the @var{i}'th character of the @var{string} argument.
A @var{i} of 0 corresponds to the first character of the string.
If @var{i} is less than 0 or greater than or equal to the length
of the string then an empty string is returned.

@item string last @var{string1} @var{string2}
@cindex @code{string last} (Tcl command)
@cindex substring search (last)
@cindex searching for substrings (last)
@cindex finding substrings (last)
Search @var{string2} for a sequence of characters that exactly match the
characters in @var{string1}.  If found, return the index of the first
character in the last such match within @var{string2}.  If there is no
match, then return -1.

@item string length @var{string}
@cindex @code{string length} (Tcl command)
@cindex length of string
@cindex cardinality of string
Returns a decimal string giving the number of characters in @var{string}.

@item string match @var{pattern} @var{string}
@cindex @code{string match} (Tcl command)
@cindex comparing strings
@cindex globbing comparison
@cindex matching with wildcards
@cindex wildcard matching
See if @var{pattern} matches @var{string}; return 1 if it does, 0
if it does not.  Matching is done in a fashion similar to that
used by the C-shell.  For the two strings to match, their contents
must be identical except that the following special sequences
may appear in @var{pattern}:

@table @code
@item *
Matches any sequence of characters in @var{string}, including a null
string.

@item ?
Matches any single character in @var{string}.

@item [@var{chars}]
Matches any character in the set given by @var{chars}.  If a sequence of
the form @var{x}-@var{y} appears in @var{chars}, then any character
between @var{x} and @var{y}, inclusive, will match.

@item \@var{x}
Matches the single character @var{x}.  This provides a way of avoiding
the special interpretation of the characters @samp{*?[]\} in
@var{pattern}.
@end table

@item string range @var{string} @var{first} @var{last}
@cindex @code{string range} (Tcl command)
@cindex substring, selecting
Returns a range of consecutive characters from @var{string}, starting
with the character whose index is @var{first} and ending with the
character whose index is @var{last}.  An index of 0 refers to the
first character of the string.  @var{last} may be @code{end} (or any
abbreviation of it) to refer to the last character of the string.
If @var{first} is less than zero then it is treated as if it were zero, and
if @var{last} is greater than or equal to the length of the string then
it is treated as if it were @code{end}.  If @var{first} is greater than
@var{last} then an empty string is returned.

@item string tolower @var{string}
@cindex @code{string tolower} (Tcl command)
@cindex minuscules, conversion to
@cindex lower case, conversion to
Returns a value equal to @var{string} except that all upper case
letters have been converted to lower case.

@item string toupper @var{string}
@cindex @code{toupper} (Tcl command)
@cindex majuscules, conversion to
@cindex upper case, conversion to
Returns a value equal to @var{string} except that all lower case
letters have been converted to upper case.

@item string trim @var{string}
@itemx string trim @var{string} @var{chars}
@cindex @code{string trim} (Tcl command)
@cindex whitespace, removing
@cindex removing leading or trailing chars
Returns a value equal to @var{string} except that any leading
or trailing characters from the set given by @var{chars} are
removed.
If @var{chars} is not specified then white space is removed
(spaces, tabs, newlines, and carriage returns).

@item string trimleft @var{string}
@itemx string trimleft @var{string} @var{chars}
@cindex @code{trimleft} (Tcl command)
@cindex removing leading chars
@cindex leading chars, removing
Returns a value equal to @var{string} except that any leading characters
from the set given by @var{chars} are removed.  If @var{chars} is not
specified then white space is removed (spaces, tabs, newlines, and
carriage returns).

@item string trimright @var{string}
@itemx string trimright @var{string} @var{chars}
@cindex @code{string trimright} (Tcl command)
@cindex removing trailing chars
@cindex trailing chars, removing
Returns a value equal to @var{string} except that any trailing
characters from the set given by @var{chars} are removed.  If
@var{chars} is not specified then white space is removed (spaces, tabs,
newlines, and carriage returns).

@item tell @var{fileId}
@cindex @code{tell} (Tcl command)
@cindex position in file
@cindex file position
Returns a decimal string giving the current access position in
@var{fileId}.  @var{fileId} must have been the return value from a
previous call to @code{open}, or it may be @code{stdin}, @code{stdout},
or @code{stderr} to refer to one of the standard I/O channels.

@item time @var{command}
@itemx time @var{command} @var{count}
@cindex @code{time} (Tcl command)
@cindex measuring execution time
@cindex execution time, measuring
This command will call the Tcl interpreter @var{count} times to execute
@var{command} (or once if @var{count} isn't specified).  It will then
return a string of the form

@example
503 microseconds per iteration
@end example

@noindent
which indicates the average amount of time required per iteration, in
microseconds.  Time is measured in elapsed time, not CPU time.

@item trace @var{subcommand}
@itemx trace @var{subcommand} @var{arg} @dots{}
@cindex @code{trace} (Tcl command)
Commands in this family cause Tcl commands to be executed whenever
certain operations are invoked.  At present, only variable tracing is
implemented.

@item trace variable @var{name} @var{ops} @var{command}
@cindex @code{trace variable} (Tcl command)
@cindex variable tracing
Arrange for @var{command} to be executed whenever variable @var{name}
is accessed in one of the ways given by @var{ops}.  @var{name} may
refer to a normal variable, an element of an array, or to an array
as a whole (i.e. @var{name} may be just the name of an array, with no
parenthesized index).  If @var{name} refers to a whole array, then
@var{command} is invoked whenever any element of the array is
manipulated.

@var{ops} indicates which operations are of interest, and consists of
one or more of the following letters:

@table @code
@item r
Invoke @var{command} whenever the variable is read.

@item w
Invoke @var{command} whenever the variable is written.

@item u
Invoke @var{command} whenever the variable is unset.  Variables
can be unset explicitly with the @code{unset} command, or
implicitly when procedures return (all of their local variables
are unset).  Variables are also unset when interpreters are
deleted, but traces will not be invoked because there is no
interpreter in which to execute them.
@end table

When the trace triggers, three arguments are appended to @var{command}
so that the actual command is @samp{@var{command} @var{name1}
@var{name2} @samp{op}}.  @var{name1} and @var{name2} give the name(s)
for the variable being accessed: if the variable is a scalar then
@var{name1} gives the variable's name and @var{name2} is an empty
string; if the variable is an array element then @var{name1} gives the
name of the array and name2 gives the index into the array; if an entire
array is being deleted and the trace was registered on the overall
array, rather than a single element, then @var{name1} gives the array
name and @var{name2} is an empty string.  @var{Op} indicates what
operation is being performed on the variable, and is one of @samp{r},
@samp{w}, or @samp{u} as defined above.

@var{command} executes in the same context as the code that invoked the
traced operation: if the variable was accessed as part of a Tcl
procedure, then @var{command} will have access to the same local
variables as code in the procedure.  This context may be different than
the context in which the trace was created.  If @var{command} invokes a
procedure (which it normally does) then the procedure will have to use
@code{upvar} or @code{uplevel} if it wishes to access the traced
variable.  Note also that @var{name1} may not necessarily be the same as
the name used to set the trace on the variable; differences can occur if
the access is made through a variable defined with the @code{upvar}
command.

For read and write traces, @var{command} can modify the variable to
affect the result of the traced operation.  If @var{command} modifies
the value of a variable during a read or write trace, then the new value
will be returned as the result of the traced operation.  The return
value from @var{command} is ignored except that if it returns an error
of any sort then the traced operation is aborted with an error message
saying that the access was denied (this mechanism can be used to
implement read-only variables, for example).  For write traces,
@var{command} is invoked after the variable's value has been changed; it
can write a new value into the variable to override the original value
specified in the write operation.  To implement read-only variables,
@var{command} will have to restore the old value of the variable.

While @var{command} is executing during a read or write trace, traces on
the variable are temporarily disabled.  This means that reads and writes
invoked by @var{command} will occur directly, without invoking
@var{command} (or any other traces) again.

When an unset trace is invoked, the variable has already been deleted:
it will appear to be undefined with no traces.  If an unset occurs
because of a procedure return, then the trace will be invoked in the
variable context of the procedure being returned to: the stack frame of
the returning procedure will no longer exist.  Traces are not disabled
during unset traces, so if an unset trace command creates a new trace
and accesses the variable, the trace will be invoked.

If there are multiple traces on a variable they are invoked in order of
creation, most-recent first.  If one trace returns an error, then no
further traces are invoked for the variable.  If an array element has a
trace set, and there is also a trace set on the array as a whole, the
trace on the overall array is invoked before the one on the element.

Once created, the trace remains in effect either until the trace is
removed with the @samp{trace vdelete} command described below, until the
variable is unset, or until the interpreter is deleted.  Unsetting an
element of array will remove any traces on that element, but will not
remove traces on the overall array.

This command returns an empty string.

@item trace vdelete @var{name} @var{ops} @var{command}
@cindex @code{trace vdelete} (Tcl command)
@cindex variable trace, deleting
@cindex deleting variable trace
If there is a trace set on variable @var{name} with the operations and
command given by @var{ops} and @var{command}, then the trace is removed,
so that @var{command} will never again be invoked.  Returns an empty
string.

@item trace vinfo @var{name}
@cindex @code{trace vinfo} (Tcl command)
@cindex list of traced variables
@cindex traced variables, listing
Returns a list containing one element for each trace currently set on
variable @var{name}.  Each element of the list is itself a list
containing two elements, which are the @var{ops} and @var{command}
associated with the trace.  If @var{name} doesn't exist or doesn't have
any traces set, then the result of the command will be an empty string.

@item unknown @var{cmdName}
@itemx unknown @var{cmdName} @var{arg} @dots{}
@cindex @code{unknown} (Tcl command)
@cindex default command
This command does not actually exist as part of Tcl, but Tcl will invoke
it if it does exist.  If the Tcl interpreter encounters a command name
for which there is not a defined command, then Tcl checks for the
existence of a command named @code{unknown}.  If there is no such
command, then the interpeter returns an error.  If the @code{unknown}
command exists, then it is invoked with arguments consisting of the
fully-substituted name and arguments for the original non-existent
command.  The @code{unknown} command typically does things like
searching through library directories for a command procedure with the
name @var{cmdName}, or expanding abbreviated command names to
full-length, or automatically executing unknown commands as UNIX
sub-processes.  In some cases (such as expanding abbreviations)
@code{unknown} will change the original command slightly and then
(re-)execute it.  The result of the @code{unknown} command is used as
the result for the original non-existent command.

@item unset @var{name} @dots{}
@cindex @code{unset} (Tcl command)
@cindex removing variables
@cindex deleting variables
@cindex erasing variables
@cindex variables, erasing
Remove one or more variables.  Each @var{name} is a variable name,
specified in any of the ways acceptable to the @code{set} command.  If a
@var{name} refers to an element of an array, then that element is
removed without affecting the rest of the array.  If a @var{name}
consists of an array name with no parenthesized index, then the entire
array is deleted.  The @code{unset} command returns an empty string as
result.  An error occurs if any of the variables doesn't exist.

@item uplevel @var{command} @dots{}
@itemx uplevel @var{level} @var{command} @dots{}
@cindex @code{uplevel} (Tcl command)
@cindex stack, executing elsewhere in
@cindex executing elsewhere in stack
All of the @var{command} arguments are concatenated as if they had been
passed to @code{concat}; the result is then evaluated in the variable
context indicated by @var{level}.  @code{uplevel} returns the result of
that evaluation.  If @var{level} is an integer, then it gives a distance
(up the procedure calling stack) to move before executing the command.
If @var{level} consists of @samp{#} followed by a number then the number
gives an absolute level number.  If @var{level} is omitted then it
defaults to @samp{1}.  @var{level} cannot be defaulted if the first
@var{command} argument starts with a digit or @samp{#}.  For example,
suppose that procedure @code{a} was invoked from top-level, and that it
called @code{b}, and that @code{b} called @code{c}.  Suppose that
@code{c} invokes the @code{uplevel} command.  If @var{level} is @samp{1}
or @samp{#2} or omitted, then the command will be executed in the
variable context of @code{b}.  If @var{level} is @samp{2} or @samp{#1}
then the command will be executed in the variable context of @code{a}.
If @var{level} is @samp{3} or @samp{#0} then the command will be
executed at top-level (only global variables will be visible).  The
@code{uplevel} command causes the invoking procedure to disappear from
the procedure calling stack while the command is being executed.  In the
above example, suppose @code{c} invokes the command

@example
uplevel 1 @{set x 43; d@}
@end example

@noindent
where @code{d} is another Tcl procedure.  The @code{set} command will
modify the variable @code{x} in the context of @code{b}, and @code{d}
will execute at level 3, as if called from @code{b}.  If it in turn
executes the command

@example
uplevel @{set x 42@}
@end example

@noindent
then the @code{set} command will modify the same variable @code{x} in
the context of @code{b} context: the procedure @code{c} does not appear
to be on the call stack when @code{d} is executing.  The command
@samp{info level} may be used to obtain the level of the current
procedure.  @code{Uplevel} makes it possible to implement new control
constructs as Tcl procedures (for example, @code{uplevel} could be used
to implement the @code{while} construct as a Tcl procedure).

@item upvar @var{otherVar} @var{myVar} @dots{}
@item upvar @var{level} @var{otherVar} @var{myVar} @dots{}
@cindex @code{upvar} (Tcl command)
@cindex local variables, linking to other levels
@cindex variables across stack levels
This command arranges for one or more local variables in the current
procedure to refer to variables in an enclosing procedure call, or to
global variables.  @var{level} may have any of the forms permitted for
the @code{uplevel} command, and may be omitted if the first letter of
the first @var{otherVar} is not @samp{#} or a digit (it defaults to
@samp{1}).  For each @var{otherVar} argument, @code{upvar} makes the
variable by that name in the procedure frame given by @var{level} (or at
global level, if @var{level} is @samp{#0}) accessible in the current
procedure by the name given in the corresponding @var{myVar} argument.
The variable named by @var{otherVar} need not exist at the time of the
call; it will be created the first time @var{myVar} is referenced, just
like an ordinary variable.  @code{upvar} may only be invoked from within
procedures.  Neither @var{otherVar} or @var{myVar} may refer to an
element of an array.  @code{upvar} returns an empty string.

The @code{upvar} command simplifies the implementation of call-by-name
procedure calling and also makes it easier to build new control
constructs as Tcl procedures.  For example, consider the following
procedure:

@example
proc add2 name @{
    upvar $name x
    set x [expr $x+2]
@}
@end example

@code{add2} is invoked with an argument giving the name of a variable,
and it adds two to the value of that variable.  Although @code{add2}
could have been implemented using @code{uplevel} instead of
@code{upvar}, @code{upvar} makes it simpler for @code{add2} to access
the variable in the caller's procedure frame.

@item while @var{test} @var{body}
@cindex @code{while} (Tcl command)
@cindex looping: @code{while}
The @var{while} command evaluates @var{test} as an expression (in the
same way that @code{expr} evaluates its argument).  The value of the
expression must be numeric; if it is non-zero then @var{body} is
executed by passing it to the Tcl interpreter.  Once @var{body} has been
executed then @var{test} is evaluated again, and the process repeats
until eventually @var{test} evaluates to a zero numeric value.
@code{continue} commands may be executed inside @var{body} to terminate
the current iteration of the loop, and @code{break} commands may be
executed inside @var{body} to cause immediate termination of the
@code{while} command.  The @code{while} command always returns an empty
string.
@end table

@node Tcl Variables
@section Built-in variables

The following global variables are created and managed automatically
by the Tcl library.  Except where noted below, these variables should
normally be treated as read-only by application-specific code and by users.

@table @code
@item env
@cindex @code{env} (Tcl variable)
@cindex environment variables
This variable is maintained by Tcl as an array whose elements are the
environment variables for the process.  Reading an element will return
the value of the corresponding environment variable.  Setting an element
of the array will modify the corresponding environment variable or
create a new one if it doesn't already exist.  Unsetting an element of
@code{env} will remove the corresponding environment variable.  Changes
to the @code{env} array will affect the environment passed to children
by commands like @code{exec}.  If the entire @code{env} array is unset
then Tcl will stop monitoring @code{env} accesses and will not update
environment variables.

@item errorCode
@cindex @code{errorCode} (Tcl variable)
@cindex error reporting
@cindex reporting errors
After an error has occurred, this variable will be set to hold
additional information about the error in a form that is easy to process
with programs.  @code{errorCode} consists of a Tcl list with one or more
elements.  The first element of the list identifies a general class of
errors, and determines the format of the rest of the list.  The
following formats for @code{errorCode} are used by the Tcl core;
individual applications may define additional formats.

@table @code
@item CHILDKILLED @var{pid} @var{sigName} @var{msg}
This format is used when a child process has been killed because of a
signal.  The second element of @code{errorCode} will be the process's
identifier (in decimal).  The third element will be the symbolic name of
the signal that caused the process to terminate; it will be one of the
names from the include file @file{signal.h}, such as @code{SIGPIPE}.
The fourth element will be a short human-readable message describing the
signal, such as @samp{write on pipe with no readers} for @code{SIGPIPE}.

@item CHILDSTATUS @var{pid} @var{code}
This format is used when a child process has exited with a non-zero exit
status.  The second element of @code{errorCode} will be the process's
identifier (in decimal) and the third element will be the exit code
returned by the process (also in decimal).

@item CHILDSUSP @var{pid} @var{sigName} @var{msg}
This format is used when a child process has been suspended because of a
signal.  The second element of @code{errorCode} will be the process's
identifier, in decimal.  The third element will be the symbolic name of
the signal that caused the process to suspend; this will be one of the
names from the include file @file{signal.h}, such as @code{SIGTTIN}.
The fourth element will be a short human-readable message describing the
signal, such as @samp{background tty read} for @code{SIGTTIN}.

@item NONE
This format is used for errors where no additional information is
available for an error besides the message returned with the
error.  In these cases @code{errorCode} will consist of a list
containing a single element whose contents are @code{NONE}.

@item UNIX @var{errName} @var{msg}
If the first element of @code{errorCode} is @code{UNIX}, then the error
occurred during a @sc{unix} kernel call.  The second element of the list
will contain the symbolic name of the error that occurred, such as
@code{ENOENT}; this will be one of the values defined in the include
file @file{errno.h}.  The third element of the list will be a
human-readable message corresponding to @var{errName}, such as @samp{no
such file or directory} for the @code{ENOENT} case.

To set @code{errorCode}, applications should use library procedures such
as @code{Tcl_SetErrorCode} and @code{Tcl_UnixError}, or they may invoke
the @code{error} command.  If one of these methods hasn't been used,
then the Tcl interpreter will reset the variable to @code{NONE} after
the next error.
@end table

@item errorInfo
@cindex @code{errorInfo} (Tcl variable)
@cindex error context
@cindex stack trace
After an error has occurred, this string will contain one or more lines
identifying the Tcl commands and procedures that were being executed
when the most recent error occurred.  Its contents take the form of a
stack trace showing the various nested Tcl commands that had been
invoked at the time of the error.
@end table

@node Thanks
@section Acknowledgements
@cindex Ousterhout, John
John Ousterhout (@samp{ouster@@sprite.berkeley.edu}), of the University
of California at Berkeley, is the author of Tcl.

Many people have contributed to Tcl in various ways, but the following
people have made unusually large contributions:

@cindex Carpenter, Bill
@cindex Da Silva, Peter
@cindex Diekhans, Mark
@cindex Lehenbauer, Karl
@cindex May-Pumphrey, Mary Ann
@display
Bill Carpenter
Peter Da Silva
Mark Diekhans
Karl Lehenbauer
Mary Ann May-Pumphrey
@end display

