tcltest: do a better job of cleanup up after tests
[jimtcl.git] / jim_tcl.txt
blob88855d0349104ce5b3c6f41f2c068c359d473a10
1 Jim Tcl(n)
2 ==========
4 NAME
5 ----
6 Jim Tcl v0.77 - reference manual for the Jim Tcl scripting language
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 Tcl is a small footprint reimplementation of the Tcl scripting language.
29 The core language engine is compatible with Tcl 8.5+, while implementing
30 a significant subset of the Tcl 8.6 command set, plus additional features
31 available only in Jim Tcl.
33 Some notable differences with Tcl 8.5/8.6 are:
35 1. Object-based I/O (aio), but with a Tcl-compatibility layer
36 2. I/O: Support for sockets and pipes including udp, unix domain sockets and IPv6
37 3. Integers are 64bit
38 4. Support for references (`ref`/`getref`/`setref`) and garbage collection
39 5. Builtin dictionary type (`dict`) with some limitations compared to Tcl 8.6
40 6. `env` command to access environment variables
41 7. Operating system features: `os.fork`, `os.wait`, `os.uptime`, `signal`, `alarm`, `sleep`
42 8. Much better error reporting. `info stacktrace` as a replacement for '$errorInfo', '$errorCode'
43 9. Support for "static" variables in procedures
44 10. Threads and coroutines are not supported
45 11. Command and variable traces are not supported
46 12. Built-in command line editing
47 13. Expression shorthand syntax: +$(...)+
48 14. Modular build allows many features to be omitted or built as dynamic, loadable modules
49 15. Highly suitable for use in an embedded environment
50 16. Support for UDP, IPv6, Unix-Domain sockets in addition to TCP sockets
52 RECENT CHANGES
53 --------------
54 Changes between 0.77 and 0.78
55 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
56 1. Add serial/tty support with `aio tty`
58 Changes between 0.76 and 0.77
59 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
60 1. Add support for `aio sync`
61 2. Add SSL and TLS support in aio
62 3. Added `zlib`
63 4. Added support for boolean constants in `expr`
64 5. `string is` now supports 'boolean' class
65 6. Add support for `aio lock` and `aio unlock`
66 7. Add new `interp` command
68 Changes between 0.75 and 0.76
69 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70 1. `glob` now supports the +-tails+ option
71 2. Add support for `string cat`
72 3. Allow `info source` to add source info
74 Changes between 0.74 and 0.75
75 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
76 1. `binary`, `pack` and `unpack` now support floating point
77 2. `file copy` +-force+ handles source and target as the same file
78 3. `format` now supports +%b+ for binary conversion
79 4. `lsort` now supports +-unique+ and +-real+
80 5. Add support for half-close with `aio close` +?r|w?+
81 6. Add `socket pair` for a bidirectional pipe
82 7. Add '--random-hash' to randomise hash tables for greater security
83 8. `dict` now supports 'for', 'values', 'incr', 'append', 'lappend', 'update', 'info' and 'replace'
84 9. `file stat` no longer requires the variable name
85 10. Add support for `file link`
87 Changes between 0.73 and 0.74
88 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
89 1. Numbers with leading zeros are treated as decimal, not octal
90 2. Add `aio isatty`
91 3. Add LFS (64 bit) support for `aio seek`, `aio tell`, `aio copyto`, `file copy`
92 4. `string compare` and `string equal` now support '-length'
93 5. `glob` now supports '-directory'
95 Changes between 0.72 and 0.73
96 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
97 1. Built-in regexp now support non-capturing parentheses: (?:...)
98 2. Add `string replace`
99 3. Add `string totitle`
100 4. Add `info statics`
101 5. Add +build-jim-ext+ for easy separate building of loadable modules (extensions)
102 6. `local` now works with any command, not just procs
103 7. Add `info alias` to access the target of an alias
104 8. UTF-8 encoding past the basic multilingual plane (BMP) is supported
105 9. Add `tcl::prefix`
106 10. Add `history`
107 11. Most extensions are now enabled by default
108 12. Add support for namespaces and the `namespace` command
109 13. Add `apply`
111 Changes between 0.71 and 0.72
112 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
113 1. procs now allow 'args' and optional parameters in any position
114 2. Add Tcl-compatible expr functions, `rand()`, `srand()` and `pow()`
115 3. Add support for the '-force' option to `file delete`
116 4. Better diagnostics when `source` fails to load a script with a missing quote or bracket
117 5. New +tcl_platform(pathSeparator)+
118 6. Add support settings the modification time with `file mtime`
119 7. `exec` is now fully supported on win32 (mingw32)
120 8. `file join`, `pwd`, `glob` etc. now work for mingw32
121 9. Line editing is now supported for the win32 console (mingw32)
122 10. Add `aio listen` command
124 Changes between 0.70 and 0.71
125 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
126 1. Allow 'args' to be renamed in procs
127 2. Add +$(...)+ shorthand syntax for expressions
128 3. Add automatic reference variables in procs with +&var+ syntax
129 4. Support +jimsh --version+
130 5. Additional variables in +tcl_platform()+
131 6. `local` procs now push existing commands and `upcall` can call them
132 7. Add `loop` command (TclX compatible)
133 8. Add `aio buffering` command
134 9. `info complete` can now return the missing character
135 10. `binary format` and `binary scan` are now (optionally) supported
136 11. Add `string byterange`
137 12. Built-in regexp now support non-greedy repetition (*?, +?, ??)
139 TCL INTRODUCTION
140 -----------------
141 Tcl stands for 'tool command language' and is pronounced
142 'http://www.oxforddictionaries.com/definition/american_english/tickle[tickle]'.
143 It is actually two things: a language and a library.
145 First, Tcl is a simple textual language, intended primarily for
146 issuing commands to interactive programs such as text editors,
147 debuggers, illustrators, and shells.  It has a simple syntax and is also
148 programmable, so Tcl users can write command procedures to provide more
149 powerful commands than those in the built-in set.
151 Second, Tcl is a library package that can be embedded in application
152 programs.  The Tcl library consists of a parser for the Tcl language,
153 routines to implement the Tcl built-in commands, and procedures that
154 allow each application to extend Tcl with additional commands specific
155 to that application.  The application program generates Tcl commands and
156 passes them to the Tcl parser for execution.  Commands may be generated
157 by reading characters from an input source, or by associating command
158 strings with elements of the application's user interface, such as menu
159 entries, buttons, or keystrokes.
161 When the Tcl library receives commands it parses them into component
162 fields and executes built-in commands directly.  For commands implemented
163 by the application, Tcl calls back to the application to execute the
164 commands.  In many cases commands will invoke recursive invocations of the
165 Tcl interpreter by passing in additional strings to execute (procedures,
166 looping commands, and conditional commands all work in this way).
168 An application program gains three advantages by using Tcl for its command
169 language.  First, Tcl provides a standard syntax:  once users know Tcl,
170 they will be able to issue commands easily to any Tcl-based application.
171 Second, Tcl provides programmability.  All a Tcl application needs
172 to do is to implement a few application-specific low-level commands.
173 Tcl provides many utility commands plus a general programming interface
174 for building up complex command procedures.  By using Tcl, applications
175 need not re-implement these features.
177 Third, Tcl can be used as a common language for communicating between
178 applications.  Inter-application communication is not built into the
179 Tcl core described here, but various add-on libraries, such as the Tk
180 toolkit, allow applications to issue commands to each other.  This makes
181 it possible for applications to work together in much more powerful ways
182 than was previously possible.
184 Fourth, Jim Tcl includes a command processor, +jimsh+, which can be
185 used to run standalone Tcl scripts, or to run Tcl commands interactively.
187 This manual page focuses primarily on the Tcl language.  It describes
188 the language syntax and the built-in commands that will be available
189 in any application based on Tcl.  The individual library procedures are
190 described in more detail in separate manual pages, one per procedure.
192 JIMSH COMMAND INTERPRETER
193 -------------------------
194 A simple, but powerful command processor, +jimsh+, is part of Jim Tcl.
195 It may be invoked in interactive mode as:
197   jimsh
199 or to process the Tcl script in a file with:
201   jimsh filename
203 It may also be invoked to execute an immediate script with:
205   jimsh -e "script"
207 Interactive Mode
208 ~~~~~~~~~~~~~~~~
209 Interactive mode reads Tcl commands from standard input, evaluates
210 those commands and prints the results.
212   $ jimsh
213   Welcome to Jim version 0.73, Copyright (c) 2005-8 Salvatore Sanfilippo
214   . info version
215   0.73
216   . lsort [info commands p*]
217   package parray pid popen proc puts pwd
218   . foreach i {a b c} {
219   {> puts $i
220   {> }
221   a
222   b
223   c
224   . bad
225   invalid command name "bad"
226   [error] . exit
227   $
229 If +jimsh+ is configured with line editing (it is by default) and a VT-100-compatible
230 terminal is detected, Emacs-style line editing commands are available, including:
231 arrow keys, +\^W+ to erase a word, +\^U+ to erase the line, +^R+ for reverse incremental search
232 in history. Additionally, the +h+ command may be used to display the command history.
234 Command line history is automatically saved and loaded from +~/.jim_history+
236 In interactive mode, +jimsh+ automatically runs the script +~/.jimrc+ at startup
237 if it exists.
239 INTERPRETERS
240 ------------
241 The central data structure in Tcl is an interpreter (C type 'Jim_Interp').
242 An interpreter consists of a set of command bindings, a set of variable
243 values, and a few other miscellaneous pieces of state.  Each Tcl command
244 is interpreted in the context of a particular interpreter.
246 Some Tcl-based applications will maintain multiple interpreters
247 simultaneously, each associated with a different widget or portion of
248 the application.  Interpreters are relatively lightweight structures.
249 They can be created and deleted quickly, so application programmers should
250 feel free to use multiple interpreters if that simplifies the application.
252 DATA TYPES
253 ----------
254 Tcl supports only one type of data:  strings.  All commands, all arguments
255 to commands, all command results, and all variable values are strings.
257 Where commands require numeric arguments or return numeric results,
258 the arguments and results are passed as strings.  Many commands expect
259 their string arguments to have certain formats, but this interpretation
260 is up to the individual commands.  For example, arguments often contain
261 Tcl command strings, which may get executed as part of the commands.
262 The easiest way to understand the Tcl interpreter is to remember that
263 everything is just an operation on a string.  In many cases Tcl constructs
264 will look similar to more structured constructs from other languages.
265 However, the Tcl constructs are not structured at all; they are just
266 strings of characters, and this gives them a different behaviour than
267 the structures they may look like.
269 Although the exact interpretation of a Tcl string depends on who is doing
270 the interpretation, there are three common forms that strings take:
271 commands, expressions, and lists.  The major sections below discuss
272 these three forms in more detail.
274 BASIC COMMAND SYNTAX
275 --------------------
276 The Tcl language has syntactic similarities to both the Unix shells
277 and Lisp.  However, the interpretation of commands is different
278 in Tcl than in either of those other two systems.
279 A Tcl command string consists of one or more commands separated
280 by newline characters or semi-colons.
281 Each command consists of a collection of fields separated by
282 white space (spaces or tabs).
283 The first field must be the name of a command, and the
284 additional fields, if any, are arguments that will be passed to
285 that command.  For example, the command:
287     set a 22
289 has three fields:  the first, `set`, is the name of a Tcl command, and
290 the last two, 'a' and '22', will be passed as arguments to
291 the `set` command.  The command name may refer either to a built-in
292 Tcl command, an application-specific command bound in with the library
293 procedure 'Jim_CreateCommand', or a command procedure defined with the
294 `proc` built-in command.
296 Arguments are passed literally as text strings.  Individual commands may
297 interpret those strings in any fashion they wish.  The `set` command,
298 for example, will treat its first argument as the name of a variable
299 and its second argument as a string value to assign to that variable.
300 For other commands arguments may be interpreted as integers, lists,
301 file names, or Tcl commands.
303 Command names should normally be typed completely (e.g. no abbreviations).
304 However, if the Tcl interpreter cannot locate a command it invokes a
305 special command named `unknown` which attempts to find or create the
306 command.
308 For example, at many sites `unknown` will search through library
309 directories for the desired command and create it as a Tcl procedure if
310 it is found.  The `unknown` command often provides automatic completion
311 of abbreviated commands, but usually only for commands that were typed
312 interactively.
314 It's probably a bad idea to use abbreviations in command scripts and
315 other forms that will be re-used over time:  changes to the command set
316 may cause abbreviations to become ambiguous, resulting in scripts that
317 no longer work.
319 COMMENTS
320 --------
321 If the first non-blank character in a command is +\#+, then everything
322 from the +#+ up through the next newline character is treated as
323 a comment and ignored.  When comments are embedded inside nested
324 commands (e.g. fields enclosed in braces) they must have properly-matched
325 braces (this is necessary because when Tcl parses the top-level command
326 it doesn't yet know that the nested field will be used as a command so
327 it cannot process the nested comment character as a comment).
329 GROUPING ARGUMENTS WITH DOUBLE-QUOTES
330 -------------------------------------
331 Normally each argument field ends at the next white space, but
332 double-quotes may be used to create arguments with embedded space.
334 If an argument field begins with a double-quote, then the argument isn't
335 terminated by white space (including newlines) or a semi-colon (see below
336 for information on semi-colons); instead it ends at the next double-quote
337 character.  The double-quotes are not included in the resulting argument.
338 For example, the command
340     set a "This is a single argument"
342 will pass two arguments to `set`:  'a' and 'This is a single argument'.
344 Within double-quotes, command substitutions, variable substitutions,
345 and backslash substitutions still occur, as described below.  If the
346 first character of a command field is not a quote, then quotes receive
347 no special interpretation in the parsing of that field.
349 GROUPING ARGUMENTS WITH BRACES
350 ------------------------------
351 Curly braces may also be used for grouping arguments.  They are similar
352 to quotes except for two differences.  First, they nest; this makes them
353 easier to use for complicated arguments like nested Tcl command strings.
354 Second, the substitutions described below for commands, variables, and
355 backslashes do *not* occur in arguments enclosed in braces, so braces
356 can be used to prevent substitutions where they are undesirable.
358 If an argument field begins with a left brace, then the argument ends
359 at the matching right brace.  Tcl will strip off the outermost layer
360 of braces and pass the information between the braces to the command
361 without any further modification.  For example, in the command
363     set a {xyz a {b c d}}
365 the `set` command will receive two arguments: 'a'
366 and 'xyz a {b c d}'.
368 When braces or quotes are in effect, the matching brace or quote need
369 not be on the same line as the starting quote or brace; in this case
370 the newline will be included in the argument field along with any other
371 characters up to the matching brace or quote.  For example, the `eval`
372 command takes one argument, which is a command string; `eval` invokes
373 the Tcl interpreter to execute the command string.  The command
375     eval {
376       set a 22
377       set b 33
378     }
380 will assign the value '22' to 'a' and '33' to 'b'.
382 If the first character of a command field is not a left
383 brace, then neither left nor right
384 braces in the field will be treated specially (except as part of
385 variable substitution; see below).
387 COMMAND SUBSTITUTION WITH BRACKETS
388 ----------------------------------
389 If an open bracket occurs in a field of a command, then command
390 substitution occurs (except for fields enclosed in braces).  All of the
391 text up to the matching close bracket is treated as a Tcl command and
392 executed immediately.  Then the result of that command is substituted
393 for the bracketed text.  For example, consider the command
395     set a [set b]
397 When the `set` command has only a single argument, it is the name of a
398 variable and `set` returns the contents of that variable.  In this case,
399 if variable 'b' has the value 'foo', then the command above is equivalent
400 to the command
402     set a foo
404 Brackets can be used in more complex ways.  For example, if the variable
405 'b' has the value 'foo' and the variable 'c' has the value 'gorp',
406 then the command
408     set a xyz[set b].[set c]
410 is equivalent to the command
412     set a xyzfoo.gorp
415 A bracketed command may contain multiple commands separated by newlines
416 or semi-colons in the usual fashion.  In this case the value of the last
417 command is used for substitution.  For example, the command
419     set a x[set b 22
420     expr $b+2]x
422 is equivalent to the command
424     set a x24x
427 If a field is enclosed in braces then the brackets and the characters
428 between them are not interpreted specially; they are passed through to
429 the argument verbatim.
431 VARIABLE SUBSTITUTION WITH $
432 ----------------------------
433 The dollar sign (+$+) may be used as a special shorthand form for
434 substituting variable values.  If +$+ appears in an argument that isn't
435 enclosed in braces then variable substitution will occur.  The characters
436 after the +$+, up to the first character that isn't a number, letter,
437 or underscore, are taken as a variable name and the string value of that
438 variable is substituted for the name.
440 For example, if variable 'foo' has the value 'test', then the command
442     set a $foo.c
444 is equivalent to the command
446     set a test.c
448 There are two special forms for variable substitution.  If the next
449 character after the name of the variable is an open parenthesis, then
450 the variable is assumed to be an array name, and all of the characters
451 between the open parenthesis and the next close parenthesis are taken as
452 an index into the array.  Command substitutions and variable substitutions
453 are performed on the information between the parentheses before it is
454 used as an index.
456 For example, if the variable 'x' is an array with one element named
457 'first' and value '87' and another element named '14' and value 'more',
458 then the command
460     set a xyz$x(first)zyx
462 is equivalent to the command
464     set a xyz87zyx
466 If the variable 'index' has the value '14', then the command
468     set a xyz$x($index)zyx
470 is equivalent to the command
472     set a xyzmorezyx
474 For more information on arrays, see VARIABLES AND ARRAYS below.
476 The second special form for variables occurs when the dollar sign is
477 followed by an open curly brace.  In this case the variable name consists
478 of all the characters up to the next curly brace.
480 Array references are not possible in this form:  the name between braces
481 is assumed to refer to a scalar variable.  For example, if variable
482 'foo' has the value 'test', then the command
484     set a abc${foo}bar
486 is equivalent to the command
488     set a abctestbar
491 Variable substitution does not occur in arguments that are enclosed in
492 braces:  the dollar sign and variable name are passed through to the
493 argument verbatim.
495 The dollar sign abbreviation is simply a shorthand form.  +$a+ is
496 completely equivalent to +[set a]+; it is provided as a convenience
497 to reduce typing.
499 SEPARATING COMMANDS WITH SEMI-COLONS
500 ------------------------------------
501 Normally, each command occupies one line (the command is terminated by a
502 newline character).  However, semi-colon (+;+) is treated as a command
503 separator character; multiple commands may be placed on one line by
504 separating them with a semi-colon.  Semi-colons are not treated as
505 command separators if they appear within curly braces or double-quotes.
507 BACKSLASH SUBSTITUTION
508 ----------------------
509 Backslashes may be used to insert non-printing characters into command
510 fields and also to insert special characters like braces and brackets
511 into fields without them being interpreted specially as described above.
513 The backslash sequences understood by the Tcl interpreter are
514 listed below.  In each case, the backslash
515 sequence is replaced by the given character:
516 [[BackslashSequences]]
517 +{backslash}b+::
518     Backspace (0x8)
520 +{backslash}f+::
521     Form feed (0xc)
523 +{backslash}n+::
524     Newline (0xa)
526 +{backslash}r+::
527     Carriage-return (0xd).
529 +{backslash}t+::
530     Tab (0x9).
532 +{backslash}v+::
533     Vertical tab (0xb).
535 +{backslash}{+::
536     Left brace ({).
538 +{backslash}}+::
539     Right brace (}).
541 +{backslash}[+::
542     Open bracket ([).
544 +{backslash}]+::
545     Close bracket (]).
547 +{backslash}$+::
548     Dollar sign ($).
550 +{backslash}<space>+::
551     Space ( ): doesn't terminate argument.
553 +{backslash};+::
554     Semi-colon: doesn't terminate command.
556 +{backslash}"+::
557     Double-quote.
559 +{backslash}<newline>+::
560     Nothing:  this joins two lines together
561     into a single line.  This backslash feature is unique in that
562     it will be applied even when the sequence occurs within braces.
564 +{backslash}{backslash}+::
565     Backslash ('{backslash}').
567 +{backslash}ddd+::
568     The digits +'ddd'+ (one, two, or three of them) give the octal value of
569     the character.  Note that Jim supports null characters in strings.
571 +{backslash}unnnn+::
572 +{backslash}u\{nnn\}+::
573 +{backslash}Unnnnnnnn+::
574     The UTF-8 encoding of the unicode codepoint represented by the hex digits, +'nnnn'+, is inserted.
575     The 'u' form allows for one to four hex digits.
576     The 'U' form allows for one to eight hex digits.
577     The 'u\{nnn\}' form allows for one to eight hex digits, but makes it easier to insert
578     characters UTF-8 characters which are followed by a hex digit.
580 For example, in the command
582     set a \{x\[\ yz\141
584 the second argument to `set` will be +{x[ yza+.
586 If a backslash is followed by something other than one of the options
587 described above, then the backslash is transmitted to the argument
588 field without any special processing, and the Tcl scanner continues
589 normal processing with the next character.  For example, in the
590 command
592     set \*a \\\{foo
594 The first argument to `set` will be +{backslash}*a+ and the second
595 argument will be +{backslash}{foo+.
597 If an argument is enclosed in braces, then backslash sequences inside
598 the argument are parsed but no substitution occurs (except for
599 backslash-newline):  the backslash
600 sequence is passed through to the argument as is, without making
601 any special interpretation of the characters in the backslash sequence.
602 In particular, backslashed braces are not counted in locating the
603 matching right brace that terminates the argument.
604 For example, in the
605 command
607     set a {\{abc}
609 the second argument to `set` will be +{backslash}{abc+.
611 This backslash mechanism is not sufficient to generate absolutely
612 any argument structure; it only covers the
613 most common cases.  To produce particularly complicated arguments
614 it is probably easiest to use the `format` command along with
615 command substitution.
617 STRING AND LIST INDEX SPECIFICATIONS
618 ------------------------------------
620 Many string and list commands take one or more 'index' parameters which
621 specify a position in the string relative to the start or end of the string/list.
623 The index may be one of the following forms:
625 +integer+::
626     A simple integer, where '0' refers to the first element of the string
627     or list.
629 +integer+integer+ or::
630 +integer-integer+::
631     The sum or difference of the two integers. e.g. +2+3+ refers to the 5th element.
632     This is useful when used with (e.g.) +$i+1+ rather than the more verbose
633     +[expr {$i+1\}]+
635 +end+::
636     The last element of the string or list.
638 +end-integer+::
639     The 'nth-from-last' element of the string or list.
641 COMMAND SUMMARY
642 ---------------
643 1. A command is just a string.
644 2. Within a string commands are separated by newlines or semi-colons
645    (unless the newline or semi-colon is within braces or brackets
646    or is backslashed).
647 3. A command consists of fields.  The first field is the name of the command.
648    The other fields are strings that are passed to that command as arguments.
649 4. Fields are normally separated by white space.
650 5. Double-quotes allow white space and semi-colons to appear within
651    a single argument.
652    Command substitution, variable substitution, and backslash substitution
653    still occur inside quotes.
654 6. Braces defer interpretation of special characters.
655    If a field begins with a left brace, then it consists of everything
656    between the left brace and the matching right brace. The
657    braces themselves are not included in the argument.
658    No further processing is done on the information between the braces
659    except that backslash-newline sequences are eliminated.
660 7. If a field doesn't begin with a brace then backslash,
661    variable, and command substitution are done on the field.  Only a
662    single level of processing is done:  the results of one substitution
663    are not scanned again for further substitutions or any other
664    special treatment.  Substitution can
665    occur on any field of a command, including the command name
666    as well as the arguments.
667 8. If the first non-blank character of a command is a +\#+, everything
668    from the +#+ up through the next newline is treated as a comment
669    and ignored.
671 EXPRESSIONS
672 -----------
673 The second major interpretation applied to strings in Tcl is
674 as expressions.  Several commands, such as `expr`, `for`,
675 and `if`, treat one or more of their arguments as expressions
676 and call the Tcl expression processors ('Jim_ExprLong',
677 'Jim_ExprBoolean', etc.) to evaluate them.
679 The operators permitted in Tcl expressions are a subset of
680 the operators permitted in C expressions, and they have the
681 same meaning and precedence as the corresponding C operators.
682 Expressions almost always yield numeric results
683 (integer or floating-point values).
684 For example, the expression
686     8.2 + 6
688 evaluates to 14.2.
690 Tcl expressions differ from C expressions in the way that
691 operands are specified, and in that Tcl expressions support
692 non-numeric operands and string comparisons.
694 A Tcl expression consists of a combination of operands, operators,
695 and parentheses.
697 White space may be used between the operands and operators and
698 parentheses; it is ignored by the expression processor.
699 Where possible, operands are interpreted as integer values.
701 Integer values may be specified in decimal (the normal case) or in
702 hexadecimal (if the first two characters of the operand are '0x').
703 Note that Jim Tcl does *not* treat numbers with leading zeros as octal.
705 If an operand does not have one of the integer formats given
706 above, then it is treated as a floating-point number if that is
707 possible.  Floating-point numbers may be specified in any of the
708 ways accepted by an ANSI-compliant C compiler (except that the
709 'f', 'F', 'l', and 'L' suffixes will not be permitted in
710 most installations).  For example, all of the
711 following are valid floating-point numbers:  2.1, 3., 6e4, 7.91e+16.
713 If no numeric interpretation is possible, then an operand is left
714 as a string (and only a limited set of operators may be applied to
715 it).
717 String constants representing boolean constants
718 (+'0'+, +'1'+, +'false'+, +'off'+, +'no'+, +'true'+, +'on'+, +'yes'+)
719 are also recognized and can be used in logical operations.
721 1. Operands may be specified in any of the following ways:
723 2. As a numeric value, either integer or floating-point.
725 3. As one of valid boolean constants
727 4. As a Tcl variable, using standard '$' notation.
728 The variable's value will be used as the operand.
730 5. As a string enclosed in double-quotes.
731 The expression parser will perform backslash, variable, and
732 command substitutions on the information between the quotes,
733 and use the resulting value as the operand
735 6. As a string enclosed in braces.
736 The characters between the open brace and matching close brace
737 will be used as the operand without any substitutions.
739 7. As a Tcl command enclosed in brackets.
740 The command will be executed and its result will be used as
741 the operand.
743 Where substitutions occur above (e.g. inside quoted strings), they
744 are performed by the expression processor.
745 However, an additional layer of substitution may already have
746 been performed by the command parser before the expression
747 processor was called.
749 As discussed below, it is usually best to enclose expressions
750 in braces to prevent the command parser from performing substitutions
751 on the contents.
753 For some examples of simple expressions, suppose the variable 'a' has
754 the value 3 and the variable 'b' has the value 6.  Then the expression
755 on the left side of each of the lines below will evaluate to the value
756 on the right side of the line:
758     $a + 3.1                6.1
759     2 + "$a.$b"             5.6
760     4*[llength "6 2"]       8
761     {word one} < "word $a"  0
763 The valid operators are listed below, grouped in decreasing order
764 of precedence:
765 [[OperatorPrecedence]]
766 +int() double() round() abs(), rand(), srand()+::
767     Unary functions (except rand() which takes no arguments)
768     * +'int()'+ converts the numeric argument to an integer by truncating down.
769     * +'double()'+ converts the numeric argument to floating point.
770     * +'round()'+ converts the numeric argument to the closest integer value.
771     * +'abs()'+ takes the absolute value of the numeric argument.
772     * +'rand()'+ returns a pseudo-random floating-point value in the range (0,1).
773     * +'srand()'+ takes an integer argument to (re)seed the random number generator. Returns the first random number from that seed.
775 +sin() cos() tan() asin() acos() atan() sinh() cosh() tanh() ceil() floor() exp() log() log10() sqrt()+::
776     Unary math functions.
777     If Jim is compiled with math support, these functions are available.
779 +- + ~ !+::
780     Unary minus, unary plus, bit-wise NOT, logical NOT.  None of these operands
781     may be applied to string operands, and bit-wise NOT may be
782     applied only to integers.
784 +** pow(x,y)+::
785     Power. e.g. 'x^y^'. If Jim is compiled with math support, supports doubles and
786     integers. Otherwise supports integers only. (Note that the math-function form
787     has the same highest precedence)
789 +* / %+::
790     Multiply, divide, remainder.  None of these operands may be
791     applied to string operands, and remainder may be applied only
792     to integers.
794 ++ -+::
795     Add and subtract.  Valid for any numeric operands.
797 +<<  >> <<< >>>+::
798     Left and right shift, left and right rotate.  Valid for integer operands only.
800 +<  >  \<=  >=+::
801     Boolean less, greater, less than or equal, and greater than or equal.
802     Each operator produces 1 if the condition is true, 0 otherwise.
803     These operators may be applied to strings as well as numeric operands,
804     in which case string comparison is used.
806 +==  !=+::
807     Boolean equal and not equal.  Each operator produces a zero/one result.
808     Valid for all operand types. *Note* that values will be converted to integers
809     if possible, then floating point types, and finally strings will be compared.
810     It is recommended that 'eq' and 'ne' should be used for string comparison.
812 +eq ne+::
813     String equal and not equal.  Uses the string value directly without
814     attempting to convert to a number first.
816 +in ni+::
817     String in list and not in list. For 'in', result is 1 if the left operand (as a string)
818     is contained in the right operand (as a list), or 0 otherwise. The result for
819     +{$a ni $list}+ is equivalent to +{!($a in $list)}+.
821 +&+::
822     Bit-wise AND.  Valid for integer operands only.
824 +|+::
825     Bit-wise OR.  Valid for integer operands only.
827 +^+::
828     Bit-wise exclusive OR.  Valid for integer operands only.
830 +&&+::
831     Logical AND.  Produces a 1 result if both operands are non-zero, 0 otherwise.
832     Valid for numeric operands only (integers or floating-point).
834 +||+::
835     Logical OR.  Produces a 0 result if both operands are zero, 1 otherwise.
836     Valid for numeric operands only (integers or floating-point).
838 +x ? y : z+::
839     If-then-else, as in C.  If +'x'+
840     evaluates to non-zero, then the result is the value of +'y'+.
841     Otherwise the result is the value of +'z'+.
842     The +'x'+ operand must have a numeric value, while +'y'+ and +'z'+ can
843     be of any type.
845 See the C manual for more details on the results
846 produced by each operator.
847 All of the binary operators group left-to-right within the same
848 precedence level.  For example, the expression
850     4*2 < 7
852 evaluates to 0.
854 The +&&+, +||+, and +?:+ operators have 'lazy evaluation', just as
855 in C, which means that operands are not evaluated if they are not
856 needed to determine the outcome.  For example, in
858     $v ? [a] : [b]
860 only one of +[a]+ or +[b]+ will actually be evaluated,
861 depending on the value of +$v+.
863 All internal computations involving integers are done with the C
864 type 'long long' if available, or 'long' otherwise, and all internal
865 computations involving floating-point are done with the C type
866 'double'.
868 When converting a string to floating-point, exponent overflow is
869 detected and results in a Tcl error.
870 For conversion to integer from string, detection of overflow depends
871 on the behaviour of some routines in the local C library, so it should
872 be regarded as unreliable.
873 In any case, overflow and underflow are generally not detected
874 reliably for intermediate results.
876 Conversion among internal representations for integer, floating-point,
877 string operands is done automatically as needed.
878 For arithmetic computations, integers are used until some
879 floating-point number is introduced, after which floating-point is used.
880 For example,
882     5 / 4
884 yields the result 1, while
886     5 / 4.0
887     5 / ( [string length "abcd"] + 0.0 )
889 both yield the result 1.25.
891 String values may be used as operands of the comparison operators,
892 although the expression evaluator tries to do comparisons as integer
893 or floating-point when it can.
894 If one of the operands of a comparison is a string and the other
895 has a numeric value, the numeric operand is converted back to
896 a string using the C 'sprintf' format specifier
897 '%d' for integers and '%g' for floating-point values.
898 For example, the expressions
900     "0x03" > "2"
901     "0y" < "0x12"
903 both evaluate to 1.  The first comparison is done using integer
904 comparison, and the second is done using string comparison after
905 the second operand is converted to the string '18'.
907 In general it is safest to enclose an expression in braces when
908 entering it in a command:  otherwise, if the expression contains
909 any white space then the Tcl interpreter will split it
910 among several arguments.  For example, the command
912     expr $a + $b
914 results in three arguments being passed to `expr`:  +$a+,
915 \+, and +$b+.  In addition, if the expression isn't in braces
916 then the Tcl interpreter will perform variable and command substitution
917 immediately (it will happen in the command parser rather than in
918 the expression parser).  In many cases the expression is being
919 passed to a command that will evaluate the expression later (or
920 even many times if, for example, the expression is to be used to
921 decide when to exit a loop).  Usually the desired goal is to re-do
922 the variable or command substitutions each time the expression is
923 evaluated, rather than once and for all at the beginning.  For example,
924 the command
926     for {set i 1} $i<=10 {incr i} {...}        ** WRONG **
928 is probably intended to iterate over all values of +i+ from 1 to 10.
929 After each iteration of the body of the loop, `for` will pass
930 its second argument to the expression evaluator to see whether or not
931 to continue processing.  Unfortunately, in this case the value of +i+
932 in the second argument will be substituted once and for all when the
933 `for` command is parsed.  If +i+ was 0 before the `for`
934 command was invoked then the second argument of `for` will be +0\<=10+
935 which will always evaluate to 1, even though +i+ eventually
936 becomes greater than 10.  In the above case the loop will never
937 terminate.  Instead, the expression should be placed in braces:
939     for {set i 1} {$i<=10} {incr i} {...}      ** RIGHT **
941 This causes the substitution of 'i'
942 to be delayed; it will be re-done each time the expression is
943 evaluated, which is the desired result.
945 LISTS
946 -----
947 The third major way that strings are interpreted in Tcl is as lists.
948 A list is just a string with a list-like structure
949 consisting of fields separated by white space.  For example, the
950 string
952     Al Sue Anne John
954 is a list with four elements or fields.
955 Lists have the same basic structure as command strings, except
956 that a newline character in a list is treated as a field separator
957 just like space or tab.  Conventions for braces and quotes
958 and backslashes are the same for lists as for commands.  For example,
959 the string
961     a b\ c {d e {f g h}}
963 is a list with three elements:  +a+, +b c+, and +d e {f g h}+.
965 Whenever an element is extracted from a list, the same rules about
966 braces and quotes and backslashes are applied as for commands.  Thus in
967 the example above when the third element is extracted from the list,
968 the result is
970     d e {f g h}
972 (when the field was extracted, all that happened was to strip off
973 the outermost layer of braces).  Command substitution and
974 variable substitution are never
975 made on a list (at least, not by the list-processing commands; the
976 list can always be passed to the Tcl interpreter for evaluation).
978 The Tcl commands `concat`, `foreach`, `lappend`, `lindex`, `linsert`,
979 `list`, `llength`, `lrange`, `lreplace`, `lsearch`, and `lsort` allow
980 you to build lists, extract elements from them, search them, and perform
981 other list-related functions.
983 Advanced list commands include `lrepeat`, `lreverse`, `lmap`, `lassign`, `lset`.
985 LIST EXPANSION
986 --------------
988 A new addition to Tcl 8.5 is the ability to expand a list into separate
989 arguments. Support for this feature is also available in Jim.
991 Consider the following attempt to exec a list:
993     set cmd {ls -l}
994     exec $cmd
996 This will attempt to exec a command named "ls -l", which will clearly not
997 work. Typically eval and concat are required to solve this problem, however
998 it can be solved much more easily with +\{*\}+.
1000     exec {*}$cmd
1002 This will expand the following argument into individual elements and then evaluate
1003 the resulting command.
1005 Note that the official Tcl syntax is +\{*\}+, however +\{expand\}+ is retained
1006 for backward compatibility with experimental versions of this feature.
1008 REGULAR EXPRESSIONS
1009 -------------------
1010 Tcl provides two commands that support string matching using regular
1011 expressions, `regexp` and `regsub`, as well as `switch -regexp` and
1012 `lsearch -regexp`.
1014 Regular expressions may be implemented one of two ways. Either using the system's C library
1015 POSIX regular expression support, or using the built-in regular expression engine.
1016 The differences between these are described below.
1018 *NOTE* Tcl 7.x and 8.x use perl-style Advanced Regular Expressions (+ARE+).
1020 POSIX Regular Expressions
1021 ~~~~~~~~~~~~~~~~~~~~~~~~~
1022 If the system supports POSIX regular expressions, and UTF-8 support is not enabled,
1023 this support will be used by default. The type of regular expressions supported are
1024 Extended Regular Expressions (+ERE+) rather than Basic Regular Expressions (+BRE+).
1025 See REG_EXTENDED in the documentation.
1027 Using the system-supported POSIX regular expressions will typically
1028 make for the smallest code size, but some features such as UTF-8
1029 and +{backslash}w+, +{backslash}d+, +{backslash}s+ are not supported, and null characters
1030 in strings are not supported.
1032 See regex(3) and regex(7) for full details.
1034 Jim built-in Regular Expressions
1035 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1036 The Jim built-in regular expression engine may be selected with +./configure --with-jim-regexp+
1037 or it will be selected automatically if UTF-8 support is enabled.
1039 This engine supports UTF-8 as well as some +ARE+ features. The differences with both Tcl 7.x/8.x
1040 and POSIX are highlighted below.
1042 1. UTF-8 strings and patterns are both supported
1043 2. All Tcl character classes are supported (e.g. +[:alnum:]+, +[:digit:]+, +[:space:]+), but...
1044 3. Character classes apply to ASCII characters only
1045 4. Supported shorthand character classes: +{backslash}w+ = +[:alnum:]+, +{backslash}W+ = +^[:alnum:]+, +{backslash}d+ = +[:digit:],+ +{backslash}D+ = +^[:digit:],+ +{backslash}s+ = +[:space:]+, + +{backslash}S+ = +^[:space:]+
1046 5. Supported constraint escapes: +{backslash}m+ = +{backslash}<+ = start of word, +{backslash}M+ = +{backslash}>+ = end of word
1047 6. Backslash escapes may be used within regular expressions, such as +{backslash}n+ = newline, +{backslash}uNNNN+ = unicode
1048 7. Partially supported constraint escapes: +{backslash}A+ = start of string, +{backslash}Z+ = end of string
1049 8. Support for the +?+ non-greedy quantifier. e.g. +*?+
1050 9. Support for non-capturing parentheses +(?:...)+
1051 10. Jim Tcl considers that both patterns and strings end at a null character (+\x00+)
1053 COMMAND RESULTS
1054 ---------------
1055 Each command produces two results:  a code and a string.  The
1056 code indicates whether the command completed successfully or not,
1057 and the string gives additional information.  The valid codes are
1058 defined in jim.h, and are:
1060 +JIM_OK(0)+::
1061     This is the normal return code, and indicates that the command completed
1062     successfully.  The string gives the command's return value.
1064 +JIM_ERR(1)+::
1065     Indicates that an error occurred; the string gives a message describing
1066     the error.
1068 +JIM_RETURN(2)+::
1069     Indicates that the `return` command has been invoked, and that the
1070     current procedure (or top-level command or `source` command)
1071     should return immediately.  The
1072     string gives the return value for the procedure or command.
1074 +JIM_BREAK(3)+::
1075     Indicates that the `break` command has been invoked, so the
1076     innermost loop should abort immediately.  The string should always
1077     be empty.
1079 +JIM_CONTINUE(4)+::
1080     Indicates that the `continue` command has been invoked, so the
1081     innermost loop should go on to the next iteration.  The string
1082     should always be empty.
1084 +JIM_SIGNAL(5)+::
1085     Indicates that a signal was caught while executing a commands.
1086     The string contains the name of the signal caught.
1087     See the `signal` and `catch` commands.
1089 +JIM_EXIT(6)+::
1090     Indicates that the command called the `exit` command.
1091     The string contains the exit code.
1093 Tcl programmers do not normally need to think about return codes,
1094 since +JIM_OK+ is almost always returned.  If anything else is returned
1095 by a command, then the Tcl interpreter immediately stops processing
1096 commands and returns to its caller.  If there are several nested
1097 invocations of the Tcl interpreter in progress, then each nested
1098 command will usually return the error to its caller, until eventually
1099 the error is reported to the top-level application code.  The
1100 application will then display the error message for the user.
1102 In a few cases, some commands will handle certain `error` conditions
1103 themselves and not return them upwards.  For example, the `for`
1104 command checks for the +JIM_BREAK+ code; if it occurs, then `for`
1105 stops executing the body of the loop and returns +JIM_OK+ to its
1106 caller.  The `for` command also handles +JIM_CONTINUE+ codes and the
1107 procedure interpreter handles +JIM_RETURN+ codes.  The `catch`
1108 command allows Tcl programs to catch errors and handle them without
1109 aborting command interpretation any further.
1111 The `info returncodes` command may be used to programmatically map between
1112 return codes and names.
1114 PROCEDURES
1115 ----------
1116 Tcl allows you to extend the command interface by defining
1117 procedures.  A Tcl procedure can be invoked just like any other Tcl
1118 command (it has a name and it receives one or more arguments).
1119 The only difference is that its body isn't a piece of C code linked
1120 into the program; it is a string containing one or more other
1121 Tcl commands.
1123 The `proc` command is used to create a new Tcl command procedure:
1125 +*proc* 'name arglist ?statics? body'+
1127 The new command is named +'name'+, and it replaces any existing command
1128 there may have been by that name. Whenever the new command is
1129 invoked, the contents of +'body'+ will be executed by the Tcl
1130 interpreter.
1132 +'arglist'+ specifies the formal arguments to the procedure.
1133 It consists of a list, possibly empty, of the following
1134 argument specifiers:
1136 +name+::
1137     Required Argument - A simple argument name.
1139 +{name default}+::
1140     Optional Argument - A two-element list consisting of the
1141     argument name, followed by the default value, which will
1142     be used if the corresponding argument is not supplied.
1144 +&name+::
1145     Reference Argument - The caller is expected to pass the name of
1146     an existing variable. An implicit +`upvar` 1 origname name+ is done
1147     to make the variable available in the proc scope.
1149 +*args*+::
1150     Variable Argument - The special name +'args'+, which is
1151     assigned all remaining arguments (including none) as a list. The
1152     variable argument may only be specified once. Note that
1153     the syntax +{args newname}+ may be used to retain the special
1154     behaviour of +'args'+ with a different local name. In this case,
1155     the variable is named +'newname'+ rather than +'args'+.
1157 When the command is invoked, a local variable will be created for each of
1158 the formal arguments to the procedure; its value will be the value
1159 of corresponding argument in the invoking command or the argument's
1160 default value.
1162 Arguments with default values need not be specified in a procedure
1163 invocation.  However, there must be enough actual arguments for all
1164 required arguments, and there must not be any extra actual arguments
1165 (unless the Variable Argument is specified).
1167 Actual arguments are assigned to formal arguments as in left-to-right
1168 order with the following precedence.
1170 1. Required Arguments (including Reference Arguments)
1171 2. Optional Arguments
1172 3. Variable Argument
1174 The following example illustrates precedence. Assume a procedure declaration:
1176     proc p {{a A} args b {c C} d} {...}
1178 This procedure requires at least two arguments, but can accept an unlimited number.
1179 The following table shows how various numbers of arguments are assigned.
1180 Values marked as +-+ are assigned the default value.
1182 [width="40%",frame="topbot",options="header"]
1183 |==============
1184 |Number of arguments|a|args|b|c|d
1185 |2|-|-|1|-|2
1186 |3|1|-|2|-|3
1187 |4|1|-|2|3|4
1188 |5|1|2|3|4|5
1189 |6|1|2,3|4|5|6
1190 |==============
1192 When +'body'+ is being executed, variable names normally refer to local
1193 variables, which are created automatically when referenced and deleted
1194 when the procedure returns.  One local variable is automatically created
1195 for each of the procedure's arguments.  Global variables can be
1196 accessed by invoking the `global` command or via the +::+ prefix.
1198 New in Jim
1199 ~~~~~~~~~~
1200 In addition to procedure arguments, Jim procedures may declare static variables.
1201 These variables scoped to the procedure and initialised at procedure definition.
1202 Either from the static variable definition, or from the enclosing scope.
1204 Consider the following example:
1206     jim> set a 1
1207     jim> proc a {} {a {b 2}} {
1208         set c 1
1209         puts "$a $b $c"
1210         incr a
1211         incr b
1212         incr c
1213     }
1214     jim> a
1215     1 2 1
1216     jim> a
1217     2 3 1
1219 The static variable +'a'+ has no initialiser, so it is initialised from
1220 the enclosing scope with the value 1. (Note that it is an error if there
1221 is no variable with the same name in the enclosing scope). However +'b'+
1222 has an initialiser, so it is initialised to 2.
1224 Unlike a local variable, the value of a static variable is retained across
1225 invocations of the procedure.
1227 See the `proc` command for information on how to define procedures
1228 and what happens when they are invoked. See also NAMESPACES.
1230 VARIABLES - SCALARS AND ARRAYS
1231 ------------------------------
1232 Tcl allows the definition of variables and the use of their values
1233 either through '$'-style variable substitution, the `set`
1234 command, or a few other mechanisms.
1236 Variables need not be declared:  a new variable will automatically
1237 be created each time a new variable name is used.
1239 Tcl supports two types of variables:  scalars and arrays.
1240 A scalar variable has a single value, whereas an array variable
1241 can have any number of elements, each with a name (called
1242 its 'index') and a value.
1244 Array indexes may be arbitrary strings; they need not be numeric.
1245 Parentheses are used refer to array elements in Tcl commands.
1246 For example, the command
1248     set x(first) 44
1250 will modify the element of 'x' whose index is 'first'
1251 so that its new value is '44'.
1253 Two-dimensional arrays can be simulated in Tcl by using indexes
1254 that contain multiple concatenated values.
1255 For example, the commands
1257     set a(2,3) 1
1258     set a(3,6) 2
1260 set the elements of 'a' whose indexes are '2,3' and '3,6'.
1262 In general, array elements may be used anywhere in Tcl that scalar
1263 variables may be used.
1265 If an array is defined with a particular name, then there may
1266 not be a scalar variable with the same name.
1268 Similarly, if there is a scalar variable with a particular
1269 name then it is not possible to make array references to the
1270 variable.
1272 To convert a scalar variable to an array or vice versa, remove
1273 the existing variable with the `unset` command.
1275 The `array` command provides several features for dealing
1276 with arrays, such as querying the names of all the elements of
1277 the array and converting between an array and a list.
1279 Variables may be either global or local.  If a variable
1280 name is used when a procedure isn't being executed, then it
1281 automatically refers to a global variable.  Variable names used
1282 within a procedure normally refer to local variables associated with that
1283 invocation of the procedure.  Local variables are deleted whenever
1284 a procedure exits.  Either `global` command may be used to request
1285 that a name refer to a global variable for the duration of the current
1286 procedure (this is somewhat analogous to 'extern' in C), or the variable
1287 may be explicitly scoped with the +::+ prefix. For example
1289     set a 1
1290     set b 2
1291     proc p {} {
1292         set c 3
1293         global a
1295         puts "$a $::b $c"
1296     }
1297     p
1299 will output:
1301     1 2 3
1303 ARRAYS AS LISTS IN JIM
1304 ----------------------
1305 Unlike Tcl, Jim can automatically convert between a list (with an even
1306 number of elements) and an array value. This is similar to the way Tcl
1307 can convert between a string and a list.
1309 For example:
1311   set a {1 one 2 two}
1312   puts $a(2)
1314 will output:
1316   two
1318 Thus `array set` is equivalent to `set` when the variable does not
1319 exist or is empty.
1321 The reverse is also true where an array will be converted into
1322 a list.
1324   set a(1) one; set a(2) two
1325   puts $a
1327 will output:
1329   1 one 2 two
1331 DICTIONARY VALUES
1332 -----------------
1333 Tcl 8.5 introduced the dict command, and Jim Tcl has added a version
1334 of this command. Dictionaries provide efficient access to key-value
1335 pairs, just like arrays, but dictionaries are pure values. This
1336 means that you can pass them to a procedure just as a list or a
1337 string. Tcl dictionaries are therefore much more like Tcl lists,
1338 except that they represent a mapping from keys to values, rather
1339 than an ordered sequence.
1341 You can nest dictionaries, so that the value for a particular key
1342 consists of another dictionary. That way you can elegantly build
1343 complicated data structures, such as hierarchical databases. You
1344 can also combine dictionaries with other Tcl data structures. For
1345 instance, you can build a list of dictionaries that themselves
1346 contain lists.
1348 Dictionaries are values that contain an efficient, order-preserving
1349 mapping from arbitrary keys to arbitrary values. Each key in the
1350 dictionary maps to a single value. They have a textual format that
1351 is exactly that of any list with an even number of elements, with
1352 each mapping in the dictionary being represented as two items in
1353 the list. When a command takes a dictionary and produces a new
1354 dictionary based on it (either returning it or writing it back into
1355 the variable that the starting dictionary was read from) the new
1356 dictionary will have the same order of keys, modulo any deleted
1357 keys and with new keys added on to the end. When a string is
1358 interpreted as a dictionary and it would otherwise have duplicate
1359 keys, only the last value for a particular key is used; the others
1360 are ignored, meaning that, "apple banana" and "apple carrot apple
1361 banana" are equivalent dictionaries (with different string
1362 representations).
1364 Note that in Jim, arrays are implemented as dictionaries.
1365 Thus automatic conversion between lists and dictionaries applies
1366 as it does for arrays.
1368   jim> dict set a 1 one
1369   1 one
1370   jim> dict set a 2 two
1371   1 one 2 two
1372   jim> puts $a
1373   1 one 2 two
1374   jim> puts $a(2)
1375   two
1376   jim> dict set a 3 T three
1377   1 one 2 two 3 {T three}
1379 See the `dict` command for more details.
1381 NAMESPACES
1382 ----------
1383 Tcl added namespaces as a mechanism avoiding name clashes, especially in applications
1384 including a number of 3rd party components. While there is less need for namespaces
1385 in Jim Tcl (which does not strive to support large applications), it is convenient to
1386 provide a subset of the support for namespaces to easy porting code from Tcl.
1388 Jim Tcl currently supports "light-weight" namespaces which should be adequate for most
1389 purposes. This feature is currently experimental. See README.namespaces for more information
1390 and the documentation of the `namespace` command.
1392 GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION
1393 -----------------------------------------------
1394 Unlike Tcl, Jim has some sophisticated support for functional programming.
1395 These are described briefly below.
1397 More information may be found at http://wiki.tcl.tk/13847
1399 References
1400 ~~~~~~~~~~
1401 A reference can be thought of as holding a value with one level of indirection,
1402 where the value may be garbage collected when unreferenced.
1403 Consider the following example:
1405     jim> set r [ref "One String" test]
1406     <reference.<test___>.00000000000000000000>
1407     jim> getref $r
1408     One String
1410 The operation `ref` creates a references to the value specified by the
1411 first argument. (The second argument is a "type" used for documentation purposes).
1413 The operation `getref` is the dereferencing operation which retrieves the value
1414 stored in the reference.
1416     jim> setref $r "New String"
1417     New String
1418     jim> getref $r
1419     New String
1421 The operation `setref` replaces the value stored by the reference. If the old value
1422 is no longer accessible by any reference, it will eventually be automatically be garbage
1423 collected.
1425 Garbage Collection
1426 ~~~~~~~~~~~~~~~~~~
1427 Normally, all values in Tcl are passed by value. As such values are copied and released
1428 automatically as necessary.
1430 With the introduction of references, it is possible to create values whose lifetime
1431 transcend their scope. To support this, case, the Jim system will periodically identify
1432 and discard objects which are no longer accessible by any reference.
1434 The `collect` command may be used to force garbage collection.  Consider a reference created
1435 with a finalizer:
1437     jim> proc f {ref value} { puts "Finaliser called for $ref,$value" }
1438     jim> set r [ref "One String" test f]
1439     <reference.<test___>.00000000000
1440     jim> collect
1441     0
1442     jim> set r ""
1443     jim> collect
1444     Finaliser called for <reference.<test___>.00000000000,One String
1445     1
1447 Note that once the reference, 'r', was modified so that it no longer
1448 contained a reference to the value, the garbage collector discarded
1449 the value (after calling the finalizer).
1451 The finalizer for a reference may be examined or changed with the `finalize` command
1453     jim> finalize $r
1454     f
1455     jim> finalize $r newf
1456     newf
1458 Lambda Function
1459 ~~~~~~~~~~~~~~~
1460 Jim provides a garbage collected `lambda` function. This is a procedure
1461 which is able to create an anonymous procedure.  Consider:
1463     jim> set f [lambda {a} {{x 0}} { incr x $a }]
1464     jim> $f 1
1465     1
1466     jim> $f 2
1467     3
1468     jim> set f ""
1470 This create an anonymous procedure (with the name stored in 'f'), with a static variable
1471 which is incremented by the supplied value and the result returned.
1473 Once the procedure name is no longer accessible, it will automatically be deleted
1474 when the garbage collector runs.
1476 The procedure may also be delete immediately by renaming it "". e.g.
1478     jim> rename $f ""
1480 UTF-8 AND UNICODE
1481 -----------------
1482 If Jim is built with UTF-8 support enabled (configure --enable-utf),
1483 then most string-related commands become UTF-8 aware.  These include,
1484 but are not limited to, `string match`, `split`, `glob`, `scan` and
1485 `format`.
1487 UTF-8 encoding has many advantages, but one of the complications is that
1488 characters can take a variable number of bytes. Thus the addition of
1489 `string bytelength` which returns the number of bytes in a string,
1490 while `string length` returns the number of characters.
1492 If UTF-8 support is not enabled, all commands treat bytes as characters
1493 and `string bytelength` returns the same value as `string length`.
1495 Note that even if UTF-8 support is not enabled, the +{backslash}uNNNN+ and related syntax
1496 is still available to embed UTF-8 sequences.
1498 Jim Tcl supports all currently defined unicode codepoints. That is 21 bits, up to +'U+1FFFFF'.
1500 String Matching
1501 ~~~~~~~~~~~~~~~
1502 Commands such as `string match`, `lsearch -glob`, `array names` and others use string
1503 pattern matching rules. These commands support UTF-8. For example:
1505   string match a\[\ua0-\ubf\]b "a\u00a3b"
1507 format and scan
1508 ~~~~~~~~~~~~~~~
1509 +format %c+ allows a unicode codepoint to be be encoded. For example, the following will return
1510 a string with two bytes and one character. The same as +{backslash}ub5+
1512   format %c 0xb5
1514 `format` respects widths as character widths, not byte widths. For example, the following will
1515 return a string with three characters, not three bytes.
1517   format %.3s \ub5\ub6\ub7\ub8
1519 Similarly, +scan ... %c+ allows a UTF-8 to be decoded to a unicode codepoint. The following will set
1520 +'a'+ to 181 (0xb5) and +'b'+ to 65 (0x41).
1522   scan \u00b5A %c%c a b
1524 `scan %s` will also accept a character class, including unicode ranges.
1526 String Classes
1527 ~~~~~~~~~~~~~~
1528 `string is` has *not* been extended to classify UTF-8 characters. Therefore, the following
1529 will return 0, even though the string may be considered to be alphabetic.
1531   string is alpha \ub5Test
1533 This does not affect the string classes 'ascii', 'control', 'digit', 'double', 'integer' or 'xdigit'.
1535 Case Mapping and Conversion
1536 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1537 Jim provides a simplified unicode case mapping. This means that case conversion
1538 and comparison will not increase or decrease the number of characters in a string.
1539 (Although it may change the number of bytes).
1541 `string toupper` will convert any lowercase letters to their uppercase equivalent.
1542 Any character which is not a letter or has no uppercase equivalent is left unchanged.
1543 Similarly for `string tolower` and `string totitle`.
1545 Commands which perform case insensitive matches, such as `string compare -nocase`
1546 and `lsearch -nocase` fold both strings to uppercase before comparison.
1548 Invalid UTF-8 Sequences
1549 ~~~~~~~~~~~~~~~~~~~~~~~
1550 Some UTF-8 character sequences are invalid, such as those beginning with '0xff',
1551 those which represent character sequences longer than 3 bytes (greater than U+FFFF),
1552 and those which end prematurely, such as a lone '0xc2'.
1554 In these situations, the offending bytes are treated as single characters. For example,
1555 the following returns 2.
1557   string bytelength \xff\xff
1559 Regular Expressions
1560 ~~~~~~~~~~~~~~~~~~~
1561 If UTF-8 support is enabled, the built-in regular expression engine will be
1562 selected which supports UTF-8 strings and patterns.
1564 See REGULAR EXPRESSIONS
1566 BUILT-IN COMMANDS
1567 -----------------
1568 The Tcl library provides the following built-in commands, which will
1569 be available in any application using Tcl.  In addition to these
1570 built-in commands, there may be additional commands defined by each
1571 application, plus commands defined as Tcl procedures.
1573 In the command syntax descriptions below, words in +*boldface*+ are
1574 literals that you type verbatim to Tcl.
1576 Words in +'italics'+ are meta-symbols; they serve as names for any of
1577 a range of values that you can type.
1579 Optional arguments or groups of arguments are indicated by enclosing them
1580 in +?question-marks?+.
1582 Ellipses (+\...+) indicate that any number of additional
1583 arguments or groups of arguments may appear, in the same format
1584 as the preceding argument(s).
1586 [[CommandIndex]]
1587 Command Index
1588 ~~~~~~~~~~~~~
1589 @INSERTINDEX@
1591 alarm
1592 ~~~~~
1593 +*alarm* 'seconds'+
1595 Delivers the +SIGALRM+ signal to the process after the given
1596 number of seconds. If the platform supports 'ualarm(3)' then
1597 the argument may be a floating point value. Otherwise it must
1598 be an integer.
1600 Note that unless a signal handler for +SIGALRM+ has been installed
1601 (see `signal`), the process will exit on this signal.
1603 alias
1604 ~~~~~
1605 +*alias* 'name args\...'+
1607 Creates a single word alias (command) for one or more words. For example,
1608 the following creates an alias for the command `info exists`.
1610     alias e info exists
1611     if {[e var]} {
1612       ...
1613     }
1615 `alias` returns +'name'+, allowing it to be used with `local`.
1617 See also `proc`, `curry`, `lambda`, `local`, `info alias`, `exists -alias`
1619 append
1620 ~~~~~~
1621 +*append* 'varName value ?value value ...?'+
1623 Append all of the +'value'+ arguments to the current value
1624 of variable +'varName'+.  If +'varName'+ doesn't exist,
1625 it is given a value equal to the concatenation of all the
1626 +'value'+ arguments.
1628 This command provides an efficient way to build up long
1629 variables incrementally.
1630 For example, "`append a $b`" is much more efficient than
1631 "`set a $a$b`" if +$a+ is long.
1633 apply
1634 ~~~~~~
1635 +*apply* 'lambdaExpr ?arg1 arg2 \...?'+
1637 The command `apply` provides for anonymous procedure calls,
1638 similar to `lambda`, but without command name being created, even temporarily.
1640 The function  +'lambdaExpr'+ is a two element list +{args body}+
1641 or a three element list +{args body namespace}+. The first element
1642 args specifies the formal arguments, in the same form as the `proc` and `lambda` commands.
1644 array
1645 ~~~~~
1646 +*array* 'option arrayName ?arg\...?'+
1648 This command performs one of several operations on the
1649 variable given by +'arrayName'+.
1651 Note that in general, if the named array does not exist, the +'array'+ command behaves
1652 as though the array exists but is empty.
1654 The +'option'+ argument determines what action is carried out by the
1655 command.  The legal +'options'+ (which may be abbreviated) are:
1657 +*array exists* 'arrayName'+::
1658     Returns 1 if arrayName is an array variable, 0 if there is
1659     no variable by that name.  This command is essentially
1660     identical to `info exists`
1662 +*array get* 'arrayName ?pattern?'+::
1663     Returns a list containing pairs of elements. The first
1664     element in each pair is the name of an element in arrayName
1665     and the second element of each pair is the value of the
1666     array element. The order of the pairs is undefined. If
1667     pattern is not specified, then all of the elements of the
1668     array are included in the result. If pattern is specified,
1669     then only those elements whose names match pattern (using
1670     the matching rules of string match) are included. If arrayName
1671     isn't the name of an array variable, or if the array contains
1672     no elements, then an empty list is returned.
1674 +*array names* 'arrayName ?pattern?'+::
1675     Returns a list containing the names of all of the elements
1676     in the array that match pattern. If pattern is omitted then
1677     the command returns all of the element names in the array.
1678     If pattern is specified, then only those elements whose
1679     names match pattern (using the matching rules of string
1680     match) are included. If there are no (matching) elements
1681     in the array, or if arrayName isn't the name of an array
1682     variable, then an empty string is returned.
1684 +*array set* 'arrayName list'+::
1685     Sets the values of one or more elements in arrayName. list
1686     must have a form like that returned by array get, consisting
1687     of an even number of elements. Each odd-numbered element
1688     in list is treated as an element name within arrayName, and
1689     the following element in list is used as a new value for
1690     that array element. If the variable arrayName does not
1691     already exist and list is empty, arrayName is created with
1692     an empty array value.
1694 +*array size* 'arrayName'+::
1695     Returns the number of elements in the array. If arrayName
1696     isn't the name of an array then 0 is returned.
1698 +*array unset* 'arrayName ?pattern?'+::
1699     Unsets all of the elements in the array that match pattern
1700     (using the matching rules of string match). If arrayName
1701     isn't the name of an array variable or there are no matching
1702     elements in the array, no error will be raised. If pattern
1703     is omitted and arrayName is an array variable, then the
1704     command unsets the entire array. The command always returns
1705     an empty string.
1707 break
1708 ~~~~~
1709 +*break*+
1711 This command may be invoked only inside the body of a loop command
1712 such as `for` or `foreach` or `while`.  It returns a +JIM_BREAK+ code
1713 to signal the innermost containing loop command to return immediately.
1715 case
1716 ~~~~
1717 +*case* 'string' ?in? 'patList body ?patList body ...?'+
1719 +*case* 'string' ?in? {'patList body ?patList body ...?'}+
1721 *Note* that the `switch` command should generally be preferred unless compatibility
1722 with Tcl 6.x is desired.
1724 Match +'string'+ against each of the +'patList'+ arguments
1725 in order.  If one matches, then evaluate the following +'body'+ argument
1726 by passing it recursively to the Tcl interpreter, and return the result
1727 of that evaluation.  Each +'patList'+ argument consists of a single
1728 pattern or list of patterns.  Each pattern may contain any of the wild-cards
1729 described under `string match`.
1731 If a +'patList'+ argument is +default+, the corresponding body will be
1732 evaluated if no +'patList'+ matches +'string'+.  If no +'patList'+ argument
1733 matches +'string'+ and no default is given, then the `case` command returns
1734 an empty string.
1736 Two syntaxes are provided.
1738 The first uses a separate argument for each of the patterns and commands;
1739 this form is convenient if substitutions are desired on some of the
1740 patterns or commands.
1742 The second form places all of the patterns and commands together into
1743 a single argument; the argument must have proper list structure, with
1744 the elements of the list being the patterns and commands.
1746 The second form makes it easy to construct multi-line case commands,
1747 since the braces around the whole list make it unnecessary to include a
1748 backslash at the end of each line.
1750 Since the +'patList'+ arguments are in braces in the second form,
1751 no command or variable substitutions are performed on them;  this makes
1752 the behaviour of the second form different than the first form in some
1753 cases.
1755 Below are some examples of `case` commands:
1757     case abc in {a b} {format 1} default {format 2} a* {format 3}
1759 will return '3',
1761     case a in {
1762         {a b} {format 1}
1763         default {format 2}
1764         a* {format 3}
1765     }
1767 will return '1', and
1769     case xyz {
1770         {a b}
1771             {format 1}
1772         default
1773             {format 2}
1774         a*
1775             {format 3}
1776     }
1778 will return '2'.
1780 catch
1781 ~~~~~
1782 +*catch* ?-?no?'code \...'? ?--? 'command ?resultVarName? ?optionsVarName?'+
1784 The `catch` command may be used to prevent errors from aborting
1785 command interpretation.  `catch` evaluates +'command'+, and returns a
1786 +JIM_OK+ code, regardless of any errors that might occur while
1787 executing +'command'+ (with the possible exception of +JIM_SIGNAL+ -
1788 see below).
1790 The return value from `catch` is a decimal string giving the code
1791 returned by the Tcl interpreter after executing +'command'+.  This
1792 will be '0' (+JIM_OK+) if there were no errors in +'command'+; otherwise
1793 it will have a non-zero value corresponding to one of the exceptional
1794 return codes (see jim.h for the definitions of code values, or the
1795 `info returncodes` command).
1797 If the +'resultVarName'+ argument is given, then it gives the name
1798 of a variable; `catch` will set the value of the variable to the
1799 string returned from +'command'+ (either a result or an error message).
1801 If the +'optionsVarName'+ argument is given, then it gives the name
1802 of a variable; `catch` will set the value of the variable to a
1803 dictionary. For any return code other than +JIM_RETURN+, the value
1804 for the key +-code+ will be set to the return code. For +JIM_RETURN+
1805 it will be set to the code given in `return -code`. Additionally,
1806 for the return code +JIM_ERR+, the value of the key +-errorinfo+
1807 will contain the current stack trace (the same result as `info stacktrace`),
1808 the value of the key +-errorcode+ will contain the
1809 same value as the global variable $::errorCode, and the value of
1810 the key +-level+ will be the current return level (see `return -level`).
1811 This can be useful to rethrow an error:
1813     if {[catch {...} msg opts]} {
1814         ...maybe do something with the error...
1815         incr opts(-level)
1816         return {*}$opts $msg
1817     }
1819 Normally `catch` will +'not'+ catch any of the codes +JIM_EXIT+, +JIM_EVAL+ or +JIM_SIGNAL+.
1820 The set of codes which will be caught may be modified by specifying the one more codes before
1821 +'command'+.
1823 e.g. To catch +JIM_EXIT+ but not +JIM_BREAK+ or +JIM_CONTINUE+
1825     catch -exit -nobreak -nocontinue -- { ... }
1827 The use of +--+ is optional. It signifies that no more return code options follow.
1829 Note that if a signal marked as `signal handle` is caught with `catch -signal`, the return value
1830 (stored in +'resultVarName'+) is name of the signal caught.
1834 +*cd* 'dirName'+
1836 Change the current working directory to +'dirName'+.
1838 Returns an empty string.
1840 This command can potentially be disruptive to an application, so it may
1841 be removed in some applications.
1843 clock
1844 ~~~~~
1845 +*clock seconds*+::
1846     Returns the current time as seconds since the epoch.
1848 +*clock clicks*+::
1849     Returns the current time in `clicks'.
1851 +*clock microseconds*+::
1852     Returns the current time in microseconds.
1854 +*clock milliseconds*+::
1855     Returns the current time in milliseconds.
1857 +*clock format* 'seconds' ?*-format* 'format?'+::
1858     Format the given time (seconds since the epoch) according to the given
1859     format. See strftime(3) for supported formats.
1860     If no format is supplied, "%c" is used.
1862 +*clock scan* 'str' *-format* 'format'+::
1863     Scan the given time string using the given format string.
1864     See strptime(3) for supported formats.
1866 close
1867 ~~~~~
1868 +*close* 'fileId'+
1870 +'fileId' *close*+
1872 Closes the file given by +'fileId'+.
1873 +'fileId'+ must be the return value from a previous invocation
1874 of the `open` command; after this command, it should not be
1875 used anymore.
1877 collect
1878 ~~~~~~~
1879 +*collect*+
1881 Normally reference garbage collection is automatically performed periodically.
1882 However it may be run immediately with the `collect` command.
1884 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
1886 concat
1887 ~~~~~~
1888 +*concat* 'arg ?arg \...?'+
1890 This command treats each argument as a list and concatenates them
1891 into a single list.  It permits any number of arguments.  For example,
1892 the command
1894     concat a b {c d e} {f {g h}}
1896 will return
1898     a b c d e f {g h}
1900 as its result.
1902 continue
1903 ~~~~~~~~
1904 +*continue*+
1906 This command may be invoked only inside the body of a loop command such
1907 as `for` or `foreach` or `while`.  It returns a  +JIM_CONTINUE+ code to
1908 signal the innermost containing loop command to skip the remainder of
1909 the loop's body but continue with the next iteration of the loop.
1911 curry
1912 ~~~~~
1913 +*alias* 'args\...'+
1915 Similar to `alias` except it creates an anonymous procedure (lambda) instead of
1916 a named procedure.
1918 the following creates a local, unnamed alias for the command `info exists`.
1920     set e [local curry info exists]
1921     if {[$e var]} {
1922       ...
1923     }
1925 `curry` returns the name of the procedure.
1927 See also `proc`, `alias`, `lambda`, `local`.
1929 dict
1930 ~~~~
1931 +*dict* 'option ?arg\...?'+
1933 Performs one of several operations on dictionary values.
1935 The +'option'+ argument determines what action is carried out by the
1936 command.  The legal +'options'+ are:
1938 +*dict create* '?key value \...?'+::
1939     Create and return a new dictionary value that contains each of
1940     the key/value mappings listed as  arguments (keys and values
1941     alternating, with each key being followed by its associated
1942     value.)
1944 +*dict exists* 'dictionary key ?key \...?'+::
1945     Returns a boolean value indicating whether the given key (or path
1946     of keys through a set of nested dictionaries) exists in the given
1947     dictionary value.  This returns a true value exactly when `dict get`
1948     on that path will succeed.
1950 +*dict get* 'dictionary ?key \...?'+::
1951     Given a dictionary value (first argument) and a key (second argument),
1952     this will retrieve the value for that key. Where several keys are
1953     supplied, the behaviour of the command shall be as if the result
1954     of "`dict get $dictVal $key`" was passed as the first argument to
1955     dict get with the remaining arguments as second (and possibly
1956     subsequent) arguments. This facilitates lookups in nested dictionaries.
1957     If no keys are provided, dict would return a list containing pairs
1958     of elements in a manner similar to array get. That is, the first
1959     element of each pair would be the key and the second element would
1960     be the value for that key.  It is an error to attempt to retrieve
1961     a value for a key that is not present in the dictionary.
1963 +*dict keys* 'dictionary ?pattern?'+::
1964     Returns a list of the keys in the dictionary.
1965     If pattern is specified, then only those keys whose
1966     names match +'pattern'+ (using the matching rules of string
1967     match) are included.
1969 +*dict merge* ?'dictionary \...'?+::
1970     Return a dictionary that contains the contents of each of the
1971     +'dictionary'+ arguments. Where two (or more) dictionaries
1972     contain a mapping for the same key, the resulting dictionary
1973     maps that key to the value according to the last dictionary on
1974     the command line containing a mapping for that key.
1976 +*dict set* 'dictionaryName key ?key \...? value'+::
1977     This operation takes the +'name'+ of a variable containing a dictionary
1978     value and places an updated dictionary value in that variable
1979     containing a mapping from the given key to the given value. When
1980     multiple keys are present, this operation creates or updates a chain
1981     of nested dictionaries.
1983 +*dict size* 'dictionary'+::
1984     Return the number of key/value mappings in the given dictionary value.
1986 +*dict unset* 'dictionaryName key ?key \...? value'+::
1987     This operation (the companion to `dict set`) takes the name of a
1988     variable containing a dictionary value and places an updated
1989     dictionary value in that variable that does not contain a mapping
1990     for the given key. Where multiple keys are present, this describes
1991     a path through nested dictionaries to the mapping to remove. At
1992     least one key must be specified, but the last key on the key-path
1993     need not exist. All other components on the path must exist.
1995 +*dict with* 'dictionaryName key ?key \...? script'+::
1996     Execute the Tcl script in +'script'+ with the value for each
1997     key in +'dictionaryName'+ mapped to a variable with the same
1998     name. Where one or more keys are given, these indicate a chain
1999     of nested dictionaries, with the innermost dictionary being the
2000     one opened out for the execution of body. Making +'dictionaryName'+
2001     unreadable will make the updates to the dictionary be discarded,
2002     and this also happens if the contents of +'dictionaryName'+ are
2003     adjusted so that the chain of dictionaries no longer exists.
2004     The result of `dict with` is (unless some kind of error occurs)
2005     the result of the evaluation of body.
2006  ::
2007     The variables are mapped in the scope enclosing the `dict with`;
2008     it is recommended that this command only be used in a local
2009     scope (procedure). Because of this, the variables set by
2010     `dict with` will continue to exist after the command finishes (unless
2011     explicitly unset). Note that changes to the contents of +'dictionaryName'+
2012     only happen when +'script'+ terminates.
2014 +*dict for, values, incr, append, lappend, update, info, replace*+ to be documented...
2018 +*env* '?name? ?default?'+
2020 If +'name'+ is supplied, returns the value of +'name'+ from the initial
2021 environment (see getenv(3)). An error is returned if +'name'+ does not
2022 exist in the environment, unless +'default'+ is supplied - in which case
2023 that value is returned instead.
2025 If no arguments are supplied, returns a list of all environment variables
2026 and their values as +{name value \...}+
2028 See also the global variable +::env+
2032 +*eof* 'fileId'+
2034 +'fileId' *eof*+
2036 Returns 1 if an end-of-file condition has occurred on +'fileId'+,
2037 0 otherwise.
2039 +'fileId'+ must have been the return value from a previous call to `open`,
2040 or it may be +stdin+, +stdout+, or +stderr+ to refer to one of the
2041 standard I/O channels.
2043 error
2044 ~~~~~
2045 +*error* 'message ?stacktrace?'+
2047 Returns a +JIM_ERR+ code, which causes command interpretation to be
2048 unwound.  +'message'+ is a string that is returned to the application
2049 to indicate what went wrong.
2051 If the +'stacktrace'+ argument is provided and is non-empty,
2052 it is used to initialize the stacktrace.
2054 This feature is most useful in conjunction with the `catch` command:
2055 if a caught error cannot be handled successfully, +'stacktrace'+ can be used
2056 to return a stack trace reflecting the original point of occurrence
2057 of the error:
2059     catch {...} errMsg
2060     ...
2061     error $errMsg [info stacktrace]
2063 See also `errorInfo`, `info stacktrace`, `catch` and `return`
2065 errorInfo
2066 ~~~~~~~~~
2067 +*errorInfo* 'error ?stacktrace?'+
2069 Returns a human-readable representation of the given error message and stack trace.
2070 Typical usage is:
2072     if {[catch {...} error]} {
2073         puts stderr [errorInfo $error [info stacktrace]]
2074         exit 1
2075     }
2077 See also `error`.
2079 eval
2080 ~~~~
2081 +*eval* 'arg ?arg\...?'+
2083 `eval` takes one or more arguments, which together comprise a Tcl
2084 command (or collection of Tcl commands separated by newlines in the
2085 usual way).  `eval` concatenates all its arguments in the same
2086 fashion as the `concat` command, passes the concatenated string to the
2087 Tcl interpreter recursively, and returns the result of that
2088 evaluation (or any error generated by it).
2090 exec
2091 ~~~~
2092 +*exec* 'arg ?arg\...?'+
2094 This command treats its arguments as the specification
2095 of one or more UNIX commands to execute as subprocesses.
2096 The commands take the form of a standard shell pipeline;
2097 +|+ arguments separate commands in the
2098 pipeline and cause standard output of the preceding command
2099 to be piped into standard input of the next command (or +|&+ for
2100 both standard output and standard error).
2102 Under normal conditions the result of the `exec` command
2103 consists of the standard output produced by the last command
2104 in the pipeline followed by the standard error output.
2106 If any of the commands writes to its standard error file,
2107 then this will be included in the result after the standard output
2108 of the last command.
2110 Note that unlike Tcl, data written to standard error does not cause
2111 `exec` to return an error.
2113 If any of the commands in the pipeline exit abnormally or
2114 are killed or suspended, then `exec` will return an error.
2115 If no standard error output was produced, or is redirected,
2116 the error message will include the normal result, as above,
2117 followed by error messages describing the abnormal terminations.
2119 If any standard error output was produced, these abnormal termination
2120 messages are suppressed.
2122 If the last character of the result or error message
2123 is a newline then that character is deleted from the result
2124 or error message for consistency with normal
2125 Tcl return values.
2127 An +'arg'+ may have one of the following special forms:
2129 +>filename+::
2130     The standard output of the last command in the pipeline
2131     is redirected to the file.  In this situation `exec`
2132     will normally return an empty string.
2134 +>>filename+::
2135     As above, but append to the file.
2137 +>@fileId+::
2138     The standard output of the last command in the pipeline is
2139     redirected to the given (writable) file descriptor (e.g. stdout,
2140     stderr, or the result of `open`). In this situation `exec`
2141     will normally return an empty string.
2143 +2>filename+::
2144     The standard error of the last command in the pipeline
2145     is redirected to the file.
2147 +2>>filename+::
2148     As above, but append to the file.
2150 +2>@fileId+::
2151     The standard error of the last command in the pipeline is
2152     redirected to the given (writable) file descriptor.
2154 +2>@1+::
2155     The standard error of the last command in the pipeline is
2156     redirected to the same file descriptor as the standard output.
2158 +>&filename+::
2159     Both the standard output and standard error of the last command
2160     in the pipeline is redirected to the file.
2162 +>>&filename+::
2163     As above, but append to the file.
2165 +<filename+::
2166     The standard input of the first command in the pipeline
2167     is taken from the file.
2169 +<<string+::
2170     The standard input of the first command is taken as the
2171     given immediate value.
2173 +<@fileId+::
2174     The standard input of the first command in the pipeline
2175     is taken from the given (readable) file descriptor.
2177 If there is no redirection of standard input, standard error
2178 or standard output, these are connected to the corresponding
2179 input or output of the application.
2181 If the last +'arg'+ is +&+ then the command will be
2182 executed in background.
2183 In this case the standard output from the last command
2184 in the pipeline will
2185 go to the application's standard output unless
2186 redirected in the command, and error output from all
2187 the commands in the pipeline will go to the application's
2188 standard error file. The return value of exec in this case
2189 is a list of process ids (pids) in the pipeline.
2191 Each +'arg'+ becomes one word for a command, except for
2192 +|+, +<+, +<<+, +>+, and +&+ arguments, and the
2193 arguments that follow +<+, +<<+, and +>+.
2195 The first word in each command is taken as the command name;
2196 the directories in the PATH environment variable are searched for
2197 an executable by the given name.
2199 No `glob` expansion or other shell-like substitutions
2200 are performed on the arguments to commands.
2202 If the command fails, the global $::errorCode (and the -errorcode
2203 option in `catch`) will be set to a list, as follows:
2205 +*CHILDKILLED* 'pid sigName msg'+::
2206         This format is used when a child process has been killed
2207         because of a signal. The pid element will be the process's
2208         identifier (in decimal). The sigName element will be the
2209         symbolic name of the signal that caused the process to
2210         terminate; it will be one of the names from the include
2211         file signal.h, such as SIGPIPE. The msg element will be a
2212         short human-readable message describing the signal, such
2213         as "write on pipe with no readers" for SIGPIPE.
2215 +*CHILDSUSP* 'pid sigName msg'+::
2216         This format is used when a child process has been suspended
2217         because of a signal. The pid element will be the process's
2218         identifier, in decimal. The sigName element will be the
2219         symbolic name of the signal that caused the process to
2220         suspend; this will be one of the names from the include
2221         file signal.h, such as SIGTTIN. The msg element will be a
2222         short human-readable message describing the signal, such
2223         as "background tty read" for SIGTTIN.
2225 +*CHILDSTATUS* 'pid code'+::
2226         This format is used when a child process has exited with a
2227         non-zero exit status. The pid element will be the process's
2228         identifier (in decimal) and the code element will be the
2229         exit code returned by the process (also in decimal).
2231 The environment for the executed command is set from $::env (unless
2232 this variable is unset, in which case the original environment is used).
2234 exists
2235 ~~~~~~
2236 +*exists ?-var|-proc|-command|-alias?* 'name'+
2238 Checks the existence of the given variable, procedure, command
2239 or alias respectively and returns 1 if it exists or 0 if not.  This command
2240 provides a more simplified/convenient version of `info exists`,
2241 `info procs` and `info commands`.
2243 If the type is omitted, a type of '-var' is used. The type may be abbreviated.
2245 exit
2246 ~~~~
2247 +*exit* '?returnCode?'+
2249 Terminate the process, returning +'returnCode'+ to the
2250 parent as the exit status.
2252 If +'returnCode'+ isn't specified then it defaults
2253 to 0.
2255 Note that exit can be caught with `catch`.
2257 expr
2258 ~~~~
2259 +*expr* 'arg'+
2261 Calls the expression processor to evaluate +'arg'+, and returns
2262 the result as a string.  See the section EXPRESSIONS above.
2264 Note that Jim supports a shorthand syntax for `expr` as +$(\...)+
2265 The following two are identical.
2267   set x [expr {3 * 2 + 1}]
2268   set x $(3 * 2 + 1)
2270 file
2271 ~~~~
2272 +*file* 'option name ?arg\...?'+
2274 Operate on a file or a file name.  +'name'+ is the name of a file.
2276 +'option'+ indicates what to do with the file name.  Any unique
2277 abbreviation for +'option'+ is acceptable.  The valid options are:
2279 +*file atime* 'name'+::
2280     Return a decimal string giving the time at which file +'name'+
2281     was last accessed.  The time is measured in the standard UNIX
2282     fashion as seconds from a fixed starting time (often January 1, 1970).
2283     If the file doesn't exist or its access time cannot be queried then an
2284     error is generated.
2286 +*file copy ?-force?* 'source target'+::
2287     Copies file +'source'+ to file +'target'+. The source file must exist.
2288     The target file must not exist, unless +-force+ is specified.
2290 +*file delete ?-force? ?--?* 'name\...'+::
2291     Deletes file or directory +'name'+. If the file or directory doesn't exist, nothing happens.
2292     If it can't be deleted, an error is generated. Non-empty directories will not be deleted
2293     unless the +-force+ options is given. In this case no errors will be generated, even
2294     if the file/directory can't be deleted. Use +'--'+ if there is any possibility of
2295     the first name being +'-force'+.
2297 +*file dirname* 'name'+::
2298     Return all of the characters in +'name'+ up to but not including
2299     the last slash character.  If there are no slashes in +'name'+
2300     then return +.+ (a single dot).  If the last slash in +'name'+ is its first
2301     character, then return +/+.
2303 +*file executable* 'name'+::
2304     Return '1' if file +'name'+ is executable by
2305     the current user, '0' otherwise.
2307 +*file exists* 'name'+::
2308     Return '1' if file +'name'+ exists and the current user has
2309     search privileges for the directories leading to it, '0' otherwise.
2311 +*file extension* 'name'+::
2312     Return all of the characters in +'name'+ after and including the
2313     last dot in +'name'+.  If there is no dot in +'name'+ then return
2314     the empty string.
2316 +*file isdirectory* 'name'+::
2317     Return '1' if file +'name'+ is a directory,
2318     '0' otherwise.
2320 +*file isfile* 'name'+::
2321     Return '1' if file +'name'+ is a regular file,
2322     '0' otherwise.
2324 +*file join* 'arg\...'+::
2325     Joins multiple path components. Note that if any components is
2326     an absolute path, the preceding components are ignored.
2327     Thus +"`file` join /tmp /root"+ returns +"/root"+.
2329 +*file link* ?*-hard|-symbolic*? 'newname target'+::
2330     Creates a hard link (default) or symbolic link from +'newname'+ to +'target'+.
2331     Note that the sense of this command is the opposite of `file rename` and `file copy`
2332     and also of `ln`, but this is compatible with Tcl.
2333     An error is returned if +'target'+ doesn't exist or +'newname'+ already exists.
2335 +*file lstat* 'name varName'+::
2336     Same as 'stat' option (see below) except uses the +'lstat'+
2337     kernel call instead of +'stat'+.  This means that if +'name'+
2338     refers to a symbolic link the information returned in +'varName'+
2339     is for the link rather than the file it refers to.  On systems that
2340     don't support symbolic links this option behaves exactly the same
2341     as the 'stat' option.
2343 +*file mkdir* 'dir1 ?dir2\...?'+::
2344     Creates each directory specified. For each pathname +'dir'+ specified,
2345     this command will create all non-existing parent directories
2346     as well as +'dir'+ itself. If an existing directory is specified,
2347     then no action is taken and no error is returned. Trying to
2348     overwrite an existing file with a directory will result in an
2349     error.  Arguments are processed in the order specified, halting
2350     at the first error, if any.
2352 +*file mtime* 'name ?time?'+::
2353     Return a decimal string giving the time at which file +'name'+
2354     was last modified.  The time is measured in the standard UNIX
2355     fashion as seconds from a fixed starting time (often January 1, 1970).
2356     If the file doesn't exist or its modified time cannot be queried then an
2357     error is generated. If +'time'+ is given, sets the modification time
2358     of the file to the given value.
2360 +*file normalize* 'name'+::
2361     Return the normalized path of +'name'+. See 'realpath(3)'.
2363 +*file owned* 'name'+::
2364     Return '1' if file +'name'+ is owned by the current user,
2365     '0' otherwise.
2367 +*file readable* 'name'+::
2368     Return '1' if file +'name'+ is readable by
2369     the current user, '0' otherwise.
2371 +*file readlink* 'name'+::
2372     Returns the value of the symbolic link given by +'name'+ (i.e. the
2373     name of the file it points to).  If
2374     +'name'+ isn't a symbolic link or its value cannot be read, then
2375     an error is returned.  On systems that don't support symbolic links
2376     this option is undefined.
2378 +*file rename* ?*-force*? 'oldname' 'newname'+::
2379     Renames the file from the old name to the new name.
2380     If +'newname'+ already exists, an error is returned unless +'-force'+ is
2381     specified.
2383 +*file rootname* 'name'+::
2384     Return all of the characters in +'name'+ up to but not including
2385     the last '.' character in the name.  If +'name'+ doesn't contain
2386     a dot, then return +'name'+.
2388 +*file size* 'name'+::
2389     Return a decimal string giving the size of file +'name'+ in bytes.
2390     If the file doesn't exist or its size cannot be queried then an
2391     error is generated.
2393 +*file stat* 'name ?varName?'+::
2394     Invoke the 'stat' kernel call on +'name'+, and return the result
2395     as a dictionary with the following keys: 'atime',
2396     'ctime', 'dev', 'gid', 'ino', 'mode', 'mtime',
2397     'nlink', 'size', 'type', 'uid'.
2398     Each element except 'type' is a decimal string with the value of
2399     the corresponding field from the 'stat' return structure; see the
2400     manual entry for 'stat' for details on the meanings of the values.
2401     The 'type' element gives the type of the file in the same form
2402     returned by the command `file type`.
2403     If +'varName'+ is specified, it is taken to be the name of an array
2404     variable and the values are also stored into the array.
2406 +*file tail* 'name'+::
2407     Return all of the characters in +'name'+ after the last slash.
2408     If +'name'+ contains no slashes then return +'name'+.
2410 +*file tempfile* '?template?'+::
2411     Creates and returns the name of a unique temporary file. If +'template'+ is omitted, a
2412     default template will be used to place the file in /tmp. See 'mkstemp(3)' for
2413     the format of the template and security concerns.
2415 +*file type* 'name'+::
2416     Returns a string giving the type of file +'name'+, which will be
2417     one of +file+, +directory+, +characterSpecial+,
2418     +blockSpecial+, +fifo+, +link+, or +socket+.
2420 +*file writable* 'name'+::
2421     Return '1' if file +'name'+ is writable by
2422     the current user, '0' otherwise.
2424 The `file` commands that return 0/1 results are often used in
2425 conditional or looping commands, for example:
2427     if {![file exists foo]} {
2428         error {bad file name}
2429     } else {
2430         ...
2431     }
2433 finalize
2434 ~~~~~~~~
2435 +*finalize* 'reference ?command?'+
2437 If +'command'+ is omitted, returns the finalizer command for the given reference.
2439 Otherwise, sets a new finalizer command for the given reference. +'command'+ may be
2440 the empty string to remove the current finalizer.
2442 The reference must be a valid reference create with the `ref`
2443 command.
2445 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2447 flush
2448 ~~~~~
2449 +*flush* 'fileId'+
2451 +'fileId' *flush*+
2453 Flushes any output that has been buffered for +'fileId'+.  +'fileId'+ must
2454 have been the return value from a previous call to `open`, or it may be
2455 +stdout+ or +stderr+ to access one of the standard I/O streams; it must
2456 refer to a file that was opened for writing.  This command returns an
2457 empty string.
2461 +*for* 'start test next body'+
2463 `for` is a looping command, similar in structure to the C `for` statement.
2464 The +'start'+, +'next'+, and +'body'+ arguments must be Tcl command strings,
2465 and +'test'+ is an expression string.
2467 The `for` command first invokes the Tcl interpreter to execute +'start'+.
2468 Then it repeatedly evaluates +'test'+ as an expression; if the result is
2469 non-zero it invokes the Tcl interpreter on +'body'+, then invokes the Tcl
2470 interpreter on +'next'+, then repeats the loop.  The command terminates
2471 when +'test'+ evaluates to 0.
2473 If a `continue` command is invoked within +'body'+ then any remaining
2474 commands in the current execution of +'body'+ are skipped; processing
2475 continues by invoking the Tcl interpreter on +'next'+, then evaluating
2476 +'test'+, and so on.
2478 If a `break` command is invoked within +'body'+ or +'next'+, then the `for`
2479 command will return immediately.
2481 The operation of `break` and `continue` are similar to the corresponding
2482 statements in C.
2484 `for` returns an empty string.
2486 foreach
2487 ~~~~~~~
2488 +*foreach* 'varName list body'+
2490 +*foreach* 'varList list ?varList2 list2 \...? body'+
2492 In this command, +'varName'+ is the name of a variable, +'list'+
2493 is a list of values to assign to +'varName'+, and +'body'+ is a
2494 collection of Tcl commands.
2496 For each field in +'list'+ (in order from left to right), `foreach` assigns
2497 the contents of the field to +'varName'+ (as if the `lindex` command
2498 had been used to extract the field), then calls the Tcl interpreter to
2499 execute +'body'+.
2501 If instead of being a simple name, +'varList'+ is used, multiple assignments
2502 are made each time through the loop, one for each element of +'varList'+.
2504 For example, if there are two elements in +'varList'+ and six elements in
2505 the list, the loop will be executed three times.
2507 If the length of the list doesn't evenly divide by the number of elements
2508 in +'varList'+, the value of the remaining variables in the last iteration
2509 of the loop are undefined.
2511 The `break` and `continue` statements may be invoked inside +'body'+,
2512 with the same effect as in the `for` command.
2514 `foreach` returns an empty string.
2516 format
2517 ~~~~~~
2518 +*format* 'formatString ?arg \...?'+
2520 This command generates a formatted string in the same way as the
2521 C 'sprintf' procedure (it uses 'sprintf' in its
2522 implementation).  +'formatString'+ indicates how to format
2523 the result, using +%+ fields as in 'sprintf', and the additional
2524 arguments, if any, provide values to be substituted into the result.
2526 All of the 'sprintf' options are valid; see the 'sprintf'
2527 man page for details.  Each +'arg'+ must match the expected type
2528 from the +%+ field in +'formatString'+; the `format` command
2529 converts each argument to the correct type (floating, integer, etc.)
2530 before passing it to 'sprintf' for formatting.
2532 The only unusual conversion is for +%c+; in this case the argument
2533 must be a decimal string, which will then be converted to the corresponding
2534 ASCII (or UTF-8) character value.
2536 In addition, Jim Tcl provides basic support for conversion to binary with +%b+.
2538 `format` does backslash substitution on its +'formatString'+
2539 argument, so backslash sequences in +'formatString'+ will be handled
2540 correctly even if the argument is in braces.
2542 The return value from `format` is the formatted string.
2544 getref
2545 ~~~~~~
2546 +*getref* 'reference'+
2548 Returns the string associated with +'reference'+. The reference must
2549 be a valid reference create with the `ref` command.
2551 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2553 gets
2554 ~~~~
2555 +*gets* 'fileId ?varName?'+
2557 +'fileId' *gets* '?varName?'+
2559 Reads the next line from the file given by +'fileId'+ and discards
2560 the terminating newline character.
2562 If +'varName'+ is specified, then the line is placed in the variable
2563 by that name and the return value is a count of the number of characters
2564 read (not including the newline).
2566 If the end of the file is reached before reading
2567 any characters then -1 is returned and +'varName'+ is set to an
2568 empty string.
2570 If +'varName'+ is not specified then the return value will be
2571 the line (minus the newline character) or an empty string if
2572 the end of the file is reached before reading any characters.
2574 An empty string will also be returned if a line contains no characters
2575 except the newline, so `eof` may have to be used to determine
2576 what really happened.
2578 If the last character in the file is not a newline character, then
2579 `gets` behaves as if there were an additional newline character
2580 at the end of the file.
2582 +'fileId'+ must be +stdin+ or the return value from a previous
2583 call to `open`; it must refer to a file that was opened
2584 for reading.
2586 glob
2587 ~~~~
2588 +*glob* ?*-nocomplain*? ?*-directory* 'dir'? ?*-tails*? ?*--*? 'pattern ?pattern \...?'+
2590 This command performs filename globbing, using csh rules.  The returned
2591 value from `glob` is the list of expanded filenames.
2593 If +-nocomplain+ is specified as the first argument then an empty
2594 list may be returned;  otherwise an error is returned if the expanded
2595 list is empty.  The +-nocomplain+ argument must be provided
2596 exactly: an abbreviation will not be accepted.
2598 If +-directory+ is given, the +'dir'+ is understood to contain a
2599 directory name to search in. This allows globbing inside directories
2600 whose names may contain glob-sensitive characters. The returned names
2601 include the directory name unless +'-tails'+ is specified.
2603 If +'-tails'+ is specified, along with +-directory+, the returned names
2604 are relative to the given directory.
2606 global
2607 ~~~~~~
2609 +*global* 'varName ?varName \...?'+
2611 This command is ignored unless a Tcl procedure is being interpreted.
2612 If so, then it declares each given +'varName'+ to be a global variable
2613 rather than a local one.  For the duration of the current procedure
2614 (and only while executing in the current procedure), any reference to
2615 +'varName'+ will be bound to a global variable instead
2616 of a local one.
2618 An alternative to using `global` is to use the +::+ prefix
2619 to explicitly name a variable in the global scope.
2623 +*if* 'expr1' ?*then*? 'body1' *elseif* 'expr2' ?*then*? 'body2' *elseif* \... ?*else*? ?'bodyN'?+
2625 The `if` command evaluates +'expr1'+ as an expression (in the same way
2626 that `expr` evaluates its argument).  The value of the expression must
2627 be numeric; if it is non-zero then +'body1'+ is executed by passing it to
2628 the Tcl interpreter.
2630 Otherwise +'expr2'+ is evaluated as an expression and if it is non-zero
2631 then +'body2'+ is executed, and so on.
2633 If none of the expressions evaluates to non-zero then +'bodyN'+ is executed.
2635 The +then+ and +else+ arguments are optional "noise words" to make the
2636 command easier to read.
2638 There may be any number of +elseif+ clauses, including zero.  +'bodyN'+
2639 may also be omitted as long as +else+ is omitted too.
2641 The return value from the command is the result of the body script that
2642 was executed, or an empty string if none of the expressions was non-zero
2643 and there was no +'bodyN'+.
2645 incr
2646 ~~~~
2647 +*incr* 'varName ?increment?'+
2649 Increment the value stored in the variable whose name is +'varName'+.
2650 The value of the variable must be integral.
2652 If +'increment'+ is supplied then its value (which must be an
2653 integer) is added to the value of variable +'varName'+;  otherwise
2654 1 is added to +'varName'+.
2656 The new value is stored as a decimal string in variable +'varName'+
2657 and also returned as result.
2659 If the variable does not exist, the variable is implicitly created
2660 and set to +0+ first.
2662 info
2663 ~~~~
2665 +*info* 'option ?arg\...?'+::
2667 Provide information about various internals to the Tcl interpreter.
2668 The legal +'option'+'s (which may be abbreviated) are:
2670 +*info args* 'procname'+::
2671     Returns a list containing the names of the arguments to procedure
2672     +'procname'+, in order.  +'procname'+ must be the name of a
2673     Tcl command procedure.
2675 +*info alias* 'command'+::
2676     +'command'+ must be an alias created with `alias`. In which case the target
2677     command and arguments, as passed to `alias` are returned. See `exists -alias`
2679 +*info body* 'procname'+::
2680     Returns the body of procedure +'procname'+.  +'procname'+ must be
2681     the name of a Tcl command procedure.
2683 +*info channels*+::
2684     Returns a list of all open file handles from `open` or `socket`
2686 +*info commands* ?'pattern'?+::
2687     If +'pattern'+ isn't specified, returns a list of names of all the
2688     Tcl commands, including both the built-in commands written in C and
2689     the command procedures defined using the `proc` command.
2690     If +'pattern'+ is specified, only those names matching +'pattern'+
2691     are returned.  Matching is determined using the same rules as for
2692     `string match`.
2694 +*info complete* 'command' ?'missing'?+::
2695     Returns 1 if +'command'+ is a complete Tcl command in the sense of
2696     having no unclosed quotes, braces, brackets or array element names,
2697     If the command doesn't appear to be complete then 0 is returned.
2698     This command is typically used in line-oriented input environments
2699     to allow users to type in commands that span multiple lines;  if the
2700     command isn't complete, the script can delay evaluating it until additional
2701     lines have been typed to complete the command. If +'varName'+ is specified, the
2702     missing character is stored in the variable with that name.
2704 +*info exists* 'varName'+::
2705     Returns '1' if the variable named +'varName'+ exists in the
2706     current context (either as a global or local variable), returns '0'
2707     otherwise.
2709 +*info frame* ?'number'?+::
2710     If +'number'+ is not specified, this command returns a number
2711     which is the same result as `info level` - the current stack frame level.
2712     If +'number'+ is specified, then the result is a list consisting of the procedure,
2713     filename and line number for the procedure call at level +'number'+ on the stack.
2714     If +'number'+ is positive then it selects a particular stack level (1 refers
2715     to the top-most active procedure, 2 to the procedure it called, and
2716     so on); otherwise it gives a level relative to the current level
2717     (0 refers to the current procedure, -1 to its caller, and so on).
2718     The level has an identical meaning to `info level`.
2720 +*info globals* ?'pattern'?+::
2721     If +'pattern'+ isn't specified, returns a list of all the names
2722     of currently-defined global variables.
2723     If +'pattern'+ is specified, only those names matching +'pattern'+
2724     are returned.  Matching is determined using the same rules as for
2725     `string match`.
2727 +*info hostname*+::
2728     An alias for `os.gethostname` for compatibility with Tcl 6.x
2730 +*info level* ?'number'?+::
2731     If +'number'+ is not specified, this command returns a number
2732     giving the stack level of the invoking procedure, or 0 if the
2733     command is invoked at top-level.  If +'number'+ is specified,
2734     then the result is a list consisting of the name and arguments for the
2735     procedure call at level +'number'+ on the stack.  If +'number'+
2736     is positive then it selects a particular stack level (1 refers
2737     to the top-most active procedure, 2 to the procedure it called, and
2738     so on); otherwise it gives a level relative to the current level
2739     (0 refers to the current procedure, -1 to its caller, and so on).
2740     See the `uplevel` command for more information on what stack
2741     levels mean.
2743 +*info locals* ?'pattern'?+::
2744     If +'pattern'+ isn't specified, returns a list of all the names
2745     of currently-defined local variables, including arguments to the
2746     current procedure, if any.  Variables defined with the `global`
2747     and `upvar` commands will not be returned.  If +'pattern'+ is
2748     specified, only those names matching +'pattern'+ are returned.
2749     Matching is determined using the same rules as for `string match`.
2751 +*info nameofexecutable*+::
2752     Returns the name of the binary file from which the application
2753     was invoked. A full path will be returned, unless the path
2754     can't be determined, in which case the empty string will be returned.
2756 +*info procs* ?'pattern'?+::
2757     If +'pattern'+ isn't specified, returns a list of all the
2758     names of Tcl command procedures.
2759     If +'pattern'+ is specified, only those names matching +'pattern'+
2760     are returned.  Matching is determined using the same rules as for
2761     `string match`.
2763 +*info references*+::
2764     Returns a list of all references which have not yet been garbage
2765     collected.
2767 +*info returncodes* ?'code'?+::
2768     Returns a list representing the mapping of standard return codes
2769     to names. e.g. +{0 ok 1 error 2 return \...}+. If a code is given,
2770     instead returns the name for the given code.
2772 +*info script*+::
2773     If a Tcl script file is currently being evaluated (i.e. there is a
2774     call to 'Jim_EvalFile' active or there is an active invocation
2775     of the `source` command), then this command returns the name
2776     of the innermost file being processed.  Otherwise the command returns an
2777     empty string.
2779 +*info source* 'script ?filename line?'+::
2780     With a single argument, returns the original source location of the given script as a list of
2781     +{filename linenumber}+. If the source location can't be determined, the
2782     list +{{} 0}+ is returned. If +'filename'+ and +'line'+ are given, returns a copy
2783     of +'script'+ with the associate source information. This can be useful to produce
2784     useful messages from `eval`, etc. if the original source information may be lost.
2786 +*info stacktrace*+::
2787     After an error is caught with `catch`, returns the stack trace as a list
2788     of +{procedure filename line \...}+.
2790 +*info statics* 'procname'+::
2791     Returns a dictionary of the static variables of procedure
2792     +'procname'+.  +'procname'+ must be the name of a Tcl command
2793     procedure. An empty dictionary is returned if the procedure has
2794     no static variables.
2796 +*info version*+::
2797     Returns the version number for this version of Jim in the form +*x.yy*+.
2799 +*info vars* ?'pattern'?+::
2800     If +'pattern'+ isn't specified,
2801     returns a list of all the names of currently-visible variables, including
2802     both locals and currently-visible globals.
2803     If +'pattern'+ is specified, only those names matching +'pattern'+
2804     are returned.  Matching is determined using the same rules as for
2805     `string match`.
2807 join
2808 ~~~~
2809 +*join* 'list ?joinString?'+
2811 The +'list'+ argument must be a valid Tcl list.  This command returns the
2812 string formed by joining all of the elements of +'list'+ together with
2813 +'joinString'+ separating each adjacent pair of elements.
2815 The +'joinString'+ argument defaults to a space character.
2817 kill
2818 ~~~~
2819 +*kill* ?'SIG'|*-0*? 'pid'+
2821 Sends the given signal to the process identified by +'pid'+.
2823 The signal may be specified by name or number in one of the following forms:
2825 * +TERM+
2826 * +SIGTERM+
2827 * +-TERM+
2828 * +15+
2829 * +-15+
2831 The signal name may be in either upper or lower case.
2833 The special signal name +-0+ simply checks that a signal +'could'+ be sent.
2835 If no signal is specified, SIGTERM is used.
2837 An error is raised if the signal could not be delivered.
2839 lambda
2840 ~~~~~~
2841 +*lambda* 'args ?statics? body'+
2843 The `lambda` command is identical to `proc`, except rather than
2844 creating a named procedure, it creates an anonymous procedure and returns
2845 the name of the procedure.
2847 See `proc` and GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2849 lappend
2850 ~~~~~~~
2851 +*lappend* 'varName value ?value value \...?'+
2853 Treat the variable given by +'varName'+ as a list and append each of
2854 the +'value'+ arguments to that list as a separate element, with spaces
2855 between elements.
2857 If +'varName'+ doesn't exist, it is created as a list with elements given
2858 by the +'value'+ arguments. `lappend` is similar to `append` except that
2859 each +'value'+ is appended as a list element rather than raw text.
2861 This command provides a relatively efficient way to build up large lists.
2862 For example,
2864     lappend a $b
2866 is much more efficient than
2868     set a [concat $a [list $b]]
2870 when +$a+ is long.
2872 lassign
2873 ~~~~~~~
2874 +*lassign* 'list varName ?varName \...?'+
2876 This command treats the value +'list'+ as a list and assigns successive elements from that list to
2877 the variables given by the +'varName'+ arguments in order. If there are more variable names than
2878 list elements, the remaining variables are set to the empty string. If there are more list elements
2879 than variables, a list of unassigned elements is returned.
2881     jim> lassign {1 2 3} a b; puts a=$a,b=$b
2882     3
2883     a=1,b=2
2885 local
2886 ~~~~~
2887 +*local* 'cmd ?arg\...?'+
2889 First, `local` evaluates +'cmd'+ with the given arguments. The return value must
2890 be the name of an existing command, which is marked as having local scope.
2891 This means that when the current procedure exits, the specified
2892 command is deleted. This can be useful with `lambda`, local procedures or
2893 to automatically close a filehandle.
2895 In addition, if a command already exists with the same name,
2896 the existing command will be kept rather than deleted, and may be called
2897 via `upcall`. The previous command will be restored when the current
2898 procedure exits. See `upcall` for more details.
2900 In this example, a local procedure is created. Note that the procedure
2901 continues to have global scope while it is active.
2903     proc outer {} {
2904       # proc ... returns "inner" which is marked local
2905       local proc inner {} {
2906         # will be deleted when 'outer' exits
2907       }
2909       inner
2910       ...
2911     }
2913 In this example, the lambda is deleted at the end of the procedure rather
2914 than waiting until garbage collection.
2916     proc outer {} {
2917       set x [lambda inner {args} {
2918         # will be deleted when 'outer' exits
2919       }]
2920       # Use 'function' here which simply returns $x
2921       local function $x
2923       $x ...
2924       ...
2925     }
2927 loop
2928 ~~~~
2929 +*loop* 'var first limit ?incr? body'+
2931 Similar to `for` except simpler and possibly more efficient.
2932 With a positive increment, equivalent to:
2934   for {set var $first} {$var < $limit} {incr var $incr} $body
2936 If +'incr'+ is not specified, 1 is used.
2937 Note that setting the loop variable inside the loop does not
2938 affect the loop count.
2940 lindex
2941 ~~~~~~
2942 +*lindex* 'list ?index ...?'+
2944 Treats +'list'+ as a Tcl list and returns element +'index'+ from it
2945 (0 refers to the first element of the list).
2946 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2948 In extracting the element, +'lindex'+ observes the same rules concerning
2949 braces and quotes and backslashes as the Tcl command interpreter; however,
2950 variable substitution and command substitution do not occur.
2952 If no index values are given, simply returns +'list'+
2954 If +'index'+ is negative or greater than or equal to the number of elements
2955 in +'list'+, then an empty string is returned.
2957 If additional index arguments are supplied, then each argument is
2958 used in turn to select an element from the previous indexing
2959 operation, allowing the script to select elements from sublists.
2961 linsert
2962 ~~~~~~~
2963 +*linsert* 'list index element ?element element \...?'+
2965 This command produces a new list from +'list'+ by inserting all
2966 of the +'element'+ arguments just before the element +'index'+
2967 of +'list'+. Each +'element'+ argument will become
2968 a separate element of the new list. If +'index'+ is less than
2969 or equal to zero, then the new elements are inserted at the
2970 beginning of the list. If +'index'+ is greater than or equal
2971 to the number of elements in the list, then the new elements are
2972 appended to the list.
2974 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2976 list
2977 ~~~~
2979 +*list* 'arg ?arg \...?'+
2981 This command returns a list comprised of all the arguments, +'arg'+. Braces
2982 and backslashes get added as necessary, so that the `lindex` command
2983 may be used on the result to re-extract the original arguments, and also
2984 so that `eval` may be used to execute the resulting list, with
2985 +'arg1'+ comprising the command's name and the other args comprising
2986 its arguments. `list` produces slightly different results than
2987 `concat`:  `concat` removes one level of grouping before forming
2988 the list, while `list` works directly from the original arguments.
2989 For example, the command
2991     list a b {c d e} {f {g h}}
2993 will return
2995     a b {c d e} {f {g h}}
2997 while `concat` with the same arguments will return
2999     a b c d e f {g h}
3001 llength
3002 ~~~~~~~
3003 +*llength* 'list'+
3005 Treats +'list'+ as a list and returns a decimal string giving
3006 the number of elements in it.
3008 lset
3009 ~~~~
3010 +*lset* 'varName ?index ..? newValue'+
3012 Sets an element in a list.
3014 The `lset` command accepts a parameter, +'varName'+, which it interprets
3015 as the name of a variable containing a Tcl list. It also accepts
3016 zero or more indices into the list. Finally, it accepts a new value
3017 for an element of varName. If no indices are presented, the command
3018 takes the form:
3020     lset varName newValue
3022 In this case, newValue replaces the old value of the variable
3023 varName.
3025 When presented with a single index, the `lset` command
3026 treats the content of the varName variable as a Tcl list. It addresses
3027 the index'th element in it (0 refers to the first element of the
3028 list). When interpreting the list, `lset` observes the same rules
3029 concerning braces and quotes and backslashes as the Tcl command
3030 interpreter; however, variable substitution and command substitution
3031 do not occur. The command constructs a new list in which the
3032 designated element is replaced with newValue. This new list is
3033 stored in the variable varName, and is also the return value from
3034 the `lset` command.
3036 If index is negative or greater than or equal to the number of
3037 elements in $varName, then an error occurs.
3039 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
3041 If additional index arguments are supplied, then each argument is
3042 used in turn to address an element within a sublist designated by
3043 the previous indexing operation, allowing the script to alter
3044 elements in sublists. The command,
3046     lset a 1 2 newValue
3048 replaces element 2 of sublist 1 with +'newValue'+.
3050 The integer appearing in each index argument must be greater than
3051 or equal to zero. The integer appearing in each index argument must
3052 be strictly less than the length of the corresponding list. In other
3053 words, the `lset` command cannot change the size of a list. If an
3054 index is outside the permitted range, an error is reported.
3056 lmap
3057 ~~~~
3059 +*lmap* 'varName list body'+
3061 +*lmap* 'varList list ?varList2 list2 \...? body'+
3063 `lmap` is a "collecting" `foreach` which returns a list of its results.
3065 For example:
3067     jim> lmap i {1 2 3 4 5} {expr $i*$i}
3068     1 4 9 16 25
3069     jim> lmap a {1 2 3} b {A B C} {list $a $b}
3070     {1 A} {2 B} {3 C}
3072 If the body invokes `continue`, no value is added for this iteration.
3073 If the body invokes `break`, the loop ends and no more values are added.
3075 load
3076 ~~~~
3077 +*load* 'filename'+
3079 Loads the dynamic extension, +'filename'+. Generally the filename should have
3080 the extension +.so+. The initialisation function for the module must be based
3081 on the name of the file. For example loading +hwaccess.so+ will invoke
3082 the initialisation function, +Jim_hwaccessInit+. Normally the `load` command
3083 should not be used directly. Instead it is invoked automatically by `package require`.
3085 lrange
3086 ~~~~~~
3087 +*lrange* 'list first last'+
3089 +'list'+ must be a valid Tcl list. This command will return a new
3090 list consisting of elements +'first'+ through +'last'+, inclusive.
3092 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
3094 If +'last'+ is greater than or equal to the number of elements
3095 in the list, then it is treated as if it were +end+.
3097 If +'first'+ is greater than +'last'+ then an empty string
3098 is returned.
3100 Note: +"`lrange` 'list first first'"+ does not always produce the
3101 same result as +"`lindex` 'list first'"+ (although it often does
3102 for simple fields that aren't enclosed in braces); it does, however,
3103 produce exactly the same results as +"`list` [`lindex` 'list first']"+
3105 lreplace
3106 ~~~~~~~~
3108 +*lreplace* 'list first last ?element element \...?'+
3110 Returns a new list formed by replacing one or more elements of
3111 +'list'+ with the +'element'+ arguments.
3113 +'first'+ gives the index in +'list'+ of the first element
3114 to be replaced.
3116 If +'first'+ is less than zero then it refers to the first
3117 element of +'list'+;  the element indicated by +'first'+
3118 must exist in the list.
3120 +'last'+ gives the index in +'list'+ of the last element
3121 to be replaced;  it must be greater than or equal to +'first'+.
3123 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
3125 The +'element'+ arguments specify zero or more new arguments to
3126 be added to the list in place of those that were deleted.
3128 Each +'element'+ argument will become a separate element of
3129 the list.
3131 If no +'element'+ arguments are specified, then the elements
3132 between +'first'+ and +'last'+ are simply deleted.
3134 lrepeat
3135 ~~~~~~~~
3136 +*lrepeat* 'number element1 ?element2 \...?'+
3138 Build a list by repeating elements +'number'+ times (which must be
3139 a positive integer).
3141     jim> lrepeat 3 a b
3142     a b a b a b
3144 lreverse
3145 ~~~~~~~~
3146 +*lreverse* 'list'+
3148 Returns the list in reverse order.
3150     jim> lreverse {1 2 3}
3151     3 2 1
3153 lsearch
3154 ~~~~~~~
3155 +*lsearch* '?options? list pattern'+
3157 This command searches the elements +'list'+ to see if one of them matches +'pattern'+. If so, the
3158 command returns the index of the first matching element (unless the options +-all+, +-inline+ or +-bool+ are
3159 specified.) If not, the command returns -1. The option arguments indicates how the elements of
3160 the list are to be matched against pattern and must have one of the values below:
3162 *Note* that this command is different from Tcl in that default match type is +-exact+ rather than +-glob+.
3164 +*-exact*+::
3165     +'pattern'+ is a literal string that is compared for exact equality against each list element.
3166     This is the default.
3168 +*-glob*+::
3169     +'pattern'+ is a glob-style pattern which is matched against each list element using the same
3170     rules as the string match command.
3172 +*-regexp*+::
3173     +'pattern'+ is treated as a regular expression and matched against each list element using
3174     the rules described by `regexp`.
3176 +*-command* 'cmdname'+::
3177     +'cmdname'+ is a command which is used to match the pattern against each element of the
3178     list. It is invoked as +'cmdname' ?*-nocase*? 'pattern listvalue'+ and should return 1
3179     for a match, or 0 for no match.
3181 +*-all*+::
3182     Changes the result to be the list of all matching indices (or all matching values if
3183     +-inline+ is specified as well). If indices are returned, the indices will be in numeric
3184     order. If values are returned, the order of the values will be the order of those values
3185     within the input list.
3187 +*-inline*+::
3188     The matching value is returned instead of its index (or an empty string if no value
3189     matches). If +-all+ is also specified, then the result of the command is the list of all
3190     values that matched. The +-inline+ and +-bool+ options are mutually exclusive.
3192 +*-bool*+::
3193     Changes the result to '1' if a match was found, or '0' otherwise. If +-all+ is also specified,
3194     the result will be a list of '0' and '1' for each element of the list depending upon whether
3195     the corresponding element matches. The +-inline+ and +-bool+ options are mutually exclusive.
3197 +*-not*+::
3198     This negates the sense of the match, returning the index (or value
3199     if +-inline+ is specified) of the first non-matching value in the
3200     list. If +-bool+ is also specified, the '0' will be returned if a
3201     match is found, or '1' otherwise. If +-all+ is also specified,
3202     non-matches will be returned rather than matches.
3204 +*-nocase*+::
3205     Causes comparisons to be handled in a case-insensitive manner.
3207 lsort
3208 ~~~~~
3209 +*lsort* ?*-index* 'listindex'? ?*-nocase|-integer|-real|-command* 'cmdname'? ?*-unique*? ?*-decreasing*|*-increasing*? 'list'+
3211 Sort the elements of +'list'+, returning a new list in sorted order.
3212 By default, ASCII (or UTF-8) sorting is used, with the result in increasing order.
3214 If +-nocase+ is specified, comparisons are case-insensitive.
3216 If +-integer+ is specified, numeric sorting is used.
3218 If +-real+ is specified, floating point number sorting is used.
3220 If +-command 'cmdname'+ is specified, +'cmdname'+ is treated as a command
3221 name. For each comparison, +'cmdname $value1 $value2+' is called which
3222 should compare the values and return an integer less than, equal
3223 to, or greater than zero if the +'$value1'+ is to be considered less
3224 than, equal to, or greater than +'$value2'+, respectively.
3226 If +-decreasing+ is specified, the resulting list is in the opposite
3227 order to what it would be otherwise. +-increasing+ is the default.
3229 If +-unique+ is specified, then only the last set of duplicate elements found in the list will be retained.
3230 Note that duplicates are determined relative to the comparison used in the sort. Thus if +-index 0+ is used,
3231 +{1 a}+ and +{1 b}+ would be considered duplicates and only the second element, +{1 b}+, would be retained.
3233 If +-index 'listindex'+ is specified, each element of the list is treated as a list and
3234 the given index is extracted from the list for comparison. The list index may
3235 be any valid list index, such as +1+, +end+ or +end-2+.
3237 open
3238 ~~~~
3239 +*open* 'fileName ?access?'+
3241 +*open* '|command-pipeline ?access?'+
3243 Opens a file and returns an identifier
3244 that may be used in future invocations
3245 of commands like `read`, `puts`, and `close`.
3246 +'fileName'+ gives the name of the file to open.
3248 The +'access'+ argument indicates the way in which the file is to be accessed.
3249 It may have any of the following values:
3251 +r+::
3252     Open the file for reading only; the file must already exist.
3254 +r++::
3255     Open the file for both reading and writing; the file must
3256     already exist.
3258 +w+::
3259     Open the file for writing only. Truncate it if it exists. If it doesn't
3260     exist, create a new file.
3262 +w++::
3263     Open the file for reading and writing. Truncate it if it exists.
3264     If it doesn't exist, create a new file.
3266 +a+::
3267     Open the file for writing only. The file must already exist, and the file
3268     is positioned so that new data is appended to the file.
3270 +a++::
3271     Open the file for reading and writing. If the file doesn't
3272     exist, create a new empty file. Set the initial access position
3273     to the end of the file.
3275 +'access'+ defaults to 'r'.
3277 If a file is opened for both reading and writing, then `seek`
3278 must be invoked between a read and a write, or vice versa.
3280 If the first character of +'fileName'+ is "|" then the remaining
3281 characters of +'fileName'+ are treated as a list of arguments that
3282 describe a command pipeline to invoke, in the same style as the
3283 arguments for exec. In this case, the channel identifier returned
3284 by open may be used to write to the command's input pipe or read
3285 from its output pipe, depending on the value of +'access'+. If write-only
3286 access is used (e.g. +'access'+ is 'w'), then standard output for the
3287 pipeline is directed to the current standard output unless overridden
3288 by the command. If read-only access is used (e.g. +'access'+ is r),
3289 standard input for the pipeline is taken from the current standard
3290 input unless overridden by the command.
3292 The `pid` command may be used to return the process ids of the commands
3293 forming the command pipeline.
3295 See also `socket`, `pid`, `exec`
3297 package
3298 ~~~~~~~
3299 +*package provide* 'name ?version?'+
3301 Indicates that the current script provides the package named +'name'+.
3302 If no version is specified, '1.0' is used.
3304 Any script which provides a package may include this statement
3305 as the first statement, although it is not required.
3307 +*package require* 'name ?version?'*+
3309 Searches for the package with the given +'name'+ by examining each path
3310 in '$::auto_path' and trying to load '$path/$name.so' as a dynamic extension,
3311 or '$path/$name.tcl' as a script package.
3313 The first such file which is found is considered to provide the package.
3314 (The version number is ignored).
3316 If '$name.so' exists, it is loaded with the `load` command,
3317 otherwise if '$name.tcl' exists it is loaded with the `source` command.
3319 If `load` or `source` fails, `package require` will fail immediately.
3320 No further attempt will be made to locate the file.
3324 +*pid*+
3326 +*pid* 'fileId'+
3328 The first form returns the process identifier of the current process.
3330 The second form accepts a handle returned by `open` and returns a list
3331 of the process ids forming the pipeline in the same form as `exec ... &`.
3332 If 'fileId' represents a regular file handle rather than a command pipeline,
3333 the empty string is returned instead.
3335 See also `open`, `exec`
3337 proc
3338 ~~~~
3339 +*proc* 'name args ?statics? body'+
3341 The `proc` command creates a new Tcl command procedure, +'name'+.
3342 When the new command is invoked, the contents of +'body'+ will be executed.
3343 Tcl interpreter. +'args'+ specifies the formal arguments to the procedure.
3344 If specified, +'statics'+, declares static variables which are bound to the
3345 procedure.
3347 See PROCEDURES for detailed information about Tcl procedures.
3349 The `proc` command returns +'name'+ (which is useful with `local`).
3351 When a procedure is invoked, the procedure's return value is the
3352 value specified in a `return` command.  If the procedure doesn't
3353 execute an explicit `return`, then its return value is the value
3354 of the last command executed in the procedure's body.
3356 If an error occurs while executing the procedure body, then the
3357 procedure-as-a-whole will return that same error.
3359 puts
3360 ~~~~
3361 +*puts* ?*-nonewline*? '?fileId? string'+
3363 +'fileId' *puts* ?*-nonewline*? 'string'+
3365 Writes the characters given by +'string'+ to the file given
3366 by +'fileId'+. +'fileId'+ must have been the return
3367 value from a previous call to `open`, or it may be
3368 +stdout+ or +stderr+ to refer to one of the standard I/O
3369 channels; it must refer to a file that was opened for
3370 writing.
3372 In the first form, if no +'fileId'+ is specified then it defaults to +stdout+.
3373 `puts` normally outputs a newline character after +'string'+,
3374 but this feature may be suppressed by specifying the +-nonewline+
3375 switch.
3377 Output to files is buffered internally by Tcl; the `flush`
3378 command may be used to force buffered characters to be output.
3382 +*pwd*+
3384 Returns the path name of the current working directory.
3386 rand
3387 ~~~~
3388 +*rand* '?min? ?max?'+
3390 Returns a random integer between +'min'+ (defaults to 0) and +'max'+
3391 (defaults to the maximum integer).
3393 If only one argument is given, it is interpreted as +'max'+.
3395 range
3396 ~~~~
3397 +*range* '?start? end ?step?'+
3399 Returns a list of integers starting at +'start'+ (defaults to 0)
3400 and ranging up to but not including +'end'+ in steps of +'step'+ defaults to 1).
3402     jim> range 5
3403     0 1 2 3 4
3404     jim> range 2 5
3405     2 3 4
3406     jim> range 2 10 4
3407     2 6
3408     jim> range 7 4 -2
3409     7 5
3411 read
3412 ~~~~
3413 +*read* ?*-nonewline*? 'fileId'+
3415 +'fileId' *read* ?*-nonewline*?+
3417 +*read* 'fileId numBytes'+
3419 +'fileId' *read* 'numBytes'+
3422 In the first form, all of the remaining bytes are read from the file
3423 given by +'fileId'+; they are returned as the result of the command.
3424 If the +-nonewline+ switch is specified then the last
3425 character of the file is discarded if it is a newline.
3427 In the second form, the extra argument specifies how many bytes to read;
3428 exactly this many bytes will be read and returned, unless there are fewer than
3429 +'numBytes'+ bytes left in the file; in this case, all the remaining
3430 bytes are returned.
3432 +'fileId'+ must be +stdin+ or the return value from a previous call
3433 to `open`; it must refer to a file that was opened for reading.
3435 regexp
3436 ~~~~~~
3437 +*regexp ?-nocase? ?-line? ?-indices? ?-start* 'offset'? *?-all? ?-inline? ?--?* 'exp string ?matchVar? ?subMatchVar subMatchVar \...?'+
3439 Determines whether the regular expression +'exp'+ matches part or
3440 all of +'string'+ and returns 1 if it does, 0 if it doesn't.
3442 See REGULAR EXPRESSIONS above for complete information on the
3443 syntax of +'exp'+ and how it is matched against +'string'+.
3445 If additional arguments are specified after +'string'+ then they
3446 are treated as the names of variables to use to return
3447 information about which part(s) of +'string'+ matched +'exp'+.
3448 +'matchVar'+ will be set to the range of +'string'+ that
3449 matched all of +'exp'+. The first +'subMatchVar'+ will contain
3450 the characters in +'string'+ that matched the leftmost parenthesized
3451 subexpression within +'exp'+, the next +'subMatchVar'+ will
3452 contain the characters that matched the next parenthesized
3453 subexpression to the right in +'exp'+, and so on.
3455 Normally, +'matchVar'+ and the each +'subMatchVar'+ are set to hold the
3456 matching characters from `string`, however see +-indices+ and
3457 +-inline+ below.
3459 If there are more values for +'subMatchVar'+ than parenthesized subexpressions
3460 within +'exp'+, or if a particular subexpression in +'exp'+ doesn't
3461 match the string (e.g. because it was in a portion of the expression
3462 that wasn't matched), then the corresponding +'subMatchVar'+ will be
3463 set to +"-1 -1"+ if +-indices+ has been specified or to an empty
3464 string otherwise.
3466 The following switches modify the behaviour of +'regexp'+
3468 +*-nocase*+::
3469     Causes upper-case and lower-case characters to be treated as
3470     identical during the matching process.
3472 +*-line*+::
3473     Use newline-sensitive matching. By default, newline
3474     is a completely ordinary character with no special meaning in
3475     either REs or strings. With this flag, +[^+ bracket expressions
3476     and +.+ never match newline, an +^+ anchor matches the null
3477     string after any newline in the string in addition to its normal
3478     function, and the +$+ anchor matches the null string before any
3479     newline in the string in addition to its normal function.
3481 +*-indices*+::
3482     Changes what is stored in the subMatchVars. Instead of
3483     storing the matching characters from string, each variable
3484     will contain a list of two decimal strings giving the indices
3485     in string of the first and last characters in the matching
3486     range of characters.
3488 +*-start* 'offset'+::
3489     Specifies a character index offset into the string at which to start
3490     matching the regular expression. If +-indices+ is
3491     specified, the indices will be indexed starting from the
3492     absolute beginning of the input string. +'offset'+ will be
3493     constrained to the bounds of the input string.
3495 +*-all*+::
3496     Causes the regular expression to be matched as many times as possible
3497     in the string, returning the total number of matches found. If this
3498     is specified with match variables, they will contain information
3499     for the last match only.
3501 +*-inline*+::
3502     Causes the command to return, as a list, the data that would otherwise
3503     be placed in match variables. When using +-inline+, match variables
3504     may not be specified. If used with +-all+, the list will be concatenated
3505     at each iteration, such that a flat list is always returned. For
3506     each match iteration, the command will append the overall match
3507     data, plus one element for each subexpression in the regular
3508     expression.
3510 +*--*+::
3511     Marks the end of switches. The argument following this one will be
3512     treated as +'exp'+ even if it starts with a +-+.
3514 regsub
3515 ~~~~~~
3516 +*regsub ?-nocase? ?-all? ?-line? ?-start* 'offset'? ?*--*? 'exp string subSpec ?varName?'+
3518 This command matches the regular expression +'exp'+ against
3519 +'string'+ using the rules described in REGULAR EXPRESSIONS
3520 above.
3522 If +'varName'+ is specified, the commands stores +'string'+ to +'varName'+
3523 with the substitutions detailed below, and returns the number of
3524 substitutions made (normally 1 unless +-all+ is specified).
3525 This is 0 if there were no matches.
3527 If +'varName'+ is not specified, the substituted string will be returned
3528 instead.
3530 When copying +'string'+, the portion of +'string'+ that
3531 matched +'exp'+ is replaced with +'subSpec'+.
3532 If +'subSpec'+ contains a +&+ or +{backslash}0+, then it is replaced
3533 in the substitution with the portion of +'string'+ that
3534 matched +'exp'+.
3536 If +'subSpec'+ contains a +{backslash}n+, where +'n'+ is a digit
3537 between 1 and 9, then it is replaced in the substitution with
3538 the portion of +'string'+ that matched the +'n'+\'-th
3539 parenthesized subexpression of +'exp'+.
3540 Additional backslashes may be used in +'subSpec'+ to prevent special
3541 interpretation of +&+ or +{backslash}0+ or +{backslash}n+ or
3542 backslash.
3544 The use of backslashes in +'subSpec'+ tends to interact badly
3545 with the Tcl parser's use of backslashes, so it's generally
3546 safest to enclose +'subSpec'+ in braces if it includes
3547 backslashes.
3549 The following switches modify the behaviour of +'regsub'+
3551 +*-nocase*+::
3552     Upper-case characters in +'string'+ are converted to lower-case
3553     before matching against +'exp'+;  however, substitutions
3554     specified by +'subSpec'+ use the original unconverted form
3555     of +'string'+.
3557 +*-all*+::
3558     All ranges in +'string'+ that match +'exp'+ are found and substitution
3559     is performed for each of these ranges, rather than only the
3560     first. The +&+ and +{backslash}n+ sequences are handled for
3561     each substitution using the information from the corresponding
3562     match.
3564 +*-line*+::
3565     Use newline-sensitive matching. By default, newline
3566     is a completely ordinary character with no special meaning in
3567     either REs or strings.  With this flag, +[^+ bracket expressions
3568     and +.+ never match newline, an +^+ anchor matches the null
3569     string after any newline in the string in addition to its normal
3570     function, and the +$+ anchor matches the null string before any
3571     newline in the string in addition to its normal function.
3573 +*-start* 'offset'+::
3574     Specifies a character index offset into the string at which to
3575     start matching the regular expression. +'offset'+ will be
3576     constrained to the bounds of the input string.
3578 +*--*+::
3579     Marks the end of switches. The argument following this one will be
3580     treated as +'exp'+ even if it starts with a +-+.
3584 +*ref* 'string tag ?finalizer?'+
3586 Create a new reference containing +'string'+ of type +'tag'+.
3587 If +'finalizer'+ is specified, it is a command which will be invoked
3588 when the a garbage collection cycle runs and this reference is
3589 no longer accessible.
3591 The finalizer is invoked as:
3593   finalizer reference string
3595 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
3597 rename
3598 ~~~~~~
3599 +*rename* 'oldName newName'+
3601 Rename the command that used to be called +'oldName'+ so that it
3602 is now called +'newName'+.  If +'newName'+ is an empty string
3603 (e.g. {}) then +'oldName'+ is deleted.  The `rename` command
3604 returns an empty string as result.
3606 return
3607 ~~~~~~
3608 +*return* ?*-code* 'code'? ?*-errorinfo* 'stacktrace'? ?*-errorcode* 'errorcode'? ?*-level* 'n'? ?'value'?+
3610 Return immediately from the current procedure (or top-level command
3611 or `source` command), with +'value'+ as the return value.  If +'value'+
3612 is not specified, an empty string will be returned as result.
3614 If +-code+ is specified (as either a number or ok, error, break,
3615 continue, signal, return or exit), this code will be used instead
3616 of +JIM_OK+. This is generally useful when implementing flow of control
3617 commands.
3619 If +-level+ is specified and greater than 1, it has the effect of delaying
3620 the new return code from +-code+. This is useful when rethrowing an error
3621 from `catch`. See the implementation of try/catch in tclcompat.tcl for
3622 an example of how this is done.
3624 Note: The following options are only used when +-code+ is JIM_ERR.
3626 If +-errorinfo+ is specified (as returned from `info stacktrace`)
3627 it is used to initialize the stacktrace.
3629 If +-errorcode+ is specified, it is used to set the global variable $::errorCode.
3631 scan
3632 ~~~~
3633 +*scan* 'string format varName1 ?varName2 \...?'+
3635 This command parses fields from an input string in the same fashion
3636 as the C 'sscanf' procedure.  +'string'+ gives the input to be parsed
3637 and +'format'+ indicates how to parse it, using '%' fields as in
3638 'sscanf'.  All of the 'sscanf' options are valid; see the 'sscanf'
3639 man page for details.  Each +'varName'+ gives the name of a variable;
3640 when a field is scanned from +'string'+, the result is converted back
3641 into a string and assigned to the corresponding +'varName'+.  The
3642 only unusual conversion is for '%c'.  For '%c' conversions a single
3643 character value is converted to a decimal string, which is then
3644 assigned to the corresponding +'varName'+; no field width may be
3645 specified for this conversion.
3647 seek
3648 ~~~~
3649 +*seek* 'fileId offset ?origin?'+
3651 +'fileId' *seek* 'offset ?origin?'+
3653 Change the current access position for +'fileId'+.
3654 The +'offset'+ and +'origin'+ arguments specify the position at
3655 which the next read or write will occur for +'fileId'+.
3656 +'offset'+ must be a number (which may be negative) and +'origin'+
3657 must be one of the following:
3659 +*start*+::
3660     The new access position will be +'offset'+ bytes from the start
3661     of the file.
3663 +*current*+::
3664     The new access position will be +'offset'+ bytes from the current
3665     access position; a negative +'offset'+ moves the access position
3666     backwards in the file.
3668 +*end*+::
3669     The new access position will be +'offset'+ bytes from the end of
3670     the file.  A negative +'offset'+ places the access position before
3671     the end-of-file, and a positive +'offset'+ places the access position
3672     after the end-of-file.
3674 The +'origin'+ argument defaults to +start+.
3676 +'fileId'+ must have been the return value from a previous call to
3677 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
3678 of the standard I/O channels.
3680 This command returns an empty string.
3684 +*set* 'varName ?value?'+
3686 Returns the value of variable +'varName'+.
3688 If +'value'+ is specified, then set the value of +'varName'+ to +'value'+,
3689 creating a new variable if one doesn't already exist, and return
3690 its value.
3692 If +'varName'+ contains an open parenthesis and ends with a
3693 close parenthesis, then it refers to an array element:  the characters
3694 before the open parenthesis are the name of the array, and the characters
3695 between the parentheses are the index within the array.
3696 Otherwise +'varName'+ refers to a scalar variable.
3698 If no procedure is active, then +'varName'+ refers to a global
3699 variable.
3701 If a procedure is active, then +'varName'+ refers to a parameter
3702 or local variable of the procedure, unless the +'global'+ command
3703 has been invoked to declare +'varName'+ to be global.
3705 The +::+ prefix may also be used to explicitly reference a variable
3706 in the global scope.
3708 setref
3709 ~~~~~~
3710 +*setref* 'reference string'+
3712 Store a new string in +'reference'+, replacing the existing string.
3713 The reference must be a valid reference create with the `ref`
3714 command.
3716 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
3718 signal
3719 ~~~~~~
3720 Command for signal handling.
3722 See `kill` for the different forms which may be used to specify signals.
3724 Commands which return a list of signal names do so using the canonical form:
3725 "+SIGINT SIGTERM+".
3727 +*signal handle* ?'signals \...'?+::
3728     If no signals are given, returns a list of all signals which are currently
3729     being handled.
3730     If signals are specified, these are added to the list of signals currently
3731     being handled.
3733 +*signal ignore* ?'signals \...'?+::
3734     If no signals are given, returns a lists all signals which are currently
3735     being ignored.
3736     If signals are specified, these are added to the list of signals
3737     currently being ignored. These signals are still delivered, but
3738     are not considered by `catch -signal` or `try -signal`. Use
3739     `signal check` to determine which signals have occurred but
3740     been ignored.
3742 +*signal default* ?'signals \...'?+::
3743     If no signals are given, returns a lists all signals which are currently have
3744     the default behaviour.
3745     If signals are specified, these are added to the list of signals which have
3746     the default behaviour.
3748 +*signal check ?-clear?* ?'signals \...'?+::
3749     Returns a list of signals which have been delivered to the process
3750     but are 'ignored'. If signals are specified, only that set of signals will
3751     be checked, otherwise all signals will be checked.
3752     If +-clear+ is specified, any signals returned are removed and will not be
3753     returned by subsequent calls to `signal check` unless delivered again.
3755 +*signal throw* ?'signal'?+::
3756     Raises the given signal, which defaults to +SIGINT+ if not specified.
3757     The behaviour is identical to:
3759         kill signal [pid]
3761 Note that `signal handle` and `signal ignore` represent two forms of signal
3762 handling. `signal handle` is used in conjunction with `catch -signal` or `try -signal`
3763 to immediately abort execution when the signal is delivered. Alternatively, `signal ignore`
3764 is used in conjunction with `signal check` to handle signal synchronously. Consider the
3765 two examples below.
3767 Prevent a processing from taking too long
3769     signal handle SIGALRM
3770     alarm 20
3771     try -signal {
3772         .. possibly long running process ..
3773         alarm 0
3774     } on signal {sig} {
3775         puts stderr "Process took too long"
3776     }
3778 Handle SIGHUP to reconfigure:
3780     signal ignore SIGHUP
3781     while {1} {
3782         ... handle configuration/reconfiguration ...
3783         while {[signal check -clear SIGHUP] eq ""} {
3784             ... do processing ..
3785         }
3786         # Received SIGHUP, so reconfigure
3787     }
3789 Note: signal handling is currently not supported in child interpreters.
3790 In these interpreters, the signal command does not exist.
3792 sleep
3793 ~~~~~
3794 +*sleep* 'seconds'+
3796 Pauses for the given number of seconds, which may be a floating
3797 point value less than one to sleep for less than a second, or an
3798 integer to sleep for one or more seconds.
3800 source
3801 ~~~~~~
3802 +*source* 'fileName'+
3804 Read file +'fileName'+ and pass the contents to the Tcl interpreter
3805 as a sequence of commands to execute in the normal fashion.  The return
3806 value of `source` is the return value of the last command executed
3807 from the file.  If an error occurs in executing the contents of the
3808 file, then the `source` command will return that error.
3810 If a `return` command is invoked from within the file, the remainder of
3811 the file will be skipped and the `source` command will return
3812 normally with the result from the `return` command.
3814 split
3815 ~~~~~
3816 +*split* 'string ?splitChars?'+
3818 Returns a list created by splitting +'string'+ at each character
3819 that is in the +'splitChars'+ argument.
3821 Each element of the result list will consist of the
3822 characters from +'string'+ between instances of the
3823 characters in +'splitChars'+.
3825 Empty list elements will be generated if +'string'+ contains
3826 adjacent characters in +'splitChars'+, or if the first or last
3827 character of +'string'+ is in +'splitChars'+.
3829 If +'splitChars'+ is an empty string then each character of
3830 +'string'+ becomes a separate element of the result list.
3832 +'splitChars'+ defaults to the standard white-space characters.
3833 For example,
3835     split "comp.unix.misc" .
3837 returns +'"comp unix misc"'+ and
3839     split "Hello world" {}
3841 returns +'"H e l l o { } w o r l d"'+.
3843 stackdump
3844 ~~~~~~~~~
3846 +*stackdump* 'stacktrace'+
3848 Creates a human readable representation of a stack trace.
3850 stacktrace
3851 ~~~~~~~~~~
3853 +*stacktrace*+
3855 Returns a live stack trace as a list of +proc file line proc file line \...+.
3856 Iteratively uses `info frame` to create the stack trace. This stack trace is in the
3857 same form as produced by `catch` and `info stacktrace`
3859 See also `stackdump`.
3861 string
3862 ~~~~~~
3864 +*string* 'option arg ?arg \...?'+
3866 Perform one of several string operations, depending on +'option'+.
3867 The legal options (which may be abbreviated) are:
3869 +*string bytelength* 'string'+::
3870     Returns the length of the string in bytes. This will return
3871     the same value as `string length` if UTF-8 support is not enabled,
3872     or if the string is composed entirely of ASCII characters.
3873     See UTF-8 AND UNICODE.
3875 +*string byterange* 'string first last'+::
3876     Like `string range` except works on bytes rather than characters.
3877     These commands are identical if UTF-8 support is not enabled.
3879 +*string cat* '?string1 string2 \...?'+::
3880     Concatenates the given strings into a single string.
3882 +*string compare ?-nocase?* ?*-length* 'len? string1 string2'+::
3883     Perform a character-by-character comparison of strings +'string1'+ and
3884     +'string2'+ in the same way as the C 'strcmp' procedure.  Return
3885     -1, 0, or 1, depending on whether +'string1'+ is lexicographically
3886     less than, equal to, or greater than +'string2'+. If +-length+
3887     is specified, then only the first +'len'+ characters are used
3888     in the comparison.  If +'len'+ is negative, it is ignored.
3889     Performs a case-insensitive comparison if +-nocase+ is specified.
3891 +*string equal ?-nocase?* '?*-length* len?' 'string1 string2'+::
3892     Returns 1 if the strings are equal, or 0 otherwise. If +-length+
3893     is specified, then only the first +'len'+ characters are used
3894     in the comparison.  If +'len'+ is negative, it is ignored.
3895     Performs a case-insensitive comparison if +-nocase+ is specified.
3897 +*string first* 'string1 string2 ?firstIndex?'+::
3898     Search +'string2'+ for a sequence of characters that exactly match
3899     the characters in +'string1'+.  If found, return the index of the
3900     first character in the first such match within +'string2'+.  If not
3901     found, return -1. If +'firstIndex'+ is specified, matching will start
3902     from +'firstIndex'+ of +'string1'+.
3903  ::
3904     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'firstIndex'+.
3906 +*string index* 'string charIndex'+::
3907     Returns the +'charIndex'+'th character of the +'string'+
3908     argument.  A +'charIndex'+ of 0 corresponds to the first
3909     character of the string.
3910     If +'charIndex'+ is less than 0 or greater than
3911     or equal to the length of the string then an empty string is
3912     returned.
3913  ::
3914     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'charIndex'+.
3916 +*string is* 'class' ?*-strict*? 'string'+::
3917     Returns 1 if +'string'+ is a valid member of the specified character
3918     class, otherwise returns 0. If +-strict+ is specified, then an
3919     empty string returns 0, otherwise an empty string will return 1
3920     on any class. The following character classes are recognized
3921     (the class name can be abbreviated):
3922   ::
3923   +alnum+;;  Any alphabet or digit character.
3924   +alpha+;;  Any alphabet character.
3925   +ascii+;;  Any character with a value less than 128 (those that are in the 7-bit ascii range).
3926   +boolean+;;  Any of the valid string formats for a boolean value in Tcl (0, false, no, off, 1, true, yes, on)
3927   +control+;; Any control character.
3928   +digit+;;  Any digit character.
3929   +double+;; Any of the valid forms for a double in Tcl, with optional surrounding whitespace.
3930              In case of under/overflow in the value, 0 is returned.
3931   +graph+;;  Any printing character, except space.
3932   +integer+;; Any of the valid string formats for an integer value in Tcl, with optional surrounding whitespace.
3933   +lower+;;  Any lower case alphabet character.
3934   +print+;;  Any printing character, including space.
3935   +punct+;;  Any punctuation character.
3936   +space+;;  Any space character.
3937   +upper+;;  Any upper case alphabet character.
3938   +xdigit+;; Any hexadecimal digit character ([0-9A-Fa-f]).
3939  ::
3940     Note that string classification does +'not'+ respect UTF-8. See UTF-8 AND UNICODE
3941  ::
3942     Note that only +'lowercase'+ boolean values are recognized (Tcl accepts any case).
3944 +*string last* 'string1 string2 ?lastIndex?'+::
3945     Search +'string2'+ for a sequence of characters that exactly match
3946     the characters in +'string1'+.  If found, return the index of the
3947     first character in the last such match within +'string2'+.  If there
3948     is no match, then return -1. If +'lastIndex'+ is specified, only characters
3949     up to +'lastIndex'+ of +'string2'+ will be considered in the match.
3950  ::
3951     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'lastIndex'+.
3953 +*string length* 'string'+::
3954     Returns a decimal string giving the number of characters in +'string'+.
3955     If UTF-8 support is enabled, this may be different than the number of bytes.
3956     See UTF-8 AND UNICODE
3958 +*string map ?-nocase?* 'mapping string'+::
3959     Replaces substrings in +'string'+ based on the key-value pairs in
3960     +'mapping'+, which is a list of +key value key value \...+ as in the form
3961     returned by `array get`. Each instance of a key in the string will be
3962     replaced with its corresponding value.  If +-nocase+ is specified, then
3963     matching is done without regard to case differences. Both key and value may
3964     be multiple characters.  Replacement is done in an ordered manner, so the
3965     key appearing first in the list will be checked first, and so on. +'string'+ is
3966     only iterated over once, so earlier key replacements will have no affect for
3967     later key matches. For example,
3969       string map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc
3971  ::
3972     will return the string +01321221+.
3973  ::
3974     Note that if an earlier key is a prefix of a later one, it will completely mask the later
3975     one.  So if the previous example is reordered like this,
3977       string map {1 0 ab 2 a 3 abc 1} 1abcaababcabababc
3979  ::
3980     it will return the string +02c322c222c+.
3982 +*string match ?-nocase?* 'pattern string'+::
3983     See if +'pattern'+ matches +'string'+; return 1 if it does, 0
3984     if it doesn't.  Matching is done in a fashion similar to that
3985     used by the C-shell.  For the two strings to match, their contents
3986     must be identical except that the following special sequences
3987     may appear in +'pattern'+:
3989     +*+;;
3990         Matches any sequence of characters in +'string'+,
3991         including a null string.
3993     +?+;;
3994         Matches any single character in +'string'+.
3996     +['chars']+;;
3997         Matches any character in the set given by +'chars'+.
3998         If a sequence of the form +'x-y'+ appears in +'chars'+,
3999         then any character between +'x'+ and +'y'+, inclusive,
4000         will match.
4002     +{backslash}x+;;
4003         Matches the single character +'x'+.  This provides a way of
4004         avoiding the special interpretation of the characters +{backslash}*?[]+
4005         in +'pattern'+.
4006  ::
4007     Performs a case-insensitive comparison if +-nocase+ is specified.
4009 +*string range* 'string first last'+::
4010     Returns a range of consecutive characters from +'string'+, starting
4011     with the character whose index is +'first'+ and ending with the
4012     character whose index is +'last'+.  An index of 0 refers to the
4013     first character of the string.
4014  ::
4015     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
4016  ::
4017     If +'first'+ is less than zero then it is treated as if it were zero, and
4018     if +'last'+ is greater than or equal to the length of the string then
4019     it is treated as if it were +end+.  If +'first'+ is greater than
4020     +'last'+ then an empty string is returned.
4022 +*string repeat* 'string count'+::
4023     Returns a new string consisting of +'string'+ repeated +'count'+ times.
4025 +*string replace* 'string first last ?newstring?'+::
4026     Removes a range of consecutive characters from +'string'+, starting
4027     with the character whose index is +'first'+ and ending with the
4028     character whose index is +'last'+.  If +'newstring'+ is specified,
4029     then it is placed in the removed character range. If +'first'+ is
4030     less than zero then it is treated as if it were zero, and if +'last'+
4031     is greater than or equal to the length of the string then it is
4032     treated as if it were +end+. If +'first'+ is greater than +'last'+
4033     or the length of the initial string, or +'last'+ is less than 0,
4034     then the initial string is returned untouched.
4036 +*string reverse* 'string'+::
4037     Returns a string that is the same length as +'string'+ but
4038     with its characters in the reverse order.
4040 +*string tolower* 'string'+::
4041     Returns a value equal to +'string'+ except that all upper case
4042     letters have been converted to lower case.
4044 +*string totitle* 'string'+::
4045     Returns a value equal to +'string'+ except that the first character
4046     is converted to title case (or upper case if there is no UTF-8 titlecase variant)
4047     and all remaining characters have been converted to lower case.
4049 +*string toupper* 'string'+::
4050     Returns a value equal to +'string'+ except that all lower case
4051     letters have been converted to upper case.
4053 +*string trim* 'string ?chars?'+::
4054     Returns a value equal to +'string'+ except that any leading
4055     or trailing characters from the set given by +'chars'+ are
4056     removed.
4057     If +'chars'+ is not specified then white space is removed
4058     (spaces, tabs, newlines, and carriage returns).
4060 +*string trimleft* 'string ?chars?'+::
4061     Returns a value equal to +'string'+ except that any
4062     leading characters from the set given by +'chars'+ are
4063     removed.
4064     If +'chars'+ is not specified then white space is removed
4065     (spaces, tabs, newlines, and carriage returns).
4067 +*string trimright* 'string ?chars?'+::
4068     Returns a value equal to +'string'+ except that any
4069     trailing characters from the set given by +'chars'+ are
4070     removed.
4071     If +'chars'+ is not specified then white space is removed
4072     (spaces, tabs, newlines, and carriage returns).
4073     Null characters are always removed.
4075 subst
4076 ~~~~~
4077 +*subst ?-nobackslashes? ?-nocommands? ?-novariables?* 'string'+
4079 This command performs variable substitutions, command substitutions,
4080 and backslash substitutions on its string argument and returns the
4081 fully-substituted result. The substitutions are performed in exactly
4082 the same way as for Tcl commands. As a result, the string argument
4083 is actually substituted twice, once by the Tcl parser in the usual
4084 fashion for Tcl commands, and again by the subst command.
4086 If any of the +-nobackslashes+, +-nocommands+, or +-novariables+ are
4087 specified, then the corresponding substitutions are not performed.
4088 For example, if +-nocommands+ is specified, no command substitution
4089 is performed: open and close brackets are treated as ordinary
4090 characters with no special interpretation.
4092 *Note*: when it performs its substitutions, subst does not give any
4093 special treatment to double quotes or curly braces. For example,
4094 the following script returns +xyz \{44\}+, not +xyz \{$a\}+.
4096     set a 44
4097     subst {xyz {$a}}
4100 switch
4101 ~~~~~~
4102 +*switch* '?options? string pattern body ?pattern body \...?'+
4104 +*switch* '?options? string {pattern body ?pattern body \...?}'+
4106 The `switch` command matches its string argument against each of
4107 the pattern arguments in order. As soon as it finds a pattern that
4108 matches string it evaluates the following body and returns the
4109 result of that evaluation. If the last pattern argument is default
4110 then it matches anything. If no pattern argument matches string and
4111 no default is given, then the `switch` command returns an empty string.
4112 If the initial arguments to switch start with - then they are treated
4113 as options. The following options are currently supported:
4115     +-exact+::
4116         Use exact matching when comparing string to a
4117         pattern. This is the default.
4119     +-glob+::
4120         When matching string to the patterns, use glob-style
4121         matching (i.e. the same as implemented by the string
4122         match command).
4124     +-regexp+::
4125         When matching string to the patterns, use regular
4126         expression matching (i.e. the same as implemented
4127         by the regexp command).
4129     +-command 'commandname'+::
4130         When matching string to the patterns, use the given command, which
4131         must be a single word. The command is invoked as
4132         'commandname pattern string', or 'commandname -nocase pattern string'
4133         and must return 1 if matched, or 0 if not.
4135     +--+::
4136         Marks the end of options. The argument following
4137         this one will be treated as string even if it starts
4138         with a +-+.
4140 Two syntaxes are provided for the pattern and body arguments. The
4141 first uses a separate argument for each of the patterns and commands;
4142 this form is convenient if substitutions are desired on some of the
4143 patterns or commands. The second form places all of the patterns
4144 and commands together into a single argument; the argument must
4145 have proper list structure, with the elements of the list being the
4146 patterns and commands. The second form makes it easy to construct
4147 multi-line `switch` commands, since the braces around the whole list
4148 make it unnecessary to include a backslash at the end of each line.
4149 Since the pattern arguments are in braces in the second form, no
4150 command or variable substitutions are performed on them; this makes
4151 the behaviour of the second form different than the first form in
4152 some cases.
4154 If a body is specified as +-+ it means that the body for the next
4155 pattern should also be used as the body for this pattern (if the
4156 next pattern also has a body of +-+ then the body after that is
4157 used, and so on). This feature makes it possible to share a single
4158 body among several patterns.
4160 Below are some examples of `switch` commands:
4162     switch abc a - b {format 1} abc {format 2} default {format 3}
4164 will return 2,
4166     switch -regexp aaab {
4167            ^a.*b$ -
4168            b {format 1}
4169            a* {format 2}
4170            default {format 3}
4171     }
4173 will return 1, and
4175     switch xyz {
4176            a -
4177            b {format 1}
4178            a* {format 2}
4179            default {format 3}
4180     }
4182 will return 3.
4184 tailcall
4185 ~~~~~~~~
4186 +*tailcall* 'cmd ?arg\...?'+
4188 The `tailcall` command provides an optimised way of invoking a command whilst replacing
4189 the current call frame. This is similar to 'exec' in Bourne Shell.
4191 The following are identical except the first immediately replaces the current call frame.
4193   tailcall a b c
4195   return [uplevel 1 [list a b c]]
4197 `tailcall` is useful as a dispatch mechanism:
4199   proc a {cmd args} {
4200     tailcall sub_$cmd {*}$args
4201   }
4202   proc sub_cmd1 ...
4203   proc sub_cmd2 ...
4205 tell
4206 ~~~~
4207 +*tell* 'fileId'+
4209 +'fileId' *tell*+
4211 Returns a decimal string giving the current access position in
4212 +'fileId'+.
4214 +'fileId'+ must have been the return value from a previous call to
4215 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
4216 of the standard I/O channels.
4218 throw
4219 ~~~~~
4220 +*throw* 'code ?msg?'+
4222 This command throws an exception (return) code along with an optional message.
4223 This command is mostly for convenient usage with `try`.
4225 The command +throw break+ is equivalent to +break+.
4226 The command +throw 20 message+ can be caught with an +on 20 \...+ clause to `try`.
4228 time
4229 ~~~~
4230 +*time* 'command ?count?'+
4232 This command will call the Tcl interpreter +'count'+
4233 times to execute +'command'+ (or once if +'count'+ isn't
4234 specified).  It will then return a string of the form
4236     503 microseconds per iteration
4238 which indicates the average amount of time required per iteration,
4239 in microseconds.
4241 Time is measured in elapsed time, not CPU time.
4245 +*try* '?catchopts? tryscript' ?*on* 'returncodes {?resultvar? ?optsvar?} handlerscript \...'? ?*finally* 'finalscript'?+
4247 The `try` command is provided as a convenience for exception handling.
4249 This interpeter first evaluates +'tryscript'+ under the effect of the catch
4250 options +'catchopts'+ (e.g. +-signal -noexit --+, see `catch`).
4252 It then evaluates the script for the first matching 'on' handler
4253 (there many be zero or more) based on the return code from the `try`
4254 section. For example a normal +JIM_ERR+ error will be matched by
4255 an 'on error' handler.
4257 Finally, any +'finalscript'+ is evaluated.
4259 The result of this command is the result of +'tryscript'+, except in the
4260 case where an exception occurs in a matching 'on' handler script or the 'finally' script,
4261 in which case the result is this new exception.
4263 The specified +'returncodes'+ is a list of return codes either as names ('ok', 'error', 'break', etc.)
4264 or as integers.
4266 If +'resultvar'+ and +'optsvar'+ are specified, they are set as for `catch` before evaluating
4267 the matching handler.
4269 For example:
4271     set f [open input]
4272     try -signal {
4273         process $f
4274     } on {continue break} {} {
4275         error "Unexpected break/continue"
4276     } on error {msg opts} {
4277         puts "Dealing with error"
4278         return {*}$opts $msg
4279     } on signal sig {
4280         puts "Got signal: $sig"
4281     } finally {
4282         $f close
4283     }
4285 If break, continue or error are raised, they are dealt with by the matching
4286 handler.
4288 In any case, the file will be closed via the 'finally' clause.
4290 See also `throw`, `catch`, `return`, `error`.
4292 unknown
4293 ~~~~~~~
4294 +*unknown* 'cmdName ?arg arg ...?'+
4296 This command doesn't actually exist as part of Tcl, but Tcl will
4297 invoke it if it does exist.
4299 If the Tcl interpreter encounters a command name for which there
4300 is not a defined command, then Tcl checks for the existence of
4301 a command named `unknown`.
4303 If there is no such command, then the interpreter returns an
4304 error.
4306 If the `unknown` command exists, then it is invoked with
4307 arguments consisting of the fully-substituted name and arguments
4308 for the original non-existent command.
4310 The `unknown` command typically does things like searching
4311 through library directories for a command procedure with the name
4312 +'cmdName'+, or expanding abbreviated command names to full-length,
4313 or automatically executing unknown commands as UNIX sub-processes.
4315 In some cases (such as expanding abbreviations) `unknown` will
4316 change the original command slightly and then (re-)execute it.
4317 The result of the `unknown` command is used as the result for
4318 the original non-existent command.
4320 unset
4321 ~~~~~
4322 +*unset ?-nocomplain? ?--?* '?name name ...?'+
4324 Remove variables.
4325 Each +'name'+ is a variable name, specified in any of the
4326 ways acceptable to the `set` command.
4328 If a +'name'+ refers to an element of an array, then that
4329 element is removed without affecting the rest of the array.
4331 If a +'name'+ consists of an array name with no parenthesized
4332 index, then the entire array is deleted.
4334 The `unset` command returns an empty string as result.
4336 An error occurs if any of the variables doesn't exist, unless '-nocomplain'
4337 is specified. The '--' argument may be specified to stop option processing
4338 in case the variable name may be '-nocomplain'.
4340 upcall
4341 ~~~~~~~
4342 +*upcall* 'command ?args ...?'+
4344 May be used from within a proc defined as `local` `proc` in order to call
4345 the previous, hidden version of the same command.
4347 If there is no previous definition of the command, an error is returned.
4349 uplevel
4350 ~~~~~~~
4351 +*uplevel* '?level? command ?command ...?'+
4353 All of the +'command'+ arguments are concatenated as if they had
4354 been passed to `concat`; the result is then evaluated in the
4355 variable context indicated by +'level'+.  `uplevel` returns
4356 the result of that evaluation.  If +'level'+ is an integer, then
4357 it gives a distance (up the procedure calling stack) to move before
4358 executing the command.  If +'level'+ consists of +\#+ followed by
4359 a number then the number gives an absolute level number.  If +'level'+
4360 is omitted then it defaults to +1+.  +'level'+ cannot be
4361 defaulted if the first +'command'+ argument starts with a digit or +#+.
4363 For example, suppose that procedure 'a' was invoked
4364 from top-level, and that it called 'b', and that 'b' called 'c'.
4365 Suppose that 'c' invokes the `uplevel` command.  If +'level'+
4366 is +1+ or +#2+  or omitted, then the command will be executed
4367 in the variable context of 'b'.  If +'level'+ is +2+ or +#1+
4368 then the command will be executed in the variable context of 'a'.
4370 If +'level'+ is '3' or +#0+ then the command will be executed
4371 at top-level (only global variables will be visible).
4372 The `uplevel` command causes the invoking procedure to disappear
4373 from the procedure calling stack while the command is being executed.
4374 In the above example, suppose 'c' invokes the command
4376     uplevel 1 {set x 43; d}
4378 where 'd' is another Tcl procedure.  The `set` command will
4379 modify the variable 'x' in 'b's context, and 'd' will execute
4380 at level 3, as if called from 'b'.  If it in turn executes
4381 the command
4383     uplevel {set x 42}
4385 then the `set` command will modify the same variable 'x' in 'b's
4386 context:  the procedure 'c' does not appear to be on the call stack
4387 when 'd' is executing.  The command `info level` may
4388 be used to obtain the level of the current procedure.
4390 `uplevel` makes it possible to implement new control
4391 constructs as Tcl procedures (for example, `uplevel` could
4392 be used to implement the `while` construct as a Tcl procedure).
4394 upvar
4395 ~~~~~
4396 +*upvar* '?level? otherVar myVar ?otherVar myVar ...?'+
4398 This command arranges for one or more local variables in the current
4399 procedure to refer to variables in an enclosing procedure call or
4400 to global variables.
4402 +'level'+ may have any of the forms permitted for the `uplevel`
4403 command, and may be omitted if the first letter of the first +'otherVar'+
4404 isn't +#+ or a digit (it defaults to '1').
4406 For each +'otherVar'+ argument, `upvar` makes the variable
4407 by that name in the procedure frame given by +'level'+ (or at
4408 global level, if +'level'+ is +#0+) accessible
4409 in the current procedure by the name given in the corresponding
4410 +'myVar'+ argument.
4412 The variable named by +'otherVar'+ need not exist at the time of the
4413 call;  it will be created the first time +'myVar'+ is referenced, just like
4414 an ordinary variable.
4416 `upvar` may only be invoked from within procedures.
4418 `upvar` returns an empty string.
4420 The `upvar` command simplifies the implementation of call-by-name
4421 procedure calling and also makes it easier to build new control constructs
4422 as Tcl procedures.
4423 For example, consider the following procedure:
4425     proc add2 name {
4426         upvar $name x
4427         set x [expr $x+2]
4428     }
4430 'add2' is invoked with an argument giving the name of a variable,
4431 and it adds two to the value of that variable.
4432 Although 'add2' could have been implemented using `uplevel`
4433 instead of `upvar`, `upvar` makes it simpler for 'add2'
4434 to access the variable in the caller's procedure frame.
4436 while
4437 ~~~~~
4438 +*while* 'test body'+
4440 The +'while'+ command evaluates +'test'+ as an expression
4441 (in the same way that `expr` evaluates its argument).
4442 The value of the expression must be numeric; if it is non-zero
4443 then +'body'+ is executed by passing it to the Tcl interpreter.
4445 Once +'body'+ has been executed then +'test'+ is evaluated
4446 again, and the process repeats until eventually +'test'+
4447 evaluates to a zero numeric value.  `continue`
4448 commands may be executed inside +'body'+ to terminate the current
4449 iteration of the loop, and `break`
4450 commands may be executed inside +'body'+ to cause immediate
4451 termination of the `while` command.
4453 The `while` command always returns an empty string.
4455 OPTIONAL-EXTENSIONS
4456 -------------------
4458 The following extensions may or may not be available depending upon
4459 what options were selected when Jim Tcl was built.
4461 [[cmd_1]]
4462 posix: os.fork, os.wait, os.gethostname, os.getids, os.uptime
4463 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4464 +*os.fork*+::
4465     Invokes 'fork(2)' and returns the result.
4467 +*os.wait -nohang* 'pid'+::
4468     Invokes waitpid(2), with WNOHANG if +-nohang+ is specified.
4469     Returns a list of 3 elements.
4471    {0 none 0} if -nohang is specified, and the process is still alive.
4473    {-1 error <error-description>} if the process does not exist or has already been waited for.
4475    {<pid> exit <exit-status>} if the process exited normally.
4477    {<pid> signal <signal-number>} if the process terminated on a signal.
4479    {<pid> other 0} otherwise (core dump, stopped, continued, etc.)
4481 +*os.gethostname*+::
4482     Invokes 'gethostname(3)' and returns the result.
4484 +*os.getids*+::
4485     Returns the various user/group ids for the current process.
4487     jim> os.getids
4488     uid 1000 euid 1000 gid 100 egid 100
4490 +*os.uptime*+::
4491     Returns the number of seconds since system boot. See description of 'uptime' in 'sysinfo(2)'.
4493 ANSI I/O (aio) and EVENTLOOP API
4494 --------------------------------
4495 Jim provides an alternative object-based API for I/O.
4497 See `open` and `socket` for commands which return an I/O handle.
4501 +$handle *accept* ?addrvar?+::
4502     Server socket only: Accept a connection and return stream.
4503     If +'addrvar'+ is specified, the address of the connected client is stored
4504     in the named variable in the form 'addr:port'. See `socket` for details.
4506 +$handle *buffering none|line|full*+::
4507     Sets the buffering mode of the stream.
4509 +$handle *close* ?r(ead)|w(rite)?+::
4510     Closes the stream.
4511     The  two-argument form is a "half-close" on a socket. See the +shutdown(2)+ man page.
4513 +$handle *copyto* 'tofd ?size?'+::
4514     Copy bytes to the file descriptor +'tofd'+. If +'size'+ is specified, at most
4515     that many bytes will be copied. Otherwise copying continues until the end
4516     of the input file. Returns the number of bytes actually copied.
4518 +$handle *eof*+::
4519     Returns 1 if stream is at eof
4521 +$handle *filename*+::
4522     Returns the original filename associated with the handle.
4523     Handles returned by `socket` give the socket type instead of a filename.
4525 +$handle *flush*+::
4526     Flush the stream
4528 +$handle *gets* '?var?'+::
4529     Read one line and return it or store it in the var
4531 +$handle *isatty*+::
4532     Returns 1 if the stream is a tty device.
4534 +$handle *lock*+::
4535     Apply a POSIX lock to the open file associated with the handle using
4536     fcntl(2).
4537     The handle must be open for write access.
4538     Returns 1 if the lock was successfully obtained, 0 otherwise.
4539     An error occurs if the handle is not suitable for locking (e.g.
4540     if it is not open for write)
4542 +$handle *ndelay ?0|1?*+::
4543     Set O_NDELAY (if arg). Returns current/new setting.
4544     Note that in general ANSI I/O interacts badly with non-blocking I/O.
4545     Use with care.
4547 +$handle *puts ?-nonewline?* 'str'+::
4548     Write the string, with newline unless -nonewline
4550 +$handle *read ?-nonewline?* '?len?'+::
4551     Read and return bytes from the stream. To eof if no len.
4553 +$handle *recvfrom* 'maxlen ?addrvar?'+::
4554     Receives a message from the handle via recvfrom(2) and returns it.
4555     At most +'maxlen'+ bytes are read.
4556     If +'addrvar'+ is specified, the sending address of the message is stored in
4557     the named variable in the form 'addr:port'. See `socket` for details.
4559 +$handle *seek* 'offset' *?start|current|end?*+::
4560     Seeks in the stream (default 'current')
4562 +$handle *sendto* 'str ?addr:?port'+::
4563     Sends the string, +'str'+, to the given address via the socket using sendto(2).
4564     This is intended for udp/dgram sockets and may give an error or behave in unintended
4565     ways for other handle types.
4566     Returns the number of bytes written.
4568 +$handle *sync*+::
4569     Flush the stream, then fsync(2) to commit any changes to storage.
4570     Only available on platforms that support fsync(2).
4572 +$handle *tell*+::
4573     Returns the current seek position
4575 +$handle *tty* ?settings?+::
4576         If no arguments are given, returns a dictionary containing the tty settings for the stream.
4577         If arguments are given, they must either be a dictionary, or +setting value \...+
4578         Abbrevations are supported for both settings and values, so the following is acceptable:
4579         +$f tty parity e input c out raw+.
4580     Only available on platforms that support termios(3). Supported settings are:
4582     +*baud* 'rate'+;;
4583         Baud rate. e.g. 115200
4585     +*data 5|6|7|8*+;;
4586         Number of data bits
4588     +*stop 1|2*+;;
4589         Number of stop bits
4591     +*parity even|odd|none*+;;
4592         Parity setting
4594     +*handshake xonxoff|rtscts|none*+;;
4595                 Handshaking type
4597     +*input raw|cooked*+;;
4598                 Input character processing. In raw mode, the usual key sequences such as ^C do
4599                 not generate signals.
4601     +*output raw|cooked*+;;
4602                 Output character processing. Typically CR -> CRNL is disabled in raw mode.
4604     +*vmin* 'numchars'+;;
4605                 Minimum number of characters to read.
4607     +*vtime* 'time'+;;
4608                 Timeout for noncanonical read (units of 0.1 seconds)
4610 +$handle *ssl* *?-server cert priv?*+::
4611     Initiates a SSL/TLS session and returns a new stream
4613 +$handle *unlock*+::
4614     Release a POSIX lock previously acquired by `aio lock`.
4616 +$handle *verify*+::
4617     Verifies the certificate of a SSL/TLS stream peer
4619 +*load_ssl_certs* 'dir'+::
4620     Loads SSL/TLS CA certificates for use during verification
4622 fconfigure
4623 ~~~~~~~~~~
4624 +*fconfigure* 'handle' *?-blocking 0|1? ?-buffering noneline|full? ?-translation* 'mode'?+::
4625     For compatibility with Tcl, a limited form of the `fconfigure`
4626     command is supported.
4627     * `fconfigure ... -blocking` maps to `aio ndelay`
4628     * `fconfigure ... -buffering` maps to `aio buffering`
4629     * `fconfigure ... -translation` is accepted but ignored
4631 [[cmd_2]]
4632 eventloop: after, vwait, update
4633 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4635 The following commands allow a script to be invoked when the given condition occurs.
4636 If no script is given, returns the current script. If the given script is the empty, the
4637 handler is removed.
4639 +$handle *readable* '?readable-script?'+::
4640     Sets or returns the script for when the socket is readable.
4642 +$handle *writable* '?writable-script?'+::
4643     Sets or returns the script for when the socket is writable.
4645 +$handle *onexception* '?exception-script?'+::
4646     Sets or returns the script for when oob data received.
4648 For compatibility with 'Tcl', these may be prefixed with `fileevent`.  e.g.
4650  ::
4651     +fileevent $handle *readable* '\...'+
4653 Time-based execution is also available via the eventloop API.
4655 +*after* 'ms'+::
4656     Sleeps for the given number of milliseconds. No events are
4657     processed during this time.
4659 +*after* 'ms'|*idle* 'script ?script \...?'+::
4660     The scripts are concatenated and executed after the given
4661     number of milliseconds have elapsed.  If 'idle' is specified,
4662     the script will run the next time the event loop is processed
4663     with `vwait` or `update`. The script is only run once and
4664     then removed.  Returns an event id.
4666 +*after cancel* 'id|command'+::
4667     Cancels an `after` event with the given event id or matching
4668     command (script).  Returns the number of milliseconds
4669     remaining until the event would have fired.  Returns the
4670     empty string if no matching event is found.
4672 +*after info* '?id?'+::
4673     If +'id'+ is not given, returns a list of current `after`
4674     events.  If +'id'+ is given, returns a list containing the
4675     associated script and either 'timer' or 'idle' to indicated
4676     the type of the event. An error occurs if +'id'+ does not
4677     match an event.
4679 +*vwait* 'variable'+::
4680     A call to `vwait` enters the eventloop. `vwait` processes
4681     events until the named (global) variable changes or all
4682     event handlers are removed. The variable need not exist
4683     beforehand.  If there are no event handlers defined, `vwait`
4684     returns immediately.
4686 +*update ?idletasks?*+::
4687     A call to `update` enters the eventloop to process expired events, but
4688     no new events. If 'idletasks' is specified, only expired time events are handled,
4689     not file events.
4690     Returns once handlers have been run for all expired events.
4692 Scripts are executed at the global scope. If an error occurs during a handler script,
4693 an attempt is made to call (the user-defined command) `bgerror` with the details of the error.
4694 If the `bgerror` command does not exist, the error message details are printed to stderr instead.
4696 If a file event handler script generates an error, the handler is automatically removed
4697 to prevent infinite errors. (A time event handler is always removed after execution).
4699 +*bgerror* 'msg'+::
4700     Called when an event handler script generates an error. Note that the normal command resolution
4701     rules are used for bgerror. First the name is resolved in the current namespace, then in the
4702     global scope.
4704 socket
4705 ~~~~~~
4706 Various socket types may be created.
4708 +*socket unix* 'path'+::
4709     A unix domain socket client.
4711 +*socket unix.server* 'path'+::
4712     A unix domain socket server.
4714 +*socket ?-ipv6? stream* 'addr:port'+::
4715     A TCP socket client. (See the forms for +'addr'+ below)
4717 +*socket ?-ipv6? stream.server* '?addr:?port'+::
4718     A TCP socket server (+'addr'+ defaults to +0.0.0.0+ for IPv4 or +[::]+ for IPv6).
4720 +*socket ?-ipv6? dgram* ?'addr:port'?+::
4721     A UDP socket client. If the address is not specified,
4722     the client socket will be unbound and 'sendto' must be used
4723     to indicated the destination.
4725 +*socket ?-ipv6? dgram.server* 'addr:port'+::
4726     A UDP socket server.
4728 +*socket pipe*+::
4729     A pipe. Note that unlike all other socket types, this command returns
4730     a list of two channels: {read write}
4732 +*socket pair*+::
4733     A socketpair (see socketpair(2)). Like `socket pipe`, this command returns
4734     a list of two channels: {s1 s2}. These channels are both readable and writable.
4736 This command creates a socket connected (client) or bound (server) to the given
4737 address.
4739 The returned value is channel and may generally be used with the various file I/O
4740 commands (gets, puts, read, etc.), either as object-based syntax or Tcl-compatible syntax.
4742     . set f [socket stream www.google.com:80]
4743     aio.sockstream1
4744     . $f puts -nonewline "GET / HTTP/1.0\r\n\r\n"
4745     . $f gets
4746     HTTP/1.0 302 Found
4747     . $f close
4749 Server sockets, however support only 'accept', which is most useful in conjunction with
4750 the EVENTLOOP API.
4752     set f [socket stream.server 80]
4753     $f readable {
4754         set client [$f accept]
4755         $client gets $buf
4756         ...
4757         $client puts -nonewline "HTTP/1.1 404 Not found\r\n"
4758         $client close
4759     }
4760     vwait done
4762 The address, +'addr'+, can be given in one of the following forms:
4764 1. For IPv4 socket types, an IPv4 address such as 192.168.1.1
4765 2. For IPv6 socket types, an IPv6 address such as [fe80::1234] or [::]
4766 3. A hostname
4768 Note that on many systems, listening on an IPv6 address such as [::] will
4769 also accept requests via IPv4.
4771 Where a hostname is specified, the +'first'+ returned address is used
4772 which matches the socket type is used.
4774 The special type 'pipe' isn't really a socket.
4776     lassign [socket pipe] r w
4778     # Must close $w after exec
4779     exec ps >@$w &
4780     $w close
4782     $r readable ...
4784 syslog
4785 ~~~~~~
4786 +*syslog* '?options? ?priority? message'+
4788 This  command sends message to system syslog facility with given
4789 priority. Valid priorities are:
4791     emerg, alert, crit, err, error, warning, notice, info, debug
4793 If a message is specified, but no priority is specified, then a
4794 priority of info is used.
4796 By default, facility user is used and the value of global tcl variable
4797 argv0 is used as ident string. However, any of the following options
4798 may be specified before priority to control these parameters:
4800 +*-facility* 'value'+::
4801     Use specified facility instead of user. The following
4802     values for facility are recognized:
4804     authpriv, cron, daemon, kernel, lpr, mail, news, syslog, user,
4805     uucp, local0-local7
4807 +*-ident* 'string'+::
4808     Use given string instead of argv0 variable for ident string.
4810 +*-options* 'integer'+::
4811     Set syslog options such as +LOG_CONS+, +LOG_NDELAY+. You should
4812     use numeric values of those from your system syslog.h file,
4813     because I haven't got time to implement yet another hash
4814     table.
4816 pack: pack, unpack
4817 ~~~~~~~~~~~~~~~~~~
4818 The optional 'pack' extension provides commands to encode and decode binary strings.
4820 +*pack* 'varName value' *-intle|-intbe|-floatle|-floatbe|-str* 'bitwidth ?bitoffset?'+::
4821     Packs the binary representation of +'value'+ into the variable
4822     +'varName'+. The value is packed according to the given type
4823     (integer/floating point/string, big-endian/little-endian), width and bit offset.
4824     The variable is created if necessary (like `append`).
4825     The variable is expanded if necessary.
4827 +*unpack* 'binvalue' *-intbe|-intle|-uintbe|-uintle|-floatbe|-floatle|-str* 'bitpos bitwidth'+::
4828     Unpacks bits from +'binvalue'+ at bit position +'bitpos'+ and with +'bitwidth'+.
4829     Interprets the value according to the type (integer/floating point/string, big-endian/little-endian
4830     and signed/unsigned) and returns it. For integer types, +'bitwidth'+
4831     may be up to the size of a Jim Tcl integer (typically 64 bits). For floating point types,
4832     +'bitwidth'+ may be 32 bits (for single precision numbers) or 64 bits (for double precision).
4833     For the string type, both the width and the offset must be on a byte boundary (multiple of 8). Attempting to
4834     access outside the length of the value will return 0 for integer types, 0.0 for floating point types
4835     or the empty string for the string type.
4837 zlib
4838 ~~~~
4839 The optional 'zlib' extension provides a Tcl-compatible subset of the `zlib` command.
4841 +*crc32* 'data' '?startValue?'+::
4842     Returns the CRC32 checksum of a buffer. Optionally, an initial value may be specified; this is most useful
4843     for calculating the checksum of chunked data read from a stream (for instance, a pipe).
4845 +*deflate* 'string' '?level?'+::
4846     Compresses a buffer and outputs a raw, Deflate-compressed stream. Optionally, a compression level (1-9) may
4847     be specified to choose the desired speed vs. compression rate ratio.
4849 +*inflate* 'data' '?bufferSize?'+::
4850     Decompresses a raw, Deflate-compressed stream. When the uncompressed data size is known and specified, memory
4851     allocation is more efficient. Otherwise, decomperssion is chunked and therefore slower.
4853 +*gzip* 'string' '?-level level?'+::
4854     Compresses a buffer and adds a gzip header.
4856 +*gunzip* 'data' '?-buffersize size?'+::
4857     Decompresses a gzip-compressed buffer. Decompression is chunked, with a default, small buffer size of 64K
4858     which guarantees lower memory footprint at the cost of speed. It is recommended to use a bigger size, on
4859     systems without a severe memory constraint.
4861 binary
4862 ~~~~~~
4863 The optional, pure-Tcl 'binary' extension provides the Tcl-compatible `binary scan` and `binary format`
4864 commands based on the low-level `pack` and `unpack` commands.
4866 See the Tcl documentation at: http://www.tcl.tk/man/tcl8.5/TclCmd/binary.htm
4868 Note that 'binary format' with f/r/R specifiers (single-precision float) uses the value of Infinity
4869  in case of overflow.
4871 oo: class, super
4872 ~~~~~~~~~~~~~~~~
4873 The optional, pure-Tcl 'oo' extension provides object-oriented (OO) support for Jim Tcl.
4875 See the online documentation (http://jim.tcl.tk/index.html/doc/www/www/documentation/oo/) for more details.
4877 +*class* 'classname ?baseclasses? classvars'+::
4878     Create a new class, +'classname'+, with the given dictionary
4879     (+'classvars'+) as class variables. These are the initial variables
4880     which all newly created objects of this class are initialised with.
4881     If a list of baseclasses is given, methods and instance variables
4882     are inherited.
4884 +*super* 'method ?args \...?'+::
4885     From within a method, invokes the given method on the base class.
4886     Note that this will only call the last baseclass given.
4888 tree
4889 ~~~~
4890 The optional, pure-Tcl 'tree' extension implements an OO, general purpose tree structure
4891 similar to that provided by tcllib ::struct::tree (http://core.tcl.tk/tcllib/doc/trunk/embedded/www/tcllib/files/modules/struct/struct_tree.html)
4893 A tree is a collection of nodes, where each node (except the root node) has a single parent
4894 and zero or more child nodes (ordered), as well as zero or more attribute/value pairs.
4896 +*tree*+::
4897     Creates and returns a new tree object with a single node named "root".
4898     All operations on the tree are invoked through this object.
4900 +$tree *destroy*+::
4901     Destroy the tree and all it's nodes. (Note that the tree will also
4902     be automatically garbage collected once it goes out of scope).
4904 +$tree *set* 'nodename key value'+::
4905     Set the value for the given attribute key.
4907 +$tree *lappend* 'nodename key value \...'+::
4908     Append to the (list) value(s) for the given attribute key, or set if not yet set.
4910 +$tree *keyexists* 'nodename key'+::
4911     Returns 1 if the given attribute key exists.
4913 +$tree *get* 'nodename key'+::
4914     Returns the value associated with the given attribute key.
4916 +$tree *getall* 'nodename'+::
4917     Returns the entire attribute dictionary associated with the given key.
4919 +$tree *depth* 'nodename'+::
4920     Returns the depth of the given node. The depth of "root" is 0.
4922 +$tree *parent* 'nodename'+::
4923     Returns the node name of the parent node, or "" for the root node.
4925 +$tree *numchildren* 'nodename'+::
4926     Returns the number of child nodes.
4928 +$tree *children* 'nodename'+::
4929     Returns a list of the child nodes.
4931 +$tree *next* 'nodename'+::
4932     Returns the next sibling node, or "" if none.
4934 +$tree *insert* 'nodename ?index?'+::
4935     Add a new child node to the given node. The index is a list index
4936     such as +3+ or +end-2+. The default index is +end+.
4937     Returns the name of the newly added node.
4939 +$tree *walk* 'nodename' *dfs|bfs* {'actionvar nodevar'} 'script'+::
4940     Walks the tree starting from the given node, either breadth first (+bfs+)
4941     depth first (+dfs+).
4942     The value +"enter"+ or +"exit"+ is stored in variable +'actionvar'+.
4943     The name of each node is stored in +'nodevar'+.
4944     The script is evaluated twice for each node, on entry and exit.
4946 +$tree *dump*+::
4947     Dumps the tree contents to stdout
4949 tcl::prefix
4950 ~~~~~~~~~~~
4951 The optional tclprefix extension provides the Tcl8.6-compatible 'tcl::prefix' command
4952 (http://www.tcl.tk/man/tcl8.6/TclCmd/prefix.htm) for matching strings against a table
4953 of possible values (typically commands or options).
4955 +*tcl::prefix all* 'table string'+::
4956     Returns a list of all elements in +'table'+ that begin with the prefix +'string'+.
4958 +*tcl::prefix longest* 'table string'+::
4959     Returns the longest common prefix of all elements in +'table'+ that begin with the prefix +'string'+.
4961 +*tcl::prefix match* '?options? table string'+::
4962     If +'string'+ equals one element in +'table'+ or is a prefix to
4963     exactly one element, the matched element is returned. If not, the
4964     result depends on the +-error+ option.
4966     * +*-exact*+ Accept only exact matches.
4967     * +*-message* 'string'+ Use +'string'+ in the error message at a mismatch. Default is "option".
4968     * +*-error* 'options'+ The options are used when no match is found. If +'options'+ is
4969       empty, no error is generated and an empty string is returned.
4970       Otherwise the options are used as return options when
4971       generating the error message. The default corresponds to
4972       setting +-level 0+.
4974 history
4975 ~~~~~~~
4976 The optional history extension provides script access to the command line editing
4977 and history support available in 'jimsh'. See 'examples/jtclsh.tcl' for an example.
4978 Note: if line editing support is not available, `history getline` acts like `gets` and
4979 the remaining subcommands do nothing.
4981 +*history load* 'filename'+::
4982     Load history from a (text) file. If the file does not exist or is not readable,
4983     it is ignored.
4985 +*history getline* 'prompt ?varname?'+::
4986     Displays the given prompt and allows a line to be entered. Similarly to `gets`,
4987     if +'varname'+ is given, it receives the line and the length of the line is returned,
4988     or -1 on EOF. If +'varname'+ is not given, the line is returned directly.
4990 +*history add* 'line'+::
4991     Adds the given line to the history buffer.
4993 +*history save* 'filename'+::
4994     Saves the current history buffer to the given file.
4996 +*history show*+::
4997     Displays the current history buffer to standard output.
4999 namespace
5000 ~~~~~~~~~
5001 Provides namespace-related functions. See also: http://www.tcl.tk/man/tcl8.6/TclCmd/namespace.htm
5003 +*namespace code* 'script'+::
5004     Captures the current namespace context for later execution of
5005     the script +'script'+. It returns a new script in which script has
5006     been wrapped in a +*namespace inscope*+ command.
5008 +*namespace current*+::
5009     Returns the fully-qualified name for the current namespace.
5011 +*namespace delete* '?namespace ...?'+::
5012     Deletes all commands and variables with the given namespace prefixes.
5014 +*namespace eval* 'namespace arg ?arg...?'+::
5015     Activates a namespace called +'namespace'+ and evaluates some code in that context.
5017 +*namespace origin* 'command'+::
5018     Returns the fully-qualified name of the original command to which the imported command +'command'+ refers.
5020 +*namespace parent* ?namespace?+::
5021     Returns the fully-qualified name of the parent namespace for namespace +'namespace'+, if given, otherwise
5022     for the current namespace.
5024 +*namespace qualifiers* 'string'+::
5025     Returns any leading namespace qualifiers for +'string'+
5027 +*namespace tail* 'string'+::
5028     Returns the simple name at the end of a qualified string.
5030 +*namespace upvar* 'namespace ?arg...?'+::
5031     This command arranges for zero or more local variables in the current procedure to refer to variables in +'namespace'+
5033 +*namespace which* '?-command|-variable? name'+::
5034     Looks up +'name'+ as either a command (the default) or variable and returns its fully-qualified name.
5036 interp
5037 ~~~~~~
5038 The optional 'interp' command allows sub-interpreters to be created where commands may be run
5039 independently (but synchronously) of the main interpreter.
5041 +*interp*+::
5042     Creates and returns a new interpreter object (command).
5043         The created interpeter contains any built-in commands along with static extensions,
5044         but does not include any dynamically loaded commands (package require, load).
5045         These must be reloaded in the child interpreter if required.
5047 +*$interp delete*+::
5048     Deletes the interpeter object.
5050 +*$interp eval* 'script' ...+::
5051         Evaluates a script in the context for the child interpreter, in the same way as 'eval'.
5053 +*$interp alias* 'alias childcmd parentcmd ?arg ...?'+::
5054         Similar to 'alias', but creates a command, +'childcmd'+, in the child interpreter that is an
5055         alias for +'parentcmd'+ in the parent interpreter, with the given, fixed arguments.
5056         The alias may be deleted in the child with 'rename'.
5058 [[BuiltinVariables]]
5059 BUILT-IN VARIABLES
5060 ------------------
5062 The following global variables are created automatically
5063 by the Tcl library.
5065 +*env*+::
5066     This variable is set by Jim as an array
5067     whose elements are the environment variables for the process.
5068     Reading an element will return the value of the corresponding
5069     environment variable.
5070     This array is initialised at startup from the `env` command.
5071     It may be modified and will affect the environment passed to
5072     commands invoked with `exec`.
5074 +*platform_tcl*+::
5075     This variable is set by Jim as an array containing information
5076     about the platform on which Jim was built. Currently this includes
5077     'os' and 'platform'.
5079 +*auto_path*+::
5080     This variable contains a list of paths to search for packages.
5081     It defaults to a location based on where jim is installed
5082     (e.g. +/usr/local/lib/jim+), but may be changed by +jimsh+
5083     or the embedding application. Note that +jimsh+ will consider
5084     the environment variable +$JIMLIB+ to be a list of colon-separated
5085     list of paths to add to +*auto_path*+.
5087 +*errorCode*+::
5088     This variable holds the value of the -errorcode return
5089     option set by the most recent error that occurred in this
5090     interpreter. This list value represents additional information
5091     about the error in a form that is easy to process with
5092     programs. The first element of the list identifies a general
5093     class of errors, and determines the format of the rest of
5094     the list. The following formats for -errorcode return options
5095     are used by the Tcl core; individual applications may define
5096     additional formats. Currently only `exec` sets this variable.
5097     Otherwise it will be +NONE+.
5099 The following global variables are set by jimsh.
5101 +*tcl_interactive*+::
5102     This variable is set to 1 if jimsh is started in interactive mode
5103     or 0 otherwise.
5105 +*tcl_platform*+::
5106     This variable is set by Jim as an array containing information
5107     about the platform upon which Jim was built. The following is an
5108     example of the contents of this array.
5110     tcl_platform(byteOrder)     = littleEndian
5111     tcl_platform(engine)        = Jim
5112     tcl_platform(os)            = Darwin
5113     tcl_platform(platform)      = unix
5114     tcl_platform(pointerSize)   = 8
5115     tcl_platform(threaded)      = 0
5116     tcl_platform(wordSize)      = 8
5117     tcl_platform(pathSeparator) = :
5119 +*argv0*+::
5120     If jimsh is invoked to run a script, this variable contains the name
5121     of the script.
5123 +*argv*+::
5124     If jimsh is invoked to run a script, this variable contains a list
5125     of any arguments supplied to the script.
5127 +*argc*+::
5128     If jimsh is invoked to run a script, this variable contains the number
5129     of arguments supplied to the script.
5131 +*jim::argv0*+::
5132     The value of argv[0] when jimsh was invoked.
5134 CHANGES IN PREVIOUS RELEASES
5135 ----------------------------
5137 === In v0.70 ===
5139 1. +platform_tcl()+ settings are now automatically determined
5140 2. Add aio `$handle filename`
5141 3. Add `info channels`
5142 4. The 'bio' extension is gone. Now `aio` supports 'copyto'.
5143 5. Add `exists` command
5144 6. Add the pure-Tcl 'oo' extension
5145 7. The `exec` command now only uses vfork(), not fork()
5146 8. Unit test framework is less verbose and more Tcl-compatible
5147 9. Optional UTF-8 support
5148 10. Optional built-in regexp engine for better Tcl compatibility and UTF-8 support
5149 11. Command line editing in interactive mode, e.g. 'jimsh'
5151 === In v0.63 ===
5153 1. `source` now checks that a script is complete (.i.e. not missing a brace)
5154 2. 'info complete' now uses the real parser and so is 100% accurate
5155 3. Better access to live stack frames with 'info frame', `stacktrace` and `stackdump`
5156 4. `tailcall` no longer loses stack trace information
5157 5. Add `alias` and `curry`
5158 6. `lambda`, `alias` and `curry` are implemented via `tailcall` for efficiency
5159 7. `local` allows procedures to be deleted automatically at the end of the current procedure
5160 8. udp sockets are now supported for both clients and servers.
5161 9. vfork-based exec is now working correctly
5162 10. Add 'file tempfile'
5163 11. Add 'socket pipe'
5164 12. Enhance 'try ... on ... finally' to be more Tcl 8.6 compatible
5165 13. It is now possible to `return` from within `try`
5166 14. IPv6 support is now included
5167 15. Add 'string is'
5168 16. Event handlers works better if an error occurs. eof handler has been removed.
5169 17. `exec` now sets $::errorCode, and catch sets opts(-errorcode) for exit status
5170 18. Command pipelines via open "|..." are now supported
5171 19. `pid` can now return pids of a command pipeline
5172 20. Add 'info references'
5173 21. Add support for 'after +'ms'+', 'after idle', 'after info', `update`
5174 22. `exec` now sets environment based on $::env
5175 23. Add 'dict keys'
5176 24. Add support for 'lsort -index'
5178 === In v0.62 ===
5180 1. Add support to `exec` for '>&', '>>&', '|&', '2>@1'
5181 2. Fix `exec` error messages when special token (e.g. '>') is the last token
5182 3. Fix `subst` handling of backslash escapes.
5183 4. Allow abbreviated options for `subst`
5184 5. Add support for `return`, `break`, `continue` in subst
5185 6. Many `expr` bug fixes
5186 7. Add support for functions in `expr` (e.g. int(), abs()), and also 'in', 'ni' list operations
5187 8. The variable name argument to `regsub` is now optional
5188 9. Add support for 'unset -nocomplain'
5189 10. Add support for list commands: `lassign`, `lrepeat`
5190 11. Fully-functional `lsearch` is now implemented
5191 12. Add 'info nameofexecutable' and 'info returncodes'
5192 13. Allow `catch` to determine what return codes are caught
5193 14. Allow `incr` to increment an unset variable by first setting to 0
5194 15. Allow 'args' and optional arguments to the left or required arguments in `proc`
5195 16. Add 'file copy'
5196 17. Add 'try ... finally' command
5199 LICENCE
5200 -------
5202  Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
5203  Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
5204  Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
5205  Copyright 2008 oharboe - Oyvind Harboe - oyvind.harboe@zylin.com
5206  Copyright 2008 Andrew Lunn <andrew@lunn.ch>
5207  Copyright 2008 Duane Ellis <openocd@duaneellis.com>
5208  Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
5209  Copyright 2009 Steve Bennett <steveb@workware.net.au>
5211 [literal]
5212  Redistribution and use in source and binary forms, with or without
5213  modification, are permitted provided that the following conditions
5214  are met:
5215  1. Redistributions of source code must retain the above copyright
5216     notice, this list of conditions and the following disclaimer.
5217  2. Redistributions in binary form must reproduce the above
5218     copyright notice, this list of conditions and the following
5219     disclaimer in the documentation and/or other materials
5220     provided with the distribution.
5222  THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
5223  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
5224  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
5225  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
5226  JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
5227  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
5228  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
5229  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
5230  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
5231  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
5232  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
5233  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5235  The views and conclusions contained in the software and documentation
5236  are those of the authors and should not be interpreted as representing
5237  official policies, either expressed or implied, of the Jim Tcl Project.