Updates to the manual for hyperlinked commands
[jimtcl.git] / jim_tcl.txt
blob3dd1c42fc565fd84b8a376acdc777f58e6cba582
1 Jim Tcl(n)
2 ==========
4 NAME
5 ----
6 Jim Tcl v0.72 - overview of the Jim tool command language facilities
8 SYNOPSIS
9 --------
11   cc <source> -ljim
15   jimsh [<scriptfile>]
16   jimsh -e '<immediate-script>'
17   jimsh --version
20 .Quick Index
21 * <<CommandIndex,Command Reference>>
22 * <<OperatorPrecedence,Operator Precedence>>
23 * <<BuiltinVariables, Builtin Variables>>
24 * <<BackslashSequences, Backslash Sequences>>
26 INTRODUCTION
27 ------------
28 Jim is a reimplementation of Tcl, combining some features from
29 earlier, smaller versions of Tcl (6.x) as well as more modern
30 features from later versions of Tcl (7.x, 8.x). It also has some some
31 entirely new features not available in any version of Tcl.
33 This version is about double the size of "tinytcl" (6.8), depending upon
34 the features selected, but is significantly faster and has many new features.
36 Note that most of this man page is the original 6.8 Tcl man page, with
37 changes made for differences with Jim.
39 The major differences with Tcl 8.5/8.6 are:
41 1. Object-based I/O (aio), but with a Tcl-compatibility layer
42 2. I/O: Support for sockets and pipes including udp, unix domain sockets and IPv6
43 3. Integers are 64bit
44 4. Support for references (`ref`/`getref`/`setref`) and garbage collection
45 5. Builtin dictionary type (`dict`) with some limitations compared to Tcl 8.6
46 6. `env` command to access environment variables
47 7. `os.fork`, `os.wait`, `os.uptime`, `rand`
48 8. Much better error reporting. `info stacktrace` as a replacement for '$errorInfo', '$errorCode'
49 9. Support for "static" variables in procedures
50 10. Namespaces are not support
51 11. Variable traces are not supported
52 12. Direct command line editing rather than the `history` command
53 13. Expression shorthand syntax: +$(...)+
55 RECENT CHANGES
56 --------------
58 Changes between 0.71 and 0.72
59 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
60 1. procs now allow 'args' and optional parameters in any position
61 2. Add Tcl-compatible expr functions, `rand()` and `srand()`
62 3. Add support for the '-force' option to `file delete`
63 4. Better diagnostics when `source` fails to load a script with a missing quote or bracket
64 5. New +tcl_platform(pathSeparator)+
65 6. Add support settings the modification time with `file mtime`
67 Changes between 0.70 and 0.71
68 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
69 1. Allow 'args' to be renamed in procs
70 2. Add +$(...)+ shorthand syntax for expressions
71 3. Add automatic reference variables in procs with +&var+ syntax
72 4. Support +jimsh --version+
73 5. Additional variables in +tcl_platform()+
74 6. `local` procs now push existing commands and `upcall` can call them
75 7. Add `loop` command (TclX compatible)
76 8. Add `aio buffering` command
77 9. `info complete` can now return the missing character
78 10. `binary format` and `binary scan` are now (optionally) supported
79 11. Add `string byterange`
80 12. Built-in regexp now support non-greedy repetition (*?, +?, ??)
82 Changes between 0.63 and 0.70
83 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
84 1. +platform_tcl()+ settings are now automatically determined
85 2. Add aio `$handle filename`
86 3. Add `info channels`
87 4. The 'bio' extension is gone. Now `aio` supports 'copyto'.
88 5. Add `exists` command
89 6. Add the pure-Tcl 'oo' extension
90 7. The `exec` command now only uses vfork(), not fork()
91 8. Unit test framework is less verbose and more Tcl-compatible
92 9. Optional UTF-8 support
93 10. Optional built-in regexp engine for better Tcl compatibility and UTF-8 support
94 11. Command line editing in interactive mode, e.g. 'jimsh'
96 TCL INTRODUCTION
97 -----------------
98 Tcl stands for 'tool command language' and is pronounced 'tickle.'
99 It is actually two things: a language and a library.
101 First, Tcl is a simple textual language, intended primarily for
102 issuing commands to interactive programs such as text editors,
103 debuggers, illustrators, and shells.  It has a simple syntax and is also
104 programmable, so Tcl users can write command procedures to provide more
105 powerful commands than those in the built-in set.
107 Second, Tcl is a library package that can be embedded in application
108 programs.  The Tcl library consists of a parser for the Tcl language,
109 routines to implement the Tcl built-in commands, and procedures that
110 allow each application to extend Tcl with additional commands specific
111 to that application.  The application program generates Tcl commands and
112 passes them to the Tcl parser for execution.  Commands may be generated
113 by reading characters from an input source, or by associating command
114 strings with elements of the application's user interface, such as menu
115 entries, buttons, or keystrokes.
117 When the Tcl library receives commands it parses them into component
118 fields and executes built-in commands directly.  For commands implemented
119 by the application, Tcl calls back to the application to execute the
120 commands.  In many cases commands will invoke recursive invocations of the
121 Tcl interpreter by passing in additional strings to execute (procedures,
122 looping commands, and conditional commands all work in this way).
124 An application program gains three advantages by using Tcl for its command
125 language.  First, Tcl provides a standard syntax:  once users know Tcl,
126 they will be able to issue commands easily to any Tcl-based application.
127 Second, Tcl provides programmability.  All a Tcl application needs
128 to do is to implement a few application-specific low-level commands.
129 Tcl provides many utility commands plus a general programming interface
130 for building up complex command procedures.  By using Tcl, applications
131 need not re-implement these features.
133 Third, Tcl can be used as a common language for communicating between
134 applications.  Inter-application communication is not built into the
135 Tcl core described here, but various add-on libraries, such as the Tk
136 toolkit, allow applications to issue commands to each other.  This makes
137 it possible for applications to work together in much more powerful ways
138 than was previously possible.
140 Fourth, Jim Tcl includes a command processor, +jimsh+, which can be
141 used to run standalone Tcl scripts, or to run Tcl commands interactively.
143 This manual page focuses primarily on the Tcl language.  It describes
144 the language syntax and the built-in commands that will be available
145 in any application based on Tcl.  The individual library procedures are
146 described in more detail in separate manual pages, one per procedure.
148 JIMSH COMMAND INTERPRETER
149 -------------------------
150 A simple, but powerful command processor, +jimsh+, is part of Jim Tcl.
151 It may be invoked in interactive mode as:
153   jimsh
155 or to process the Tcl script in a file with:
157   jimsh filename
159 It may also be invoked to execute an immediate script with:
161   jimsh -e "script"
163 Interactive Mode
164 ~~~~~~~~~~~~~~~~
165 Interactive mode reads Tcl commands from standard input, evaluates
166 those commands and prints the results.
168   $ jimsh
169   Welcome to Jim version 0.71, Copyright (c) 2005-8 Salvatore Sanfilippo
170   . info version
171   0.71
172   . lsort [info commands p*]
173   package parray pid popen proc puts pwd
174   . foreach i {a b c} {
175   {> puts $i
176   {> }
177   a
178   b
179   c
180   . bad
181   invalid command name "bad"
182   [error] . exit
183   $
185 If +jimsh+ is configured with line editing (it is by default) and a VT-100-compatible
186 terminal is detected, Emacs-style line editing commands are available, including:
187 arrow keys, +\^W+ to erase a word, +\^U+ to erase the line, +^R+ for reverse incremental search
188 in history. Additionally, the +h+ command may be used to display the command history.
190 Command line history is automatically saved and loaded from +~/.jim_history+
192 In interactive mode, +jimsh+ automatically runs the script +~/.jimrc+ at startup
193 if it exists.
195 INTERPRETERS
196 ------------
197 The central data structure in Tcl is an interpreter (C type 'Jim_Interp').
198 An interpreter consists of a set of command bindings, a set of variable
199 values, and a few other miscellaneous pieces of state.  Each Tcl command
200 is interpreted in the context of a particular interpreter.
202 Some Tcl-based applications will maintain multiple interpreters
203 simultaneously, each associated with a different widget or portion of
204 the application.  Interpreters are relatively lightweight structures.
205 They can be created and deleted quickly, so application programmers should
206 feel free to use multiple interpreters if that simplifies the application.
208 DATA TYPES
209 ----------
210 Tcl supports only one type of data:  strings.  All commands, all arguments
211 to commands, all command results, and all variable values are strings.
213 Where commands require numeric arguments or return numeric results,
214 the arguments and results are passed as strings.  Many commands expect
215 their string arguments to have certain formats, but this interpretation
216 is up to the individual commands.  For example, arguments often contain
217 Tcl command strings, which may get executed as part of the commands.
218 The easiest way to understand the Tcl interpreter is to remember that
219 everything is just an operation on a string.  In many cases Tcl constructs
220 will look similar to more structured constructs from other languages.
221 However, the Tcl constructs are not structured at all; they are just
222 strings of characters, and this gives them a different behaviour than
223 the structures they may look like.
225 Although the exact interpretation of a Tcl string depends on who is doing
226 the interpretation, there are three common forms that strings take:
227 commands, expressions, and lists.  The major sections below discuss
228 these three forms in more detail.
230 BASIC COMMAND SYNTAX
231 --------------------
232 The Tcl language has syntactic similarities to both the Unix shells
233 and Lisp.  However, the interpretation of commands is different
234 in Tcl than in either of those other two systems.
235 A Tcl command string consists of one or more commands separated
236 by newline characters or semi-colons.
237 Each command consists of a collection of fields separated by
238 white space (spaces or tabs).
239 The first field must be the name of a command, and the
240 additional fields, if any, are arguments that will be passed to
241 that command.  For example, the command:
243     set a 22
245 has three fields:  the first, `set`, is the name of a Tcl command, and
246 the last two, 'a' and '22', will be passed as arguments to
247 the `set` command.  The command name may refer either to a built-in
248 Tcl command, an application-specific command bound in with the library
249 procedure 'Jim_CreateCommand', or a command procedure defined with the
250 `proc` built-in command.
252 Arguments are passed literally as text strings.  Individual commands may
253 interpret those strings in any fashion they wish.  The `set` command,
254 for example, will treat its first argument as the name of a variable
255 and its second argument as a string value to assign to that variable.
256 For other commands arguments may be interpreted as integers, lists,
257 file names, or Tcl commands.
259 Command names should normally be typed completely (e.g. no abbreviations).
260 However, if the Tcl interpreter cannot locate a command it invokes a
261 special command named `unknown` which attempts to find or create the
262 command.
264 For example, at many sites `unknown` will search through library
265 directories for the desired command and create it as a Tcl procedure if
266 it is found.  The `unknown` command often provides automatic completion
267 of abbreviated commands, but usually only for commands that were typed
268 interactively.
270 It's probably a bad idea to use abbreviations in command scripts and
271 other forms that will be re-used over time:  changes to the command set
272 may cause abbreviations to become ambiguous, resulting in scripts that
273 no longer work.
275 COMMENTS
276 --------
277 If the first non-blank character in a command is +\#+, then everything
278 from the +#+ up through the next newline character is treated as
279 a comment and ignored.  When comments are embedded inside nested
280 commands (e.g. fields enclosed in braces) they must have properly-matched
281 braces (this is necessary because when Tcl parses the top-level command
282 it doesn't yet know that the nested field will be used as a command so
283 it cannot process the nested comment character as a comment).
285 GROUPING ARGUMENTS WITH DOUBLE-QUOTES
286 -------------------------------------
287 Normally each argument field ends at the next white space, but
288 double-quotes may be used to create arguments with embedded space.
290 If an argument field begins with a double-quote, then the argument isn't
291 terminated by white space (including newlines) or a semi-colon (see below
292 for information on semi-colons); instead it ends at the next double-quote
293 character.  The double-quotes are not included in the resulting argument.
294 For example, the command
296     set a "This is a single argument"
298 will pass two arguments to `set`:  'a' and 'This is a single argument'.
300 Within double-quotes, command substitutions, variable substitutions,
301 and backslash substitutions still occur, as described below.  If the
302 first character of a command field is not a quote, then quotes receive
303 no special interpretation in the parsing of that field.
305 GROUPING ARGUMENTS WITH BRACES
306 ------------------------------
307 Curly braces may also be used for grouping arguments.  They are similar
308 to quotes except for two differences.  First, they nest; this makes them
309 easier to use for complicated arguments like nested Tcl command strings.
310 Second, the substitutions described below for commands, variables, and
311 backslashes do *not* occur in arguments enclosed in braces, so braces
312 can be used to prevent substitutions where they are undesirable.
314 If an argument field begins with a left brace, then the argument ends
315 at the matching right brace.  Tcl will strip off the outermost layer
316 of braces and pass the information between the braces to the command
317 without any further modification.  For example, in the command
319     set a {xyz a {b c d}}
321 the `set` command will receive two arguments: 'a'
322 and 'xyz a {b c d}'.
324 When braces or quotes are in effect, the matching brace or quote need
325 not be on the same line as the starting quote or brace; in this case
326 the newline will be included in the argument field along with any other
327 characters up to the matching brace or quote.  For example, the `eval`
328 command takes one argument, which is a command string; `eval` invokes
329 the Tcl interpreter to execute the command string.  The command
331     eval {
332       set a 22
333       set b 33
334     }
336 will assign the value '22' to 'a' and '33' to 'b'.
338 If the first character of a command field is not a left
339 brace, then neither left nor right
340 braces in the field will be treated specially (except as part of
341 variable substitution; see below).
343 COMMAND SUBSTITUTION WITH BRACKETS
344 ----------------------------------
345 If an open bracket occurs in a field of a command, then command
346 substitution occurs (except for fields enclosed in braces).  All of the
347 text up to the matching close bracket is treated as a Tcl command and
348 executed immediately.  Then the result of that command is substituted
349 for the bracketed text.  For example, consider the command
351     set a [set b]
353 When the `set` command has only a single argument, it is the name of a
354 variable and `set` returns the contents of that variable.  In this case,
355 if variable 'b' has the value 'foo', then the command above is equivalent
356 to the command
358     set a foo
360 Brackets can be used in more complex ways.  For example, if the variable
361 'b' has the value 'foo' and the variable 'c' has the value 'gorp',
362 then the command
364     set a xyz[set b].[set c]
366 is equivalent to the command
368     set a xyzfoo.gorp
371 A bracketed command may contain multiple commands separated by newlines
372 or semi-colons in the usual fashion.  In this case the value of the last
373 command is used for substitution.  For example, the command
375     set a x[set b 22
376     expr $b+2]x
378 is equivalent to the command
380     set a x24x
383 If a field is enclosed in braces then the brackets and the characters
384 between them are not interpreted specially; they are passed through to
385 the argument verbatim.
387 VARIABLE SUBSTITUTION WITH $
388 ----------------------------
389 The dollar sign (+$+) may be used as a special shorthand form for
390 substituting variable values.  If +$+ appears in an argument that isn't
391 enclosed in braces then variable substitution will occur.  The characters
392 after the +$+, up to the first character that isn't a number, letter,
393 or underscore, are taken as a variable name and the string value of that
394 variable is substituted for the name.
396 For example, if variable 'foo' has the value 'test', then the command
398     set a $foo.c
400 is equivalent to the command
402     set a test.c
404 There are two special forms for variable substitution.  If the next
405 character after the name of the variable is an open parenthesis, then
406 the variable is assumed to be an array name, and all of the characters
407 between the open parenthesis and the next close parenthesis are taken as
408 an index into the array.  Command substitutions and variable substitutions
409 are performed on the information between the parentheses before it is
410 used as an index.
412 For example, if the variable 'x' is an array with one element named
413 'first' and value '87' and another element named '14' and value 'more',
414 then the command
416     set a xyz$x(first)zyx
418 is equivalent to the command
420     set a xyz87zyx
422 If the variable 'index' has the value '14', then the command
424     set a xyz$x($index)zyx
426 is equivalent to the command
428     set a xyzmorezyx
430 For more information on arrays, see VARIABLES AND ARRAYS below.
432 The second special form for variables occurs when the dollar sign is
433 followed by an open curly brace.  In this case the variable name consists
434 of all the characters up to the next curly brace.
436 Array references are not possible in this form:  the name between braces
437 is assumed to refer to a scalar variable.  For example, if variable
438 'foo' has the value 'test', then the command
440     set a abc${foo}bar
442 is equivalent to the command
444     set a abctestbar
447 Variable substitution does not occur in arguments that are enclosed in
448 braces:  the dollar sign and variable name are passed through to the
449 argument verbatim.
451 The dollar sign abbreviation is simply a shorthand form.  +$a+ is
452 completely equivalent to +[set a]+; it is provided as a convenience
453 to reduce typing.
455 SEPARATING COMMANDS WITH SEMI-COLONS
456 ------------------------------------
457 Normally, each command occupies one line (the command is terminated by a
458 newline character).  However, semi-colon (+;+) is treated as a command
459 separator character; multiple commands may be placed on one line by
460 separating them with a semi-colon.  Semi-colons are not treated as
461 command separators if they appear within curly braces or double-quotes.
463 BACKSLASH SUBSTITUTION
464 ----------------------
465 Backslashes may be used to insert non-printing characters into command
466 fields and also to insert special characters like braces and brackets
467 into fields without them being interpreted specially as described above.
469 The backslash sequences understood by the Tcl interpreter are
470 listed below.  In each case, the backslash
471 sequence is replaced by the given character:
472 [[BackslashSequences]]
473 +{backslash}b+::
474     Backspace (0x8)
476 +{backslash}f+::
477     Form feed (0xc)
479 +{backslash}n+::
480     Newline (0xa)
482 +{backslash}r+::
483     Carriage-return (0xd).
485 +{backslash}t+::
486     Tab (0x9).
488 +{backslash}v+::
489     Vertical tab (0xb).
491 +{backslash}{+::
492     Left brace ({).
494 +{backslash}}+::
495     Right brace (}).
497 +{backslash}[+::
498     Open bracket ([).
500 +{backslash}]+::
501     Close bracket (]).
503 +{backslash}$+::
504     Dollar sign ($).
506 +{backslash}<space>+::
507     Space ( ): doesn't terminate argument.
509 +{backslash};+::
510     Semi-colon: doesn't terminate command.
512 +{backslash}"+::
513     Double-quote.
515 +{backslash}<newline>+::
516     Nothing:  this joins two lines together
517     into a single line.  This backslash feature is unique in that
518     it will be applied even when the sequence occurs within braces.
520 +{backslash}{backslash}+::
521     Backslash ('{backslash}').
523 +{backslash}'ddd'+::
524     The digits +'ddd'+ (one, two, or three of them) give the octal value of
525     the character.  Note that Jim supports null characters in strings.
527 +{backslash}'unnnn'+::
528     The hex digits +'nnnn'+ (between one and four of them) give a unicode codepoint.
529     The UTF-8 encoding of the codepoint is inserted.
531 For example, in the command
533     set a \{x\[\ yz\141
535 the second argument to `set` will be +{x[ yza+.
537 If a backslash is followed by something other than one of the options
538 described above, then the backslash is transmitted to the argument
539 field without any special processing, and the Tcl scanner continues
540 normal processing with the next character.  For example, in the
541 command
543     set \*a \\\{foo
545 The first argument to `set` will be +{backslash}*a+ and the second
546 argument will be +{backslash}{foo+.
548 If an argument is enclosed in braces, then backslash sequences inside
549 the argument are parsed but no substitution occurs (except for
550 backslash-newline):  the backslash
551 sequence is passed through to the argument as is, without making
552 any special interpretation of the characters in the backslash sequence.
553 In particular, backslashed braces are not counted in locating the
554 matching right brace that terminates the argument.
555 For example, in the
556 command
558     set a {\{abc}
560 the second argument to `set` will be +{backslash}{abc+.
562 This backslash mechanism is not sufficient to generate absolutely
563 any argument structure; it only covers the
564 most common cases.  To produce particularly complicated arguments
565 it is probably easiest to use the `format` command along with
566 command substitution.
568 STRING AND LIST INDEX SPECIFICATIONS
569 ------------------------------------
571 Many string and list commands take one or more 'index' parameters which
572 specify a position in the string relative to the start or end of the string/list.
574 The index may be one of the following forms:
576 +integer+::
577     A simple integer, where '0' refers to the first element of the string
578     or list.
580 +integer+integer+ or::
581 +integer-integer+::
582     The sum or difference of the two integers. e.g. +2+3+ refers to the 5th element.
583     This is useful when used with (e.g.) +$i+1+ rather than the more verbose
584     +[expr {$i+1\}]+
586 +end+::
587     The last element of the string or list.
589 +end-integer+::
590     The 'nth-from-last' element of the string or list.
592 COMMAND SUMMARY
593 ---------------
594 1. A command is just a string.
595 2. Within a string commands are separated by newlines or semi-colons
596    (unless the newline or semi-colon is within braces or brackets
597    or is backslashed).
598 3. A command consists of fields.  The first field is the name of the command.
599    The other fields are strings that are passed to that command as arguments.
600 4. Fields are normally separated by white space.
601 5. Double-quotes allow white space and semi-colons to appear within
602    a single argument.
603    Command substitution, variable substitution, and backslash substitution
604    still occur inside quotes.
605 6. Braces defer interpretation of special characters.
606    If a field begins with a left brace, then it consists of everything
607    between the left brace and the matching right brace. The
608    braces themselves are not included in the argument.
609    No further processing is done on the information between the braces
610    except that backslash-newline sequences are eliminated.
611 7. If a field doesn't begin with a brace then backslash,
612    variable, and command substitution are done on the field.  Only a
613    single level of processing is done:  the results of one substitution
614    are not scanned again for further substitutions or any other
615    special treatment.  Substitution can
616    occur on any field of a command, including the command name
617    as well as the arguments.
618 8. If the first non-blank character of a command is a +\#+, everything
619    from the +#+ up through the next newline is treated as a comment
620    and ignored.
622 EXPRESSIONS
623 -----------
624 The second major interpretation applied to strings in Tcl is
625 as expressions.  Several commands, such as `expr`, `for`,
626 and `if`, treat one or more of their arguments as expressions
627 and call the Tcl expression processors ('Jim_ExprLong',
628 'Jim_ExprBoolean', etc.) to evaluate them.
630 The operators permitted in Tcl expressions are a subset of
631 the operators permitted in C expressions, and they have the
632 same meaning and precedence as the corresponding C operators.
633 Expressions almost always yield numeric results
634 (integer or floating-point values).
635 For example, the expression
637     8.2 + 6
639 evaluates to 14.2.
641 Tcl expressions differ from C expressions in the way that
642 operands are specified, and in that Tcl expressions support
643 non-numeric operands and string comparisons.
645 A Tcl expression consists of a combination of operands, operators,
646 and parentheses.
648 White space may be used between the operands and operators and
649 parentheses; it is ignored by the expression processor.
650 Where possible, operands are interpreted as integer values.
652 Integer values may be specified in decimal (the normal case), in octal (if the
653 first character of the operand is '0'), or in hexadecimal (if the first
654 two characters of the operand are '0x').
656 If an operand does not have one of the integer formats given
657 above, then it is treated as a floating-point number if that is
658 possible.  Floating-point numbers may be specified in any of the
659 ways accepted by an ANSI-compliant C compiler (except that the
660 'f', 'F', 'l', and 'L' suffixes will not be permitted in
661 most installations).  For example, all of the
662 following are valid floating-point numbers:  2.1, 3., 6e4, 7.91e+16.
664 If no numeric interpretation is possible, then an operand is left
665 as a string (and only a limited set of operators may be applied to
666 it).
668 1. Operands may be specified in any of the following ways:
670 2. As a numeric value, either integer or floating-point.
672 3. As a Tcl variable, using standard '$' notation.
673 The variable's value will be used as the operand.
675 4. As a string enclosed in double-quotes.
676 The expression parser will perform backslash, variable, and
677 command substitutions on the information between the quotes,
678 and use the resulting value as the operand
680 5. As a string enclosed in braces.
681 The characters between the open brace and matching close brace
682 will be used as the operand without any substitutions.
684 6. As a Tcl command enclosed in brackets.
685 The command will be executed and its result will be used as
686 the operand.
688 Where substitutions occur above (e.g. inside quoted strings), they
689 are performed by the expression processor.
690 However, an additional layer of substitution may already have
691 been performed by the command parser before the expression
692 processor was called.
694 As discussed below, it is usually best to enclose expressions
695 in braces to prevent the command parser from performing substitutions
696 on the contents.
698 For some examples of simple expressions, suppose the variable 'a' has
699 the value 3 and the variable 'b' has the value 6.  Then the expression
700 on the left side of each of the lines below will evaluate to the value
701 on the right side of the line:
703     $a + 3.1                6.1
704     2 + "$a.$b"             5.6
705     4*[llength "6 2"]       8
706     {word one} < "word $a"  0
708 The valid operators are listed below, grouped in decreasing order
709 of precedence:
710 [[OperatorPrecedence]]
711 +int() double() round() abs(), rand(), srand()+::
712     Unary functions (except rand() which takes no arguments)
713     int() converts the numeric argument to an integer by truncating down.
714     double() converts the numeric argument to floating point.
715     round() converts the numeric argument to the closest integer value.
716     abs() takes the absolute value of the numeric argument.
717     rand() takes the absolute value of the numeric argument.
718     rand() returns a pseudo-random floating-point value in the range (0,1).
719     srand() takes an integer argument to (re)seed the random number generator. Returns the first random number from that seed.
721 +sin() cos() tan() asin() acos() atan() sinh() cosh() tanh() ceil() floor() exp() log() log10() sqrt()+::
722     Unary math functions.
723     If Jim is compiled with math support, these functions are available.
725 +- + ~ !+::
726     Unary minus, unary plus, bit-wise NOT, logical NOT.  None of these operands
727     may be applied to string operands, and bit-wise NOT may be
728     applied only to integers.
730 +**+::
731     Power. e.g. pow(). If Jim is compiled with math support, supports doubles and
732     integers. Otherwise supports integers only.
734 +* / %+::
735     Multiply, divide, remainder.  None of these operands may be
736     applied to string operands, and remainder may be applied only
737     to integers.
739 +\+ -+::
740     Add and subtract.  Valid for any numeric operands.
742 +<<  >> <<< >>>+::
743     Left and right shift, left and right rotate.  Valid for integer operands only.
745 +<  >  \<=  >=+::
746     Boolean less, greater, less than or equal, and greater than or equal.
747     Each operator produces 1 if the condition is true, 0 otherwise.
748     These operators may be applied to strings as well as numeric operands,
749     in which case string comparison is used.
751 +==  !=+::
752     Boolean equal and not equal.  Each operator produces a zero/one result.
753     Valid for all operand types. *Note* that values will be converted to integers
754     if possible, then floating point types, and finally strings will be compared.
755     It is recommended that 'eq' and 'ne' should be used for string comparison.
757 +eq ne+::
758     String equal and not equal.  Uses the string value directly without
759     attempting to convert to a number first.
761 +in ni+::
762     String in list and not in list. For 'in', result is 1 if the left operand (as a string)
763     is contained in the right operand (as a list), or 0 otherwise. The result for
764     +{$a ni $list}+ is equivalent to +{!($a in $list)}+.
766 +&+::
767     Bit-wise AND.  Valid for integer operands only.
769 +|+::
770     Bit-wise OR.  Valid for integer operands only.
772 +^+::
773     Bit-wise exclusive OR.  Valid for integer operands only.
775 +&&+::
776     Logical AND.  Produces a 1 result if both operands are non-zero, 0 otherwise.
777     Valid for numeric operands only (integers or floating-point).
779 +||+::
780     Logical OR.  Produces a 0 result if both operands are zero, 1 otherwise.
781     Valid for numeric operands only (integers or floating-point).
783 +x ? y : z+::
784     If-then-else, as in C.  If +'x'+
785     evaluates to non-zero, then the result is the value of +'y'+.
786     Otherwise the result is the value of +'z'+.
787     The +'x'+ operand must have a numeric value, while +'y'+ and +'z'+ can
788     be of any type.
790 See the C manual for more details on the results
791 produced by each operator.
792 All of the binary operators group left-to-right within the same
793 precedence level.  For example, the expression
795     4*2 < 7
797 evaluates to 0.
799 The +&&+, +||+, and +?:+ operators have 'lazy evaluation', just as
800 in C, which means that operands are not evaluated if they are not
801 needed to determine the outcome.  For example, in
803     $v ? [a] : [b]
805 only one of +[a]+ or +[b]+ will actually be evaluated,
806 depending on the value of +$v+.
808 All internal computations involving integers are done with the C
809 type 'long long' if available, or 'long' otherwise, and all internal
810 computations involving floating-point are done with the C type
811 'double'.
813 When converting a string to floating-point, exponent overflow is
814 detected and results in a Tcl error.
815 For conversion to integer from string, detection of overflow depends
816 on the behaviour of some routines in the local C library, so it should
817 be regarded as unreliable.
818 In any case, overflow and underflow are generally not detected
819 reliably for intermediate results.
821 Conversion among internal representations for integer, floating-point,
822 and string operands is done automatically as needed.
823 For arithmetic computations, integers are used until some
824 floating-point number is introduced, after which floating-point is used.
825 For example,
827     5 / 4
829 yields the result 1, while
831     5 / 4.0
832     5 / ( [string length "abcd"] + 0.0 )
834 both yield the result 1.25.
836 String values may be used as operands of the comparison operators,
837 although the expression evaluator tries to do comparisons as integer
838 or floating-point when it can.
839 If one of the operands of a comparison is a string and the other
840 has a numeric value, the numeric operand is converted back to
841 a string using the C 'sprintf' format specifier
842 '%d' for integers and '%g' for floating-point values.
843 For example, the expressions
845     "0x03" > "2"
846     "0y" < "0x12"
848 both evaluate to 1.  The first comparison is done using integer
849 comparison, and the second is done using string comparison after
850 the second operand is converted to the string '18'.
852 In general it is safest to enclose an expression in braces when
853 entering it in a command:  otherwise, if the expression contains
854 any white space then the Tcl interpreter will split it
855 among several arguments.  For example, the command
857     expr $a + $b
859 results in three arguments being passed to `expr`:  +$a+,
860 +\++, and +$b+.  In addition, if the expression isn't in braces
861 then the Tcl interpreter will perform variable and command substitution
862 immediately (it will happen in the command parser rather than in
863 the expression parser).  In many cases the expression is being
864 passed to a command that will evaluate the expression later (or
865 even many times if, for example, the expression is to be used to
866 decide when to exit a loop).  Usually the desired goal is to re-do
867 the variable or command substitutions each time the expression is
868 evaluated, rather than once and for all at the beginning.  For example,
869 the command
871     for {set i 1} $i<=10 {incr i} {...}        +** WRONG **+
873 is probably intended to iterate over all values of +i+ from 1 to 10.
874 After each iteration of the body of the loop, `for` will pass
875 its second argument to the expression evaluator to see whether or not
876 to continue processing.  Unfortunately, in this case the value of +i+
877 in the second argument will be substituted once and for all when the
878 `for` command is parsed.  If +i+ was 0 before the `for`
879 command was invoked then the second argument of `for` will be +0\<=10+
880 which will always evaluate to 1, even though +i+ eventually
881 becomes greater than 10.  In the above case the loop will never
882 terminate.  Instead, the expression should be placed in braces:
884     for {set i 1} {$i<=10} {incr i} {...}      +** RIGHT **+
886 This causes the substitution of 'i'
887 to be delayed; it will be re-done each time the expression is
888 evaluated, which is the desired result.
890 LISTS
891 -----
892 The third major way that strings are interpreted in Tcl is as lists.
893 A list is just a string with a list-like structure
894 consisting of fields separated by white space.  For example, the
895 string
897     Al Sue Anne John
899 is a list with four elements or fields.
900 Lists have the same basic structure as command strings, except
901 that a newline character in a list is treated as a field separator
902 just like space or tab.  Conventions for braces and quotes
903 and backslashes are the same for lists as for commands.  For example,
904 the string
906     a b\ c {d e {f g h}}
908 is a list with three elements:  +a+, +b c+, and +d e {f g h}+.
910 Whenever an element is extracted from a list, the same rules about
911 braces and quotes and backslashes are applied as for commands.  Thus in
912 the example above when the third element is extracted from the list,
913 the result is
915     d e {f g h}
917 (when the field was extracted, all that happened was to strip off
918 the outermost layer of braces).  Command substitution and
919 variable substitution are never
920 made on a list (at least, not by the list-processing commands; the
921 list can always be passed to the Tcl interpreter for evaluation).
923 The Tcl commands `concat`, `foreach`, `lappend`, `lindex`, `linsert`,
924 `list`, `llength`, `lrange`, `lreplace`, `lsearch`, and `lsort` allow
925 you to build lists, extract elements from them, search them, and perform
926 other list-related functions.
928 Advanced list commands include `lrepeat`, `lreverse`, `lmap`, `lassign`, `lset`.
930 LIST EXPANSION
931 --------------
933 A new addition to Tcl 8.5 is the ability to expand a list into separate
934 arguments. Support for this feature is also available in Jim.
936 Consider the following attempt to exec a list:
938     set cmd {ls -l}
939     exec $cmd
941 This will attempt to exec the a command named "ls -l", which will clearly not
942 work. Typically eval and concat are required to solve this problem, however
943 it can be solved much more easily with +\{*\}+.
945     exec {*}$cmd
947 This will expand the following argument into individual elements and then evaluate
948 the resulting command.
950 Note that the official Tcl syntax is +\{*\}+, however +\{expand\}+ is retained
951 for backward compatibility with experimental versions of this feature.
953 REGULAR EXPRESSIONS
954 -------------------
955 Tcl provides two commands that support string matching using regular
956 expressions, `regexp` and `regsub`, as well as `switch -regexp` and
957 `lsearch -regexp`.
959 Regular expressions may be implemented one of two ways. Either using the system's C library
960 POSIX regular expression support, or using the built-in regular expression engine.
961 The differences between these are described below.
963 *NOTE* Tcl 7.x and 8.x use perl-style Advanced Regular Expressions (+ARE+).
965 POSIX Regular Expressions
966 ~~~~~~~~~~~~~~~~~~~~~~~~~
967 If the system supports POSIX regular expressions, and UTF-8 support is not enabled,
968 this support will be used by default. The type of regular expressions supported are
969 Extended Regular Expressions (+ERE+) rather than Basic Regular Expressions (+BRE+).
970 See REG_EXTENDED in the documentation.
972 Using the system-supported POSIX regular expressions will typically
973 make for the smallest code size, but some features such as UTF-8
974 and +{backslash}w+, +{backslash}d+, +{backslash}s+ are not supported.
976 See regex(3) and regex(7) for full details.
978 Jim built-in Regular Expressions
979 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
980 The Jim built-in regulare expression engine may be selected with +./configure --with-jim-regexp+
981 or it will be selected automatically if UTF-8 support is enabled.
983 This engine supports UTF-8 as well as some +ARE+ features. The differences with both Tcl 7.x/8.x
984 and POSIX are highlighted below.
986 1. UTF-8 strings and patterns are both supported
987 2. Supported character classes: +[:alnum:]+, +[:digit:]+ and +[:space:]+
988 3. Supported shorthand character classes: +{backslash}w = +[:alnum:]+, +{backslash}d+ = +[:digit:],+ +{backslash}s+ = +[:space:]+
989 4. Character classes apply to ASCII characters only
990 5. Supported constraint escapes: +{backslash}m+ = +{backslash}<+ = start of word, +{backslash}M+ = +{backslash}>+ = end of word
991 6. Backslash escapes may be used within regular expressions, such as +{backslash}n+ = newline, +{backslash}uNNNN+ = unicode
992 7. No support for the +?+ non-greedy quantifier. e.g. +*?+
994 COMMAND RESULTS
995 ---------------
996 Each command produces two results:  a code and a string.  The
997 code indicates whether the command completed successfully or not,
998 and the string gives additional information.  The valid codes are
999 defined in jim.h, and are:
1001 +JIM_OK(0)+::
1002     This is the normal return code, and indicates that the command completed
1003     successfully.  The string gives the command's return value.
1005 +JIM_ERR(1)+::
1006     Indicates that an error occurred; the string gives a message describing
1007     the error.
1009 +JIM_RETURN(2)+::
1010     Indicates that the `return` command has been invoked, and that the
1011     current procedure (or top-level command or `source` command)
1012     should return immediately.  The
1013     string gives the return value for the procedure or command.
1015 +JIM_BREAK(3)+::
1016     Indicates that the `break` command has been invoked, so the
1017     innermost loop should abort immediately.  The string should always
1018     be empty.
1020 +JIM_CONTINUE(4)+::
1021     Indicates that the `continue` command has been invoked, so the
1022     innermost loop should go on to the next iteration.  The string
1023     should always be empty.
1025 +JIM_SIGNAL(5)+::
1026     Indicates that a signal was caught while executing a commands.
1027     The string contains the name of the signal caught.
1028     See the `signal` and `catch` commands.
1030 +JIM_EXIT(6)+::
1031     Indicates that the command called the `exit` command.
1032     The string contains the exit code.
1034 Tcl programmers do not normally need to think about return codes,
1035 since +JIM_OK+ is almost always returned.  If anything else is returned
1036 by a command, then the Tcl interpreter immediately stops processing
1037 commands and returns to its caller.  If there are several nested
1038 invocations of the Tcl interpreter in progress, then each nested
1039 command will usually return the error to its caller, until eventually
1040 the error is reported to the top-level application code.  The
1041 application will then display the error message for the user.
1043 In a few cases, some commands will handle certain `error` conditions
1044 themselves and not return them upwards.  For example, the `for`
1045 command checks for the +JIM_BREAK+ code; if it occurs, then `for`
1046 stops executing the body of the loop and returns +JIM_OK+ to its
1047 caller.  The `for` command also handles +JIM_CONTINUE+ codes and the
1048 procedure interpreter handles +JIM_RETURN+ codes.  The `catch`
1049 command allows Tcl programs to catch errors and handle them without
1050 aborting command interpretation any further.
1052 The `info returncodes` command may be used to programmatically map between
1053 return codes and names.
1055 PROCEDURES
1056 ----------
1057 Tcl allows you to extend the command interface by defining
1058 procedures.  A Tcl procedure can be invoked just like any other Tcl
1059 command (it has a name and it receives one or more arguments).
1060 The only difference is that its body isn't a piece of C code linked
1061 into the program; it is a string containing one or more other
1062 Tcl commands.
1064 The `proc` command is used to create a new Tcl command procedure:
1066 +*proc* 'name arglist ?statics? body'+
1068 The new command is named +'name'+, and it replaces any existing command
1069 there may have been by that name. Whenever the new command is
1070 invoked, the contents of +'body'+ will be executed by the Tcl
1071 interpreter.
1073 +'arglist'+ specifies the formal arguments to the procedure.
1074 It consists of a list, possibly empty, of the following
1075 argument specifiers:
1077 +name+::
1078     Required Argument - A simple argument name.
1080 +name default+::
1081     Optional Argument - A two-element list consisting of the
1082     argument name, followed by the default value, which will
1083     be used if the corresponding argument is not supplied.
1085 +&name+::
1086     Reference Argument - The caller is expected to pass the name of
1087     an existing variable. An implicit `upvar 1 'origname' 'name'` is done
1088     to make the variable available in the proc scope.
1090 +*args*+::
1091     Variable Argument - The special name +'args'+, which is
1092     assigned all remaining arguments (including none) as a list. The
1093     variable argument may only be specified once. Note that
1094     the syntax +args newname+ may be used to retain the special
1095     behaviour of +'args'+ with a different local name. In this case,
1096     the variable is named +'newname'+ rather than +'args'+.
1098 When the command is invoked, a local variable will be created for each of
1099 the formal arguments to the procedure; its value will be the value
1100 of corresponding argument in the invoking command or the argument's
1101 default value.
1103 Arguments with default values need not be specified in a procedure
1104 invocation.  However, there must be enough actual arguments for all
1105 required arguments, and there must not be any extra actual arguments
1106 (unless the Variable Argument is specified).
1108 Actual arguments are assigned to formal arguments as in left-to-right
1109 order with the following precedence.
1111 1. Required Arguments (including Reference Arguments)
1112 2. Optional Arguments
1113 3. Variable Argument
1115 The following example illustrates precedence. Assume a procedure declaration:
1117     proc p {{a A} args b {c C} d} {...}
1119 This procedure requires at least two arguments, but can accept an unlimited number.
1120 The following table shows how various numbers of arguments are assigned.
1121 Values marked as +-+ are assigned the default value.
1123 [width="40%",frame="topbot",options="header"]
1124 |==============
1125 |Number of arguments|a|args|b|c|d
1126 |2|-|-|1|-|2
1127 |3|1|-|2|-|3
1128 |4|1|-|2|3|4
1129 |5|1|2|3|4|5
1130 |6|1|2,3|4|5|6
1131 |==============
1133 When +'body'+ is being executed, variable names normally refer to local
1134 variables, which are created automatically when referenced and deleted
1135 when the procedure returns.  One local variable is automatically created
1136 for each of the procedure's arguments.  Global variables can be
1137 accessed by invoking the `global` command or via the +::+ prefix.
1139 New in Jim
1140 ~~~~~~~~~~
1141 In addition to procedure arguments, Jim procedures may declare static variables.
1142 These variables scoped to the procedure and initialised at procedure definition.
1143 Either from the static variable definition, or from the enclosing scope.
1145 Consider the following example:
1147     jim> set a 1
1148     jim> proc a {} {a {b 2}} {
1149         set c 1
1150         puts "$a $b $c"
1151         incr a
1152         incr b
1153         incr c
1154     }
1155     jim> a
1156     1 2 1
1157     jim> a
1158     2 3 1
1160 The static variable +'a'+ has no initialiser, so it is initialised from
1161 the enclosing scope with the value 1. (Note that it is an error if there
1162 is no variable with the same name in the enclosing scope). However +'b'+
1163 has an initialiser, so it is initialised to 2.
1165 Unlike a local variable, the value of a static variable is retained across
1166 invocations of the procedure.
1168 See the `proc` command for information on
1169 how to define procedures and what happens when they are invoked.
1171 VARIABLES - SCALARS AND ARRAYS
1172 ------------------------------
1173 Tcl allows the definition of variables and the use of their values
1174 either through '$'-style variable substitution, the `set`
1175 command, or a few other mechanisms.
1177 Variables need not be declared:  a new variable will automatically
1178 be created each time a new variable name is used.
1180 Tcl supports two types of variables:  scalars and arrays.
1181 A scalar variable has a single value, whereas an array variable
1182 can have any number of elements, each with a name (called
1183 its 'index') and a value.
1185 Array indexes may be arbitrary strings; they need not be numeric.
1186 Parentheses are used refer to array elements in Tcl commands.
1187 For example, the command
1189     set x(first) 44
1191 will modify the element of 'x' whose index is 'first'
1192 so that its new value is '44'.
1194 Two-dimensional arrays can be simulated in Tcl by using indexes
1195 that contain multiple concatenated values.
1196 For example, the commands
1198     set a(2,3) 1
1199     set a(3,6) 2
1201 set the elements of 'a' whose indexes are '2,3' and '3,6'.
1203 In general, array elements may be used anywhere in Tcl that scalar
1204 variables may be used.
1206 If an array is defined with a particular name, then there may
1207 not be a scalar variable with the same name.
1209 Similarly, if there is a scalar variable with a particular
1210 name then it is not possible to make array references to the
1211 variable.
1213 To convert a scalar variable to an array or vice versa, remove
1214 the existing variable with the `unset` command.
1216 The `array` command provides several features for dealing
1217 with arrays, such as querying the names of all the elements of
1218 the array and converting between an array and a list.
1220 Variables may be either global or local.  If a variable
1221 name is used when a procedure isn't being executed, then it
1222 automatically refers to a global variable.  Variable names used
1223 within a procedure normally refer to local variables associated with that
1224 invocation of the procedure.  Local variables are deleted whenever
1225 a procedure exits.  Either `global` command may be used to request
1226 that a name refer to a global variable for the duration of the current
1227 procedure (this is somewhat analogous to 'extern' in C), or the variable
1228 may be explicitly scoped with the +::+ prefix. For example
1230     set a 1
1231     set b 2
1232     proc p {} {
1233         set c 3
1234         global a
1236         puts "$a $::b $c"
1237     }
1238     p
1240 will output:
1242     1 2 3
1244 ARRAYS AS LISTS IN JIM
1245 ----------------------
1246 Unlike Tcl, Jim can automatically convert between a list (with an even
1247 number of elements) and an array value. This is similar to the way Tcl
1248 can convert between a string and a list.
1250 For example:
1252   set a {1 one 2 two}
1253   puts $a(2)
1255 will output:
1257   two
1259 Thus `array set` is equivalent to `set` when the variable does not
1260 exist or is empty.
1262 The reverse is also true where an array will be converted into
1263 a list.
1265   set a(1) one; set a(2) two
1266   puts $a
1268 will output:
1270   1 one 2 two
1272 DICTIONARY VALUES
1273 -----------------
1274 Tcl 8.5 introduced the dict command, and Jim Tcl has added a version
1275 of this command. Dictionaries provide efficient access to key-value
1276 pairs, just like arrays, but dictionaries are pure values. This
1277 means that you can pass them to a procedure just as a list or a
1278 string. Tcl dictionaries are therefore much more like Tcl lists,
1279 except that they represent a mapping from keys to values, rather
1280 than an ordered sequence.
1282 You can nest dictionaries, so that the value for a particular key
1283 consists of another dictionary. That way you can elegantly build
1284 complicated data structures, such as hierarchical databases. You
1285 can also combine dictionaries with other Tcl data structures. For
1286 instance, you can build a list of dictionaries that themselves
1287 contain lists.
1289 Dictionaries are values that contain an efficient, order-preserving
1290 mapping from arbitrary keys to arbitrary values. Each key in the
1291 dictionary maps to a single value. They have a textual format that
1292 is exactly that of any list with an even number of elements, with
1293 each mapping in the dictionary being represented as two items in
1294 the list. When a command takes a dictionary and produces a new
1295 dictionary based on it (either returning it or writing it back into
1296 the variable that the starting dictionary was read from) the new
1297 dictionary will have the same order of keys, modulo any deleted
1298 keys and with new keys added on to the end. When a string is
1299 interpreted as a dictionary and it would otherwise have duplicate
1300 keys, only the last value for a particular key is used; the others
1301 are ignored, meaning that, "apple banana" and "apple carrot apple
1302 banana" are equivalent dictionaries (with different string
1303 representations).
1305 Note that in Jim, arrays are implemented as dictionaries.
1306 Thus automatic conversion between lists and dictionaries applies
1307 as it does for arrays.
1309   jim> dict set a 1 one
1310   1 one
1311   jim> dict set a 2 two
1312   1 one 2 two
1313   jim> puts $a
1314   1 one 2 two
1315   jim> puts $a(2)
1316   two
1317   jim> dict set a 3 T three
1318   1 one 2 two 3 {T three}
1320 See the `dict` command for more details.
1322 GARBAGE COLLECTION, REFERENCES, LAMBDA
1323 --------------------------------------
1324 Unlike Tcl, Jim has some sophisticated support for functional programming.
1325 These are described briefly below.
1327 More information may be found at http://wiki.tcl.tk/13847
1329 References
1330 ~~~~~~~~~~
1331 A reference can be thought of as holding a value with one level of indirection,
1332 where the value may be garbage collected when unreferenced.
1333 Consider the following example:
1335     jim> set r [ref "One String" test]
1336     <reference.<test___>.00000000000000000000>
1337     jim> getref $r
1338     One String
1340 The operation `ref` creates a references to the value specified by the
1341 first argument. (The second argument is a "type" used for documentation purposes).
1343 The operation `getref` is the dereferencing operation which retrieves the value
1344 stored in the reference.
1346     jim> setref $r "New String"
1347     New String
1348     jim> getref $r
1349     New String
1351 The operation `setref` replaces the value stored by the reference. If the old value
1352 is no longer accessible by any reference, it will eventually be automatically be garbage
1353 collected.
1355 Garbage Collection
1356 ~~~~~~~~~~~~~~~~~~
1357 Normally, all values in Tcl are passed by value. As such values are copied and released
1358 automatically as necessary.
1360 With the introduction of references, it is possible to create values whose lifetime
1361 transcend their scope. To support this, case, the Jim system will periodically identify
1362 and discard objects which are no longer accessible by any reference.
1364 The `collect` command may be used to force garbage collection.  Consider a reference created
1365 with a finalizer:
1367     jim> proc f {ref value} { puts "Finaliser called for $ref,$value" }
1368     jim> set r [ref "One String" test f]
1369     <reference.<test___>.00000000000
1370     jim> collect
1371     0
1372     jim> set r ""
1373     jim> collect
1374     Finaliser called for <reference.<test___>.00000000000,One String
1375     1
1377 Note that once the reference, 'r', was modified so that it no longer
1378 contained a reference to the value, the garbage collector discarded
1379 the value (after calling the finalizer).
1381 The finalizer for a reference may be examined or changed with the `finalize` command
1383     jim> finalize $r
1384     f
1385     jim> finalize $r newf
1386     newf
1388 Lambda
1389 ~~~~~~
1390 Jim provides a garbage collected lambda function. This is a procedure
1391 which is able to create an anonymous procedure.  Consider:
1393     jim> set f [lambda {a} {{x 0}} { incr x $a }]
1394     jim> $f 1
1395     1
1396     jim> $f 2
1397     3
1398     jim> set f ""
1400 This create an anonymous procedure (with the name stored in 'f'), with a static variable
1401 which is incremented by the supplied value and the result returned.
1403 Once the procedure name is no longer accessible, it will automatically be deleted
1404 when the garbage collector runs.
1406 The procedure may also be delete immediately by renaming it "". e.g.
1408     jim> rename $f ""
1410 UTF-8 AND UNICODE
1411 -----------------
1412 If Jim is built with UTF-8 support enabled (configure --enable-utf),
1413 then most string-related commands become UTF-8 aware.  These include,
1414 but are not limited to, `string match`, `split`, `glob`, `scan` and
1415 `format`.
1417 UTF-8 encoding has many advantages, but one of the complications is that
1418 characters can take a variable number of bytes. Thus the addition of
1419 `string bytelength` which returns the number of bytes in a string,
1420 while `string length` returns the number of characters.
1422 If UTF-8 support is not enabled, all commands treat bytes as characters
1423 and `string bytelength` returns the same value as `string length`.
1425 Note that even if UTF-8 support is not enabled, the +{backslash}uNNNN+ syntax
1426 is still available to embed UTF-8 sequences.
1428 String Matching
1429 ~~~~~~~~~~~~~~~
1430 Commands such as `string match`, `lsearch -glob`, `array names` and others use string
1431 pattern matching rules. These commands support UTF-8. For example:
1433   string match a\[\ua0-\ubf\]b "a\u00a3b"
1435 format and scan
1436 ~~~~~~~~~~~~~~~
1437 +format %c+ allows a unicode codepoint to be be encoded. For example, the following will return
1438 a string with two bytes and one character. The same as +{backslash}ub5+
1440   format %c 0xb5
1442 `format` respects widths as character widths, not byte widths. For example, the following will
1443 return a string with three characters, not three bytes.
1445   format %.3s \ub5\ub6\ub7\ub8
1447 Similarly, +scan ... %c+ allows a UTF-8 to be decoded to a unicode codepoint. The following will set
1448 +'a'+ to 181 (0xb5) and +'b'+ to 65 (0x41).
1450   scan \u00b5A %c%c a b
1452 `scan %s` will also accept a character class, including unicode ranges.
1454 String Classes
1455 ~~~~~~~~~~~~~~
1456 `string is` has *not* been extended to classify UTF-8 characters. Therefore, the following
1457 will return 0, even though the string may be considered to be alphabetic.
1459   string is alpha \ub5Test
1461 This does not affect the string classes 'ascii', 'control', 'digit', 'double', 'integer' or 'xdigit'.
1463 Case Mapping and Conversion
1464 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1465 Jim provides a simplified unicode case mapping. This means that case conversion
1466 and comparison will not increase or decrease the number of characters in a string.
1468 `string toupper` will convert any lowercase letters to their uppercase equivalent.
1469 Any character which is not a letter or has no uppercase equivalent is left unchanged.
1470 Similarly for `string tolower`.
1472 Commands which perform case insensitive matches, such as `string compare -nocase`
1473 and `lsearch -nocase` fold both strings to uppercase before comparison.
1475 Invalid UTF-8 Sequences
1476 ~~~~~~~~~~~~~~~~~~~~~~~
1477 Some UTF-8 character sequences are invalid, such as those beginning with '0xff',
1478 those which represent character sequences longer than 3 bytes (greater than U+FFFF),
1479 and those which end prematurely, such as a lone '0xc2'.
1481 In these situations, the offending bytes are treated as single characters. For example,
1482 the following returns 2.
1484   string bytelength \xff\xff
1486 Regular Expressions
1487 ~~~~~~~~~~~~~~~~~~~
1488 If UTF-8 support is enabled, the built-in regular expression engine will be
1489 selected which supports UTF-8 strings and patterns.
1491 See REGULAR EXPRESSIONS
1493 BUILT-IN COMMANDS
1494 -----------------
1495 The Tcl library provides the following built-in commands, which will
1496 be available in any application using Tcl.  In addition to these
1497 built-in commands, there may be additional commands defined by each
1498 application, plus commands defined as Tcl procedures.
1500 In the command syntax descriptions below, words in +*boldface*+ are
1501 literals that you type verbatim to Tcl.
1503 Words in +'italics'+ are meta-symbols; they serve as names for any of
1504 a range of values that you can type.
1506 Optional arguments or groups of arguments are indicated by enclosing them
1507 in +?question-marks?+.
1509 Ellipses (+\...+) indicate that any number of additional
1510 arguments or groups of arguments may appear, in the same format
1511 as the preceding argument(s).
1513 [[CommandIndex]]
1514 Command Index
1515 ~~~~~~~~~~~~~
1516 @INSERTINDEX@
1518 alarm
1519 ~~~~~
1520 +*alarm* 'seconds'+
1522 Delivers the +SIGALRM+ signal to the process after the given
1523 number of seconds. If the platform supports 'ualarm(3)' then
1524 the argument may be a floating point value. Otherwise it must
1525 be an integer.
1527 Note that unless a signal handler for +SIGALRM+ has been installed
1528 (see `signal`), the process will exit on this signal.
1530 alias
1531 ~~~~~
1532 +*alias* 'name args\...'+
1534 Creates a single word alias (`proc`) for one or more words. For example,
1535 the following creates an alias for the command `info exists`.
1537     alias e info exists
1538     if {[e var]} {
1539       ...
1540     }
1542 `alias` returns +'name'+, allowing it to be used with `local`.
1544 See also `proc`, `curry`, `lambda`, `local`.
1546 append
1547 ~~~~~~
1548 +*append* 'varName value ?value value ...?'+
1550 Append all of the +'value'+ arguments to the current value
1551 of variable +'varName'+.  If +'varName'+ doesn't exist,
1552 it is given a value equal to the concatenation of all the
1553 +'value'+ arguments.
1555 This command provides an efficient way to build up long
1556 variables incrementally.
1557 For example, "`append a $b`" is much more efficient than
1558 "`set a $a$b`" if +$a+ is long.
1560 array
1561 ~~~~~
1562 +*array* 'option arrayName ?arg\...?'+
1564 This command performs one of several operations on the
1565 variable given by +'arrayName'+.
1567 Note that in general, if the named array does not exist, the +'array'+ command behaves
1568 as though the array exists but is empty.
1570 The +'option'+ argument determines what action is carried out by the
1571 command.  The legal +'options'+ (which may be abbreviated) are:
1573 +*array exists* 'arrayName'+::
1574     Returns 1 if arrayName is an array variable, 0 if there is
1575     no variable by that name.  This command is essentially
1576     identical to `info exists`
1578 +*array get* 'arrayName ?pattern?'+::
1579     Returns a list containing pairs of elements. The first
1580     element in each pair is the name of an element in arrayName
1581     and the second element of each pair is the value of the
1582     array element. The order of the pairs is undefined. If
1583     pattern is not specified, then all of the elements of the
1584     array are included in the result. If pattern is specified,
1585     then only those elements whose names match pattern (using
1586     the matching rules of string match) are included. If arrayName
1587     isn't the name of an array variable, or if the array contains
1588     no elements, then an empty list is returned.
1590 +*array names* 'arrayName ?pattern?'+::
1591     Returns a list containing the names of all of the elements
1592     in the array that match pattern. If pattern is omitted then
1593     the command returns all of the element names in the array.
1594     If pattern is specified, then only those elements whose
1595     names match pattern (using the matching rules of string
1596     match) are included. If there are no (matching) elements
1597     in the array, or if arrayName isn't the name of an array
1598     variable, then an empty string is returned.
1600 +*array set* 'arrayName list'+::
1601     Sets the values of one or more elements in arrayName. list
1602     must have a form like that returned by array get, consisting
1603     of an even number of elements. Each odd-numbered element
1604     in list is treated as an element name within arrayName, and
1605     the following element in list is used as a new value for
1606     that array element. If the variable arrayName does not
1607     already exist and list is empty, arrayName is created with
1608     an empty array value.
1610 +*array size* 'arrayName'+::
1611     Returns the number of elements in the array. If arrayName
1612     isn't the name of an array then 0 is returned.
1614 +*array unset* 'arrayName ?pattern?'+::
1615     Unsets all of the elements in the array that match pattern
1616     (using the matching rules of string match). If arrayName
1617     isn't the name of an array variable or there are no matching
1618     elements in the array, no error will be raised. If pattern
1619     is omitted and arrayName is an array variable, then the
1620     command unsets the entire array. The command always returns
1621     an empty string.
1623 break
1624 ~~~~~
1625 +*break*+
1627 This command may be invoked only inside the body of a loop command
1628 such as `for` or `foreach` or `while`.  It returns a +JIM_BREAK+ code
1629 to signal the innermost containing loop command to return immediately.
1631 case
1632 ~~~~
1633 +*case* 'string' ?in? 'patList body ?patList body ...?'+
1635 +*case* 'string' ?in? {'patList body ?patList body ...?'}+
1637 *Note* that the `switch` command should generally be preferred unless compatibility
1638 with Tcl 6.x is desired.
1640 Match +'string'+ against each of the +'patList'+ arguments
1641 in order.  If one matches, then evaluate the following +'body'+ argument
1642 by passing it recursively to the Tcl interpreter, and return the result
1643 of that evaluation.  Each +'patList'+ argument consists of a single
1644 pattern or list of patterns.  Each pattern may contain any of the wild-cards
1645 described under `string match`.
1647 If a +'patList'+ argument is +default+, the corresponding body will be
1648 evaluated if no +'patList'+ matches +'string'+.  If no +'patList'+ argument
1649 matches +'string'+ and no default is given, then the `case` command returns
1650 an empty string.
1652 Two syntaxes are provided.
1654 The first uses a separate argument for each of the patterns and commands;
1655 this form is convenient if substitutions are desired on some of the
1656 patterns or commands.
1658 The second form places all of the patterns and commands together into
1659 a single argument; the argument must have proper list structure, with
1660 the elements of the list being the patterns and commands.
1662 The second form makes it easy to construct multi-line case commands,
1663 since the braces around the whole list make it unnecessary to include a
1664 backslash at the end of each line.
1666 Since the +'patList'+ arguments are in braces in the second form,
1667 no command or variable substitutions are performed on them;  this makes
1668 the behaviour of the second form different than the first form in some
1669 cases.
1671 Below are some examples of `case` commands:
1673     case abc in {a b} {format 1} default {format 2} a* {format 3}
1675 will return '3',
1677     case a in {
1678         {a b} {format 1}
1679         default {format 2}
1680         a* {format 3}
1681     }
1683 will return '1', and
1685     case xyz {
1686         {a b}
1687             {format 1}
1688         default
1689             {format 2}
1690         a*
1691             {format 3}
1692     }
1694 will return '2'.
1696 catch
1697 ~~~~~
1698 +*catch* ?-?no?'code \...'? ?--? 'command ?resultVarName? ?optionsVarName?'+
1700 The `catch` command may be used to prevent errors from aborting
1701 command interpretation.  `catch` evaluates +'command'+, and returns a
1702 +JIM_OK+ code, regardless of any errors that might occur while
1703 executing +'command'+ (with the possible exception of +JIM_SIGNAL+ -
1704 see below).
1706 The return value from `catch` is a decimal string giving the code
1707 returned by the Tcl interpreter after executing +'command'+.  This
1708 will be '0' (+JIM_OK+) if there were no errors in +'command'+; otherwise
1709 it will have a non-zero value corresponding to one of the exceptional
1710 return codes (see jim.h for the definitions of code values, or the
1711 `info returncodes` command).
1713 If the +'resultVarName'+ argument is given, then it gives the name
1714 of a variable; `catch` will set the value of the variable to the
1715 string returned from +'command'+ (either a result or an error message).
1717 If the +'optionsVarName'+ argument is given, then it gives the name
1718 of a variable; `catch` will set the value of the variable to a
1719 dictionary. For any return code other than +JIM_RETURN+, the value
1720 for the key +-code+ will be set to the return code. For +JIM_RETURN+
1721 it will be set to the code given in `return -code`. Additionally,
1722 for the return code +JIM_ERR+, the value of the key +-errorinfo+
1723 will contain the current stack trace (the same result as `info stacktrace`),
1724 the value of the key +-errorcode+ will contain the
1725 same value as the global variable $::errorCode, and the value of
1726 the key +-level+ will be the current return level (see `return -level`).
1727 This can be useful to rethrow an error:
1729     if {[catch {...} msg opts]} {
1730         ...maybe do something with the error...
1731         incr opts(-level)
1732         return {*}$opts $msg
1733     }
1735 Normally `catch` will +'not'+ catch any of the codes +JIM_EXIT+, +JIM_EVAL+ or +JIM_SIGNAL+.
1736 The set of codes which will be caught may be modified by specifying the one more codes before
1737 +'command'+.
1739 e.g. To catch +JIM_EXIT+ but not +JIM_BREAK+ or +JIM_CONTINUE+
1741     catch -exit -nobreak -nocontinue -- { ... }
1743 The use of +--+ is optional. It signifies that no more return code options follow.
1745 Note that if a signal marked as `signal handle` is caught with `catch -signal`, the return value
1746 (stored in +'resultVarName'+) is name of the signal caught.
1750 +*cd* 'dirName'+
1752 Change the current working directory to +'dirName'+.
1754 Returns an empty string.
1756 This command can potentially be disruptive to an application, so it may
1757 be removed in some applications.
1759 clock
1760 ~~~~~
1761 +*clock seconds*+::
1762     Returns the current time as seconds since the epoch.
1764 +*clock format* 'seconds' ?*-format* 'format?'+::
1765     Format the given time (seconds since the epoch) according to the given
1766     format. See strftime(3) for supported formats.
1767     If no format is supplied, "%c" is used.
1769 +*clock scan* 'str' *-format* 'format'+::
1770     Scan the given time string using the given format string.
1771     See strptime(3) for supported formats.
1773 close
1774 ~~~~~
1775 +*close* 'fileId'+
1777 +'fileId' *close*+
1779 Closes the file given by +'fileId'+.
1780 +'fileId'+ must be the return value from a previous invocation
1781 of the `open` command; after this command, it should not be
1782 used anymore.
1784 collect
1785 ~~~~~~~
1786 +*collect*+
1788 Normally reference garbage collection is automatically performed periodically.
1789 However it may be run immediately with the `collect` command.
1791 See GARBAGE COLLECTION, REFERENCES, LAMBDA for more detail.
1793 concat
1794 ~~~~~~
1795 +*concat* 'arg ?arg \...?'+
1797 This command treats each argument as a list and concatenates them
1798 into a single list.  It permits any number of arguments.  For example,
1799 the command
1801     concat a b {c d e} {f {g h}}
1803 will return
1805     a b c d e f {g h}
1807 as its result.
1809 continue
1810 ~~~~~~~~
1811 +*continue*+
1813 This command may be invoked only inside the body of a loop command such
1814 as `for` or `foreach` or `while`.  It returns a  +JIM_CONTINUE+ code to
1815 signal the innermost containing loop command to skip the remainder of
1816 the loop's body but continue with the next iteration of the loop.
1818 curry
1819 ~~~~~
1820 +*alias* 'args\...'+
1822 Similar to `alias` except it creates an anonymous procedure (lambda) instead of
1823 a named procedure.
1825 the following creates a local, unnamed alias for the command `info exists`.
1827     set e [local curry info exists]
1828     if {[$e var]} {
1829       ...
1830     }
1832 `curry` returns the name of the procedure.
1834 See also `proc`, `alias`, `lambda`, `local`.
1836 dict
1837 ~~~~
1838 +*dict* 'option ?arg\...?'+
1840 Performs one of several operations on dictionary values.
1842 The +'option'+ argument determines what action is carried out by the
1843 command.  The legal +'options'+ are:
1845 +*dict create* '?key value \...?'+::
1846     Create and return a new dictionary value that contains each of
1847     the key/value mappings listed as  arguments (keys and values
1848     alternating, with each key being followed by its associated
1849     value.)
1851 +*dict exists* 'dictionary key ?key \...?'+::
1852     Returns a boolean value indicating whether the given key (or path
1853     of keys through a set of nested dictionaries) exists in the given
1854     dictionary value.  This returns a true value exactly when `dict get`
1855     on that path will succeed.
1857 +*dict get* 'dictionary ?key \...?'+::
1858     Given a dictionary value (first argument) and a key (second argument),
1859     this will retrieve the value for that key. Where several keys are
1860     supplied, the behaviour of the command shall be as if the result
1861     of "`dict get $dictVal $key`" was passed as the first argument to
1862     dict get with the remaining arguments as second (and possibly
1863     subsequent) arguments. This facilitates lookups in nested dictionaries.
1864     If no keys are provided, dict would return a list containing pairs
1865     of elements in a man- ner similar to array get. That is, the first
1866     element of each pair would be the key and the second element would
1867     be the value for that key.  It is an error to attempt to retrieve
1868     a value for a key that is not present in the dictionary.
1870 +*dict keys* 'dictionary ?pattern?'+::
1871     Returns a list of the keys in the dictionary.
1872     If pattern is specified, then only those keys whose
1873     names match +'pattern'+ (using the matching rules of string
1874     match) are included.
1876 +*dict keys* 'dictionary ?pattern?'+::
1877     Returns a list of the keys in the dictionary.
1878     If pattern is specified, then only those keys whose
1879     names match +'pattern'+ (using the matching rules of string
1880     match) are included.
1882 +*dict set* 'dictionaryName key ?key \...? value'+::
1883     This operation takes the +'name'+ of a variable containing a dictionary
1884     value and places an updated dictionary value in that variable
1885     containing a mapping from the given key to the given value. When
1886     multiple keys are present, this operation creates or updates a chain
1887     of nested dictionaries.
1889 +*dict unset* 'dictionaryName key ?key \...? value'+::
1890     This operation (the companion to `dict set`) takes the name of a
1891     variable containing a dictionary value and places an updated
1892     dictionary value in that variable that does not contain a mapping
1893     for the given key. Where multiple keys are present, this describes
1894     a path through nested dictionaries to the mapping to remove. At
1895     least one key must be specified, but the last key on the key-path
1896     need not exist. All other components on the path must exist.
1900 +*env* '?name? ?default?'+
1902 If +'name'+ is supplied, returns the value of +'name'+ from the initial
1903 environment (see getenv(3)). An error is returned if +'name'+ does not
1904 exist in the environment, unless +'default'+ is supplied - in which case
1905 that value is returned instead.
1907 If no arguments are supplied, returns a list of all environment variables
1908 and their values as +{name value \...}+
1910 See also the global variable +::env+
1914 +*eof* 'fileId'+
1916 +'fileId' *eof*+
1918 Returns 1 if an end-of-file condition has occurred on +'fileId'+,
1919 0 otherwise.
1921 +'fileId'+ must have been the return value from a previous call to `open`,
1922 or it may be +stdin+, +stdout+, or +stderr+ to refer to one of the
1923 standard I/O channels.
1925 error
1926 ~~~~~
1927 +*error* 'message ?stacktrace?'+
1929 Returns a +JIM_ERR+ code, which causes command interpretation to be
1930 unwound.  +'message'+ is a string that is returned to the application
1931 to indicate what went wrong.
1933 If the +'stacktrace'+ argument is provided and is non-empty,
1934 it is used to initialize the stacktrace.
1936 This feature is most useful in conjunction with the `catch` command:
1937 if a caught error cannot be handled successfully, +'stacktrace'+ can be used
1938 to return a stack trace reflecting the original point of occurrence
1939 of the error:
1941     catch {...} errMsg
1942     ...
1943     error $errMsg [info stacktrace]
1945 See also `errorInfo`, `info stacktrace`, `catch` and `return`
1947 errorInfo
1948 ~~~~~~~~~
1949 +*errorInfo* 'error ?stacktrace?'+
1951 Returns a human-readable representation of the given error message and stack trace.
1952 Typical usage is:
1954     if {[catch {...} error]} {
1955         puts stderr [errorInfo $error [info stacktrace]]
1956         exit 1
1957     }
1959 See also `error`.
1961 eval
1962 ~~~~
1963 +*eval* 'arg ?arg\...?'+
1965 `eval` takes one or more arguments, which together comprise a Tcl
1966 command (or collection of Tcl commands separated by newlines in the
1967 usual way).  `eval` concatenates all its arguments in the same
1968 fashion as the `concat` command, passes the concatenated string to the
1969 Tcl interpreter recursively, and returns the result of that
1970 evaluation (or any error generated by it).
1972 exec
1973 ~~~~
1974 +*exec* 'arg ?arg\...?'+
1976 This command treats its arguments as the specification
1977 of one or more UNIX commands to execute as subprocesses.
1978 The commands take the form of a standard shell pipeline;
1979 +|+ arguments separate commands in the
1980 pipeline and cause standard output of the preceding command
1981 to be piped into standard input of the next command (or +|&+ for
1982 both standard output and standard error).
1984 Under normal conditions the result of the `exec` command
1985 consists of the standard output produced by the last command
1986 in the pipeline.
1988 If any of the commands in the pipeline exit abnormally or
1989 are killed or suspended, then `exec` will return an error
1990 and the error message will include the pipeline's output followed by
1991 error messages describing the abnormal terminations.
1993 If any of the commands writes to its standard error file,
1994 then `exec` will return an error, and the error message
1995 will include the pipeline's output, followed by messages
1996 about abnormal terminations (if any), followed by the standard error
1997 output.
1999 If the last character of the result or error message
2000 is a newline then that character is deleted from the result
2001 or error message for consistency with normal
2002 Tcl return values.
2004 An +'arg'+ may have one of the following special forms:
2006 +>filename+::
2007     The standard output of the last command in the pipeline
2008     is redirected to the file.  In this situation `exec`
2009     will normally return an empty string.
2011 +>>filename+::
2012     As above, but append to the file.
2014 +>@fileId+::
2015     The standard output of the last command in the pipeline is
2016     redirected to the given (writable) file descriptor (e.g. stdout,
2017     stderr, or the result of `open`). In this situation `exec`
2018     will normally return an empty string.
2020 +2>filename+::
2021     The standard error of the last command in the pipeline
2022     is redirected to the file.
2024 +2>>filename+::
2025     As above, but append to the file.
2027 +2>@fileId+::
2028     The standard error of the last command in the pipeline is
2029     redirected to the given (writable) file descriptor.
2031 +2>@1+::
2032     The standard error of the last command in the pipeline is
2033     redirected to the same file descriptor as the standard output.
2035 +>&filename+::
2036     Both the standard output and standard error of the last command
2037     in the pipeline is redirected to the file.
2039 +>>&filename+::
2040     As above, but append to the file.
2042 +<filename+::
2043     The standard input of the first command in the pipeline
2044     is taken from the file.
2046 +<<string+::
2047     The standard input of the first command is taken as the
2048     given immediate value.
2050 +<@fileId+::
2051     The standard input of the first command in the pipeline
2052     is taken from the given (readable) file descriptor.
2054 If there is no redirection of standard input, standard error
2055 or standard output, these are connected to the corresponding
2056 input or output of the application.
2058 If the last +'arg'+ is +&+ then the command will be
2059 executed in background.
2060 In this case the standard output from the last command
2061 in the pipeline will
2062 go to the application's standard output unless
2063 redirected in the command, and error output from all
2064 the commands in the pipeline will go to the application's
2065 standard error file. The return value of exec in this case
2066 is a list of process ids (pids) in the pipeline.
2068 Each +'arg'+ becomes one word for a command, except for
2069 +|+, +<+, +<<+, +>+, and +&+ arguments, and the
2070 arguments that follow +<+, +<<+, and +>+.
2072 The first word in each command is taken as the command name;
2073 the directories in the PATH environment variable are searched for
2074 an executable by the given name.
2076 No `glob` expansion or other shell-like substitutions
2077 are performed on the arguments to commands.
2079 If the command fails, the global $::errorCode (and the -errorcode
2080 option in `catch`) will be set to a list, as follows:
2082 +*CHILDKILLED* 'pid sigName msg'+::
2083         This format is used when a child process has been killed
2084         because of a signal. The pid element will be the process's
2085         identifier (in decimal). The sigName element will be the
2086         symbolic name of the signal that caused the process to
2087         terminate; it will be one of the names from the include
2088         file signal.h, such as SIGPIPE. The msg element will be a
2089         short human-readable message describing the signal, such
2090         as "write on pipe with no readers" for SIGPIPE.
2092 +*CHILDSUSP* 'pid sigName msg'+::
2093         This format is used when a child process has been suspended
2094         because of a signal. The pid element will be the process's
2095         identifier, in decimal. The sigName element will be the
2096         symbolic name of the signal that caused the process to
2097         suspend; this will be one of the names from the include
2098         file signal.h, such as SIGTTIN. The msg element will be a
2099         short human-readable message describing the signal, such
2100         as "background tty read" for SIGTTIN.
2102 +*CHILDSTATUS* 'pid code'+::
2103         This format is used when a child process has exited with a
2104         non-zero exit status. The pid element will be the process's
2105         identifier (in decimal) and the code element will be the
2106         exit code returned by the process (also in decimal).
2108 The environment for the executed command is set from $::env (unless
2109 this variable is unset, in which case the original environment is used).
2111 exists
2112 ~~~~~~
2113 +*exists ?-var|-proc|-command?* 'name'+
2115 Checks the existence of the given variable, procedure or command
2116 respectively and returns 1 if it exists or 0 if not.  This command
2117 provides a more simplified/convenient version of `info exists`,
2118 `info procs` and `info commands`.
2120 If the type is omitted, a type of '-var' is used. The type may be abbreviated.
2122 exit
2123 ~~~~
2124 +*exit* '?returnCode?'+
2126 Terminate the process, returning +'returnCode'+ to the
2127 parent as the exit status.
2129 If +'returnCode'+ isn't specified then it defaults
2130 to 0.
2132 Note that exit can be caught with `catch`.
2134 expr
2135 ~~~~
2136 +*expr* 'arg'+
2138 Calls the expression processor to evaluate +'arg'+, and returns
2139 the result as a string.  See the section EXPRESSIONS above.
2141 Note that Jim supports a shorthand syntax for `expr` as +$(\...)+
2142 The following two are identical.
2144   set x [expr {3 * 2 + 1}]
2145   set x $(3 * 2 + 1)
2147 file
2148 ~~~~
2149 +*file* 'option name ?arg\...?'+
2151 Operate on a file or a file name.  +'name'+ is the name of a file.
2153 +'option'+ indicates what to do with the file name.  Any unique
2154 abbreviation for +'option'+ is acceptable.  The valid options are:
2156 +*file atime* 'name'+::
2157     Return a decimal string giving the time at which file +'name'+
2158     was last accessed.  The time is measured in the standard UNIX
2159     fashion as seconds from a fixed starting time (often January 1, 1970).
2160     If the file doesn't exist or its access time cannot be queried then an
2161     error is generated.
2163 +*file copy ?-force?* 'source target'+::
2164     Copies file +'source'+ to file +'target'+. The source file must exist.
2165     The target file must not exist, unless +-force+ is specified.
2167 +*file delete ?-force?* 'name\...'+::
2168     Deletes file or directory +'name'+. If the file or directory doesn't exist, nothing happens.
2169     If it can't be deleted, an error is generated. Non-empty directories will not be deleted
2170     unless the +-force+ options is given. In this case no errors will be generated, even
2171     if the file/directory can't be deleted.
2173 +*file dirname* 'name'+::
2174     Return all of the characters in +'name'+ up to but not including
2175     the last slash character.  If there are no slashes in +'name'+
2176     then return +.+ (a single dot).  If the last slash in +'name'+ is its first
2177     character, then return +/+.
2179 +*file executable* 'name'+::
2180     Return '1' if file +'name'+ is executable by
2181     the current user, '0' otherwise.
2183 +*file exists* 'name'+::
2184     Return '1' if file +'name'+ exists and the current user has
2185     search privileges for the directories leading to it, '0' otherwise.
2187 +*file extension* 'name'+::
2188     Return all of the characters in +'name'+ after and including the
2189     last dot in +'name'+.  If there is no dot in +'name'+ then return
2190     the empty string.
2192 +*file isdirectory* 'name'+::
2193     Return '1' if file +'name'+ is a directory,
2194     '0' otherwise.
2196 +*file isfile* 'name'+::
2197     Return '1' if file +'name'+ is a regular file,
2198     '0' otherwise.
2200 +*file join* 'arg\...'+::
2201     Joins multiple path components. Note that if any components is
2202     an absolute path, the preceding components are ignored.
2203     Thus +"`file` join /tmp /root"+ returns +"/root"+.
2205 +*file lstat* 'name varName'+::
2206     Same as 'stat' option (see below) except uses the +'lstat'+
2207     kernel call instead of +'stat'+.  This means that if +'name'+
2208     refers to a symbolic link the information returned in +'varName'+
2209     is for the link rather than the file it refers to.  On systems that
2210     don't support symbolic links this option behaves exactly the same
2211     as the 'stat' option.
2213 +*file mkdir* 'dir1 ?dir2\...?'+::
2214     Creates each directory specified. For each pathname +'dir'+ specified,
2215     this command will create all non-existing parent directories
2216     as well as +'dir'+ itself. If an existing directory is specified,
2217     then no action is taken and no error is returned. Trying to
2218     overwrite an existing file with a directory will result in an
2219     error.  Arguments are processed in the order specified, halting
2220     at the first error, if any.
2222 +*file mtime* 'name ?time?'+::
2223     Return a decimal string giving the time at which file +'name'+
2224     was last modified.  The time is measured in the standard UNIX
2225     fashion as seconds from a fixed starting time (often January 1, 1970).
2226     If the file doesn't exist or its modified time cannot be queried then an
2227     error is generated. If +'time'+ is given, sets the modification time
2228     of the file to the given value.
2230 +*file normalize* 'name'+::
2231     Return the normalized path of +'name'+. See 'realpath(3)'.
2233 +*file owned* 'name'+::
2234     Return '1' if file +'name'+ is owned by the current user,
2235     '0' otherwise.
2237 +*file readable* 'name'+::
2238     Return '1' if file +'name'+ is readable by
2239     the current user, '0' otherwise.
2241 +*file readlink* 'name'+::
2242     Returns the value of the symbolic link given by +'name'+ (i.e. the
2243     name of the file it points to).  If
2244     +'name'+ isn't a symbolic link or its value cannot be read, then
2245     an error is returned.  On systems that don't support symbolic links
2246     this option is undefined.
2248 +*file rename* 'oldname' 'newname'+::
2249     Renames the file from the old name to the new name.
2251 +*file rootname* 'name'+::
2252     Return all of the characters in +'name'+ up to but not including
2253     the last '.' character in the name.  If +'name'+ doesn't contain
2254     a dot, then return +'name'+.
2256 +*file size* 'name'+::
2257     Return a decimal string giving the size of file +'name'+ in bytes.
2258     If the file doesn't exist or its size cannot be queried then an
2259     error is generated.
2261 +*file stat* 'name varName'+::
2262     Invoke the 'stat' kernel call on +'name'+, and use the
2263     variable given by +'varName'+ to hold information returned from
2264     the kernel call.
2265     +'varName'+ is treated as an array variable,
2266     and the following elements of that variable are set: 'atime',
2267     'ctime', 'dev', 'gid', 'ino', 'mode', 'mtime',
2268     'nlink', 'size', 'type', 'uid'.
2269     Each element except 'type' is a decimal string with the value of
2270     the corresponding field from the 'stat' return structure; see the
2271     manual entry for 'stat' for details on the meanings of the values.
2272     The 'type' element gives the type of the file in the same form
2273     returned by the command `file type`.
2274     This command returns an empty string.
2276 +*file tail* 'name'+::
2277     Return all of the characters in +'name'+ after the last slash.
2278     If +'name'+ contains no slashes then return +'name'+.
2280 +*file tempfile* '?template?'+::
2281     Creates and returns the name of a unique temporary file. If +'template'+ is omitted, a
2282     default template will be used to place the file in /tmp. See 'mkstemp(3)' for
2283     the format of the template and security concerns.
2285 +*file type* 'name'+::
2286     Returns a string giving the type of file +'name'+, which will be
2287     one of +file+, +directory+, +characterSpecial+,
2288     +blockSpecial+, +fifo+, +link+, or +socket+.
2290 +*file writable* 'name'+::
2291     Return '1' if file +'name'+ is writable by
2292     the current user, '0' otherwise.
2294 The `file` commands that return 0/1 results are often used in
2295 conditional or looping commands, for example:
2297     if {![file exists foo]} {
2298         error {bad file name}
2299     } else {
2300         ...
2301     }
2303 finalize
2304 ~~~~~~~~
2305 +*finalize* 'reference ?command?'+
2307 If +'command'+ is omitted, returns the finalizer command for the given reference.
2309 Otherwise, sets a new finalizer command for the given reference. +'command'+ may be
2310 the empty string to remove the current finalizer.
2312 The reference must be a valid reference create with the `ref`
2313 command.
2315 See GARBAGE COLLECTION, REFERENCES, LAMBDA for more detail.
2317 flush
2318 ~~~~~
2319 +*flush* 'fileId'+
2321 +'fileId' *flush*+
2323 Flushes any output that has been buffered for +'fileId'+.  +'fileId'+ must
2324 have been the return value from a previous call to `open`, or it may be
2325 +stdout+ or +stderr+ to access one of the standard I/O streams; it must
2326 refer to a file that was opened for writing.  This command returns an
2327 empty string.
2331 +*for* 'start test next body'+
2333 `for` is a looping command, similar in structure to the C `for` statement.
2334 The +'start'+, +'next'+, and +'body'+ arguments must be Tcl command strings,
2335 and +'test'+ is an expression string.
2337 The `for` command first invokes the Tcl interpreter to execute +'start'+.
2338 Then it repeatedly evaluates +'test'+ as an expression; if the result is
2339 non-zero it invokes the Tcl interpreter on +'body'+, then invokes the Tcl
2340 interpreter on +'next'+, then repeats the loop.  The command terminates
2341 when +'test'+ evaluates to 0.
2343 If a `continue` command is invoked within +'body'+ then any remaining
2344 commands in the current execution of +'body'+ are skipped; processing
2345 continues by invoking the Tcl interpreter on +'next'+, then evaluating
2346 +'test'+, and so on.
2348 If a `break` command is invoked within +'body'+ or +'next'+, then the `for`
2349 command will return immediately.
2351 The operation of `break` and `continue` are similar to the corresponding
2352 statements in C.
2354 `for` returns an empty string.
2356 foreach
2357 ~~~~~~~
2358 +*foreach* 'varName list body'+
2360 +*foreach* 'varList list ?varList2 list2 \...? body'+
2362 In this command, +'varName'+ is the name of a variable, +'list'+
2363 is a list of values to assign to +'varName'+, and +'body'+ is a
2364 collection of Tcl commands.
2366 For each field in +'list'+ (in order from left to right), `foreach` assigns
2367 the contents of the field to +'varName'+ (as if the `lindex` command
2368 had been used to extract the field), then calls the Tcl interpreter to
2369 execute +'body'+.
2371 If instead of being a simple name, +'varList'+ is used, multiple assignments
2372 are made each time through the loop, one for each element of +'varList'+.
2374 For example, if there are two elements in +'varList'+ and six elements in
2375 the list, the loop will be executed three times.
2377 If the length of the list doesn't evenly divide by the number of elements
2378 in +'varList'+, the value of the remaining variables in the last iteration
2379 of the loop are undefined.
2381 The `break` and `continue` statements may be invoked inside +'body'+,
2382 with the same effect as in the `for` command.
2384 `foreach` returns an empty string.
2386 format
2387 ~~~~~~
2388 +*format* 'formatString ?arg \...?'+
2390 This command generates a formatted string in the same way as the
2391 C 'sprintf' procedure (it uses 'sprintf' in its
2392 implementation).  +'formatString'+ indicates how to format
2393 the result, using +%+ fields as in 'sprintf', and the additional
2394 arguments, if any, provide values to be substituted into the result.
2396 All of the 'sprintf' options are valid; see the 'sprintf'
2397 man page for details.  Each +'arg'+ must match the expected type
2398 from the +%+ field in +'formatString'+; the `format` command
2399 converts each argument to the correct type (floating, integer, etc.)
2400 before passing it to 'sprintf' for formatting.
2402 The only unusual conversion is for +%c+; in this case the argument
2403 must be a decimal string, which will then be converted to the corresponding
2404 ASCII character value.
2406 `format` does backslash substitution on its +'formatString'+
2407 argument, so backslash sequences in +'formatString'+ will be handled
2408 correctly even if the argument is in braces.
2410 The return value from `format` is the formatted string.
2412 getref
2413 ~~~~~~
2414 +*getref* 'reference'+
2416 Returns the string associated with +'reference'+. The reference must
2417 be a valid reference create with the `ref` command.
2419 See GARBAGE COLLECTION, REFERENCES, LAMBDA for more detail.
2421 gets
2422 ~~~~
2423 +*gets* 'fileId ?varName?'+
2425 +'fileId' *gets* '?varName?'+
2427 Reads the next line from the file given by +'fileId'+ and discards
2428 the terminating newline character.
2430 If +'varName'+ is specified, then the line is placed in the variable
2431 by that name and the return value is a count of the number of characters
2432 read (not including the newline).
2434 If the end of the file is reached before reading
2435 any characters then -1 is returned and +'varName'+ is set to an
2436 empty string.
2438 If +'varName'+ is not specified then the return value will be
2439 the line (minus the newline character) or an empty string if
2440 the end of the file is reached before reading any characters.
2442 An empty string will also be returned if a line contains no characters
2443 except the newline, so `eof` may have to be used to determine
2444 what really happened.
2446 If the last character in the file is not a newline character, then
2447 `gets` behaves as if there were an additional newline character
2448 at the end of the file.
2450 +'fileId'+ must be +stdin+ or the return value from a previous
2451 call to `open`; it must refer to a file that was opened
2452 for reading.
2454 glob
2455 ~~~~
2456 +*glob* ?*-nocomplain*? 'pattern ?pattern \...?'+
2458 This command performs filename globbing, using csh rules.  The returned
2459 value from `glob` is the list of expanded filenames.
2461 If +-nocomplain+ is specified as the first argument then an empty
2462 list may be returned;  otherwise an error is returned if the expanded
2463 list is empty.  The +-nocomplain+ argument must be provided
2464 exactly: an abbreviation will not be accepted.
2466 global
2467 ~~~~~~
2469 +*global* 'varName ?varName \...?'+
2471 This command is ignored unless a Tcl procedure is being interpreted.
2472 If so, then it declares each given +'varName'+ to be a global variable
2473 rather than a local one.  For the duration of the current procedure
2474 (and only while executing in the current procedure), any reference to
2475 +'varName'+ will be bound to a global variable instead
2476 of a local one.
2478 An alternative to using `global` is to use the +::+ prefix
2479 to explicitly name a variable in the global scope.
2483 +*if* 'expr1' ?*then*? 'body1' *elseif* 'expr2' ?*then*? 'body2' *elseif* \... ?*else*? ?'bodyN'?+
2485 The `if` command evaluates +'expr1'+ as an expression (in the same way
2486 that `expr` evaluates its argument).  The value of the expression must
2487 be numeric; if it is non-zero then +'body1'+ is executed by passing it to
2488 the Tcl interpreter.
2490 Otherwise +'expr2'+ is evaluated as an expression and if it is non-zero
2491 then +'body2'+ is executed, and so on.
2493 If none of the expressions evaluates to non-zero then +'bodyN'+ is executed.
2495 The +then+ and +else+ arguments are optional "noise words" to make the
2496 command easier to read.
2498 There may be any number of +elseif+ clauses, including zero.  +'bodyN'+
2499 may also be omitted as long as +else+ is omitted too.
2501 The return value from the command is the result of the body script that
2502 was executed, or an empty string if none of the expressions was non-zero
2503 and there was no +'bodyN'+.
2505 incr
2506 ~~~~
2507 +*incr* 'varName ?increment?'+
2509 Increment the value stored in the variable whose name is +'varName'+.
2510 The value of the variable must be integral.
2512 If +'increment'+ is supplied then its value (which must be an
2513 integer) is added to the value of variable +'varName'+;  otherwise
2514 1 is added to +'varName'+.
2516 The new value is stored as a decimal string in variable +'varName'+
2517 and also returned as result.
2519 If the variable does not exist, the variable is implicitly created
2520 and set to +0+ first.
2522 info
2523 ~~~~
2525 +*info* 'option ?arg\...?'+::
2527 Provide information about various internals to the Tcl interpreter.
2528 The legal +'option'+'s (which may be abbreviated) are:
2530 +*info args* 'procname'+::
2531     Returns a list containing the names of the arguments to procedure
2532     +'procname'+, in order.  +'procname'+ must be the name of a
2533     Tcl command procedure.
2535 +*info body* 'procname'+::
2536     Returns the body of procedure +'procname'+.  +'procname'+ must be
2537     the name of a Tcl command procedure.
2539 +*info channels*+::
2540     Returns a list of all open file handles from `open` or `socket`
2542 +*info commands* ?'pattern'?+::
2543     If +'pattern'+ isn't specified, returns a list of names of all the
2544     Tcl commands, including both the built-in commands written in C and
2545     the command procedures defined using the `proc` command.
2546     If +'pattern'+ is specified, only those names matching +'pattern'+
2547     are returned.  Matching is determined using the same rules as for
2548     `string match`.
2550 +*info complete* 'command' ?'missing'?+::
2551     Returns 1 if +'command'+ is a complete Tcl command in the sense of
2552     having no unclosed quotes, braces, brackets or array element names,
2553     If the command doesn't appear to be complete then 0 is returned.
2554     This command is typically used in line-oriented input environments
2555     to allow users to type in commands that span multiple lines;  if the
2556     command isn't complete, the script can delay evaluating it until additional
2557     lines have been typed to complete the command. If +'varName'+ is specified, the
2558     missing character is stored in the variable with that name.
2560 +*info exists* 'varName'+::
2561     Returns '1' if the variable named +'varName'+ exists in the
2562     current context (either as a global or local variable), returns '0'
2563     otherwise.
2565 +*info frame* ?'number'?+::
2566     If +'number'+ is not specified, this command returns a number
2567     which is the same result as `info level` - the current stack frame level.
2568     If +'number'+ is specified, then the result is a list consisting of the procedure,
2569     filename and line number for the procedure call at level +'number'+ on the stack.
2570     If +'number'+ is positive then it selects a particular stack level (1 refers
2571     to the top-most active procedure, 2 to the procedure it called, and
2572     so on); otherwise it gives a level relative to the current level
2573     (0 refers to the current procedure, -1 to its caller, and so on).
2574     The level has an identical meaning to `info level`.
2576 +*info globals* ?'pattern'?+::
2577     If +'pattern'+ isn't specified, returns a list of all the names
2578     of currently-defined global variables.
2579     If +'pattern'+ is specified, only those names matching +'pattern'+
2580     are returned.  Matching is determined using the same rules as for
2581     `string match`.
2583 +*info hostname*+::
2584     An alias for `os.gethostname` for compatibility with Tcl 6.x
2586 +*info level* ?'number'?+::
2587     If +'number'+ is not specified, this command returns a number
2588     giving the stack level of the invoking procedure, or 0 if the
2589     command is invoked at top-level.  If +'number'+ is specified,
2590     then the result is a list consisting of the name and arguments for the
2591     procedure call at level +'number'+ on the stack.  If +'number'+
2592     is positive then it selects a particular stack level (1 refers
2593     to the top-most active procedure, 2 to the procedure it called, and
2594     so on); otherwise it gives a level relative to the current level
2595     (0 refers to the current procedure, -1 to its caller, and so on).
2596     See the `uplevel` command for more information on what stack
2597     levels mean.
2599 +*info locals* ?'pattern'?+::
2600     If +'pattern'+ isn't specified, returns a list of all the names
2601     of currently-defined local variables, including arguments to the
2602     current procedure, if any.  Variables defined with the `global`
2603     and `upvar` commands will not be returned.  If +'pattern'+ is
2604     specified, only those names matching +'pattern'+ are returned.
2605     Matching is determined using the same rules as for `string match`.
2607 +*info nameofexecutable*+::
2608     Returns the name of the binary file from which the application
2609     was invoked. A full path will be returned, unless the path
2610     can't be determined, in which case the empty string will be returned.
2612 +*info procs* ?'pattern'?+::
2613     If +'pattern'+ isn't specified, returns a list of all the
2614     names of Tcl command procedures.
2615     If +'pattern'+ is specified, only those names matching +'pattern'+
2616     are returned.  Matching is determined using the same rules as for
2617     `string match`.
2619 +*info references*+::
2620     Returns a list of all references which have not yet been garbage
2621     collected.
2623 +*info returncodes* ?'code'?+::
2624     Returns a list representing the mapping of standard return codes
2625     to names. e.g. +{0 ok 1 error 2 return \...}+. If a code is given,
2626     instead returns the name for the given code.
2628 +*info script*+::
2629     If a Tcl script file is currently being evaluated (i.e. there is a
2630     call to 'Jim_EvalFile' active or there is an active invocation
2631     of the `source` command), then this command returns the name
2632     of the innermost file being processed.  Otherwise the command returns an
2633     empty string.
2635 +*info source* 'script'+::
2636     Returns the original source location of the given script as a list of
2637     +{filename linenumber}+. If the source location can't be determined, the
2638     list +{{} 0}+ is returned.
2640 +*info stacktrace*+::
2641     After an error is caught with `catch`, returns the stack trace as a list
2642     of +{procedure filename line \...}+.
2644 +*info version*+::
2645     Returns the version number for this version of Jim in the form +*x.yy*+.
2647 +*info vars* ?'pattern'?+::
2648     If +'pattern'+ isn't specified,
2649     returns a list of all the names of currently-visible variables, including
2650     both locals and currently-visible globals.
2651     If +'pattern'+ is specified, only those names matching +'pattern'+
2652     are returned.  Matching is determined using the same rules as for
2653     `string match`.
2655 join
2656 ~~~~
2657 +*join* 'list ?joinString?'+
2659 The +'list'+ argument must be a valid Tcl list.  This command returns the
2660 string formed by joining all of the elements of +'list'+ together with
2661 +'joinString'+ separating each adjacent pair of elements.
2663 The +'joinString'+ argument defaults to a space character.
2665 kill
2666 ~~~~
2667 +*kill* ?'SIG'|*-0*? 'pid'+
2669 Sends the given signal to the process identified by +'pid'+.
2671 The signal may be specified by name or number in one of the following forms:
2673 * +TERM+
2674 * +SIGTERM+
2675 * +-TERM+
2676 * +15+
2677 * +-15+
2679 The signal name may be in either upper or lower case.
2681 The special signal name +-0+ simply checks that a signal +'could'+ be sent.
2683 If no signal is specified, SIGTERM is used.
2685 An error is raised if the signal could not be delivered.
2687 lambda
2688 ~~~~~~
2689 +*lambda* 'args ?statics? body'+
2691 The `lambda` command is identical to `proc`, except rather than
2692 creating a named procedure, it creates an anonymous procedure and returns
2693 the name of the procedure.
2695 See `proc` and GARBAGE COLLECTION, REFERENCES, LAMBDA for more detail.
2697 lappend
2698 ~~~~~~~
2699 +*lappend* 'varName value ?value value \...?'+
2701 Treat the variable given by +'varName'+ as a list and append each of
2702 the +'value'+ arguments to that list as a separate element, with spaces
2703 between elements.
2705 If +'varName'+ doesn't exist, it is created as a list with elements given
2706 by the +'value'+ arguments. `lappend` is similar to `append` except that
2707 each +'value'+ is appended as a list element rather than raw text.
2709 This command provides a relatively efficient way to build up large lists.
2710 For example,
2712     lappend a $b
2714 is much more efficient than
2716     set a [concat $a [list $b]]
2718 when +$a+ is long.
2720 lassign
2721 ~~~~~~~
2722 +*lassign* 'list varName ?varName \...?'+
2724 This command treats the value +'list'+ as a list and assigns successive elements from that list to
2725 the variables given by the +'varName'+ arguments in order. If there are more variable names than
2726 list elements, the remaining variables are set to the empty string. If there are more list ele-
2727 ments than variables, a list of unassigned elements is returned.
2729     jim> lassign {1 2 3} a b; puts a=$a,b=$b
2730     3
2731     a=1,b=2
2733 local
2734 ~~~~~
2735 +*local* 'args'+
2737 Executes it's arguments as a command (per `eval`) and considers the return
2738 value to be a procedure name, which is marked as having local scope.
2739 This means that when the current procedure exits, the specified
2740 procedure is deleted. This can be useful with `lambda` or simply
2741 local procedures.
2743 In addition, if a command already exists with the same name,
2744 the existing command will be kept rather than deleted, and may be called
2745 via `upcall`. The previous command will be restored when the current
2746 command is deleted. See `upcall` for more details.
2748 In this example, a local procedure is created. Note that the procedure
2749 continues to have global scope while it is active.
2751     proc outer {} {
2752       # proc ... returns "inner" which is marked local
2753       local proc inner {} {
2754         # will be deleted when 'outer' exits
2755       }
2757       inner
2758       ...
2759     }
2761 In this example, the lambda is deleted at the end of the procedure rather
2762 than waiting until garbage collection.
2764     proc outer {} {
2765       set x [lambda inner {args} {
2766         # will be deleted when 'outer' exits
2767       }]
2768       # Use 'function' here which simply returns $x
2769       local function $x
2771       $x ...
2772       ...
2773     }
2775 loop
2776 ~~~~
2777 +*loop* 'var first limit ?incr? body'+
2779 Similar to `for` except simpler and possibly more efficient.
2780 With a positive increment, equivalent to:
2782   for {set var $first} {$var < $limit} {incr var $incr} $body
2784 If +'incr'+ is not specified, 1 is used.
2785 Note that setting the loop variable inside the loop does not
2786 affect the loop count.
2788 lindex
2789 ~~~~~~
2790 +*lindex* 'list index'+
2792 Treats +'list'+ as a Tcl list and returns element +'index'+ from it
2793 (0 refers to the first element of the list).
2794 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2796 In extracting the element, +'lindex'+ observes the same rules concerning
2797 braces and quotes and backslashes as the Tcl command interpreter; however,
2798 variable substitution and command substitution do not occur.
2800 If +'index'+ is negative or greater than or equal to the number of elements
2801 in +'value'+, then an empty string is returned.
2803 linsert
2804 ~~~~~~~
2805 +*linsert* 'list index element ?element element \...?'+
2807 This command produces a new list from +'list'+ by inserting all
2808 of the +'element'+ arguments just before the element +'index'+
2809 of +'list'+. Each +'element'+ argument will become
2810 a separate element of the new list. If +'index'+ is less than
2811 or equal to zero, then the new elements are inserted at the
2812 beginning of the list. If +'index'+ is greater than or equal
2813 to the number of elements in the list, then the new elements are
2814 appended to the list.
2816 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2818 list
2819 ~~~~
2821 +*list* 'arg ?arg \...?'+
2823 This command returns a list comprised of all the arguments, +'arg'+. Braces
2824 and backslashes get added as necessary, so that the `lindex` command
2825 may be used on the result to re-extract the original arguments, and also
2826 so that `eval` may be used to execute the resulting list, with
2827 +'arg1'+ comprising the command's name and the other args comprising
2828 its arguments. `list` produces slightly different results than
2829 `concat`:  `concat` removes one level of grouping before forming
2830 the list, while `list` works directly from the original arguments.
2831 For example, the command
2833     list a b {c d e} {f {g h}}
2835 will return
2837     a b {c d e} {f {g h}}
2839 while `concat` with the same arguments will return
2841     a b c d e f {g h}
2843 llength
2844 ~~~~~~~
2845 +*llength* 'list'+
2847 Treats +'list'+ as a list and returns a decimal string giving
2848 the number of elements in it.
2850 lset
2851 ~~~~
2852 +*lset* 'varName ?index ..? newValue'+
2854 Sets an element in a list.
2856 The `lset` command accepts a parameter, +'varName'+, which it interprets
2857 as the name of a variable containing a Tcl list. It also accepts
2858 zero or more indices into the list. Finally, it accepts a new value
2859 for an element of varName. If no indices are presented, the command
2860 takes the form:
2862     lset varName newValue
2864 In this case, newValue replaces the old value of the variable
2865 varName.
2867 When presented with a single index, the `lset` command
2868 treats the content of the varName variable as a Tcl list. It addresses
2869 the index'th element in it (0 refers to the first element of the
2870 list). When interpreting the list, `lset` observes the same rules
2871 concerning braces and quotes and backslashes as the Tcl command
2872 interpreter; however, variable substitution and command substitution
2873 do not occur. The command constructs a new list in which the
2874 designated element is replaced with newValue. This new list is
2875 stored in the variable varName, and is also the return value from
2876 the `lset` command.
2878 If index is negative or greater than or equal to the number of
2879 elements in $varName, then an error occurs.
2881 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2883 If additional index arguments are supplied, then each argument is
2884 used in turn to address an element within a sublist designated by
2885 the previous indexing operation, allowing the script to alter
2886 elements in sublists. The command,
2888     lset a 1 2 newValue
2890 replaces element 2 of sublist 1 with +'newValue'+.
2892 The integer appearing in each index argument must be greater than
2893 or equal to zero. The integer appearing in each index argument must
2894 be strictly less than the length of the corresponding list. In other
2895 words, the `lset` command cannot change the size of a list. If an
2896 index is outside the permitted range, an error is reported.
2898 lmap
2899 ~~~~
2901 +*lmap* 'varName list body'+
2903 +*lmap* 'varList list ?varList2 list2 \...? body'+
2905 `lmap` is a "collecting" `foreach` which returns a list of its results.
2907 For example:
2909     jim> lmap i {1 2 3 4 5} {expr $i*$i}
2910     1 4 9 16 25
2911     jim> lmap a {1 2 3} b {A B C} {list $a $b}
2912     {1 A} {2 B} {3 C}
2914 If the body invokes `continue`, no value is added for this iteration.
2915 If the body invokes `break`, the loop ends and no more values are added.
2917 load
2918 ~~~~
2919 +*load* 'filename'+
2921 Loads the dynamic extension, +'filename'+. Generally the filename should have
2922 the extension +.so+. The initialisation function for the module must be based
2923 on the name of the file. For example loading +hwaccess.so+ will invoke
2924 the initialisation function, +Jim_hwaccessInit+. Normally the `load` command
2925 should not be used directly. Instead it is invoked automatically by `package require`.
2927 lrange
2928 ~~~~~~
2929 +*lrange* 'list first last'+
2931 +'list'+ must be a valid Tcl list. This command will return a new
2932 list consisting of elements +'first'+ through +'last'+, inclusive.
2934 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
2936 If +'last'+ is greater than or equal to the number of elements
2937 in the list, then it is treated as if it were +end+.
2939 If +'first'+ is greater than +'last'+ then an empty string
2940 is returned.
2942 Note: +"`lrange` 'list first first'"+ does not always produce the
2943 same result as +"`lindex` 'list first'"+ (although it often does
2944 for simple fields that aren't enclosed in braces); it does, however,
2945 produce exactly the same results as +"`list` [`lindex` 'list first']"+
2947 lreplace
2948 ~~~~~~~~
2950 +*lreplace* 'list first last ?element element \...?'+
2952 Returns a new list formed by replacing one or more elements of
2953 +'list'+ with the +'element'+ arguments.
2955 +'first'+ gives the index in +'list'+ of the first element
2956 to be replaced.
2958 If +'first'+ is less than zero then it refers to the first
2959 element of +'list'+;  the element indicated by +'first'+
2960 must exist in the list.
2962 +'last'+ gives the index in +'list'+ of the last element
2963 to be replaced;  it must be greater than or equal to +'first'+.
2965 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
2967 The +'element'+ arguments specify zero or more new arguments to
2968 be added to the list in place of those that were deleted.
2970 Each +'element'+ argument will become a separate element of
2971 the list.
2973 If no +'element'+ arguments are specified, then the elements
2974 between +'first'+ and +'last'+ are simply deleted.
2976 lrepeat
2977 ~~~~~~~~
2978 +*lrepeat* 'number element1 ?element2 \...?'+
2980 Build a list by repeating elements +'number'+ times (which must be
2981 a positive integer).
2983     jim> lrepeat 3 a b
2984     a b a b a b
2986 lreverse
2987 ~~~~~~~~
2988 +*lreverse* 'list'+
2990 Returns the list in reverse order.
2992     jim> lreverse {1 2 3}
2993     3 2 1
2995 lsearch
2996 ~~~~~~~
2997 +*lsearch* '?options? list pattern'+
2999 This command searches the elements +'list'+ to see if one of them matches +'pattern'+. If so, the
3000 command returns the index of the first matching element (unless the options -all, -inline or -bool are
3001 specified.) If not, the command returns -1. The option arguments indicates how the elements of
3002 the list are to be matched against pattern and must have one of the values below:
3004 *Note* that this command is different from Tcl in that default match type is +-exact+ rather than +-glob+.
3006 +'-exact'+::
3007     +'pattern'+ is a literal string that is compared for exact equality against each list element.
3008     This is the default.
3010 +'-glob'+::
3011     +'pattern'+ is a glob-style pattern which is matched against each list element using the same
3012     rules as the string match command.
3014 +'-regexp'+::
3015     +'pattern'+ is treated as a regular expression and matched against each list element using
3016     the rules described by `regexp`.
3018 +'-all'+::
3019     Changes the result to be the list of all matching indices (or all matching values if
3020     +-inline+ is specified as well). If indices are returned, the indices will be in numeric
3021     order. If values are returned, the order of the values will be the order of those values
3022     within the input list.
3024 +'-inline'+::
3025     The matching value is returned instead of its index (or an empty string if no value
3026     matches). If +-all+ is also specified, then the result of the command is the list of all
3027     values that matched. The +-inline+ and +-bool' options are mutually exclusive.
3029 +'-bool'+::
3030     Changes the result to '1' if a match was found, or '0' otherwise. If +-all+ is also specified,
3031     the result will be a list of '0' and '1' for each element of the list depending upon whether
3032     the corresponding element matches. The +-inline+ and +-bool+ options are mutually exclusive.
3034 +'-not'+::
3035     This negates the sense of the match, returning the index (or value
3036     if +-inline+ is specified) of the first non-matching value in the
3037     list. If +-bool+ is also specified, the '0' will be returned if a
3038     match is found, or '1' otherwise. If +-all+ is also specified,
3039     non-matches will be returned rather than matches.
3041 +'-nocase'+::
3042     Causes comparisons to be handled in a case-insensitive manner.
3044 lsort
3045 ~~~~~
3046 +*lsort* ?*-index* 'listindex'? ?*-integer*|*-command* 'cmdname'? ?*-decreasing*|*-increasing*? 'list'+
3048 Sort the elements of +'list'+, returning a new list in sorted order.
3049 By default, ASCII sorting is used, with the result in increasing order.
3051 If +-integer+ is specified, numeric sorting is used.
3053 If +-command 'cmdname'+ is specified, +'cmdname'+ is treated as a command
3054 name. For each comparison, +'cmdname $value1 $value2+' is called which
3055 should compare the values and return an integer less than, equal
3056 to, or greater than zero if the +'$value1'+ is to be considered less
3057 than, equal to, or greater than +'$value2'+, respectively.
3059 If +-decreasing+ is specified, the resulting list is in the opposite
3060 order to what it would be otherwise. +-increasing+ is the default.
3062 If +-index 'listindex'+ is specified, each element of the list is treated as a list and
3063 the given index is extracted from the list for comparison. The list index may
3064 be any valid list index, such as +1+, +end+ or +end-2+.
3066 If +-index 'listindex'+ is specified, each element of the list is treated as a list and
3067 the given index is extracted from the list for comparison. The list index may
3068 be any valid list index, such as +1+, +end+ or +end-2+.
3070 open
3071 ~~~~
3072 +*open* 'fileName ?access?'+
3074 +*open* '|command-pipeline ?access?'+
3076 Opens a file and returns an identifier
3077 that may be used in future invocations
3078 of commands like `read`, `puts`, and `close`.
3079 +'fileName'+ gives the name of the file to open.
3081 The +'access'+ argument indicates the way in which the file is to be accessed.
3082 It may have any of the following values:
3084 +r+::
3085     Open the file for reading only; the file must already exist.
3087 +r\++::
3088     Open the file for both reading and writing; the file must
3089     already exist.
3091 +w+::
3092     Open the file for writing only. Truncate it if it exists. If it doesn't
3093     exist, create a new file.
3095 +w\++::
3096     Open the file for reading and writing. Truncate it if it exists.
3097     If it doesn't exist, create a new file.
3099 +a+::
3100     Open the file for writing only. The file must already exist, and the file
3101     is positioned so that new data is appended to the file.
3103 +a\++::
3104     Open the file for reading and writing. If the file doesn't
3105     exist, create a new empty file. Set the initial access position
3106     to the end of the file.
3108 +'access'+ defaults to 'r'.
3110 If a file is opened for both reading and writing, then `seek`
3111 must be invoked between a read and a write, or vice versa.
3113 If the first character of +'fileName'+ is "|" then the remaining
3114 characters of +'fileName'+ are treated as a list of arguments that
3115 describe a command pipeline to invoke, in the same style as the
3116 arguments for exec. In this case, the channel identifier returned
3117 by open may be used to write to the command's input pipe or read
3118 from its output pipe, depending on the value of +'access'+. If write-only
3119 access is used (e.g. +'access'+ is 'w'), then standard output for the
3120 pipeline is directed to the current standard output unless overridden
3121 by the command. If read-only access is used (e.g. +'access'+ is r),
3122 standard input for the pipeline is taken from the current standard
3123 input unless overridden by the command.
3125 The `pid` command may be used to return the process ids of the commands
3126 forming the command pipeline.
3128 See also `socket`, `pid`, `exec`
3130 package
3131 ~~~~~~~
3132 +*package provide* 'name ?version?'+
3134 Indicates that the current script provides the package named +'name'+.
3135 If no version is specified, '1.0' is used.
3137 Any script which provides a package may include this statement
3138 as the first statement, although it is not required.
3140 +*package require* 'name ?version?'*+
3142 Searches for the package with the given +'name'+ by examining each path
3143 in '$::auto_path' and trying to load '$path/$name.so' as a dynamic extension,
3144 or '$path/$name.tcl' as a script package.
3146 The first such file which is found is considered to provide the the package.
3147 (The version number is ignored).
3149 If '$name.so' exists, it is loaded with the `load` command,
3150 otherwise if '$name.tcl' exists it is loaded with the `source` command.
3152 If `load` or `source` fails, `package require` will fail immediately.
3153 No further attempt will be made to locate the file.
3157 +*pid*+
3159 +*pid* 'fileId'+
3161 The first form returns the process identifier of the current process.
3163 The second form accepts a handle returned by `open` and returns a list
3164 of the process ids forming the pipeline in the same form as `exec ... &`.
3165 If 'fileId' represents a regular file handle rather than a command pipeline,
3166 the empty string is returned instead.
3168 See also `open`, `exec`
3170 proc
3171 ~~~~
3172 +*proc* 'name args ?statics? body'+
3174 The `proc` command creates a new Tcl command procedure, +'name'+.
3175 When the new command is invoked, the contents of +'body'+ will be executed.
3176 Tcl interpreter. +'args'+ specifies the formal arguments to the procedure.
3177 If specified, +'static'+, declares static variables which are bound to the
3178 procedure.
3180 See PROCEDURES for detailed information about Tcl procedures.
3182 The `proc` command returns +'name'+ (which is useful with `local`).
3184 When a procedure is invoked, the procedure's return value is the
3185 value specified in a `return` command.  If the procedure doesn't
3186 execute an explicit `return`, then its return value is the value
3187 of the last command executed in the procedure's body.
3189 If an error occurs while executing the procedure body, then the
3190 procedure-as-a-whole will return that same error.
3192 puts
3193 ~~~~
3194 +*puts* ?*-nonewline*? '?fileId? string'+
3196 +'fileId' *puts* ?*-nonewline*? 'string'+
3198 Writes the characters given by +'string'+ to the file given
3199 by +'fileId'+. +'fileId'+ must have been the return
3200 value from a previous call to `open`, or it may be
3201 +stdout+ or +stderr+ to refer to one of the standard I/O
3202 channels; it must refer to a file that was opened for
3203 writing.
3205 In the first form, if no +'fileId'+ is specified then it defaults to +stdout+.
3206 `puts` normally outputs a newline character after +'string'+,
3207 but this feature may be suppressed by specifying the +-nonewline+
3208 switch.
3210 Output to files is buffered internally by Tcl; the `flush`
3211 command may be used to force buffered characters to be output.
3215 +*pwd*+
3217 Returns the path name of the current working directory.
3219 rand
3220 ~~~~
3221 +*rand* '?min? ?max?'+
3223 Returns a random integer between +'min'+ (defaults to 0) and +'max'+
3224 (defaults to the maximum integer).
3226 If only one argument is given, it is interpreted as +'max'+.
3228 range
3229 ~~~~
3230 +*range* '?start? end ?step?'+
3232 Returns a list of integers starting at +'start'+ (defaults to 0)
3233 and ranging up to but not including +'end'+ in steps of +'step'+ defaults to 1).
3235     jim> range 5
3236     0 1 2 3 4
3237     jim> range 2 5
3238     2 3 4
3239     jim> range 2 10 4
3240     2 6
3241     jim> range 7 4 -2
3242     7 5
3244 read
3245 ~~~~
3246 +*read* ?*-nonewline*? 'fileId'+
3248 +'fileId' *read* ?*-nonewline*?+
3250 +*read* 'fileId numBytes'+
3252 +'fileId' *read* 'numBytes'+
3255 In the first form, all of the remaining bytes are read from the file
3256 given by +'fileId'+; they are returned as the result of the command.
3257 If the +-nonewline+ switch is specified then the last
3258 character of the file is discarded if it is a newline.
3260 In the second form, the extra argument specifies how many bytes to read;
3261 exactly this many bytes will be read and returned, unless there are fewer than
3262 +'numBytes'+ bytes left in the file; in this case, all the remaining
3263 bytes are returned.
3265 +'fileId'+ must be +stdin+ or the return value from a previous call
3266 to `open`; it must refer to a file that was opened for reading.
3268 regexp
3269 ~~~~~~
3270 +*regexp ?-nocase? ?-line? ?-indices? ?-start* 'offset'? *?-all? ?-inline? ?--?* 'exp string ?matchVar? ?subMatchVar subMatchVar \...?'+
3272 Determines whether the regular expression +'exp'+ matches part or
3273 all of +'string'+ and returns 1 if it does, 0 if it doesn't.
3275 See REGULAR EXPRESSIONS above for complete information on the
3276 syntax of +'exp'+ and how it is matched against +'string'+.
3278 If additional arguments are specified after +'string'+ then they
3279 are treated as the names of variables to use to return
3280 information about which part(s) of +'string'+ matched +'exp'+.
3281 +'matchVar'+ will be set to the range of +'string'+ that
3282 matched all of +'exp'+. The first +'subMatchVar'+ will contain
3283 the characters in +'string'+ that matched the leftmost parenthesized
3284 subexpression within +'exp'+, the next +'subMatchVar'+ will
3285 contain the characters that matched the next parenthesized
3286 subexpression to the right in +'exp'+, and so on.
3288 Normally, +'matchVar'+ and the each +'subMatchVar'+ are set to hold the
3289 matching characters from `string`, however see +-indices+ and
3290 +-inline+ below.
3292 If there are more values for +'subMatchVar'+ than parenthesized subexpressions
3293 within +'exp'+, or if a particular subexpression in +'exp'+ doesn't
3294 match the string (e.g. because it was in a portion of the expression
3295 that wasn't matched), then the corresponding +'subMatchVar'+ will be
3296 set to +"-1 -1"+ if +-indices+ has been specified or to an empty
3297 string otherwise.
3299 The following switches modify the behaviour of +'regexp'+
3301 +*-nocase*+::
3302     Causes upper-case and lower-case characters to be treated as
3303     identical during the matching process.
3305 +*-line*+::
3306     Use newline-sensitive matching. By default, newline
3307     is a completely ordinary character with no special meaning in
3308     either REs or strings. With this flag, +[^+ bracket expressions
3309     and +.+ never match newline, a +^+ anchor matches the null
3310     string after any newline in the string in addition to its normal
3311     function, and the +$+ anchor matches the null string before any
3312     newline in the string in addition to its normal function.
3314 +*-indices*+::
3315     Changes what is stored in the subMatchVars. Instead of
3316     storing the matching characters from string, each variable
3317     will contain a list of two decimal strings giving the indices
3318     in string of the first and last characters in the matching
3319     range of characters.
3321 +*-start* 'offset'+::
3322     Specifies a character index offset into the string at which to start
3323     matching the regular expression. If +-indices+ is
3324     specified, the indices will be indexed starting from the
3325     absolute beginning of the input string. +'offset'+ will be
3326     constrained to the bounds of the input string.
3328 +*-all*+::
3329     Causes the regular expression to be matched as many times as possible
3330     in the string, returning the total number of matches found. If this
3331     is specified with match variables, they will contain information
3332     for the last match only.
3334 +*-inline*+::
3335     Causes the command to return, as a list, the data that would otherwise
3336     be placed in match variables. When using +-inline+, match variables
3337     may not be specified. If used with +-all+, the list will be concatenated
3338     at each iteration, such that a flat list is always returned. For
3339     each match iteration, the command will append the overall match
3340     data, plus one element for each subexpression in the regular
3341     expression.
3343 +*--*+::
3344     Marks the end of switches. The argument following this one will be
3345     treated as +'exp'+ even if it starts with a +-+.
3347 regsub
3348 ~~~~~~
3349 +*regsub ?-nocase? ?-all? ?-line? ?-start* 'offset'? ?*--*? 'exp string subSpec ?varName?'+
3351 This command matches the regular expression +'exp'+ against
3352 +'string'+ using the rules described in REGULAR EXPRESSIONS
3353 above.
3355 If +'varName'+ is specified, the commands stores +'string'+ to +'varName'+
3356 with the substitutions detailed below, and returns the number of
3357 substitutions made (normally 1 unless +-all+ is specified).
3358 This is 0 if there were no matches.
3360 If +'varName'+ is not specified, the substituted string will be returned
3361 instead.
3363 When copying +'string'+, the portion of +'string'+ that
3364 matched +'exp'+ is replaced with +'subSpec'+.
3365 If +'subSpec'+ contains a +&+ or +{backslash}0+, then it is replaced
3366 in the substitution with the portion of +'string'+ that
3367 matched +'exp'+.
3369 If +'subSpec'+ contains a +{backslash}n+, where +'n'+ is a digit
3370 between 1 and 9, then it is replaced in the substitution with
3371 the portion of +'string'+ that matched the +''+n+''+-th
3372 parenthesized subexpression of +'exp'+.
3373 Additional backslashes may be used in +'subSpec'+ to prevent special
3374 interpretation of +&+ or +{backslash}0+ or +{backslash}n+ or
3375 backslash.
3377 The use of backslashes in +'subSpec'+ tends to interact badly
3378 with the Tcl parser's use of backslashes, so it's generally
3379 safest to enclose +'subSpec'+ in braces if it includes
3380 backslashes.
3382 The following switches modify the behaviour of +'regsub'+
3384 +*-nocase*+::
3385     Upper-case characters in +'string'+ are converted to lower-case
3386     before matching against +'exp'+;  however, substitutions
3387     specified by +'subSpec'+ use the original unconverted form
3388     of +'string'+.
3390 +*-all*+::
3391     All ranges in +'string'+ that match +'exp'+ are found and substitution
3392     is performed for each of these ranges, rather than only the
3393     first. The +&+ and +{backslash}n+ sequences are handled for
3394     each substitution using the information from the corresponding
3395     match.
3397 +*-line*+::
3398     Use newline-sensitive matching. By default, newline
3399     is a completely ordinary character with no special meaning in
3400     either REs or strings.  With this flag, +[^+ bracket expressions
3401     and +.+ never match newline, a +^+ anchor matches the null
3402     string after any newline in the string in addition to its normal
3403     function, and the +$+ anchor matches the null string before any
3404     newline in the string in addition to its normal function.
3406 +*-start* 'offset'+::
3407     Specifies a character index offset into the string at which to
3408     start matching the regular expression. +'offset'+ will be
3409     constrained to the bounds of the input string.
3411 +*--*+::
3412     Marks the end of switches. The argument following this one will be
3413     treated as +'exp'+ even if it starts with a +-+.
3417 +*ref* 'string tag ?finalizer?'+
3419 Create a new reference containing +'string'+ of type +'tag'+.
3420 If +'finalizer'+ is specified, it is a command which will be invoked
3421 when the a garbage collection cycle runs and this reference is
3422 no longer accessible.
3424 The finalizer is invoked as:
3426   +finalizer 'reference string'+
3428 See GARBAGE COLLECTION, REFERENCES, LAMBDA for more detail.
3430 rename
3431 ~~~~~~
3432 +*rename* 'oldName newName'+
3434 Rename the command that used to be called +'oldName'+ so that it
3435 is now called +'newName'+.  If +'newName'+ is an empty string
3436 (e.g. {}) then +'oldName'+ is deleted.  The `rename` command
3437 returns an empty string as result.
3439 return
3440 ~~~~~~
3441 +*return* ?*-code* 'code'? ?*-errorinfo* 'stacktrace'? ?*-errorcode* 'errorcode'? ?*-level* 'n'? ?'value'?+
3443 Return immediately from the current procedure (or top-level command
3444 or `source` command), with +'value'+ as the return value.  If +'value'+
3445 is not specified, an empty string will be returned as result.
3447 If +-code+ is specified (as either a number or ok, error, break,
3448 continue, signal, return or exit), this code will be used instead
3449 of +JIM_OK+. This is generally useful when implementing flow of control
3450 commands.
3452 If +-level+ is specified and greater than 1, it has the effect of delaying
3453 the new return code from +-code+. This is useful when rethrowing an error
3454 from `catch`. See the implementation of try/catch in tclcompat.tcl for
3455 an example of how this is done.
3457 Note: The following options are only used when +-code+ is JIM_ERR.
3459 If +-errorinfo+ is specified (as returned from `info stacktrace`)
3460 it is used to initialize the stacktrace.
3462 If +-errorcode+ is specified, it is used to set the global variable $::errorCode.
3464 scan
3465 ~~~~
3466 +*scan* 'string format varName1 ?varName2 \...?'+
3468 This command parses fields from an input string in the same fashion
3469 as the C 'sscanf' procedure.  +'string'+ gives the input to be parsed
3470 and +'format'+ indicates how to parse it, using '%' fields as in
3471 'sscanf'.  All of the 'sscanf' options are valid; see the 'sscanf'
3472 man page for details.  Each +'varName'+ gives the name of a variable;
3473 when a field is scanned from +'string'+, the result is converted back
3474 into a string and assigned to the corresponding +'varName'+.  The
3475 only unusual conversion is for '%c'.  For '%c' conversions a single
3476 character value is converted to a decimal string, which is then
3477 assigned to the corresponding +'varName'+; no field width may be
3478 specified for this conversion.
3480 seek
3481 ~~~~
3482 +*seek* 'fileId offset ?origin?'+
3484 +'fileId' *seek* 'offset ?origin?'+
3486 Change the current access position for +'fileId'+.
3487 The +'offset'+ and +'origin'+ arguments specify the position at
3488 which the next read or write will occur for +'fileId'+.
3489 +'offset'+ must be a number (which may be negative) and +'origin'+
3490 must be one of the following:
3492 +*start*+::
3493     The new access position will be +'offset'+ bytes from the start
3494     of the file.
3496 +*current*+::
3497     The new access position will be +'offset'+ bytes from the current
3498     access position; a negative +'offset'+ moves the access position
3499     backwards in the file.
3501 +*end*+::
3502     The new access position will be +'offset'+ bytes from the end of
3503     the file.  A negative +'offset'+ places the access position before
3504     the end-of-file, and a positive +'offset'+ places the access position
3505     after the end-of-file.
3507 The +'origin'+ argument defaults to +start+.
3509 +'fileId'+ must have been the return value from a previous call to
3510 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
3511 of the standard I/O channels.
3513 This command returns an empty string.
3517 +*set* 'varName ?value?'+
3519 Returns the value of variable +'varName'+.
3521 If +'value'+ is specified, then set the value of +'varName'+ to +'value'+,
3522 creating a new variable if one doesn't already exist, and return
3523 its value.
3525 If +'varName'+ contains an open parenthesis and ends with a
3526 close parenthesis, then it refers to an array element:  the characters
3527 before the open parenthesis are the name of the array, and the characters
3528 between the parentheses are the index within the array.
3529 Otherwise +'varName'+ refers to a scalar variable.
3531 If no procedure is active, then +'varName'+ refers to a global
3532 variable.
3534 If a procedure is active, then +'varName'+ refers to a parameter
3535 or local variable of the procedure, unless the +'global'+ command
3536 has been invoked to declare +'varName'+ to be global.
3538 The +::+ prefix may also be used to explicitly reference a variable
3539 in the global scope.
3541 setref
3542 ~~~~~~
3543 +*setref* 'reference string'+
3545 Store a new string in +'reference'+, replacing the existing string.
3546 The reference must be a valid reference create with the `ref`
3547 command.
3549 See GARBAGE COLLECTION, REFERENCES, LAMBDA for more detail.
3551 signal
3552 ~~~~~~
3553 Command for signal handling.
3555 See `kill` for the different forms which may be used to specify signals.
3557 Commands which return a list of signal names do so using the canonical form:
3558 "+SIGINT SIGTERM+".
3560 +*signal handle* ?'signals \...'?+::
3561     If no signals are given, returns a list of all signals which are currently
3562     being handled.
3563     If signals are specified, these are added to the list of signals currently
3564     being handled.
3566 +*signal ignore* ?'signals \...'?+::
3567     If no signals are given, returns a lists all signals which are currently
3568     being ignored.
3569     If signals are specified, these are added to the list of signals
3570     currently being ignored. These signals are still delivered, but
3571     are not considered by `catch -signal` or `try -signal`. Use
3572     `signal check` to determine which signals have occurred but
3573     been ignored.
3575 +*signal default* ?'signals \...'?+::
3576     If no signals are given, returns a lists all signals which are currently have
3577     the default behaviour.
3578     If signals are specified, these are added to the list of signals which have
3579     the default behaviour.
3581 +*signal check ?-clear?* ?'signals \...'?+::
3582     Returns a list of signals which have been delivered to the process
3583     but are 'ignored'. If signals are specified, only that set of signals will
3584     be checked, otherwise all signals will be checked.
3585     If +-clear+ is specified, any signals returned are removed and will not be
3586     returned by subsequent calls to `signal check` unless delivered again.
3588 +*signal throw* ?'signal'?+::
3589     Raises the given signal, which defaults to +SIGINT+ if not specified.
3590     The behaviour is identical to:
3592         kill signal [pid]
3594 Note that `signal handle` and `signal ignore` represent two forms of signal
3595 handling. `signal handle` is used in conjunction with `catch -signal` or `try -signal`
3596 to immediately abort execution when the signal is delivered. Alternatively, `signal ignore`
3597 is used in conjunction with `signal check` to handle signal synchronously. Consider the
3598 two examples below.
3600 Prevent a processing from taking too long
3602     signal handle SIGALRM
3603     alarm 20
3604     try -signal {
3605         .. possibly long running process ..
3606         alarm 0
3607     } on signal {sig} {
3608         puts stderr "Process took too long"
3609     }
3611 Handle SIGHUP to reconfigure:
3613     signal ignore SIGHUP
3614     while {1} {
3615         ... handle configuration/reconfiguration ...
3616         while {[signal check -clear SIGHUP] eq ""} {
3617             ... do processing ..
3618         }
3619         # Received SIGHUP, so reconfigure
3620     }
3622 sleep
3623 ~~~~~
3624 +*sleep* 'seconds'+
3626 Pauses for the given number of seconds, which may be a floating
3627 point value less than one to sleep for less than a second, or an
3628 integer to sleep for one or more seconds.
3630 source
3631 ~~~~~~
3632 +*source* 'fileName'+
3634 Read file +'fileName'+ and pass the contents to the Tcl interpreter
3635 as a sequence of commands to execute in the normal fashion.  The return
3636 value of `source` is the return value of the last command executed
3637 from the file.  If an error occurs in executing the contents of the
3638 file, then the `source` command will return that error.
3640 If a `return` command is invoked from within the file, the remainder of
3641 the file will be skipped and the `source` command will return
3642 normally with the result from the `return` command.
3644 split
3645 ~~~~~
3646 +*split* 'string ?splitChars?'+
3648 Returns a list created by splitting +'string'+ at each character
3649 that is in the +'splitChars'+ argument.
3651 Each element of the result list will consist of the
3652 characters from +'string'+ between instances of the
3653 characters in +'splitChars'+.
3655 Empty list elements will be generated if +'string'+ contains
3656 adjacent characters in +'splitChars'+, or if the first or last
3657 character of +'string'+ is in +'splitChars'+.
3659 If +'splitChars'+ is an empty string then each character of
3660 +'string'+ becomes a separate element of the result list.
3662 +'splitChars'+ defaults to the standard white-space characters.
3663 For example,
3665     split "comp.unix.misc" .
3667 returns +'"comp unix misc"'+ and
3669     split "Hello world" {}
3671 returns +'"H e l l o { } w o r l d"'+.
3673 stackdump
3674 ~~~~~~~~~
3676 +*stackdump* 'stacktrace'+
3678 Creates a human readable representation of a stack trace.
3680 stacktrace
3681 ~~~~~~~~~~
3683 +*stacktrace*+
3685 Returns a live stack trace as a list of +proc file line proc file line \...+.
3686 Iteratively uses `info frame` to create the stack trace. This stack trace is in the
3687 same form as produced by `catch` and `info stacktrace`
3689 See also `stackdump`.
3691 string
3692 ~~~~~~
3694 +*string* 'option arg ?arg \...?'+
3696 Perform one of several string operations, depending on +'option'+.
3697 The legal options (which may be abbreviated) are:
3699 +*string bytelength* 'string'+::
3700     Returns the length of the string in bytes. This will return
3701     the same value as `string length` if UTF-8 support is not enabled,
3702     or if the string is composed entirely of ASCII characters.
3703     See UTF-8 AND UNICODE.
3705 +*string compare ?-nocase?* 'string1 string2'+::
3706     Perform a character-by-character comparison of strings +'string1'+ and
3707     +'string2'+ in the same way as the C 'strcmp' procedure.  Return
3708     -1, 0, or 1, depending on whether +'string1'+ is lexicographically
3709     less than, equal to, or greater than +'string2'+.
3710     Performs a case-insensitive comparison if +-nocase+ is specified.
3712 +*string equal ?-nocase?* 'string1 string2'+::
3713     Returns 1 if the strings are equal, or 0 otherwise.
3714     Performs a case-insensitive comparison if +-nocase+ is specified.
3716 +*string first* 'string1 string2 ?firstIndex?'+::
3717     Search +'string2'+ for a sequence of characters that exactly match
3718     the characters in +'string1'+.  If found, return the index of the
3719     first character in the first such match within +'string2'+.  If not
3720     found, return -1. If +'firstIndex'+ is specified, matching will start
3721     from +'firstIndex'+ of +'string1'+.
3722  ::
3723     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'firstIndex'+.
3725 +*string index* 'string charIndex'+::
3726     Returns the +'charIndex'+'th character of the +'string'+
3727     argument.  A +'charIndex'+ of 0 corresponds to the first
3728     character of the string.
3729     If +'charIndex'+ is less than 0 or greater than
3730     or equal to the length of the string then an empty string is
3731     returned.
3732  ::
3733     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'charIndex'+.
3735 +*string is* 'class' ?*-strict*? 'string'+::
3736     Returns 1 if +'string'+ is a valid member of the specified character
3737     class, otherwise returns 0. If +-strict+ is specified, then an
3738     empty string returns 0, otherwise an empty string will return 1
3739     on any class. The following character classes are recognized
3740     (the class name can be abbreviated):
3741   ::
3742   +alnum+;;  Any alphabet or digit character.
3743   +alpha+;;  Any alphabet character.
3744   +ascii+;;  Any character with a value less than 128 (those that are in the 7-bit ascii range).
3745   +control+;; Any control character.
3746   +digit+;;  Any digit character.
3747   +double+;; Any of the valid forms for a double in Tcl, with optional surrounding whitespace.
3748              In case of under/overflow in the value, 0 is returned.
3749   +graph+;;  Any printing character, except space.
3750   +integer+;; Any of the valid string formats for an integer value in Tcl, with optional surrounding whitespace.
3751   +lower+;;  Any lower case alphabet character.
3752   +print+;;  Any printing character, including space.
3753   +punct+;;  Any punctuation character.
3754   +space+;;  Any space character.
3755   +upper+;;  Any upper case alphabet character.
3756   +xdigit+;; Any hexadecimal digit character ([0-9A-Fa-f]).
3757  ::
3758     Note that string classification does +'not'+ respect UTF-8. See UTF-8 AND UNICODE
3760 +*string last* 'string1 string2 ?lastIndex?'+::
3761     Search +'string2'+ for a sequence of characters that exactly match
3762     the characters in +'string1'+.  If found, return the index of the
3763     first character in the last such match within +'string2'+.  If there
3764     is no match, then return -1. If +'lastIndex'+ is specified, only characters
3765     up to +'lastIndex'+ of +'string2'+ will be considered in the match.
3766  ::
3767     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'lastIndex'+.
3769 +*string length* 'string'+::
3770     Returns a decimal string giving the number of characters in +'string'+.
3771     If UTF-8 support is enabled, this may be different than the number of bytes.
3772     See UTF-8 AND UNICODE
3774 +*string match ?-nocase?* 'pattern string'+::
3775     See if +'pattern'+ matches +'string'+; return 1 if it does, 0
3776     if it doesn't.  Matching is done in a fashion similar to that
3777     used by the C-shell.  For the two strings to match, their contents
3778     must be identical except that the following special sequences
3779     may appear in +'pattern'+:
3781     +*+;;
3782         Matches any sequence of characters in +'string'+,
3783         including a null string.
3785     +?+;;
3786         Matches any single character in +'string'+.
3788     +[+'chars'+]+;;
3789         Matches any character in the set given by +'chars'+.
3790         If a sequence of the form +'x'+-+'y'+ appears in +'chars'+,
3791         then any character between +'x'+ and +'y'+, inclusive,
3792         will match.
3794     +{backslash}x+;;
3795         Matches the single character +'x'+.  This provides a way of
3796         avoiding the special interpretation of the characters \`\*?[]\`
3797         in +''+pattern+''+.
3798  ::
3799     Performs a case-insensitive comparison if +-nocase+ is specified.
3801 +*string range* 'string first last'+::
3802     Returns a range of consecutive characters from +'string'+, starting
3803     with the character whose index is +'first'+ and ending with the
3804     character whose index is +'last'+.  An index of 0 refers to the
3805     first character of the string.
3806  ::
3807     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
3808  ::
3809     If +'first'+ is less than zero then it is treated as if it were zero, and
3810     if +'last'+ is greater than or equal to the length of the string then
3811     it is treated as if it were +end+.  If +'first'+ is greater than
3812     +'last'+ then an empty string is returned.
3814 +*string byterange* 'string first last'+::
3815     Like 'string range' except works on bytes rather than characters. These commands
3816     are identical if UTF-8 support is not enabled
3818 +*string repeat* 'string count'+::
3819     Returns a new string consisting of +'string'+ repeated +'count'+ times.
3821 +*string reverse* 'string'+::
3822     Returns a string that is the same length as +'string'+ but
3823     with its characters in the reverse order.
3825 +*string tolower* 'string'+::
3826     Returns a value equal to +'string'+ except that all upper case
3827     letters have been converted to lower case.
3829 +*string toupper* 'string'+::
3830     Returns a value equal to +'string'+ except that all lower case
3831     letters have been converted to upper case.
3833 +*string trim* 'string ?chars?'+::
3834     Returns a value equal to +'string'+ except that any leading
3835     or trailing characters from the set given by +'chars'+ are
3836     removed.
3837     If +'chars'+ is not specified then white space is removed
3838     (spaces, tabs, newlines, and carriage returns).
3840 +*string trimleft* 'string ?chars?'+::
3841     Returns a value equal to +'string'+ except that any
3842     leading characters from the set given by +'chars'+ are
3843     removed.
3844     If +'chars'+ is not specified then white space is removed
3845     (spaces, tabs, newlines, and carriage returns).
3847 +*string trimright* 'string ?chars?'+::
3848     Returns a value equal to +'string'+ except that any
3849     trailing characters from the set given by +'chars'+ are
3850     removed.
3851     If +'chars'+ is not specified then white space is removed
3852     (spaces, tabs, newlines, and carriage returns).
3853     Null characters are always removed.
3855 subst
3856 ~~~~~
3857 +*subst ?-nobackslashes? ?-nocommands? ?-novariables?* 'string'+
3859 This command performs variable substitutions, command substitutions,
3860 and backslash substitutions on its string argument and returns the
3861 fully-substituted result. The substitutions are performed in exactly
3862 the same way as for Tcl commands. As a result, the string argument
3863 is actually substituted twice, once by the Tcl parser in the usual
3864 fashion for Tcl commands, and again by the subst command.
3866 If any of the +-nobackslashes+, +-nocommands+, or +-novariables+ are
3867 specified, then the corresponding substitutions are not performed.
3868 For example, if +-nocommands+ is specified, no command substitution
3869 is performed: open and close brackets are treated as ordinary
3870 characters with no special interpretation.
3872 *Note*: when it performs its substitutions, subst does not give any
3873 special treatment to double quotes or curly braces. For example,
3874 the following script returns +xyz \{44\}+, not +xyz \{$a\}+.
3876     set a 44
3877     subst {xyz {$a}}
3880 switch
3881 ~~~~~~
3882 +*switch* '?options? string pattern body ?pattern body \...?'+
3884 +*switch* '?options? string {pattern body ?pattern body \...?}'+
3886 The `switch` command matches its string argument against each of
3887 the pattern arguments in order. As soon as it finds a pattern that
3888 matches string it evaluates the following body and returns the
3889 result of that evaluation. If the last pattern argument is default
3890 then it matches anything. If no pattern argument matches string and
3891 no default is given, then the `switch` command returns an empty string.
3892 If the initial arguments to switch start with - then they are treated
3893 as options. The following options are currently supported:
3895     +-exact+::
3896         Use exact matching when comparing string to a
3897         pattern. This is the default.
3899     +-glob+::
3900         When matching string to the patterns, use glob-style
3901         matching (i.e. the same as implemented by the string
3902         match command).
3904     +-regexp+::
3905         When matching string to the patterns, use regular
3906         expression matching (i.e. the same as implemented
3907         by the regexp command).
3909     +-command 'commandname'+::
3910         When matching string to the patterns, use the given command, which
3911         must be a single word. The command is invoked as
3912         'commandname pattern string', or 'commandname -nocase pattern string'
3913         and must return 1 if matched, or 0 if not.
3915     +--+::
3916         Marks the end of options. The argument following
3917         this one will be treated as string even if it starts
3918         with a +-+.
3920 Two syntaxes are provided for the pattern and body arguments. The
3921 first uses a separate argument for each of the patterns and commands;
3922 this form is convenient if substitutions are desired on some of the
3923 patterns or commands. The second form places all of the patterns
3924 and commands together into a single argument; the argument must
3925 have proper list structure, with the elements of the list being the
3926 patterns and commands. The second form makes it easy to construct
3927 multi-line `switch` commands, since the braces around the whole list
3928 make it unnecessary to include a backslash at the end of each line.
3929 Since the pattern arguments are in braces in the second form, no
3930 command or variable substitutions are performed on them; this makes
3931 the behaviour of the second form different than the first form in
3932 some cases.
3934 If a body is specified as +-+ it means that the body for the next
3935 pattern should also be used as the body for this pattern (if the
3936 next pattern also has a body of +-+ then the body after that is
3937 used, and so on). This feature makes it possible to share a single
3938 body among several patterns.
3940 Below are some examples of `switch` commands:
3942     switch abc a - b {format 1} abc {format 2} default {format 3}
3944 will return 2,
3946     switch -regexp aaab {
3947            ^a.*b$ -
3948            b {format 1}
3949            a* {format 2}
3950            default {format 3}
3951     }
3953 will return 1, and
3955     switch xyz {
3956            a -
3957            b {format 1}
3958            a* {format 2}
3959            default {format 3}
3960     }
3962 will return 3.
3964 tailcall
3965 ~~~~~~~~
3966 +*tailcall* 'cmd ?arg\...?'+
3968 The `tailcall` command provides an optimised way of invoking a command whilst replacing
3969 the current call frame. This is similar to 'exec' in Bourne Shell.
3971 The following are identical except the first immediately replaces the current call frame.
3973   tailcall a b c
3975   return [uplevel 1 a b c]
3977 `tailcall` is useful for a dispatch mechanism:
3979   proc a {cmd args} {
3980     tailcall sub_$cmd {*}$args
3981   }
3982   proc sub_cmd1 ...
3983   proc sub_cmd2 ...
3985 tell
3986 ~~~~
3987 +*tell* 'fileId'+
3989 +'fileId' *tell*+
3991 Returns a decimal string giving the current access position in
3992 +'fileId'+.
3994 +'fileId'+ must have been the return value from a previous call to
3995 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
3996 of the standard I/O channels.
3998 throw
3999 ~~~~~
4000 +*throw* 'code ?msg?'+
4002 This command throws an exception (return) code along with an optional message.
4003 This command is mostly for convenient usage with `try`.
4005 The command +throw break+ is equivalent to +break+.
4006 The command +throw 20 message+ can be caught with an +on 20 \...+ clause to `try`.
4008 time
4009 ~~~~
4010 +*time* 'command ?count?'+
4012 This command will call the Tcl interpreter +'count'+
4013 times to execute +'command'+ (or once if +'count'+ isn't
4014 specified).  It will then return a string of the form
4016     503 microseconds per iteration
4018 which indicates the average amount of time required per iteration,
4019 in microseconds.
4021 Time is measured in elapsed time, not CPU time.
4025 +*try* '?catchopts? tryscript' ?*on* 'returncodes {?resultvar? ?optsvar?} handlerscript \...'? ?*finally* 'finalscript'?+
4027 The `try` command is provided as a convenience for exception handling.
4029 This interpeter first evaluates +'tryscript'+ under the effect of the catch
4030 options +'catchopts'+ (e.g. +-signal -noexit --+, see `catch`).
4032 It then evaluates the script for the first matching 'on' handler
4033 (there many be zero or more) based on the return code from the `try`
4034 section. For example a normal +JIM_ERR+ error will be matched by
4035 an 'on error' handler.
4037 Finally, any +'finalscript'+ is evaluated.
4039 The result of this command is the result of +'tryscript'+, except in the
4040 case where an exception occurs in a matching 'on' handler script or the 'finally' script,
4041 in which case the result is this new exception.
4043 The specified +'returncodes'+ is a list of return codes either as names ('ok', 'error', 'break', etc.)
4044 or as integers.
4046 If +'resultvar'+ and +'optsvar'+ are specified, they are set as for `catch` before evaluating
4047 the matching handler.
4049 For example:
4051     set f [open input]
4052     try -signal {
4053         process $f
4054     } on {continue break} {} {
4055         error "Unexpected break/continue"
4056     } on error {msg opts} {
4057         puts "Dealing with error"
4058         return {*}$opts $msg
4059     } on signal sig {
4060         puts "Got signal: $sig"
4061     } finally {
4062         $f close
4063     }
4065 If break, continue or error are raised, they are dealt with by the matching
4066 handler.
4068 In any case, the file will be closed via the 'finally' clause.
4070 See also `throw`, `catch`, `return`, `error`.
4072 unknown
4073 ~~~~~~~
4074 +*unknown* 'cmdName ?arg arg ...?'+
4076 This command doesn't actually exist as part of Tcl, but Tcl will
4077 invoke it if it does exist.
4079 If the Tcl interpreter encounters a command name for which there
4080 is not a defined command, then Tcl checks for the existence of
4081 a command named `unknown`.
4083 If there is no such command, then the interpreter returns an
4084 error.
4086 If the `unknown` command exists, then it is invoked with
4087 arguments consisting of the fully-substituted name and arguments
4088 for the original non-existent command.
4090 The `unknown` command typically does things like searching
4091 through library directories for a command procedure with the name
4092 +'cmdName'+, or expanding abbreviated command names to full-length,
4093 or automatically executing unknown commands as UNIX sub-processes.
4095 In some cases (such as expanding abbreviations) `unknown` will
4096 change the original command slightly and then (re-)execute it.
4097 The result of the `unknown` command is used as the result for
4098 the original non-existent command.
4100 unset
4101 ~~~~~
4102 +*unset ?-nocomplain? ?--?* '?name name ...?'+
4104 Remove variables.
4105 Each +'name'+ is a variable name, specified in any of the
4106 ways acceptable to the `set` command.
4108 If a +'name'+ refers to an element of an array, then that
4109 element is removed without affecting the rest of the array.
4111 If a +'name'+ consists of an array name with no parenthesized
4112 index, then the entire array is deleted.
4114 The `unset` command returns an empty string as result.
4116 An error occurs if any of the variables doesn't exist, unless '-nocomplain'
4117 is specified. The '--' argument may be specified to stop option processing
4118 in case the variable name may be '-nocomplain'.
4120 upcall
4121 ~~~~~~~
4122 +*upcall* 'command ?args ...?'+
4124 May be used from within a proc defined as `local` `proc` in order to call
4125 the previous, hidden version of the same command.
4127 If there is no previous definition of the command, an error is returned.
4129 uplevel
4130 ~~~~~~~
4131 +*uplevel* '?level? command ?command ...?'+
4133 All of the +'command'+ arguments are concatenated as if they had
4134 been passed to `concat`; the result is then evaluated in the
4135 variable context indicated by +'level'+.  `uplevel` returns
4136 the result of that evaluation.  If +'level'+ is an integer, then
4137 it gives a distance (up the procedure calling stack) to move before
4138 executing the command.  If +'level'+ consists of +\#+ followed by
4139 a number then the number gives an absolute level number.  If +'level'+
4140 is omitted then it defaults to +1+.  +'level'+ cannot be
4141 defaulted if the first +'command'+ argument starts with a digit or +#+.
4143 For example, suppose that procedure 'a' was invoked
4144 from top-level, and that it called 'b', and that 'b' called 'c'.
4145 Suppose that 'c' invokes the `uplevel` command.  If +'level'+
4146 is +1+ or +#2+  or omitted, then the command will be executed
4147 in the variable context of 'b'.  If +'level'+ is +2+ or +#1+
4148 then the command will be executed in the variable context of 'a'.
4150 If +'level'+ is '3' or +#0+ then the command will be executed
4151 at top-level (only global variables will be visible).
4152 The `uplevel` command causes the invoking procedure to disappear
4153 from the procedure calling stack while the command is being executed.
4154 In the above example, suppose 'c' invokes the command
4156     uplevel 1 {set x 43; d}
4158 where 'd' is another Tcl procedure.  The `set` command will
4159 modify the variable 'x' in 'b's context, and 'd' will execute
4160 at level 3, as if called from 'b'.  If it in turn executes
4161 the command
4163     uplevel {set x 42}
4165 then the `set` command will modify the same variable 'x' in 'b's
4166 context:  the procedure 'c' does not appear to be on the call stack
4167 when 'd' is executing.  The command `info level` may
4168 be used to obtain the level of the current procedure.
4170 `uplevel` makes it possible to implement new control
4171 constructs as Tcl procedures (for example, `uplevel` could
4172 be used to implement the `while` construct as a Tcl procedure).
4174 upvar
4175 ~~~~~
4176 +*upvar* '?level? otherVar myVar ?otherVar myVar ...?'+
4178 This command arranges for one or more local variables in the current
4179 procedure to refer to variables in an enclosing procedure call or
4180 to global variables.
4182 +'level'+ may have any of the forms permitted for the `uplevel`
4183 command, and may be omitted if the first letter of the first +'otherVar'+
4184 isn't +#+ or a digit (it defaults to '1').
4186 For each +'otherVar'+ argument, `upvar` makes the variable
4187 by that name in the procedure frame given by +'level'+ (or at
4188 global level, if +'level'+ is +#0+) accessible
4189 in the current procedure by the name given in the corresponding
4190 +'myVar'+ argument.
4192 The variable named by +'otherVar'+ need not exist at the time of the
4193 call;  it will be created the first time +'myVar'+ is referenced, just like
4194 an ordinary variable.
4196 `upvar` may only be invoked from within procedures.
4198 `upvar` returns an empty string.
4200 The `upvar` command simplifies the implementation of call-by-name
4201 procedure calling and also makes it easier to build new control constructs
4202 as Tcl procedures.
4203 For example, consider the following procedure:
4205     proc add2 name {
4206         upvar $name x
4207         set x [expr $x+2]
4208     }
4210 'add2' is invoked with an argument giving the name of a variable,
4211 and it adds two to the value of that variable.
4212 Although 'add2' could have been implemented using `uplevel`
4213 instead of `upvar`, `upvar` makes it simpler for 'add2'
4214 to access the variable in the caller's procedure frame.
4216 while
4217 ~~~~~
4218 +*while* 'test body'+
4220 The +'while'+ command evaluates +'test'+ as an expression
4221 (in the same way that `expr` evaluates its argument).
4222 The value of the expression must be numeric; if it is non-zero
4223 then +'body'+ is executed by passing it to the Tcl interpreter.
4225 Once +'body'+ has been executed then +'test'+ is evaluated
4226 again, and the process repeats until eventually +'test'+
4227 evaluates to a zero numeric value.  `continue`
4228 commands may be executed inside +'body'+ to terminate the current
4229 iteration of the loop, and `break`
4230 commands may be executed inside +'body'+ to cause immediate
4231 termination of the `while` command.
4233 The `while` command always returns an empty string.
4235 OPTIONAL-EXTENSIONS
4236 -------------------
4238 The following extensions may or may not be available depending upon
4239 what options were selected when Jim Tcl was built.
4241 [[cmd_1]]
4242 posix: os.fork, os.wait, os.gethostname, os.getids, os.uptime
4243 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4244 +*os.fork*+::
4245     Invokes 'fork(2)' and returns the result.
4247 +*os.wait -nohang* 'pid'+::
4248     Invokes waitpid(2), with WNOHANG if +-nohang+ is specified.
4249     Returns a list of 3 elements.
4251    {0 none 0} if -nohang is specified, and the process is still alive.
4253    {-1 error <error-description>} if the process does not exist or has already been waited for.
4255    {<pid> exit <exit-status>} if the process exited normally.
4257    {<pid> signal <signal-number>} if the process terminated on a signal.
4259    {<pid> other 0} otherwise (core dump, stopped, continued, etc.)
4261 +*os.gethostname*+::
4262     Invokes 'gethostname(3)' and returns the result.
4264 +*os.getids*+::
4265     Returns the various user/group ids for the current process.
4267     jim> os.getids
4268     uid 1000 euid 1000 gid 100 egid 100
4270 +*os.uptime*+::
4271     Returns the number of seconds since system boot. See description of 'uptime' in 'sysinfo(2)'.
4273 ANSI I/O (aio) and EVENTLOOP API
4274 --------------------------------
4275 Jim provides an alternative object-based API for I/O.
4277 See `open` and `socket` for commands which return an I/O handle.
4281 +$handle *read ?-nonewline?* '?len?'+::
4282     Read and return bytes from the stream. To eof if no len.
4284 +$handle +'gets'+ '?var?'+::
4285     Read one line and return it or store it in the var
4287 +$handle *puts ?-nonewline?* 'str'+::
4288     Write the string, with newline unless -nonewline
4290 +$handle +'copyto'+ 'tofd ?size?'+::
4291     Copy bytes to the file descriptor +'tofd'+. If +'size'+ is specified, at most
4292     that many bytes will be copied. Otherwise copying continues until the end
4293     of the input file. Returns the number of bytes actually copied.
4295 +$handle *flush*+::
4296     Flush the stream
4298 +$handle *filename*+::
4299     Returns the original filename associated with the handle.
4300     Handles returned by `socket` give the socket type instead of a filename.
4302 +$handle *eof*+::
4303     Returns 1 if stream is at eof
4305 +$handle *close*+::
4306     Closes the stream
4308 +$handle +'seek'+ 'offset' *?start|current|end?*+::
4309     Seeks in the stream (default 'current')
4311 +$handle *tell*+::
4312     Returns the current seek position
4314 +$handle *filename*+::
4315     Returns the original filename used when opening the file.
4316     If the handle was returned from `socket`, the type of the
4317     handle is returned instead.
4319 +$handle *ndelay ?0|1?*+::
4320     Set O_NDELAY (if arg). Returns current/new setting.
4321     Note that in general ANSI I/O interacts badly with non-blocking I/O.
4322     Use with care.
4324 +$handle *buffering none|line|full*+::
4325     Sets the buffering mode of the stream.
4327 +$handle *accept*+::
4328     Server socket only: Accept a connection and return stream
4330 +$handle +'sendto'+ 'str ?hostname:?port'+::
4331     Sends the string, +'str'+, to the given address via the socket using sendto(2).
4332     This is intended for udp sockets and may give an error or behave in unintended
4333     ways for other handle types.
4334     Returns the number of bytes written.
4336 +$handle +'recvfrom'+ 'maxlen ?addrvar?'+::
4337     Receives a message from the handle via recvfrom(2) and returns it.
4338     At most +'maxlen'+ bytes are read.
4339     If +'addrvar'+ is specified, the sending address of the message is stored in
4340     the named variable in the form 'addr:port'. See `socket` for details.
4342 [[cmd_2]]
4343 eventloop: after, vwait, update
4344 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4346 The following commands allow a script to be invoked when the given condition occurs.
4347 If no script is given, returns the current script. If the given script is the empty, the
4348 handler is removed.
4350 +$handle *readable* '?readable-script?'+::
4351     Sets or returns the script for when the socket is readable.
4353 +$handle *writable* '?writable-script?'+::
4354     Sets or returns the script for when the socket is writable.
4356 +$handle *onexception* '?exception-script?'+::
4357     Sets or returns the script for when when oob data received.
4359 For compatibility with 'Tcl', these may be prefixed with `fileevent`.  e.g.
4361  ::
4362     +fileevent $handle *readable* '\...'+
4364 Time-based execution is also available via the eventloop API.
4366 +*after* 'ms'+::
4367     Sleeps for the given number of milliseconds. No events are
4368     processed during this time.
4370 +*after* 'ms'|*idle* script ?script \...?'+::
4371     The scripts are concatenated and executed after the given
4372     number of milliseconds have elapsed.  If 'idle' is specified,
4373     the script will run the next time the event loop is processed
4374     with `vwait` or `update`. The script is only run once and
4375     then removed.  Returns an event id.
4377 +*after cancel* 'id|command'+::
4378     Cancels an `after` event with the given event id or matching
4379     command (script).  Returns the number of milliseconds
4380     remaining until the event would have fired.  Returns the
4381     empty string if no matching event is found.
4383 +*after info* '?id?'+::
4384     If +'id'+ is not given, returns a list of current `after`
4385     events.  If +'id'+ is given, returns a list containing the
4386     associated script and either 'timer' or 'idle' to indicated
4387     the type of the event. An error occurs if +'id'+ does not
4388     match an event.
4390 +*vwait* 'variable'+::
4391     A call to `vwait` is enters the eventloop. `vwait` processes
4392     events until the named (global) variable changes or all
4393     event handlers are removed. The variable need not exist
4394     beforehand.  If there are no event handlers defined, `vwait`
4395     returns immediately.
4397 +*update ?idletasks?*+::
4398     A call to `update` enters the eventloop to process expired events, but
4399     no new events. If 'idletasks' is specified, only expired time events are handled,
4400     not file events.
4401     Returns once handlers have been run for all expired events.
4403 Scripts are executed at the global scope. If an error occurs during a handler script,
4404 an attempt is made to call (the user-defined command) `bgerror` with the details of the error.
4405 If the `bgerror` commands does not exist, it is printed to stderr instead.
4407 If a file event handler script generates an error, the handler is automatically removed
4408 to prevent infinite errors. (A time event handler is always removed after execution).
4410 +*bgerror* 'error'+::
4411     Called when an event handler script generates an error.
4413 socket
4414 ~~~~~~
4415 Various socket types may be created.
4417 +*socket unix* 'path'+::
4418     A unix domain socket client.
4420 +*socket unix.server* 'path'+::
4421     A unix domain socket server.
4423 +*socket ?-ipv6? stream* 'addr:port'+::
4424     A TCP socket client.
4426 +*socket ?-ipv6? stream.server* '?addr:?port'+::
4427     A TCP socket server (+'addr'+ defaults to +0.0.0.0+ for IPv4 or +[::]+ for IPv6).
4429 +*socket ?-ipv6? dgram* ?'addr:port'?+::
4430     A UDP socket client. If the address is not specified,
4431     the client socket will be unbound and 'sendto' must be used
4432     to indicated the destination.
4434 +*socket ?-ipv6? dgram.server* 'addr:port'+::
4435     A UDP socket server.
4437 +*socket pipe*+::
4438     A pipe. Note that unlike all other socket types, this command returns
4439     a list of two channels: {read write}
4441 This command creates a socket connected (client) or bound (server) to the given
4442 address.
4444 The returned value is channel and may generally be used with the various file I/O
4445 commands (gets, puts, read, etc.), either as object-based syntax or Tcl-compatible syntax.
4447     set f [socket stream www.google.com:80]
4448     aio.sockstream1
4449     $f puts -nonewline "GET / HTTP/1.0\r\n\r\n"
4450     $f gets
4451     HTTP/1.0 302 Found
4452     $f close
4454 Server sockets, however support only 'accept', which is most useful in conjunction with
4455 the EVENTLOOP API.
4457     set f [socket stream.server 80]
4458     $f readable {
4459         set client [$f accept]
4460         $client gets $buf
4461         ...
4462         $client puts -nonewline "HTTP/1.1 404 Not found\r\n"
4463         $client close
4464     }
4465     vwait done
4467 The address, +'addr'+, can be given in one of the following forms:
4469 1. For IPv4 socket types, an IPv4 address such as 192.168.1.1
4470 2. For IPv6 socket types, an IPv6 address such as [fe80::1234] or [::]
4471 3. A hostname
4473 Note that on many systems, listening on an IPv6 address such as [::] will
4474 also accept requests via IPv4.
4476 Where a hostname is specified, the +'first'+ returned address is used
4477 which matches the socket type is used.
4479 The special type 'pipe' isn't really a socket.
4481     lassign [socket pipe] r w
4483     # Must close $w after exec
4484     exec ps >@$w &
4485     $w close
4487     $r readable ...
4489 syslog
4490 ~~~~~~
4491 +*syslog* '?options? ?priority? message'+
4493 This  command sends message to system syslog facility with given
4494 priority. Valid priorities are:
4496     emerg, alert, crit, err, error, warning, notice, info, debug
4498 If a message is specified, but no priority is specified, then a
4499 priority of info is used.
4501 By default, facility user is used and the value of global tcl variable
4502 argv0 is used as ident string. However, any of the following options
4503 may be specified before priority to control these parameters:
4505 +*-facility* 'value'+::
4506     Use specified facility instead of user. The following
4507     values for facility are recognized:
4509     authpriv, cron, daemon, kernel, lpr, mail, news, syslog, user,
4510     uucp, local0-local7
4512 +*-ident* 'string'+::
4513     Use given string instead of argv0 variable for ident string.
4515 +*-options* 'integer'+::
4516     Set syslog options such as +LOG_CONS+, +LOG_NDELAY+. You should
4517     use numeric values of those from your system syslog.h file,
4518     because I haven't got time to implement yet another hash
4519     table.
4521 [[BuiltinVariables]]
4522 BUILT-IN VARIABLES
4523 ------------------
4525 The following global variables are created automatically
4526 by the Tcl library.
4528 +*env*+::
4529     This variable is set by Jim as an array
4530     whose elements are the environment variables for the process.
4531     Reading an element will return the value of the corresponding
4532     environment variable.
4533     This array is initialised at startup from the `env` command.
4534     It may be modified and will affect the environment passed to
4535     commands invoked with `exec`.
4537 +*platform_tcl*+::
4538     This variable is set by Jim as an array containing information
4539     about the platform on which Jim was built. Currently this includes
4540     'os' and 'platform'.
4542 +*auto_path*+::
4543     This variable contains a list of paths to search for packages.
4544     It defaults to a location based on where jim is installed
4545     (e.g. +/usr/local/lib/jim+), but may be changed by +jimsh+
4546     or the embedding application. Note that +jimsh+ will consider
4547     the environment variable +$JIMLIB+ to be a list of colon-separated
4548     list of paths to add to +*auto_path*+.
4550 +*errorCode*+::
4551     This variable holds the value of the -errorcode return
4552     option set by the most recent error that occurred in this
4553     interpreter. This list value represents additional information
4554     about the error in a form that is easy to process with
4555     programs. The first element of the list identifies a general
4556     class of errors, and determines the format of the rest of
4557     the list. The following formats for -errorcode return options
4558     are used by the Tcl core; individual applications may define
4559     additional formats. Currently only `exec` sets this variable.
4560     Otherwise it will be +NONE+.
4562 The following global variables are set by jimsh.
4564 +*tcl_interactive*+::
4565     This variable is set to 1 if jimsh is started in interactive mode
4566     or 0 otherwise.
4568 +*tcl_platform*+::
4569     This variable is set by Jim as an array containing information
4570     about the platform upon which Jim was built. The following is an
4571     example of the contents of this array.
4573     tcl_platform(byteOrder)     = littleEndian
4574     tcl_platform(os)            = Darwin
4575     tcl_platform(platform)      = unix
4576     tcl_platform(pointerSize)   = 8
4577     tcl_platform(threaded)      = 0
4578     tcl_platform(wordSize)      = 8
4579     tcl_platform(pathSeparator) = :
4581 +*argv0*+::
4582     If jimsh is invoked to run a script, this variable contains the name
4583     of the script.
4585 +*argv*+::
4586     If jimsh is invoked to run a script, this variable contains a list
4587     of any arguments supplied to the script.
4589 +*argc*+::
4590     If jimsh is invoked to run a script, this variable contains the number
4591     of arguments supplied to the script.
4593 +*jim_argv0*+::
4594     The value of argv[0] when jimsh was invoked.
4596 CHANGES IN PREVIOUS RELEASES
4597 ----------------------------
4599 === In v0.63 ===
4601 1. `source` now checks that a script is complete (.i.e. not missing a brace)
4602 2. 'info complete' now uses the real parser and so is 100% accurate
4603 3. Better access to live stack frames with 'info frame', `stacktrace` and `stackdump`
4604 4. `tailcall` no longer loses stack trace information
4605 5. Add `alias` and `curry`
4606 6. `lambda`, `alias` and `curry` are implemented via `tailcall` for efficiency
4607 7. `local` allows procedures to be deleted automatically at the end of the current procedure
4608 8. udp sockets are now supported for both clients and servers.
4609 9. vfork-based exec is now working correctly
4610 10. Add 'file tempfile'
4611 11. Add 'socket pipe'
4612 12. Enhance 'try ... on ... finally' to be more Tcl 8.6 compatible
4613 13. It is now possible to `return` from within `try`
4614 14. IPv6 support is now included
4615 15. Add 'string is'
4616 16. Event handlers works better if an error occurs. eof handler has been removed.
4617 17. `exec` now sets $::errorCode, and catch sets opts(-errorcode) for exit status
4618 18. Command pipelines via open "|..." are now supported
4619 19. `pid` can now return pids of a command pipeline
4620 20. Add 'info references'
4621 21. Add support for 'after +'ms'+', 'after idle', 'after info', `update`
4622 22. `exec` now sets environment based on $::env
4623 23. Add 'dict keys'
4624 24. Add support for 'lsort -index'
4626 === In v0.62 ===
4628 1. Add support to `exec` for '>&', '>>&', '|&', '2>@1'
4629 2. Fix `exec` error messages when special token (e.g. '>') is the last token
4630 3. Fix `subst` handling of backslash escapes.
4631 4. Allow abbreviated options for `subst`
4632 5. Add support for `return`, `break`, `continue` in subst
4633 6. Many `expr` bug fixes
4634 7. Add support for functions in `expr` (e.g. int(), abs()), and also 'in', 'ni' list operations
4635 8. The variable name argument to `regsub` is now optional
4636 9. Add support for 'unset -nocomplain'
4637 10. Add support for list commands: `lassign`, `lrepeat`
4638 11. Fully-functional `lsearch` is now implemented
4639 12. Add 'info nameofexecutable' and 'info returncodes'
4640 13. Allow `catch` to determine what return codes are caught
4641 14. Allow `incr` to increment an unset variable by first setting to 0
4642 15. Allow 'args' and optional arguments to the left or required arguments in `proc`
4643 16. Add 'file copy'
4644 17. Add 'try ... finally' command
4647 LICENCE
4648 -------
4650  Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
4651  Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
4652  Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
4653  Copyright 2008 oharboe - Oyvind Harboe - oyvind.harboe@zylin.com
4654  Copyright 2008 Andrew Lunn <andrew@lunn.ch>
4655  Copyright 2008 Duane Ellis <openocd@duaneellis.com>
4656  Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
4657  Copyright 2009 Steve Bennett <steveb@workware.net.au>
4659 [literal]
4660  Redistribution and use in source and binary forms, with or without
4661  modification, are permitted provided that the following conditions
4662  are met:
4663  1. Redistributions of source code must retain the above copyright
4664     notice, this list of conditions and the following disclaimer.
4665  2. Redistributions in binary form must reproduce the above
4666     copyright notice, this list of conditions and the following
4667     disclaimer in the documentation and/or other materials
4668     provided with the distribution.
4670  THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
4671  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
4672  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
4673  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
4674  JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
4675  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
4676  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4677  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4678  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
4679  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
4680  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
4681  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4683  The views and conclusions contained in the software and documentation
4684  are those of the authors and should not be interpreted as representing
4685  official policies, either expressed or implied, of the Jim Tcl Project.