Update version to 0.77
[jimtcl.git] / jim_tcl.txt
blob7d8cd641c7f117a87e2b11c54d9fb68d67168a07
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.76 and 0.77
55 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
56 1. Add support for `aio sync`
57 2. Add SSL and TLS support in aio
58 3. Added `zlib`
59 4. Added support for boolean constants in `expr`
60 5. `string is` now supports 'boolean' class
61 6. Add support for `aio lock` and `aio unlock`
62 7. Add new `interp` command
64 Changes between 0.75 and 0.76
65 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
66 1. `glob` now supports the +-tails+ option
67 2. Add support for `string cat`
68 3. Allow `info source` to add source info
70 Changes between 0.74 and 0.75
71 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
72 1. `binary`, `pack` and `unpack` now support floating point
73 2. `file copy` +-force+ handles source and target as the same file
74 3. `format` now supports +%b+ for binary conversion
75 4. `lsort` now supports +-unique+ and +-real+
76 5. Add support for half-close with `aio close` +?r|w?+
77 6. Add `socket pair` for a bidirectional pipe
78 7. Add '--random-hash' to randomise hash tables for greater security
79 8. `dict` now supports 'for', 'values', 'incr', 'append', 'lappend', 'update', 'info' and 'replace'
80 9. `file stat` no longer requires the variable name
81 10. Add support for `file link`
83 Changes between 0.73 and 0.74
84 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
85 1. Numbers with leading zeros are treated as decimal, not octal
86 2. Add `aio isatty`
87 3. Add LFS (64 bit) support for `aio seek`, `aio tell`, `aio copyto`, `file copy`
88 4. `string compare` and `string equal` now support '-length'
89 5. `glob` now supports '-directory'
91 Changes between 0.72 and 0.73
92 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
93 1. Built-in regexp now support non-capturing parentheses: (?:...)
94 2. Add `string replace`
95 3. Add `string totitle`
96 4. Add `info statics`
97 5. Add +build-jim-ext+ for easy separate building of loadable modules (extensions)
98 6. `local` now works with any command, not just procs
99 7. Add `info alias` to access the target of an alias
100 8. UTF-8 encoding past the basic multilingual plane (BMP) is supported
101 9. Add `tcl::prefix`
102 10. Add `history`
103 11. Most extensions are now enabled by default
104 12. Add support for namespaces and the `namespace` command
105 13. Add `apply`
107 Changes between 0.71 and 0.72
108 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
109 1. procs now allow 'args' and optional parameters in any position
110 2. Add Tcl-compatible expr functions, `rand()`, `srand()` and `pow()`
111 3. Add support for the '-force' option to `file delete`
112 4. Better diagnostics when `source` fails to load a script with a missing quote or bracket
113 5. New +tcl_platform(pathSeparator)+
114 6. Add support settings the modification time with `file mtime`
115 7. `exec` is now fully supported on win32 (mingw32)
116 8. `file join`, `pwd`, `glob` etc. now work for mingw32
117 9. Line editing is now supported for the win32 console (mingw32)
118 10. Add `aio listen` command
120 Changes between 0.70 and 0.71
121 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
122 1. Allow 'args' to be renamed in procs
123 2. Add +$(...)+ shorthand syntax for expressions
124 3. Add automatic reference variables in procs with +&var+ syntax
125 4. Support +jimsh --version+
126 5. Additional variables in +tcl_platform()+
127 6. `local` procs now push existing commands and `upcall` can call them
128 7. Add `loop` command (TclX compatible)
129 8. Add `aio buffering` command
130 9. `info complete` can now return the missing character
131 10. `binary format` and `binary scan` are now (optionally) supported
132 11. Add `string byterange`
133 12. Built-in regexp now support non-greedy repetition (*?, +?, ??)
135 TCL INTRODUCTION
136 -----------------
137 Tcl stands for 'tool command language' and is pronounced
138 'http://www.oxforddictionaries.com/definition/american_english/tickle[tickle]'.
139 It is actually two things: a language and a library.
141 First, Tcl is a simple textual language, intended primarily for
142 issuing commands to interactive programs such as text editors,
143 debuggers, illustrators, and shells.  It has a simple syntax and is also
144 programmable, so Tcl users can write command procedures to provide more
145 powerful commands than those in the built-in set.
147 Second, Tcl is a library package that can be embedded in application
148 programs.  The Tcl library consists of a parser for the Tcl language,
149 routines to implement the Tcl built-in commands, and procedures that
150 allow each application to extend Tcl with additional commands specific
151 to that application.  The application program generates Tcl commands and
152 passes them to the Tcl parser for execution.  Commands may be generated
153 by reading characters from an input source, or by associating command
154 strings with elements of the application's user interface, such as menu
155 entries, buttons, or keystrokes.
157 When the Tcl library receives commands it parses them into component
158 fields and executes built-in commands directly.  For commands implemented
159 by the application, Tcl calls back to the application to execute the
160 commands.  In many cases commands will invoke recursive invocations of the
161 Tcl interpreter by passing in additional strings to execute (procedures,
162 looping commands, and conditional commands all work in this way).
164 An application program gains three advantages by using Tcl for its command
165 language.  First, Tcl provides a standard syntax:  once users know Tcl,
166 they will be able to issue commands easily to any Tcl-based application.
167 Second, Tcl provides programmability.  All a Tcl application needs
168 to do is to implement a few application-specific low-level commands.
169 Tcl provides many utility commands plus a general programming interface
170 for building up complex command procedures.  By using Tcl, applications
171 need not re-implement these features.
173 Third, Tcl can be used as a common language for communicating between
174 applications.  Inter-application communication is not built into the
175 Tcl core described here, but various add-on libraries, such as the Tk
176 toolkit, allow applications to issue commands to each other.  This makes
177 it possible for applications to work together in much more powerful ways
178 than was previously possible.
180 Fourth, Jim Tcl includes a command processor, +jimsh+, which can be
181 used to run standalone Tcl scripts, or to run Tcl commands interactively.
183 This manual page focuses primarily on the Tcl language.  It describes
184 the language syntax and the built-in commands that will be available
185 in any application based on Tcl.  The individual library procedures are
186 described in more detail in separate manual pages, one per procedure.
188 JIMSH COMMAND INTERPRETER
189 -------------------------
190 A simple, but powerful command processor, +jimsh+, is part of Jim Tcl.
191 It may be invoked in interactive mode as:
193   jimsh
195 or to process the Tcl script in a file with:
197   jimsh filename
199 It may also be invoked to execute an immediate script with:
201   jimsh -e "script"
203 Interactive Mode
204 ~~~~~~~~~~~~~~~~
205 Interactive mode reads Tcl commands from standard input, evaluates
206 those commands and prints the results.
208   $ jimsh
209   Welcome to Jim version 0.73, Copyright (c) 2005-8 Salvatore Sanfilippo
210   . info version
211   0.73
212   . lsort [info commands p*]
213   package parray pid popen proc puts pwd
214   . foreach i {a b c} {
215   {> puts $i
216   {> }
217   a
218   b
219   c
220   . bad
221   invalid command name "bad"
222   [error] . exit
223   $
225 If +jimsh+ is configured with line editing (it is by default) and a VT-100-compatible
226 terminal is detected, Emacs-style line editing commands are available, including:
227 arrow keys, +\^W+ to erase a word, +\^U+ to erase the line, +^R+ for reverse incremental search
228 in history. Additionally, the +h+ command may be used to display the command history.
230 Command line history is automatically saved and loaded from +~/.jim_history+
232 In interactive mode, +jimsh+ automatically runs the script +~/.jimrc+ at startup
233 if it exists.
235 INTERPRETERS
236 ------------
237 The central data structure in Tcl is an interpreter (C type 'Jim_Interp').
238 An interpreter consists of a set of command bindings, a set of variable
239 values, and a few other miscellaneous pieces of state.  Each Tcl command
240 is interpreted in the context of a particular interpreter.
242 Some Tcl-based applications will maintain multiple interpreters
243 simultaneously, each associated with a different widget or portion of
244 the application.  Interpreters are relatively lightweight structures.
245 They can be created and deleted quickly, so application programmers should
246 feel free to use multiple interpreters if that simplifies the application.
248 DATA TYPES
249 ----------
250 Tcl supports only one type of data:  strings.  All commands, all arguments
251 to commands, all command results, and all variable values are strings.
253 Where commands require numeric arguments or return numeric results,
254 the arguments and results are passed as strings.  Many commands expect
255 their string arguments to have certain formats, but this interpretation
256 is up to the individual commands.  For example, arguments often contain
257 Tcl command strings, which may get executed as part of the commands.
258 The easiest way to understand the Tcl interpreter is to remember that
259 everything is just an operation on a string.  In many cases Tcl constructs
260 will look similar to more structured constructs from other languages.
261 However, the Tcl constructs are not structured at all; they are just
262 strings of characters, and this gives them a different behaviour than
263 the structures they may look like.
265 Although the exact interpretation of a Tcl string depends on who is doing
266 the interpretation, there are three common forms that strings take:
267 commands, expressions, and lists.  The major sections below discuss
268 these three forms in more detail.
270 BASIC COMMAND SYNTAX
271 --------------------
272 The Tcl language has syntactic similarities to both the Unix shells
273 and Lisp.  However, the interpretation of commands is different
274 in Tcl than in either of those other two systems.
275 A Tcl command string consists of one or more commands separated
276 by newline characters or semi-colons.
277 Each command consists of a collection of fields separated by
278 white space (spaces or tabs).
279 The first field must be the name of a command, and the
280 additional fields, if any, are arguments that will be passed to
281 that command.  For example, the command:
283     set a 22
285 has three fields:  the first, `set`, is the name of a Tcl command, and
286 the last two, 'a' and '22', will be passed as arguments to
287 the `set` command.  The command name may refer either to a built-in
288 Tcl command, an application-specific command bound in with the library
289 procedure 'Jim_CreateCommand', or a command procedure defined with the
290 `proc` built-in command.
292 Arguments are passed literally as text strings.  Individual commands may
293 interpret those strings in any fashion they wish.  The `set` command,
294 for example, will treat its first argument as the name of a variable
295 and its second argument as a string value to assign to that variable.
296 For other commands arguments may be interpreted as integers, lists,
297 file names, or Tcl commands.
299 Command names should normally be typed completely (e.g. no abbreviations).
300 However, if the Tcl interpreter cannot locate a command it invokes a
301 special command named `unknown` which attempts to find or create the
302 command.
304 For example, at many sites `unknown` will search through library
305 directories for the desired command and create it as a Tcl procedure if
306 it is found.  The `unknown` command often provides automatic completion
307 of abbreviated commands, but usually only for commands that were typed
308 interactively.
310 It's probably a bad idea to use abbreviations in command scripts and
311 other forms that will be re-used over time:  changes to the command set
312 may cause abbreviations to become ambiguous, resulting in scripts that
313 no longer work.
315 COMMENTS
316 --------
317 If the first non-blank character in a command is +\#+, then everything
318 from the +#+ up through the next newline character is treated as
319 a comment and ignored.  When comments are embedded inside nested
320 commands (e.g. fields enclosed in braces) they must have properly-matched
321 braces (this is necessary because when Tcl parses the top-level command
322 it doesn't yet know that the nested field will be used as a command so
323 it cannot process the nested comment character as a comment).
325 GROUPING ARGUMENTS WITH DOUBLE-QUOTES
326 -------------------------------------
327 Normally each argument field ends at the next white space, but
328 double-quotes may be used to create arguments with embedded space.
330 If an argument field begins with a double-quote, then the argument isn't
331 terminated by white space (including newlines) or a semi-colon (see below
332 for information on semi-colons); instead it ends at the next double-quote
333 character.  The double-quotes are not included in the resulting argument.
334 For example, the command
336     set a "This is a single argument"
338 will pass two arguments to `set`:  'a' and 'This is a single argument'.
340 Within double-quotes, command substitutions, variable substitutions,
341 and backslash substitutions still occur, as described below.  If the
342 first character of a command field is not a quote, then quotes receive
343 no special interpretation in the parsing of that field.
345 GROUPING ARGUMENTS WITH BRACES
346 ------------------------------
347 Curly braces may also be used for grouping arguments.  They are similar
348 to quotes except for two differences.  First, they nest; this makes them
349 easier to use for complicated arguments like nested Tcl command strings.
350 Second, the substitutions described below for commands, variables, and
351 backslashes do *not* occur in arguments enclosed in braces, so braces
352 can be used to prevent substitutions where they are undesirable.
354 If an argument field begins with a left brace, then the argument ends
355 at the matching right brace.  Tcl will strip off the outermost layer
356 of braces and pass the information between the braces to the command
357 without any further modification.  For example, in the command
359     set a {xyz a {b c d}}
361 the `set` command will receive two arguments: 'a'
362 and 'xyz a {b c d}'.
364 When braces or quotes are in effect, the matching brace or quote need
365 not be on the same line as the starting quote or brace; in this case
366 the newline will be included in the argument field along with any other
367 characters up to the matching brace or quote.  For example, the `eval`
368 command takes one argument, which is a command string; `eval` invokes
369 the Tcl interpreter to execute the command string.  The command
371     eval {
372       set a 22
373       set b 33
374     }
376 will assign the value '22' to 'a' and '33' to 'b'.
378 If the first character of a command field is not a left
379 brace, then neither left nor right
380 braces in the field will be treated specially (except as part of
381 variable substitution; see below).
383 COMMAND SUBSTITUTION WITH BRACKETS
384 ----------------------------------
385 If an open bracket occurs in a field of a command, then command
386 substitution occurs (except for fields enclosed in braces).  All of the
387 text up to the matching close bracket is treated as a Tcl command and
388 executed immediately.  Then the result of that command is substituted
389 for the bracketed text.  For example, consider the command
391     set a [set b]
393 When the `set` command has only a single argument, it is the name of a
394 variable and `set` returns the contents of that variable.  In this case,
395 if variable 'b' has the value 'foo', then the command above is equivalent
396 to the command
398     set a foo
400 Brackets can be used in more complex ways.  For example, if the variable
401 'b' has the value 'foo' and the variable 'c' has the value 'gorp',
402 then the command
404     set a xyz[set b].[set c]
406 is equivalent to the command
408     set a xyzfoo.gorp
411 A bracketed command may contain multiple commands separated by newlines
412 or semi-colons in the usual fashion.  In this case the value of the last
413 command is used for substitution.  For example, the command
415     set a x[set b 22
416     expr $b+2]x
418 is equivalent to the command
420     set a x24x
423 If a field is enclosed in braces then the brackets and the characters
424 between them are not interpreted specially; they are passed through to
425 the argument verbatim.
427 VARIABLE SUBSTITUTION WITH $
428 ----------------------------
429 The dollar sign (+$+) may be used as a special shorthand form for
430 substituting variable values.  If +$+ appears in an argument that isn't
431 enclosed in braces then variable substitution will occur.  The characters
432 after the +$+, up to the first character that isn't a number, letter,
433 or underscore, are taken as a variable name and the string value of that
434 variable is substituted for the name.
436 For example, if variable 'foo' has the value 'test', then the command
438     set a $foo.c
440 is equivalent to the command
442     set a test.c
444 There are two special forms for variable substitution.  If the next
445 character after the name of the variable is an open parenthesis, then
446 the variable is assumed to be an array name, and all of the characters
447 between the open parenthesis and the next close parenthesis are taken as
448 an index into the array.  Command substitutions and variable substitutions
449 are performed on the information between the parentheses before it is
450 used as an index.
452 For example, if the variable 'x' is an array with one element named
453 'first' and value '87' and another element named '14' and value 'more',
454 then the command
456     set a xyz$x(first)zyx
458 is equivalent to the command
460     set a xyz87zyx
462 If the variable 'index' has the value '14', then the command
464     set a xyz$x($index)zyx
466 is equivalent to the command
468     set a xyzmorezyx
470 For more information on arrays, see VARIABLES AND ARRAYS below.
472 The second special form for variables occurs when the dollar sign is
473 followed by an open curly brace.  In this case the variable name consists
474 of all the characters up to the next curly brace.
476 Array references are not possible in this form:  the name between braces
477 is assumed to refer to a scalar variable.  For example, if variable
478 'foo' has the value 'test', then the command
480     set a abc${foo}bar
482 is equivalent to the command
484     set a abctestbar
487 Variable substitution does not occur in arguments that are enclosed in
488 braces:  the dollar sign and variable name are passed through to the
489 argument verbatim.
491 The dollar sign abbreviation is simply a shorthand form.  +$a+ is
492 completely equivalent to +[set a]+; it is provided as a convenience
493 to reduce typing.
495 SEPARATING COMMANDS WITH SEMI-COLONS
496 ------------------------------------
497 Normally, each command occupies one line (the command is terminated by a
498 newline character).  However, semi-colon (+;+) is treated as a command
499 separator character; multiple commands may be placed on one line by
500 separating them with a semi-colon.  Semi-colons are not treated as
501 command separators if they appear within curly braces or double-quotes.
503 BACKSLASH SUBSTITUTION
504 ----------------------
505 Backslashes may be used to insert non-printing characters into command
506 fields and also to insert special characters like braces and brackets
507 into fields without them being interpreted specially as described above.
509 The backslash sequences understood by the Tcl interpreter are
510 listed below.  In each case, the backslash
511 sequence is replaced by the given character:
512 [[BackslashSequences]]
513 +{backslash}b+::
514     Backspace (0x8)
516 +{backslash}f+::
517     Form feed (0xc)
519 +{backslash}n+::
520     Newline (0xa)
522 +{backslash}r+::
523     Carriage-return (0xd).
525 +{backslash}t+::
526     Tab (0x9).
528 +{backslash}v+::
529     Vertical tab (0xb).
531 +{backslash}{+::
532     Left brace ({).
534 +{backslash}}+::
535     Right brace (}).
537 +{backslash}[+::
538     Open bracket ([).
540 +{backslash}]+::
541     Close bracket (]).
543 +{backslash}$+::
544     Dollar sign ($).
546 +{backslash}<space>+::
547     Space ( ): doesn't terminate argument.
549 +{backslash};+::
550     Semi-colon: doesn't terminate command.
552 +{backslash}"+::
553     Double-quote.
555 +{backslash}<newline>+::
556     Nothing:  this joins two lines together
557     into a single line.  This backslash feature is unique in that
558     it will be applied even when the sequence occurs within braces.
560 +{backslash}{backslash}+::
561     Backslash ('{backslash}').
563 +{backslash}ddd+::
564     The digits +'ddd'+ (one, two, or three of them) give the octal value of
565     the character.  Note that Jim supports null characters in strings.
567 +{backslash}unnnn+::
568 +{backslash}u\{nnn\}+::
569 +{backslash}Unnnnnnnn+::
570     The UTF-8 encoding of the unicode codepoint represented by the hex digits, +'nnnn'+, is inserted.
571     The 'u' form allows for one to four hex digits.
572     The 'U' form allows for one to eight hex digits.
573     The 'u\{nnn\}' form allows for one to eight hex digits, but makes it easier to insert
574     characters UTF-8 characters which are followed by a hex digit.
576 For example, in the command
578     set a \{x\[\ yz\141
580 the second argument to `set` will be +{x[ yza+.
582 If a backslash is followed by something other than one of the options
583 described above, then the backslash is transmitted to the argument
584 field without any special processing, and the Tcl scanner continues
585 normal processing with the next character.  For example, in the
586 command
588     set \*a \\\{foo
590 The first argument to `set` will be +{backslash}*a+ and the second
591 argument will be +{backslash}{foo+.
593 If an argument is enclosed in braces, then backslash sequences inside
594 the argument are parsed but no substitution occurs (except for
595 backslash-newline):  the backslash
596 sequence is passed through to the argument as is, without making
597 any special interpretation of the characters in the backslash sequence.
598 In particular, backslashed braces are not counted in locating the
599 matching right brace that terminates the argument.
600 For example, in the
601 command
603     set a {\{abc}
605 the second argument to `set` will be +{backslash}{abc+.
607 This backslash mechanism is not sufficient to generate absolutely
608 any argument structure; it only covers the
609 most common cases.  To produce particularly complicated arguments
610 it is probably easiest to use the `format` command along with
611 command substitution.
613 STRING AND LIST INDEX SPECIFICATIONS
614 ------------------------------------
616 Many string and list commands take one or more 'index' parameters which
617 specify a position in the string relative to the start or end of the string/list.
619 The index may be one of the following forms:
621 +integer+::
622     A simple integer, where '0' refers to the first element of the string
623     or list.
625 +integer+integer+ or::
626 +integer-integer+::
627     The sum or difference of the two integers. e.g. +2+3+ refers to the 5th element.
628     This is useful when used with (e.g.) +$i+1+ rather than the more verbose
629     +[expr {$i+1\}]+
631 +end+::
632     The last element of the string or list.
634 +end-integer+::
635     The 'nth-from-last' element of the string or list.
637 COMMAND SUMMARY
638 ---------------
639 1. A command is just a string.
640 2. Within a string commands are separated by newlines or semi-colons
641    (unless the newline or semi-colon is within braces or brackets
642    or is backslashed).
643 3. A command consists of fields.  The first field is the name of the command.
644    The other fields are strings that are passed to that command as arguments.
645 4. Fields are normally separated by white space.
646 5. Double-quotes allow white space and semi-colons to appear within
647    a single argument.
648    Command substitution, variable substitution, and backslash substitution
649    still occur inside quotes.
650 6. Braces defer interpretation of special characters.
651    If a field begins with a left brace, then it consists of everything
652    between the left brace and the matching right brace. The
653    braces themselves are not included in the argument.
654    No further processing is done on the information between the braces
655    except that backslash-newline sequences are eliminated.
656 7. If a field doesn't begin with a brace then backslash,
657    variable, and command substitution are done on the field.  Only a
658    single level of processing is done:  the results of one substitution
659    are not scanned again for further substitutions or any other
660    special treatment.  Substitution can
661    occur on any field of a command, including the command name
662    as well as the arguments.
663 8. If the first non-blank character of a command is a +\#+, everything
664    from the +#+ up through the next newline is treated as a comment
665    and ignored.
667 EXPRESSIONS
668 -----------
669 The second major interpretation applied to strings in Tcl is
670 as expressions.  Several commands, such as `expr`, `for`,
671 and `if`, treat one or more of their arguments as expressions
672 and call the Tcl expression processors ('Jim_ExprLong',
673 'Jim_ExprBoolean', etc.) to evaluate them.
675 The operators permitted in Tcl expressions are a subset of
676 the operators permitted in C expressions, and they have the
677 same meaning and precedence as the corresponding C operators.
678 Expressions almost always yield numeric results
679 (integer or floating-point values).
680 For example, the expression
682     8.2 + 6
684 evaluates to 14.2.
686 Tcl expressions differ from C expressions in the way that
687 operands are specified, and in that Tcl expressions support
688 non-numeric operands and string comparisons.
690 A Tcl expression consists of a combination of operands, operators,
691 and parentheses.
693 White space may be used between the operands and operators and
694 parentheses; it is ignored by the expression processor.
695 Where possible, operands are interpreted as integer values.
697 Integer values may be specified in decimal (the normal case) or in
698 hexadecimal (if the first two characters of the operand are '0x').
699 Note that Jim Tcl does *not* treat numbers with leading zeros as octal.
701 If an operand does not have one of the integer formats given
702 above, then it is treated as a floating-point number if that is
703 possible.  Floating-point numbers may be specified in any of the
704 ways accepted by an ANSI-compliant C compiler (except that the
705 'f', 'F', 'l', and 'L' suffixes will not be permitted in
706 most installations).  For example, all of the
707 following are valid floating-point numbers:  2.1, 3., 6e4, 7.91e+16.
709 If no numeric interpretation is possible, then an operand is left
710 as a string (and only a limited set of operators may be applied to
711 it).
713 String constants representing boolean constants
714 (+'0'+, +'1'+, +'false'+, +'off'+, +'no'+, +'true'+, +'on'+, +'yes'+)
715 are also recognized and can be used in logical operations.
717 1. Operands may be specified in any of the following ways:
719 2. As a numeric value, either integer or floating-point.
721 3. As one of valid boolean constants
723 4. As a Tcl variable, using standard '$' notation.
724 The variable's value will be used as the operand.
726 5. As a string enclosed in double-quotes.
727 The expression parser will perform backslash, variable, and
728 command substitutions on the information between the quotes,
729 and use the resulting value as the operand
731 6. As a string enclosed in braces.
732 The characters between the open brace and matching close brace
733 will be used as the operand without any substitutions.
735 7. As a Tcl command enclosed in brackets.
736 The command will be executed and its result will be used as
737 the operand.
739 Where substitutions occur above (e.g. inside quoted strings), they
740 are performed by the expression processor.
741 However, an additional layer of substitution may already have
742 been performed by the command parser before the expression
743 processor was called.
745 As discussed below, it is usually best to enclose expressions
746 in braces to prevent the command parser from performing substitutions
747 on the contents.
749 For some examples of simple expressions, suppose the variable 'a' has
750 the value 3 and the variable 'b' has the value 6.  Then the expression
751 on the left side of each of the lines below will evaluate to the value
752 on the right side of the line:
754     $a + 3.1                6.1
755     2 + "$a.$b"             5.6
756     4*[llength "6 2"]       8
757     {word one} < "word $a"  0
759 The valid operators are listed below, grouped in decreasing order
760 of precedence:
761 [[OperatorPrecedence]]
762 +int() double() round() abs(), rand(), srand()+::
763     Unary functions (except rand() which takes no arguments)
764     * +'int()'+ converts the numeric argument to an integer by truncating down.
765     * +'double()'+ converts the numeric argument to floating point.
766     * +'round()'+ converts the numeric argument to the closest integer value.
767     * +'abs()'+ takes the absolute value of the numeric argument.
768     * +'rand()'+ returns a pseudo-random floating-point value in the range (0,1).
769     * +'srand()'+ takes an integer argument to (re)seed the random number generator. Returns the first random number from that seed.
771 +sin() cos() tan() asin() acos() atan() sinh() cosh() tanh() ceil() floor() exp() log() log10() sqrt()+::
772     Unary math functions.
773     If Jim is compiled with math support, these functions are available.
775 +- + ~ !+::
776     Unary minus, unary plus, bit-wise NOT, logical NOT.  None of these operands
777     may be applied to string operands, and bit-wise NOT may be
778     applied only to integers.
780 +** pow(x,y)+::
781     Power. e.g. 'x^y^'. If Jim is compiled with math support, supports doubles and
782     integers. Otherwise supports integers only. (Note that the math-function form
783     has the same highest precedence)
785 +* / %+::
786     Multiply, divide, remainder.  None of these operands may be
787     applied to string operands, and remainder may be applied only
788     to integers.
790 ++ -+::
791     Add and subtract.  Valid for any numeric operands.
793 +<<  >> <<< >>>+::
794     Left and right shift, left and right rotate.  Valid for integer operands only.
796 +<  >  \<=  >=+::
797     Boolean less, greater, less than or equal, and greater than or equal.
798     Each operator produces 1 if the condition is true, 0 otherwise.
799     These operators may be applied to strings as well as numeric operands,
800     in which case string comparison is used.
802 +==  !=+::
803     Boolean equal and not equal.  Each operator produces a zero/one result.
804     Valid for all operand types. *Note* that values will be converted to integers
805     if possible, then floating point types, and finally strings will be compared.
806     It is recommended that 'eq' and 'ne' should be used for string comparison.
808 +eq ne+::
809     String equal and not equal.  Uses the string value directly without
810     attempting to convert to a number first.
812 +in ni+::
813     String in list and not in list. For 'in', result is 1 if the left operand (as a string)
814     is contained in the right operand (as a list), or 0 otherwise. The result for
815     +{$a ni $list}+ is equivalent to +{!($a in $list)}+.
817 +&+::
818     Bit-wise AND.  Valid for integer operands only.
820 +|+::
821     Bit-wise OR.  Valid for integer operands only.
823 +^+::
824     Bit-wise exclusive OR.  Valid for integer operands only.
826 +&&+::
827     Logical AND.  Produces a 1 result if both operands are non-zero, 0 otherwise.
828     Valid for numeric operands only (integers or floating-point).
830 +||+::
831     Logical OR.  Produces a 0 result if both operands are zero, 1 otherwise.
832     Valid for numeric operands only (integers or floating-point).
834 +x ? y : z+::
835     If-then-else, as in C.  If +'x'+
836     evaluates to non-zero, then the result is the value of +'y'+.
837     Otherwise the result is the value of +'z'+.
838     The +'x'+ operand must have a numeric value, while +'y'+ and +'z'+ can
839     be of any type.
841 See the C manual for more details on the results
842 produced by each operator.
843 All of the binary operators group left-to-right within the same
844 precedence level.  For example, the expression
846     4*2 < 7
848 evaluates to 0.
850 The +&&+, +||+, and +?:+ operators have 'lazy evaluation', just as
851 in C, which means that operands are not evaluated if they are not
852 needed to determine the outcome.  For example, in
854     $v ? [a] : [b]
856 only one of +[a]+ or +[b]+ will actually be evaluated,
857 depending on the value of +$v+.
859 All internal computations involving integers are done with the C
860 type 'long long' if available, or 'long' otherwise, and all internal
861 computations involving floating-point are done with the C type
862 'double'.
864 When converting a string to floating-point, exponent overflow is
865 detected and results in a Tcl error.
866 For conversion to integer from string, detection of overflow depends
867 on the behaviour of some routines in the local C library, so it should
868 be regarded as unreliable.
869 In any case, overflow and underflow are generally not detected
870 reliably for intermediate results.
872 Conversion among internal representations for integer, floating-point,
873 string operands is done automatically as needed.
874 For arithmetic computations, integers are used until some
875 floating-point number is introduced, after which floating-point is used.
876 For example,
878     5 / 4
880 yields the result 1, while
882     5 / 4.0
883     5 / ( [string length "abcd"] + 0.0 )
885 both yield the result 1.25.
887 String values may be used as operands of the comparison operators,
888 although the expression evaluator tries to do comparisons as integer
889 or floating-point when it can.
890 If one of the operands of a comparison is a string and the other
891 has a numeric value, the numeric operand is converted back to
892 a string using the C 'sprintf' format specifier
893 '%d' for integers and '%g' for floating-point values.
894 For example, the expressions
896     "0x03" > "2"
897     "0y" < "0x12"
899 both evaluate to 1.  The first comparison is done using integer
900 comparison, and the second is done using string comparison after
901 the second operand is converted to the string '18'.
903 In general it is safest to enclose an expression in braces when
904 entering it in a command:  otherwise, if the expression contains
905 any white space then the Tcl interpreter will split it
906 among several arguments.  For example, the command
908     expr $a + $b
910 results in three arguments being passed to `expr`:  +$a+,
911 \+, and +$b+.  In addition, if the expression isn't in braces
912 then the Tcl interpreter will perform variable and command substitution
913 immediately (it will happen in the command parser rather than in
914 the expression parser).  In many cases the expression is being
915 passed to a command that will evaluate the expression later (or
916 even many times if, for example, the expression is to be used to
917 decide when to exit a loop).  Usually the desired goal is to re-do
918 the variable or command substitutions each time the expression is
919 evaluated, rather than once and for all at the beginning.  For example,
920 the command
922     for {set i 1} $i<=10 {incr i} {...}        ** WRONG **
924 is probably intended to iterate over all values of +i+ from 1 to 10.
925 After each iteration of the body of the loop, `for` will pass
926 its second argument to the expression evaluator to see whether or not
927 to continue processing.  Unfortunately, in this case the value of +i+
928 in the second argument will be substituted once and for all when the
929 `for` command is parsed.  If +i+ was 0 before the `for`
930 command was invoked then the second argument of `for` will be +0\<=10+
931 which will always evaluate to 1, even though +i+ eventually
932 becomes greater than 10.  In the above case the loop will never
933 terminate.  Instead, the expression should be placed in braces:
935     for {set i 1} {$i<=10} {incr i} {...}      ** RIGHT **
937 This causes the substitution of 'i'
938 to be delayed; it will be re-done each time the expression is
939 evaluated, which is the desired result.
941 LISTS
942 -----
943 The third major way that strings are interpreted in Tcl is as lists.
944 A list is just a string with a list-like structure
945 consisting of fields separated by white space.  For example, the
946 string
948     Al Sue Anne John
950 is a list with four elements or fields.
951 Lists have the same basic structure as command strings, except
952 that a newline character in a list is treated as a field separator
953 just like space or tab.  Conventions for braces and quotes
954 and backslashes are the same for lists as for commands.  For example,
955 the string
957     a b\ c {d e {f g h}}
959 is a list with three elements:  +a+, +b c+, and +d e {f g h}+.
961 Whenever an element is extracted from a list, the same rules about
962 braces and quotes and backslashes are applied as for commands.  Thus in
963 the example above when the third element is extracted from the list,
964 the result is
966     d e {f g h}
968 (when the field was extracted, all that happened was to strip off
969 the outermost layer of braces).  Command substitution and
970 variable substitution are never
971 made on a list (at least, not by the list-processing commands; the
972 list can always be passed to the Tcl interpreter for evaluation).
974 The Tcl commands `concat`, `foreach`, `lappend`, `lindex`, `linsert`,
975 `list`, `llength`, `lrange`, `lreplace`, `lsearch`, and `lsort` allow
976 you to build lists, extract elements from them, search them, and perform
977 other list-related functions.
979 Advanced list commands include `lrepeat`, `lreverse`, `lmap`, `lassign`, `lset`.
981 LIST EXPANSION
982 --------------
984 A new addition to Tcl 8.5 is the ability to expand a list into separate
985 arguments. Support for this feature is also available in Jim.
987 Consider the following attempt to exec a list:
989     set cmd {ls -l}
990     exec $cmd
992 This will attempt to exec a command named "ls -l", which will clearly not
993 work. Typically eval and concat are required to solve this problem, however
994 it can be solved much more easily with +\{*\}+.
996     exec {*}$cmd
998 This will expand the following argument into individual elements and then evaluate
999 the resulting command.
1001 Note that the official Tcl syntax is +\{*\}+, however +\{expand\}+ is retained
1002 for backward compatibility with experimental versions of this feature.
1004 REGULAR EXPRESSIONS
1005 -------------------
1006 Tcl provides two commands that support string matching using regular
1007 expressions, `regexp` and `regsub`, as well as `switch -regexp` and
1008 `lsearch -regexp`.
1010 Regular expressions may be implemented one of two ways. Either using the system's C library
1011 POSIX regular expression support, or using the built-in regular expression engine.
1012 The differences between these are described below.
1014 *NOTE* Tcl 7.x and 8.x use perl-style Advanced Regular Expressions (+ARE+).
1016 POSIX Regular Expressions
1017 ~~~~~~~~~~~~~~~~~~~~~~~~~
1018 If the system supports POSIX regular expressions, and UTF-8 support is not enabled,
1019 this support will be used by default. The type of regular expressions supported are
1020 Extended Regular Expressions (+ERE+) rather than Basic Regular Expressions (+BRE+).
1021 See REG_EXTENDED in the documentation.
1023 Using the system-supported POSIX regular expressions will typically
1024 make for the smallest code size, but some features such as UTF-8
1025 and +{backslash}w+, +{backslash}d+, +{backslash}s+ are not supported, and null characters
1026 in strings are not supported.
1028 See regex(3) and regex(7) for full details.
1030 Jim built-in Regular Expressions
1031 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1032 The Jim built-in regular expression engine may be selected with +./configure --with-jim-regexp+
1033 or it will be selected automatically if UTF-8 support is enabled.
1035 This engine supports UTF-8 as well as some +ARE+ features. The differences with both Tcl 7.x/8.x
1036 and POSIX are highlighted below.
1038 1. UTF-8 strings and patterns are both supported
1039 2. All Tcl character classes are supported (e.g. +[:alnum:]+, +[:digit:]+, +[:space:]+), but...
1040 3. Character classes apply to ASCII characters only
1041 4. Supported shorthand character classes: +{backslash}w+ = +[:alnum:]+, +{backslash}W+ = +^[:alnum:]+, +{backslash}d+ = +[:digit:],+ +{backslash}D+ = +^[:digit:],+ +{backslash}s+ = +[:space:]+, + +{backslash}S+ = +^[:space:]+
1042 5. Supported constraint escapes: +{backslash}m+ = +{backslash}<+ = start of word, +{backslash}M+ = +{backslash}>+ = end of word
1043 6. Backslash escapes may be used within regular expressions, such as +{backslash}n+ = newline, +{backslash}uNNNN+ = unicode
1044 7. Partially supported constraint escapes: +{backslash}A+ = start of string, +{backslash}Z+ = end of string
1045 8. Support for the +?+ non-greedy quantifier. e.g. +*?+
1046 9. Support for non-capturing parentheses +(?:...)+
1047 10. Jim Tcl considers that both patterns and strings end at a null character (+\x00+)
1049 COMMAND RESULTS
1050 ---------------
1051 Each command produces two results:  a code and a string.  The
1052 code indicates whether the command completed successfully or not,
1053 and the string gives additional information.  The valid codes are
1054 defined in jim.h, and are:
1056 +JIM_OK(0)+::
1057     This is the normal return code, and indicates that the command completed
1058     successfully.  The string gives the command's return value.
1060 +JIM_ERR(1)+::
1061     Indicates that an error occurred; the string gives a message describing
1062     the error.
1064 +JIM_RETURN(2)+::
1065     Indicates that the `return` command has been invoked, and that the
1066     current procedure (or top-level command or `source` command)
1067     should return immediately.  The
1068     string gives the return value for the procedure or command.
1070 +JIM_BREAK(3)+::
1071     Indicates that the `break` command has been invoked, so the
1072     innermost loop should abort immediately.  The string should always
1073     be empty.
1075 +JIM_CONTINUE(4)+::
1076     Indicates that the `continue` command has been invoked, so the
1077     innermost loop should go on to the next iteration.  The string
1078     should always be empty.
1080 +JIM_SIGNAL(5)+::
1081     Indicates that a signal was caught while executing a commands.
1082     The string contains the name of the signal caught.
1083     See the `signal` and `catch` commands.
1085 +JIM_EXIT(6)+::
1086     Indicates that the command called the `exit` command.
1087     The string contains the exit code.
1089 Tcl programmers do not normally need to think about return codes,
1090 since +JIM_OK+ is almost always returned.  If anything else is returned
1091 by a command, then the Tcl interpreter immediately stops processing
1092 commands and returns to its caller.  If there are several nested
1093 invocations of the Tcl interpreter in progress, then each nested
1094 command will usually return the error to its caller, until eventually
1095 the error is reported to the top-level application code.  The
1096 application will then display the error message for the user.
1098 In a few cases, some commands will handle certain `error` conditions
1099 themselves and not return them upwards.  For example, the `for`
1100 command checks for the +JIM_BREAK+ code; if it occurs, then `for`
1101 stops executing the body of the loop and returns +JIM_OK+ to its
1102 caller.  The `for` command also handles +JIM_CONTINUE+ codes and the
1103 procedure interpreter handles +JIM_RETURN+ codes.  The `catch`
1104 command allows Tcl programs to catch errors and handle them without
1105 aborting command interpretation any further.
1107 The `info returncodes` command may be used to programmatically map between
1108 return codes and names.
1110 PROCEDURES
1111 ----------
1112 Tcl allows you to extend the command interface by defining
1113 procedures.  A Tcl procedure can be invoked just like any other Tcl
1114 command (it has a name and it receives one or more arguments).
1115 The only difference is that its body isn't a piece of C code linked
1116 into the program; it is a string containing one or more other
1117 Tcl commands.
1119 The `proc` command is used to create a new Tcl command procedure:
1121 +*proc* 'name arglist ?statics? body'+
1123 The new command is named +'name'+, and it replaces any existing command
1124 there may have been by that name. Whenever the new command is
1125 invoked, the contents of +'body'+ will be executed by the Tcl
1126 interpreter.
1128 +'arglist'+ specifies the formal arguments to the procedure.
1129 It consists of a list, possibly empty, of the following
1130 argument specifiers:
1132 +name+::
1133     Required Argument - A simple argument name.
1135 +{name default}+::
1136     Optional Argument - A two-element list consisting of the
1137     argument name, followed by the default value, which will
1138     be used if the corresponding argument is not supplied.
1140 +&name+::
1141     Reference Argument - The caller is expected to pass the name of
1142     an existing variable. An implicit +`upvar` 1 origname name+ is done
1143     to make the variable available in the proc scope.
1145 +*args*+::
1146     Variable Argument - The special name +'args'+, which is
1147     assigned all remaining arguments (including none) as a list. The
1148     variable argument may only be specified once. Note that
1149     the syntax +{args newname}+ may be used to retain the special
1150     behaviour of +'args'+ with a different local name. In this case,
1151     the variable is named +'newname'+ rather than +'args'+.
1153 When the command is invoked, a local variable will be created for each of
1154 the formal arguments to the procedure; its value will be the value
1155 of corresponding argument in the invoking command or the argument's
1156 default value.
1158 Arguments with default values need not be specified in a procedure
1159 invocation.  However, there must be enough actual arguments for all
1160 required arguments, and there must not be any extra actual arguments
1161 (unless the Variable Argument is specified).
1163 Actual arguments are assigned to formal arguments as in left-to-right
1164 order with the following precedence.
1166 1. Required Arguments (including Reference Arguments)
1167 2. Optional Arguments
1168 3. Variable Argument
1170 The following example illustrates precedence. Assume a procedure declaration:
1172     proc p {{a A} args b {c C} d} {...}
1174 This procedure requires at least two arguments, but can accept an unlimited number.
1175 The following table shows how various numbers of arguments are assigned.
1176 Values marked as +-+ are assigned the default value.
1178 [width="40%",frame="topbot",options="header"]
1179 |==============
1180 |Number of arguments|a|args|b|c|d
1181 |2|-|-|1|-|2
1182 |3|1|-|2|-|3
1183 |4|1|-|2|3|4
1184 |5|1|2|3|4|5
1185 |6|1|2,3|4|5|6
1186 |==============
1188 When +'body'+ is being executed, variable names normally refer to local
1189 variables, which are created automatically when referenced and deleted
1190 when the procedure returns.  One local variable is automatically created
1191 for each of the procedure's arguments.  Global variables can be
1192 accessed by invoking the `global` command or via the +::+ prefix.
1194 New in Jim
1195 ~~~~~~~~~~
1196 In addition to procedure arguments, Jim procedures may declare static variables.
1197 These variables scoped to the procedure and initialised at procedure definition.
1198 Either from the static variable definition, or from the enclosing scope.
1200 Consider the following example:
1202     jim> set a 1
1203     jim> proc a {} {a {b 2}} {
1204         set c 1
1205         puts "$a $b $c"
1206         incr a
1207         incr b
1208         incr c
1209     }
1210     jim> a
1211     1 2 1
1212     jim> a
1213     2 3 1
1215 The static variable +'a'+ has no initialiser, so it is initialised from
1216 the enclosing scope with the value 1. (Note that it is an error if there
1217 is no variable with the same name in the enclosing scope). However +'b'+
1218 has an initialiser, so it is initialised to 2.
1220 Unlike a local variable, the value of a static variable is retained across
1221 invocations of the procedure.
1223 See the `proc` command for information on how to define procedures
1224 and what happens when they are invoked. See also NAMESPACES.
1226 VARIABLES - SCALARS AND ARRAYS
1227 ------------------------------
1228 Tcl allows the definition of variables and the use of their values
1229 either through '$'-style variable substitution, the `set`
1230 command, or a few other mechanisms.
1232 Variables need not be declared:  a new variable will automatically
1233 be created each time a new variable name is used.
1235 Tcl supports two types of variables:  scalars and arrays.
1236 A scalar variable has a single value, whereas an array variable
1237 can have any number of elements, each with a name (called
1238 its 'index') and a value.
1240 Array indexes may be arbitrary strings; they need not be numeric.
1241 Parentheses are used refer to array elements in Tcl commands.
1242 For example, the command
1244     set x(first) 44
1246 will modify the element of 'x' whose index is 'first'
1247 so that its new value is '44'.
1249 Two-dimensional arrays can be simulated in Tcl by using indexes
1250 that contain multiple concatenated values.
1251 For example, the commands
1253     set a(2,3) 1
1254     set a(3,6) 2
1256 set the elements of 'a' whose indexes are '2,3' and '3,6'.
1258 In general, array elements may be used anywhere in Tcl that scalar
1259 variables may be used.
1261 If an array is defined with a particular name, then there may
1262 not be a scalar variable with the same name.
1264 Similarly, if there is a scalar variable with a particular
1265 name then it is not possible to make array references to the
1266 variable.
1268 To convert a scalar variable to an array or vice versa, remove
1269 the existing variable with the `unset` command.
1271 The `array` command provides several features for dealing
1272 with arrays, such as querying the names of all the elements of
1273 the array and converting between an array and a list.
1275 Variables may be either global or local.  If a variable
1276 name is used when a procedure isn't being executed, then it
1277 automatically refers to a global variable.  Variable names used
1278 within a procedure normally refer to local variables associated with that
1279 invocation of the procedure.  Local variables are deleted whenever
1280 a procedure exits.  Either `global` command may be used to request
1281 that a name refer to a global variable for the duration of the current
1282 procedure (this is somewhat analogous to 'extern' in C), or the variable
1283 may be explicitly scoped with the +::+ prefix. For example
1285     set a 1
1286     set b 2
1287     proc p {} {
1288         set c 3
1289         global a
1291         puts "$a $::b $c"
1292     }
1293     p
1295 will output:
1297     1 2 3
1299 ARRAYS AS LISTS IN JIM
1300 ----------------------
1301 Unlike Tcl, Jim can automatically convert between a list (with an even
1302 number of elements) and an array value. This is similar to the way Tcl
1303 can convert between a string and a list.
1305 For example:
1307   set a {1 one 2 two}
1308   puts $a(2)
1310 will output:
1312   two
1314 Thus `array set` is equivalent to `set` when the variable does not
1315 exist or is empty.
1317 The reverse is also true where an array will be converted into
1318 a list.
1320   set a(1) one; set a(2) two
1321   puts $a
1323 will output:
1325   1 one 2 two
1327 DICTIONARY VALUES
1328 -----------------
1329 Tcl 8.5 introduced the dict command, and Jim Tcl has added a version
1330 of this command. Dictionaries provide efficient access to key-value
1331 pairs, just like arrays, but dictionaries are pure values. This
1332 means that you can pass them to a procedure just as a list or a
1333 string. Tcl dictionaries are therefore much more like Tcl lists,
1334 except that they represent a mapping from keys to values, rather
1335 than an ordered sequence.
1337 You can nest dictionaries, so that the value for a particular key
1338 consists of another dictionary. That way you can elegantly build
1339 complicated data structures, such as hierarchical databases. You
1340 can also combine dictionaries with other Tcl data structures. For
1341 instance, you can build a list of dictionaries that themselves
1342 contain lists.
1344 Dictionaries are values that contain an efficient, order-preserving
1345 mapping from arbitrary keys to arbitrary values. Each key in the
1346 dictionary maps to a single value. They have a textual format that
1347 is exactly that of any list with an even number of elements, with
1348 each mapping in the dictionary being represented as two items in
1349 the list. When a command takes a dictionary and produces a new
1350 dictionary based on it (either returning it or writing it back into
1351 the variable that the starting dictionary was read from) the new
1352 dictionary will have the same order of keys, modulo any deleted
1353 keys and with new keys added on to the end. When a string is
1354 interpreted as a dictionary and it would otherwise have duplicate
1355 keys, only the last value for a particular key is used; the others
1356 are ignored, meaning that, "apple banana" and "apple carrot apple
1357 banana" are equivalent dictionaries (with different string
1358 representations).
1360 Note that in Jim, arrays are implemented as dictionaries.
1361 Thus automatic conversion between lists and dictionaries applies
1362 as it does for arrays.
1364   jim> dict set a 1 one
1365   1 one
1366   jim> dict set a 2 two
1367   1 one 2 two
1368   jim> puts $a
1369   1 one 2 two
1370   jim> puts $a(2)
1371   two
1372   jim> dict set a 3 T three
1373   1 one 2 two 3 {T three}
1375 See the `dict` command for more details.
1377 NAMESPACES
1378 ----------
1379 Tcl added namespaces as a mechanism avoiding name clashes, especially in applications
1380 including a number of 3rd party components. While there is less need for namespaces
1381 in Jim Tcl (which does not strive to support large applications), it is convenient to
1382 provide a subset of the support for namespaces to easy porting code from Tcl.
1384 Jim Tcl currently supports "light-weight" namespaces which should be adequate for most
1385 purposes. This feature is currently experimental. See README.namespaces for more information
1386 and the documentation of the `namespace` command.
1388 GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION
1389 -----------------------------------------------
1390 Unlike Tcl, Jim has some sophisticated support for functional programming.
1391 These are described briefly below.
1393 More information may be found at http://wiki.tcl.tk/13847
1395 References
1396 ~~~~~~~~~~
1397 A reference can be thought of as holding a value with one level of indirection,
1398 where the value may be garbage collected when unreferenced.
1399 Consider the following example:
1401     jim> set r [ref "One String" test]
1402     <reference.<test___>.00000000000000000000>
1403     jim> getref $r
1404     One String
1406 The operation `ref` creates a references to the value specified by the
1407 first argument. (The second argument is a "type" used for documentation purposes).
1409 The operation `getref` is the dereferencing operation which retrieves the value
1410 stored in the reference.
1412     jim> setref $r "New String"
1413     New String
1414     jim> getref $r
1415     New String
1417 The operation `setref` replaces the value stored by the reference. If the old value
1418 is no longer accessible by any reference, it will eventually be automatically be garbage
1419 collected.
1421 Garbage Collection
1422 ~~~~~~~~~~~~~~~~~~
1423 Normally, all values in Tcl are passed by value. As such values are copied and released
1424 automatically as necessary.
1426 With the introduction of references, it is possible to create values whose lifetime
1427 transcend their scope. To support this, case, the Jim system will periodically identify
1428 and discard objects which are no longer accessible by any reference.
1430 The `collect` command may be used to force garbage collection.  Consider a reference created
1431 with a finalizer:
1433     jim> proc f {ref value} { puts "Finaliser called for $ref,$value" }
1434     jim> set r [ref "One String" test f]
1435     <reference.<test___>.00000000000
1436     jim> collect
1437     0
1438     jim> set r ""
1439     jim> collect
1440     Finaliser called for <reference.<test___>.00000000000,One String
1441     1
1443 Note that once the reference, 'r', was modified so that it no longer
1444 contained a reference to the value, the garbage collector discarded
1445 the value (after calling the finalizer).
1447 The finalizer for a reference may be examined or changed with the `finalize` command
1449     jim> finalize $r
1450     f
1451     jim> finalize $r newf
1452     newf
1454 Lambda Function
1455 ~~~~~~~~~~~~~~~
1456 Jim provides a garbage collected `lambda` function. This is a procedure
1457 which is able to create an anonymous procedure.  Consider:
1459     jim> set f [lambda {a} {{x 0}} { incr x $a }]
1460     jim> $f 1
1461     1
1462     jim> $f 2
1463     3
1464     jim> set f ""
1466 This create an anonymous procedure (with the name stored in 'f'), with a static variable
1467 which is incremented by the supplied value and the result returned.
1469 Once the procedure name is no longer accessible, it will automatically be deleted
1470 when the garbage collector runs.
1472 The procedure may also be delete immediately by renaming it "". e.g.
1474     jim> rename $f ""
1476 UTF-8 AND UNICODE
1477 -----------------
1478 If Jim is built with UTF-8 support enabled (configure --enable-utf),
1479 then most string-related commands become UTF-8 aware.  These include,
1480 but are not limited to, `string match`, `split`, `glob`, `scan` and
1481 `format`.
1483 UTF-8 encoding has many advantages, but one of the complications is that
1484 characters can take a variable number of bytes. Thus the addition of
1485 `string bytelength` which returns the number of bytes in a string,
1486 while `string length` returns the number of characters.
1488 If UTF-8 support is not enabled, all commands treat bytes as characters
1489 and `string bytelength` returns the same value as `string length`.
1491 Note that even if UTF-8 support is not enabled, the +{backslash}uNNNN+ and related syntax
1492 is still available to embed UTF-8 sequences.
1494 Jim Tcl supports all currently defined unicode codepoints. That is 21 bits, up to +'U+1FFFFF'.
1496 String Matching
1497 ~~~~~~~~~~~~~~~
1498 Commands such as `string match`, `lsearch -glob`, `array names` and others use string
1499 pattern matching rules. These commands support UTF-8. For example:
1501   string match a\[\ua0-\ubf\]b "a\u00a3b"
1503 format and scan
1504 ~~~~~~~~~~~~~~~
1505 +format %c+ allows a unicode codepoint to be be encoded. For example, the following will return
1506 a string with two bytes and one character. The same as +{backslash}ub5+
1508   format %c 0xb5
1510 `format` respects widths as character widths, not byte widths. For example, the following will
1511 return a string with three characters, not three bytes.
1513   format %.3s \ub5\ub6\ub7\ub8
1515 Similarly, +scan ... %c+ allows a UTF-8 to be decoded to a unicode codepoint. The following will set
1516 +'a'+ to 181 (0xb5) and +'b'+ to 65 (0x41).
1518   scan \u00b5A %c%c a b
1520 `scan %s` will also accept a character class, including unicode ranges.
1522 String Classes
1523 ~~~~~~~~~~~~~~
1524 `string is` has *not* been extended to classify UTF-8 characters. Therefore, the following
1525 will return 0, even though the string may be considered to be alphabetic.
1527   string is alpha \ub5Test
1529 This does not affect the string classes 'ascii', 'control', 'digit', 'double', 'integer' or 'xdigit'.
1531 Case Mapping and Conversion
1532 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1533 Jim provides a simplified unicode case mapping. This means that case conversion
1534 and comparison will not increase or decrease the number of characters in a string.
1535 (Although it may change the number of bytes).
1537 `string toupper` will convert any lowercase letters to their uppercase equivalent.
1538 Any character which is not a letter or has no uppercase equivalent is left unchanged.
1539 Similarly for `string tolower` and `string totitle`.
1541 Commands which perform case insensitive matches, such as `string compare -nocase`
1542 and `lsearch -nocase` fold both strings to uppercase before comparison.
1544 Invalid UTF-8 Sequences
1545 ~~~~~~~~~~~~~~~~~~~~~~~
1546 Some UTF-8 character sequences are invalid, such as those beginning with '0xff',
1547 those which represent character sequences longer than 3 bytes (greater than U+FFFF),
1548 and those which end prematurely, such as a lone '0xc2'.
1550 In these situations, the offending bytes are treated as single characters. For example,
1551 the following returns 2.
1553   string bytelength \xff\xff
1555 Regular Expressions
1556 ~~~~~~~~~~~~~~~~~~~
1557 If UTF-8 support is enabled, the built-in regular expression engine will be
1558 selected which supports UTF-8 strings and patterns.
1560 See REGULAR EXPRESSIONS
1562 BUILT-IN COMMANDS
1563 -----------------
1564 The Tcl library provides the following built-in commands, which will
1565 be available in any application using Tcl.  In addition to these
1566 built-in commands, there may be additional commands defined by each
1567 application, plus commands defined as Tcl procedures.
1569 In the command syntax descriptions below, words in +*boldface*+ are
1570 literals that you type verbatim to Tcl.
1572 Words in +'italics'+ are meta-symbols; they serve as names for any of
1573 a range of values that you can type.
1575 Optional arguments or groups of arguments are indicated by enclosing them
1576 in +?question-marks?+.
1578 Ellipses (+\...+) indicate that any number of additional
1579 arguments or groups of arguments may appear, in the same format
1580 as the preceding argument(s).
1582 [[CommandIndex]]
1583 Command Index
1584 ~~~~~~~~~~~~~
1585 @INSERTINDEX@
1587 alarm
1588 ~~~~~
1589 +*alarm* 'seconds'+
1591 Delivers the +SIGALRM+ signal to the process after the given
1592 number of seconds. If the platform supports 'ualarm(3)' then
1593 the argument may be a floating point value. Otherwise it must
1594 be an integer.
1596 Note that unless a signal handler for +SIGALRM+ has been installed
1597 (see `signal`), the process will exit on this signal.
1599 alias
1600 ~~~~~
1601 +*alias* 'name args\...'+
1603 Creates a single word alias (command) for one or more words. For example,
1604 the following creates an alias for the command `info exists`.
1606     alias e info exists
1607     if {[e var]} {
1608       ...
1609     }
1611 `alias` returns +'name'+, allowing it to be used with `local`.
1613 See also `proc`, `curry`, `lambda`, `local`, `info alias`, `exists -alias`
1615 append
1616 ~~~~~~
1617 +*append* 'varName value ?value value ...?'+
1619 Append all of the +'value'+ arguments to the current value
1620 of variable +'varName'+.  If +'varName'+ doesn't exist,
1621 it is given a value equal to the concatenation of all the
1622 +'value'+ arguments.
1624 This command provides an efficient way to build up long
1625 variables incrementally.
1626 For example, "`append a $b`" is much more efficient than
1627 "`set a $a$b`" if +$a+ is long.
1629 apply
1630 ~~~~~~
1631 +*apply* 'lambdaExpr ?arg1 arg2 \...?'+
1633 The command `apply` provides for anonymous procedure calls,
1634 similar to `lambda`, but without command name being created, even temporarily.
1636 The function  +'lambdaExpr'+ is a two element list +{args body}+
1637 or a three element list +{args body namespace}+. The first element
1638 args specifies the formal arguments, in the same form as the `proc` and `lambda` commands.
1640 array
1641 ~~~~~
1642 +*array* 'option arrayName ?arg\...?'+
1644 This command performs one of several operations on the
1645 variable given by +'arrayName'+.
1647 Note that in general, if the named array does not exist, the +'array'+ command behaves
1648 as though the array exists but is empty.
1650 The +'option'+ argument determines what action is carried out by the
1651 command.  The legal +'options'+ (which may be abbreviated) are:
1653 +*array exists* 'arrayName'+::
1654     Returns 1 if arrayName is an array variable, 0 if there is
1655     no variable by that name.  This command is essentially
1656     identical to `info exists`
1658 +*array get* 'arrayName ?pattern?'+::
1659     Returns a list containing pairs of elements. The first
1660     element in each pair is the name of an element in arrayName
1661     and the second element of each pair is the value of the
1662     array element. The order of the pairs is undefined. If
1663     pattern is not specified, then all of the elements of the
1664     array are included in the result. If pattern is specified,
1665     then only those elements whose names match pattern (using
1666     the matching rules of string match) are included. If arrayName
1667     isn't the name of an array variable, or if the array contains
1668     no elements, then an empty list is returned.
1670 +*array names* 'arrayName ?pattern?'+::
1671     Returns a list containing the names of all of the elements
1672     in the array that match pattern. If pattern is omitted then
1673     the command returns all of the element names in the array.
1674     If pattern is specified, then only those elements whose
1675     names match pattern (using the matching rules of string
1676     match) are included. If there are no (matching) elements
1677     in the array, or if arrayName isn't the name of an array
1678     variable, then an empty string is returned.
1680 +*array set* 'arrayName list'+::
1681     Sets the values of one or more elements in arrayName. list
1682     must have a form like that returned by array get, consisting
1683     of an even number of elements. Each odd-numbered element
1684     in list is treated as an element name within arrayName, and
1685     the following element in list is used as a new value for
1686     that array element. If the variable arrayName does not
1687     already exist and list is empty, arrayName is created with
1688     an empty array value.
1690 +*array size* 'arrayName'+::
1691     Returns the number of elements in the array. If arrayName
1692     isn't the name of an array then 0 is returned.
1694 +*array unset* 'arrayName ?pattern?'+::
1695     Unsets all of the elements in the array that match pattern
1696     (using the matching rules of string match). If arrayName
1697     isn't the name of an array variable or there are no matching
1698     elements in the array, no error will be raised. If pattern
1699     is omitted and arrayName is an array variable, then the
1700     command unsets the entire array. The command always returns
1701     an empty string.
1703 break
1704 ~~~~~
1705 +*break*+
1707 This command may be invoked only inside the body of a loop command
1708 such as `for` or `foreach` or `while`.  It returns a +JIM_BREAK+ code
1709 to signal the innermost containing loop command to return immediately.
1711 case
1712 ~~~~
1713 +*case* 'string' ?in? 'patList body ?patList body ...?'+
1715 +*case* 'string' ?in? {'patList body ?patList body ...?'}+
1717 *Note* that the `switch` command should generally be preferred unless compatibility
1718 with Tcl 6.x is desired.
1720 Match +'string'+ against each of the +'patList'+ arguments
1721 in order.  If one matches, then evaluate the following +'body'+ argument
1722 by passing it recursively to the Tcl interpreter, and return the result
1723 of that evaluation.  Each +'patList'+ argument consists of a single
1724 pattern or list of patterns.  Each pattern may contain any of the wild-cards
1725 described under `string match`.
1727 If a +'patList'+ argument is +default+, the corresponding body will be
1728 evaluated if no +'patList'+ matches +'string'+.  If no +'patList'+ argument
1729 matches +'string'+ and no default is given, then the `case` command returns
1730 an empty string.
1732 Two syntaxes are provided.
1734 The first uses a separate argument for each of the patterns and commands;
1735 this form is convenient if substitutions are desired on some of the
1736 patterns or commands.
1738 The second form places all of the patterns and commands together into
1739 a single argument; the argument must have proper list structure, with
1740 the elements of the list being the patterns and commands.
1742 The second form makes it easy to construct multi-line case commands,
1743 since the braces around the whole list make it unnecessary to include a
1744 backslash at the end of each line.
1746 Since the +'patList'+ arguments are in braces in the second form,
1747 no command or variable substitutions are performed on them;  this makes
1748 the behaviour of the second form different than the first form in some
1749 cases.
1751 Below are some examples of `case` commands:
1753     case abc in {a b} {format 1} default {format 2} a* {format 3}
1755 will return '3',
1757     case a in {
1758         {a b} {format 1}
1759         default {format 2}
1760         a* {format 3}
1761     }
1763 will return '1', and
1765     case xyz {
1766         {a b}
1767             {format 1}
1768         default
1769             {format 2}
1770         a*
1771             {format 3}
1772     }
1774 will return '2'.
1776 catch
1777 ~~~~~
1778 +*catch* ?-?no?'code \...'? ?--? 'command ?resultVarName? ?optionsVarName?'+
1780 The `catch` command may be used to prevent errors from aborting
1781 command interpretation.  `catch` evaluates +'command'+, and returns a
1782 +JIM_OK+ code, regardless of any errors that might occur while
1783 executing +'command'+ (with the possible exception of +JIM_SIGNAL+ -
1784 see below).
1786 The return value from `catch` is a decimal string giving the code
1787 returned by the Tcl interpreter after executing +'command'+.  This
1788 will be '0' (+JIM_OK+) if there were no errors in +'command'+; otherwise
1789 it will have a non-zero value corresponding to one of the exceptional
1790 return codes (see jim.h for the definitions of code values, or the
1791 `info returncodes` command).
1793 If the +'resultVarName'+ argument is given, then it gives the name
1794 of a variable; `catch` will set the value of the variable to the
1795 string returned from +'command'+ (either a result or an error message).
1797 If the +'optionsVarName'+ argument is given, then it gives the name
1798 of a variable; `catch` will set the value of the variable to a
1799 dictionary. For any return code other than +JIM_RETURN+, the value
1800 for the key +-code+ will be set to the return code. For +JIM_RETURN+
1801 it will be set to the code given in `return -code`. Additionally,
1802 for the return code +JIM_ERR+, the value of the key +-errorinfo+
1803 will contain the current stack trace (the same result as `info stacktrace`),
1804 the value of the key +-errorcode+ will contain the
1805 same value as the global variable $::errorCode, and the value of
1806 the key +-level+ will be the current return level (see `return -level`).
1807 This can be useful to rethrow an error:
1809     if {[catch {...} msg opts]} {
1810         ...maybe do something with the error...
1811         incr opts(-level)
1812         return {*}$opts $msg
1813     }
1815 Normally `catch` will +'not'+ catch any of the codes +JIM_EXIT+, +JIM_EVAL+ or +JIM_SIGNAL+.
1816 The set of codes which will be caught may be modified by specifying the one more codes before
1817 +'command'+.
1819 e.g. To catch +JIM_EXIT+ but not +JIM_BREAK+ or +JIM_CONTINUE+
1821     catch -exit -nobreak -nocontinue -- { ... }
1823 The use of +--+ is optional. It signifies that no more return code options follow.
1825 Note that if a signal marked as `signal handle` is caught with `catch -signal`, the return value
1826 (stored in +'resultVarName'+) is name of the signal caught.
1830 +*cd* 'dirName'+
1832 Change the current working directory to +'dirName'+.
1834 Returns an empty string.
1836 This command can potentially be disruptive to an application, so it may
1837 be removed in some applications.
1839 clock
1840 ~~~~~
1841 +*clock seconds*+::
1842     Returns the current time as seconds since the epoch.
1844 +*clock clicks*+::
1845     Returns the current time in `clicks'.
1847 +*clock microseconds*+::
1848     Returns the current time in microseconds.
1850 +*clock milliseconds*+::
1851     Returns the current time in milliseconds.
1853 +*clock format* 'seconds' ?*-format* 'format?'+::
1854     Format the given time (seconds since the epoch) according to the given
1855     format. See strftime(3) for supported formats.
1856     If no format is supplied, "%c" is used.
1858 +*clock scan* 'str' *-format* 'format'+::
1859     Scan the given time string using the given format string.
1860     See strptime(3) for supported formats.
1862 close
1863 ~~~~~
1864 +*close* 'fileId'+
1866 +'fileId' *close*+
1868 Closes the file given by +'fileId'+.
1869 +'fileId'+ must be the return value from a previous invocation
1870 of the `open` command; after this command, it should not be
1871 used anymore.
1873 collect
1874 ~~~~~~~
1875 +*collect*+
1877 Normally reference garbage collection is automatically performed periodically.
1878 However it may be run immediately with the `collect` command.
1880 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
1882 concat
1883 ~~~~~~
1884 +*concat* 'arg ?arg \...?'+
1886 This command treats each argument as a list and concatenates them
1887 into a single list.  It permits any number of arguments.  For example,
1888 the command
1890     concat a b {c d e} {f {g h}}
1892 will return
1894     a b c d e f {g h}
1896 as its result.
1898 continue
1899 ~~~~~~~~
1900 +*continue*+
1902 This command may be invoked only inside the body of a loop command such
1903 as `for` or `foreach` or `while`.  It returns a  +JIM_CONTINUE+ code to
1904 signal the innermost containing loop command to skip the remainder of
1905 the loop's body but continue with the next iteration of the loop.
1907 curry
1908 ~~~~~
1909 +*alias* 'args\...'+
1911 Similar to `alias` except it creates an anonymous procedure (lambda) instead of
1912 a named procedure.
1914 the following creates a local, unnamed alias for the command `info exists`.
1916     set e [local curry info exists]
1917     if {[$e var]} {
1918       ...
1919     }
1921 `curry` returns the name of the procedure.
1923 See also `proc`, `alias`, `lambda`, `local`.
1925 dict
1926 ~~~~
1927 +*dict* 'option ?arg\...?'+
1929 Performs one of several operations on dictionary values.
1931 The +'option'+ argument determines what action is carried out by the
1932 command.  The legal +'options'+ are:
1934 +*dict create* '?key value \...?'+::
1935     Create and return a new dictionary value that contains each of
1936     the key/value mappings listed as  arguments (keys and values
1937     alternating, with each key being followed by its associated
1938     value.)
1940 +*dict exists* 'dictionary key ?key \...?'+::
1941     Returns a boolean value indicating whether the given key (or path
1942     of keys through a set of nested dictionaries) exists in the given
1943     dictionary value.  This returns a true value exactly when `dict get`
1944     on that path will succeed.
1946 +*dict get* 'dictionary ?key \...?'+::
1947     Given a dictionary value (first argument) and a key (second argument),
1948     this will retrieve the value for that key. Where several keys are
1949     supplied, the behaviour of the command shall be as if the result
1950     of "`dict get $dictVal $key`" was passed as the first argument to
1951     dict get with the remaining arguments as second (and possibly
1952     subsequent) arguments. This facilitates lookups in nested dictionaries.
1953     If no keys are provided, dict would return a list containing pairs
1954     of elements in a manner similar to array get. That is, the first
1955     element of each pair would be the key and the second element would
1956     be the value for that key.  It is an error to attempt to retrieve
1957     a value for a key that is not present in the dictionary.
1959 +*dict keys* 'dictionary ?pattern?'+::
1960     Returns a list of the keys in the dictionary.
1961     If pattern is specified, then only those keys whose
1962     names match +'pattern'+ (using the matching rules of string
1963     match) are included.
1965 +*dict merge* ?'dictionary \...'?+::
1966     Return a dictionary that contains the contents of each of the
1967     +'dictionary'+ arguments. Where two (or more) dictionaries
1968     contain a mapping for the same key, the resulting dictionary
1969     maps that key to the value according to the last dictionary on
1970     the command line containing a mapping for that key.
1972 +*dict set* 'dictionaryName key ?key \...? value'+::
1973     This operation takes the +'name'+ of a variable containing a dictionary
1974     value and places an updated dictionary value in that variable
1975     containing a mapping from the given key to the given value. When
1976     multiple keys are present, this operation creates or updates a chain
1977     of nested dictionaries.
1979 +*dict size* 'dictionary'+::
1980     Return the number of key/value mappings in the given dictionary value.
1982 +*dict unset* 'dictionaryName key ?key \...? value'+::
1983     This operation (the companion to `dict set`) takes the name of a
1984     variable containing a dictionary value and places an updated
1985     dictionary value in that variable that does not contain a mapping
1986     for the given key. Where multiple keys are present, this describes
1987     a path through nested dictionaries to the mapping to remove. At
1988     least one key must be specified, but the last key on the key-path
1989     need not exist. All other components on the path must exist.
1991 +*dict with* 'dictionaryName key ?key \...? script'+::
1992     Execute the Tcl script in +'script'+ with the value for each
1993     key in +'dictionaryName'+ mapped to a variable with the same
1994     name. Where one or more keys are given, these indicate a chain
1995     of nested dictionaries, with the innermost dictionary being the
1996     one opened out for the execution of body. Making +'dictionaryName'+
1997     unreadable will make the updates to the dictionary be discarded,
1998     and this also happens if the contents of +'dictionaryName'+ are
1999     adjusted so that the chain of dictionaries no longer exists.
2000     The result of `dict with` is (unless some kind of error occurs)
2001     the result of the evaluation of body.
2002  ::
2003     The variables are mapped in the scope enclosing the `dict with`;
2004     it is recommended that this command only be used in a local
2005     scope (procedure). Because of this, the variables set by
2006     `dict with` will continue to exist after the command finishes (unless
2007     explicitly unset). Note that changes to the contents of +'dictionaryName'+
2008     only happen when +'script'+ terminates.
2010 +*dict for, values, incr, append, lappend, update, info, replace*+ to be documented...
2014 +*env* '?name? ?default?'+
2016 If +'name'+ is supplied, returns the value of +'name'+ from the initial
2017 environment (see getenv(3)). An error is returned if +'name'+ does not
2018 exist in the environment, unless +'default'+ is supplied - in which case
2019 that value is returned instead.
2021 If no arguments are supplied, returns a list of all environment variables
2022 and their values as +{name value \...}+
2024 See also the global variable +::env+
2028 +*eof* 'fileId'+
2030 +'fileId' *eof*+
2032 Returns 1 if an end-of-file condition has occurred on +'fileId'+,
2033 0 otherwise.
2035 +'fileId'+ must have been the return value from a previous call to `open`,
2036 or it may be +stdin+, +stdout+, or +stderr+ to refer to one of the
2037 standard I/O channels.
2039 error
2040 ~~~~~
2041 +*error* 'message ?stacktrace?'+
2043 Returns a +JIM_ERR+ code, which causes command interpretation to be
2044 unwound.  +'message'+ is a string that is returned to the application
2045 to indicate what went wrong.
2047 If the +'stacktrace'+ argument is provided and is non-empty,
2048 it is used to initialize the stacktrace.
2050 This feature is most useful in conjunction with the `catch` command:
2051 if a caught error cannot be handled successfully, +'stacktrace'+ can be used
2052 to return a stack trace reflecting the original point of occurrence
2053 of the error:
2055     catch {...} errMsg
2056     ...
2057     error $errMsg [info stacktrace]
2059 See also `errorInfo`, `info stacktrace`, `catch` and `return`
2061 errorInfo
2062 ~~~~~~~~~
2063 +*errorInfo* 'error ?stacktrace?'+
2065 Returns a human-readable representation of the given error message and stack trace.
2066 Typical usage is:
2068     if {[catch {...} error]} {
2069         puts stderr [errorInfo $error [info stacktrace]]
2070         exit 1
2071     }
2073 See also `error`.
2075 eval
2076 ~~~~
2077 +*eval* 'arg ?arg\...?'+
2079 `eval` takes one or more arguments, which together comprise a Tcl
2080 command (or collection of Tcl commands separated by newlines in the
2081 usual way).  `eval` concatenates all its arguments in the same
2082 fashion as the `concat` command, passes the concatenated string to the
2083 Tcl interpreter recursively, and returns the result of that
2084 evaluation (or any error generated by it).
2086 exec
2087 ~~~~
2088 +*exec* 'arg ?arg\...?'+
2090 This command treats its arguments as the specification
2091 of one or more UNIX commands to execute as subprocesses.
2092 The commands take the form of a standard shell pipeline;
2093 +|+ arguments separate commands in the
2094 pipeline and cause standard output of the preceding command
2095 to be piped into standard input of the next command (or +|&+ for
2096 both standard output and standard error).
2098 Under normal conditions the result of the `exec` command
2099 consists of the standard output produced by the last command
2100 in the pipeline followed by the standard error output.
2102 If any of the commands writes to its standard error file,
2103 then this will be included in the result after the standard output
2104 of the last command.
2106 Note that unlike Tcl, data written to standard error does not cause
2107 `exec` to return an error.
2109 If any of the commands in the pipeline exit abnormally or
2110 are killed or suspended, then `exec` will return an error.
2111 If no standard error output was produced, or is redirected,
2112 the error message will include the normal result, as above,
2113 followed by error messages describing the abnormal terminations.
2115 If any standard error output was produced, these abnormal termination
2116 messages are suppressed.
2118 If the last character of the result or error message
2119 is a newline then that character is deleted from the result
2120 or error message for consistency with normal
2121 Tcl return values.
2123 An +'arg'+ may have one of the following special forms:
2125 +>filename+::
2126     The standard output of the last command in the pipeline
2127     is redirected to the file.  In this situation `exec`
2128     will normally return an empty string.
2130 +>>filename+::
2131     As above, but append to the file.
2133 +>@fileId+::
2134     The standard output of the last command in the pipeline is
2135     redirected to the given (writable) file descriptor (e.g. stdout,
2136     stderr, or the result of `open`). In this situation `exec`
2137     will normally return an empty string.
2139 +2>filename+::
2140     The standard error of the last command in the pipeline
2141     is redirected to the file.
2143 +2>>filename+::
2144     As above, but append to the file.
2146 +2>@fileId+::
2147     The standard error of the last command in the pipeline is
2148     redirected to the given (writable) file descriptor.
2150 +2>@1+::
2151     The standard error of the last command in the pipeline is
2152     redirected to the same file descriptor as the standard output.
2154 +>&filename+::
2155     Both the standard output and standard error of the last command
2156     in the pipeline is redirected to the file.
2158 +>>&filename+::
2159     As above, but append to the file.
2161 +<filename+::
2162     The standard input of the first command in the pipeline
2163     is taken from the file.
2165 +<<string+::
2166     The standard input of the first command is taken as the
2167     given immediate value.
2169 +<@fileId+::
2170     The standard input of the first command in the pipeline
2171     is taken from the given (readable) file descriptor.
2173 If there is no redirection of standard input, standard error
2174 or standard output, these are connected to the corresponding
2175 input or output of the application.
2177 If the last +'arg'+ is +&+ then the command will be
2178 executed in background.
2179 In this case the standard output from the last command
2180 in the pipeline will
2181 go to the application's standard output unless
2182 redirected in the command, and error output from all
2183 the commands in the pipeline will go to the application's
2184 standard error file. The return value of exec in this case
2185 is a list of process ids (pids) in the pipeline.
2187 Each +'arg'+ becomes one word for a command, except for
2188 +|+, +<+, +<<+, +>+, and +&+ arguments, and the
2189 arguments that follow +<+, +<<+, and +>+.
2191 The first word in each command is taken as the command name;
2192 the directories in the PATH environment variable are searched for
2193 an executable by the given name.
2195 No `glob` expansion or other shell-like substitutions
2196 are performed on the arguments to commands.
2198 If the command fails, the global $::errorCode (and the -errorcode
2199 option in `catch`) will be set to a list, as follows:
2201 +*CHILDKILLED* 'pid sigName msg'+::
2202         This format is used when a child process has been killed
2203         because of a signal. The pid element will be the process's
2204         identifier (in decimal). The sigName element will be the
2205         symbolic name of the signal that caused the process to
2206         terminate; it will be one of the names from the include
2207         file signal.h, such as SIGPIPE. The msg element will be a
2208         short human-readable message describing the signal, such
2209         as "write on pipe with no readers" for SIGPIPE.
2211 +*CHILDSUSP* 'pid sigName msg'+::
2212         This format is used when a child process has been suspended
2213         because of a signal. The pid element will be the process's
2214         identifier, in decimal. The sigName element will be the
2215         symbolic name of the signal that caused the process to
2216         suspend; this will be one of the names from the include
2217         file signal.h, such as SIGTTIN. The msg element will be a
2218         short human-readable message describing the signal, such
2219         as "background tty read" for SIGTTIN.
2221 +*CHILDSTATUS* 'pid code'+::
2222         This format is used when a child process has exited with a
2223         non-zero exit status. The pid element will be the process's
2224         identifier (in decimal) and the code element will be the
2225         exit code returned by the process (also in decimal).
2227 The environment for the executed command is set from $::env (unless
2228 this variable is unset, in which case the original environment is used).
2230 exists
2231 ~~~~~~
2232 +*exists ?-var|-proc|-command|-alias?* 'name'+
2234 Checks the existence of the given variable, procedure, command
2235 or alias respectively and returns 1 if it exists or 0 if not.  This command
2236 provides a more simplified/convenient version of `info exists`,
2237 `info procs` and `info commands`.
2239 If the type is omitted, a type of '-var' is used. The type may be abbreviated.
2241 exit
2242 ~~~~
2243 +*exit* '?returnCode?'+
2245 Terminate the process, returning +'returnCode'+ to the
2246 parent as the exit status.
2248 If +'returnCode'+ isn't specified then it defaults
2249 to 0.
2251 Note that exit can be caught with `catch`.
2253 expr
2254 ~~~~
2255 +*expr* 'arg'+
2257 Calls the expression processor to evaluate +'arg'+, and returns
2258 the result as a string.  See the section EXPRESSIONS above.
2260 Note that Jim supports a shorthand syntax for `expr` as +$(\...)+
2261 The following two are identical.
2263   set x [expr {3 * 2 + 1}]
2264   set x $(3 * 2 + 1)
2266 file
2267 ~~~~
2268 +*file* 'option name ?arg\...?'+
2270 Operate on a file or a file name.  +'name'+ is the name of a file.
2272 +'option'+ indicates what to do with the file name.  Any unique
2273 abbreviation for +'option'+ is acceptable.  The valid options are:
2275 +*file atime* 'name'+::
2276     Return a decimal string giving the time at which file +'name'+
2277     was last accessed.  The time is measured in the standard UNIX
2278     fashion as seconds from a fixed starting time (often January 1, 1970).
2279     If the file doesn't exist or its access time cannot be queried then an
2280     error is generated.
2282 +*file copy ?-force?* 'source target'+::
2283     Copies file +'source'+ to file +'target'+. The source file must exist.
2284     The target file must not exist, unless +-force+ is specified.
2286 +*file delete ?-force? ?--?* 'name\...'+::
2287     Deletes file or directory +'name'+. If the file or directory doesn't exist, nothing happens.
2288     If it can't be deleted, an error is generated. Non-empty directories will not be deleted
2289     unless the +-force+ options is given. In this case no errors will be generated, even
2290     if the file/directory can't be deleted. Use +'--'+ if there is any possibility of
2291     the first name being +'-force'+.
2293 +*file dirname* 'name'+::
2294     Return all of the characters in +'name'+ up to but not including
2295     the last slash character.  If there are no slashes in +'name'+
2296     then return +.+ (a single dot).  If the last slash in +'name'+ is its first
2297     character, then return +/+.
2299 +*file executable* 'name'+::
2300     Return '1' if file +'name'+ is executable by
2301     the current user, '0' otherwise.
2303 +*file exists* 'name'+::
2304     Return '1' if file +'name'+ exists and the current user has
2305     search privileges for the directories leading to it, '0' otherwise.
2307 +*file extension* 'name'+::
2308     Return all of the characters in +'name'+ after and including the
2309     last dot in +'name'+.  If there is no dot in +'name'+ then return
2310     the empty string.
2312 +*file isdirectory* 'name'+::
2313     Return '1' if file +'name'+ is a directory,
2314     '0' otherwise.
2316 +*file isfile* 'name'+::
2317     Return '1' if file +'name'+ is a regular file,
2318     '0' otherwise.
2320 +*file join* 'arg\...'+::
2321     Joins multiple path components. Note that if any components is
2322     an absolute path, the preceding components are ignored.
2323     Thus +"`file` join /tmp /root"+ returns +"/root"+.
2325 +*file link* ?*-hard|-symbolic*? 'newname target'+::
2326     Creates a hard link (default) or symbolic link from +'newname'+ to +'target'+.
2327     Note that the sense of this command is the opposite of `file rename` and `file copy`
2328     and also of `ln`, but this is compatible with Tcl.
2329     An error is returned if +'target'+ doesn't exist or +'newname'+ already exists.
2331 +*file lstat* 'name varName'+::
2332     Same as 'stat' option (see below) except uses the +'lstat'+
2333     kernel call instead of +'stat'+.  This means that if +'name'+
2334     refers to a symbolic link the information returned in +'varName'+
2335     is for the link rather than the file it refers to.  On systems that
2336     don't support symbolic links this option behaves exactly the same
2337     as the 'stat' option.
2339 +*file mkdir* 'dir1 ?dir2\...?'+::
2340     Creates each directory specified. For each pathname +'dir'+ specified,
2341     this command will create all non-existing parent directories
2342     as well as +'dir'+ itself. If an existing directory is specified,
2343     then no action is taken and no error is returned. Trying to
2344     overwrite an existing file with a directory will result in an
2345     error.  Arguments are processed in the order specified, halting
2346     at the first error, if any.
2348 +*file mtime* 'name ?time?'+::
2349     Return a decimal string giving the time at which file +'name'+
2350     was last modified.  The time is measured in the standard UNIX
2351     fashion as seconds from a fixed starting time (often January 1, 1970).
2352     If the file doesn't exist or its modified time cannot be queried then an
2353     error is generated. If +'time'+ is given, sets the modification time
2354     of the file to the given value.
2356 +*file normalize* 'name'+::
2357     Return the normalized path of +'name'+. See 'realpath(3)'.
2359 +*file owned* 'name'+::
2360     Return '1' if file +'name'+ is owned by the current user,
2361     '0' otherwise.
2363 +*file readable* 'name'+::
2364     Return '1' if file +'name'+ is readable by
2365     the current user, '0' otherwise.
2367 +*file readlink* 'name'+::
2368     Returns the value of the symbolic link given by +'name'+ (i.e. the
2369     name of the file it points to).  If
2370     +'name'+ isn't a symbolic link or its value cannot be read, then
2371     an error is returned.  On systems that don't support symbolic links
2372     this option is undefined.
2374 +*file rename* ?*-force*? 'oldname' 'newname'+::
2375     Renames the file from the old name to the new name.
2376     If +'newname'+ already exists, an error is returned unless +'-force'+ is
2377     specified.
2379 +*file rootname* 'name'+::
2380     Return all of the characters in +'name'+ up to but not including
2381     the last '.' character in the name.  If +'name'+ doesn't contain
2382     a dot, then return +'name'+.
2384 +*file size* 'name'+::
2385     Return a decimal string giving the size of file +'name'+ in bytes.
2386     If the file doesn't exist or its size cannot be queried then an
2387     error is generated.
2389 +*file stat* 'name ?varName?'+::
2390     Invoke the 'stat' kernel call on +'name'+, and return the result
2391     as a dictionary with the following keys: 'atime',
2392     'ctime', 'dev', 'gid', 'ino', 'mode', 'mtime',
2393     'nlink', 'size', 'type', 'uid'.
2394     Each element except 'type' is a decimal string with the value of
2395     the corresponding field from the 'stat' return structure; see the
2396     manual entry for 'stat' for details on the meanings of the values.
2397     The 'type' element gives the type of the file in the same form
2398     returned by the command `file type`.
2399     If +'varName'+ is specified, it is taken to be the name of an array
2400     variable and the values are also stored into the array.
2402 +*file tail* 'name'+::
2403     Return all of the characters in +'name'+ after the last slash.
2404     If +'name'+ contains no slashes then return +'name'+.
2406 +*file tempfile* '?template?'+::
2407     Creates and returns the name of a unique temporary file. If +'template'+ is omitted, a
2408     default template will be used to place the file in /tmp. See 'mkstemp(3)' for
2409     the format of the template and security concerns.
2411 +*file type* 'name'+::
2412     Returns a string giving the type of file +'name'+, which will be
2413     one of +file+, +directory+, +characterSpecial+,
2414     +blockSpecial+, +fifo+, +link+, or +socket+.
2416 +*file writable* 'name'+::
2417     Return '1' if file +'name'+ is writable by
2418     the current user, '0' otherwise.
2420 The `file` commands that return 0/1 results are often used in
2421 conditional or looping commands, for example:
2423     if {![file exists foo]} {
2424         error {bad file name}
2425     } else {
2426         ...
2427     }
2429 finalize
2430 ~~~~~~~~
2431 +*finalize* 'reference ?command?'+
2433 If +'command'+ is omitted, returns the finalizer command for the given reference.
2435 Otherwise, sets a new finalizer command for the given reference. +'command'+ may be
2436 the empty string to remove the current finalizer.
2438 The reference must be a valid reference create with the `ref`
2439 command.
2441 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2443 flush
2444 ~~~~~
2445 +*flush* 'fileId'+
2447 +'fileId' *flush*+
2449 Flushes any output that has been buffered for +'fileId'+.  +'fileId'+ must
2450 have been the return value from a previous call to `open`, or it may be
2451 +stdout+ or +stderr+ to access one of the standard I/O streams; it must
2452 refer to a file that was opened for writing.  This command returns an
2453 empty string.
2457 +*for* 'start test next body'+
2459 `for` is a looping command, similar in structure to the C `for` statement.
2460 The +'start'+, +'next'+, and +'body'+ arguments must be Tcl command strings,
2461 and +'test'+ is an expression string.
2463 The `for` command first invokes the Tcl interpreter to execute +'start'+.
2464 Then it repeatedly evaluates +'test'+ as an expression; if the result is
2465 non-zero it invokes the Tcl interpreter on +'body'+, then invokes the Tcl
2466 interpreter on +'next'+, then repeats the loop.  The command terminates
2467 when +'test'+ evaluates to 0.
2469 If a `continue` command is invoked within +'body'+ then any remaining
2470 commands in the current execution of +'body'+ are skipped; processing
2471 continues by invoking the Tcl interpreter on +'next'+, then evaluating
2472 +'test'+, and so on.
2474 If a `break` command is invoked within +'body'+ or +'next'+, then the `for`
2475 command will return immediately.
2477 The operation of `break` and `continue` are similar to the corresponding
2478 statements in C.
2480 `for` returns an empty string.
2482 foreach
2483 ~~~~~~~
2484 +*foreach* 'varName list body'+
2486 +*foreach* 'varList list ?varList2 list2 \...? body'+
2488 In this command, +'varName'+ is the name of a variable, +'list'+
2489 is a list of values to assign to +'varName'+, and +'body'+ is a
2490 collection of Tcl commands.
2492 For each field in +'list'+ (in order from left to right), `foreach` assigns
2493 the contents of the field to +'varName'+ (as if the `lindex` command
2494 had been used to extract the field), then calls the Tcl interpreter to
2495 execute +'body'+.
2497 If instead of being a simple name, +'varList'+ is used, multiple assignments
2498 are made each time through the loop, one for each element of +'varList'+.
2500 For example, if there are two elements in +'varList'+ and six elements in
2501 the list, the loop will be executed three times.
2503 If the length of the list doesn't evenly divide by the number of elements
2504 in +'varList'+, the value of the remaining variables in the last iteration
2505 of the loop are undefined.
2507 The `break` and `continue` statements may be invoked inside +'body'+,
2508 with the same effect as in the `for` command.
2510 `foreach` returns an empty string.
2512 format
2513 ~~~~~~
2514 +*format* 'formatString ?arg \...?'+
2516 This command generates a formatted string in the same way as the
2517 C 'sprintf' procedure (it uses 'sprintf' in its
2518 implementation).  +'formatString'+ indicates how to format
2519 the result, using +%+ fields as in 'sprintf', and the additional
2520 arguments, if any, provide values to be substituted into the result.
2522 All of the 'sprintf' options are valid; see the 'sprintf'
2523 man page for details.  Each +'arg'+ must match the expected type
2524 from the +%+ field in +'formatString'+; the `format` command
2525 converts each argument to the correct type (floating, integer, etc.)
2526 before passing it to 'sprintf' for formatting.
2528 The only unusual conversion is for +%c+; in this case the argument
2529 must be a decimal string, which will then be converted to the corresponding
2530 ASCII (or UTF-8) character value.
2532 In addition, Jim Tcl provides basic support for conversion to binary with +%b+.
2534 `format` does backslash substitution on its +'formatString'+
2535 argument, so backslash sequences in +'formatString'+ will be handled
2536 correctly even if the argument is in braces.
2538 The return value from `format` is the formatted string.
2540 getref
2541 ~~~~~~
2542 +*getref* 'reference'+
2544 Returns the string associated with +'reference'+. The reference must
2545 be a valid reference create with the `ref` command.
2547 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2549 gets
2550 ~~~~
2551 +*gets* 'fileId ?varName?'+
2553 +'fileId' *gets* '?varName?'+
2555 Reads the next line from the file given by +'fileId'+ and discards
2556 the terminating newline character.
2558 If +'varName'+ is specified, then the line is placed in the variable
2559 by that name and the return value is a count of the number of characters
2560 read (not including the newline).
2562 If the end of the file is reached before reading
2563 any characters then -1 is returned and +'varName'+ is set to an
2564 empty string.
2566 If +'varName'+ is not specified then the return value will be
2567 the line (minus the newline character) or an empty string if
2568 the end of the file is reached before reading any characters.
2570 An empty string will also be returned if a line contains no characters
2571 except the newline, so `eof` may have to be used to determine
2572 what really happened.
2574 If the last character in the file is not a newline character, then
2575 `gets` behaves as if there were an additional newline character
2576 at the end of the file.
2578 +'fileId'+ must be +stdin+ or the return value from a previous
2579 call to `open`; it must refer to a file that was opened
2580 for reading.
2582 glob
2583 ~~~~
2584 +*glob* ?*-nocomplain*? ?*-directory* 'dir'? ?*-tails*? ?*--*? 'pattern ?pattern \...?'+
2586 This command performs filename globbing, using csh rules.  The returned
2587 value from `glob` is the list of expanded filenames.
2589 If +-nocomplain+ is specified as the first argument then an empty
2590 list may be returned;  otherwise an error is returned if the expanded
2591 list is empty.  The +-nocomplain+ argument must be provided
2592 exactly: an abbreviation will not be accepted.
2594 If +-directory+ is given, the +'dir'+ is understood to contain a
2595 directory name to search in. This allows globbing inside directories
2596 whose names may contain glob-sensitive characters. The returned names
2597 include the directory name unless +'-tails'+ is specified.
2599 If +'-tails'+ is specified, along with +-directory+, the returned names
2600 are relative to the given directory.
2602 global
2603 ~~~~~~
2605 +*global* 'varName ?varName \...?'+
2607 This command is ignored unless a Tcl procedure is being interpreted.
2608 If so, then it declares each given +'varName'+ to be a global variable
2609 rather than a local one.  For the duration of the current procedure
2610 (and only while executing in the current procedure), any reference to
2611 +'varName'+ will be bound to a global variable instead
2612 of a local one.
2614 An alternative to using `global` is to use the +::+ prefix
2615 to explicitly name a variable in the global scope.
2619 +*if* 'expr1' ?*then*? 'body1' *elseif* 'expr2' ?*then*? 'body2' *elseif* \... ?*else*? ?'bodyN'?+
2621 The `if` command evaluates +'expr1'+ as an expression (in the same way
2622 that `expr` evaluates its argument).  The value of the expression must
2623 be numeric; if it is non-zero then +'body1'+ is executed by passing it to
2624 the Tcl interpreter.
2626 Otherwise +'expr2'+ is evaluated as an expression and if it is non-zero
2627 then +'body2'+ is executed, and so on.
2629 If none of the expressions evaluates to non-zero then +'bodyN'+ is executed.
2631 The +then+ and +else+ arguments are optional "noise words" to make the
2632 command easier to read.
2634 There may be any number of +elseif+ clauses, including zero.  +'bodyN'+
2635 may also be omitted as long as +else+ is omitted too.
2637 The return value from the command is the result of the body script that
2638 was executed, or an empty string if none of the expressions was non-zero
2639 and there was no +'bodyN'+.
2641 incr
2642 ~~~~
2643 +*incr* 'varName ?increment?'+
2645 Increment the value stored in the variable whose name is +'varName'+.
2646 The value of the variable must be integral.
2648 If +'increment'+ is supplied then its value (which must be an
2649 integer) is added to the value of variable +'varName'+;  otherwise
2650 1 is added to +'varName'+.
2652 The new value is stored as a decimal string in variable +'varName'+
2653 and also returned as result.
2655 If the variable does not exist, the variable is implicitly created
2656 and set to +0+ first.
2658 info
2659 ~~~~
2661 +*info* 'option ?arg\...?'+::
2663 Provide information about various internals to the Tcl interpreter.
2664 The legal +'option'+'s (which may be abbreviated) are:
2666 +*info args* 'procname'+::
2667     Returns a list containing the names of the arguments to procedure
2668     +'procname'+, in order.  +'procname'+ must be the name of a
2669     Tcl command procedure.
2671 +*info alias* 'command'+::
2672     +'command'+ must be an alias created with `alias`. In which case the target
2673     command and arguments, as passed to `alias` are returned. See `exists -alias`
2675 +*info body* 'procname'+::
2676     Returns the body of procedure +'procname'+.  +'procname'+ must be
2677     the name of a Tcl command procedure.
2679 +*info channels*+::
2680     Returns a list of all open file handles from `open` or `socket`
2682 +*info commands* ?'pattern'?+::
2683     If +'pattern'+ isn't specified, returns a list of names of all the
2684     Tcl commands, including both the built-in commands written in C and
2685     the command procedures defined using the `proc` command.
2686     If +'pattern'+ is specified, only those names matching +'pattern'+
2687     are returned.  Matching is determined using the same rules as for
2688     `string match`.
2690 +*info complete* 'command' ?'missing'?+::
2691     Returns 1 if +'command'+ is a complete Tcl command in the sense of
2692     having no unclosed quotes, braces, brackets or array element names,
2693     If the command doesn't appear to be complete then 0 is returned.
2694     This command is typically used in line-oriented input environments
2695     to allow users to type in commands that span multiple lines;  if the
2696     command isn't complete, the script can delay evaluating it until additional
2697     lines have been typed to complete the command. If +'varName'+ is specified, the
2698     missing character is stored in the variable with that name.
2700 +*info exists* 'varName'+::
2701     Returns '1' if the variable named +'varName'+ exists in the
2702     current context (either as a global or local variable), returns '0'
2703     otherwise.
2705 +*info frame* ?'number'?+::
2706     If +'number'+ is not specified, this command returns a number
2707     which is the same result as `info level` - the current stack frame level.
2708     If +'number'+ is specified, then the result is a list consisting of the procedure,
2709     filename and line number for the procedure call at level +'number'+ on the stack.
2710     If +'number'+ is positive then it selects a particular stack level (1 refers
2711     to the top-most active procedure, 2 to the procedure it called, and
2712     so on); otherwise it gives a level relative to the current level
2713     (0 refers to the current procedure, -1 to its caller, and so on).
2714     The level has an identical meaning to `info level`.
2716 +*info globals* ?'pattern'?+::
2717     If +'pattern'+ isn't specified, returns a list of all the names
2718     of currently-defined global variables.
2719     If +'pattern'+ is specified, only those names matching +'pattern'+
2720     are returned.  Matching is determined using the same rules as for
2721     `string match`.
2723 +*info hostname*+::
2724     An alias for `os.gethostname` for compatibility with Tcl 6.x
2726 +*info level* ?'number'?+::
2727     If +'number'+ is not specified, this command returns a number
2728     giving the stack level of the invoking procedure, or 0 if the
2729     command is invoked at top-level.  If +'number'+ is specified,
2730     then the result is a list consisting of the name and arguments for the
2731     procedure call at level +'number'+ on the stack.  If +'number'+
2732     is positive then it selects a particular stack level (1 refers
2733     to the top-most active procedure, 2 to the procedure it called, and
2734     so on); otherwise it gives a level relative to the current level
2735     (0 refers to the current procedure, -1 to its caller, and so on).
2736     See the `uplevel` command for more information on what stack
2737     levels mean.
2739 +*info locals* ?'pattern'?+::
2740     If +'pattern'+ isn't specified, returns a list of all the names
2741     of currently-defined local variables, including arguments to the
2742     current procedure, if any.  Variables defined with the `global`
2743     and `upvar` commands will not be returned.  If +'pattern'+ is
2744     specified, only those names matching +'pattern'+ are returned.
2745     Matching is determined using the same rules as for `string match`.
2747 +*info nameofexecutable*+::
2748     Returns the name of the binary file from which the application
2749     was invoked. A full path will be returned, unless the path
2750     can't be determined, in which case the empty string will be returned.
2752 +*info procs* ?'pattern'?+::
2753     If +'pattern'+ isn't specified, returns a list of all the
2754     names of Tcl command procedures.
2755     If +'pattern'+ is specified, only those names matching +'pattern'+
2756     are returned.  Matching is determined using the same rules as for
2757     `string match`.
2759 +*info references*+::
2760     Returns a list of all references which have not yet been garbage
2761     collected.
2763 +*info returncodes* ?'code'?+::
2764     Returns a list representing the mapping of standard return codes
2765     to names. e.g. +{0 ok 1 error 2 return \...}+. If a code is given,
2766     instead returns the name for the given code.
2768 +*info script*+::
2769     If a Tcl script file is currently being evaluated (i.e. there is a
2770     call to 'Jim_EvalFile' active or there is an active invocation
2771     of the `source` command), then this command returns the name
2772     of the innermost file being processed.  Otherwise the command returns an
2773     empty string.
2775 +*info source* 'script ?filename line?'+::
2776     With a single argument, returns the original source location of the given script as a list of
2777     +{filename linenumber}+. If the source location can't be determined, the
2778     list +{{} 0}+ is returned. If +'filename'+ and +'line'+ are given, returns a copy
2779     of +'script'+ with the associate source information. This can be useful to produce
2780     useful messages from `eval`, etc. if the original source information may be lost.
2782 +*info stacktrace*+::
2783     After an error is caught with `catch`, returns the stack trace as a list
2784     of +{procedure filename line \...}+.
2786 +*info statics* 'procname'+::
2787     Returns a dictionary of the static variables of procedure
2788     +'procname'+.  +'procname'+ must be the name of a Tcl command
2789     procedure. An empty dictionary is returned if the procedure has
2790     no static variables.
2792 +*info version*+::
2793     Returns the version number for this version of Jim in the form +*x.yy*+.
2795 +*info vars* ?'pattern'?+::
2796     If +'pattern'+ isn't specified,
2797     returns a list of all the names of currently-visible variables, including
2798     both locals and currently-visible globals.
2799     If +'pattern'+ is specified, only those names matching +'pattern'+
2800     are returned.  Matching is determined using the same rules as for
2801     `string match`.
2803 join
2804 ~~~~
2805 +*join* 'list ?joinString?'+
2807 The +'list'+ argument must be a valid Tcl list.  This command returns the
2808 string formed by joining all of the elements of +'list'+ together with
2809 +'joinString'+ separating each adjacent pair of elements.
2811 The +'joinString'+ argument defaults to a space character.
2813 kill
2814 ~~~~
2815 +*kill* ?'SIG'|*-0*? 'pid'+
2817 Sends the given signal to the process identified by +'pid'+.
2819 The signal may be specified by name or number in one of the following forms:
2821 * +TERM+
2822 * +SIGTERM+
2823 * +-TERM+
2824 * +15+
2825 * +-15+
2827 The signal name may be in either upper or lower case.
2829 The special signal name +-0+ simply checks that a signal +'could'+ be sent.
2831 If no signal is specified, SIGTERM is used.
2833 An error is raised if the signal could not be delivered.
2835 lambda
2836 ~~~~~~
2837 +*lambda* 'args ?statics? body'+
2839 The `lambda` command is identical to `proc`, except rather than
2840 creating a named procedure, it creates an anonymous procedure and returns
2841 the name of the procedure.
2843 See `proc` and GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2845 lappend
2846 ~~~~~~~
2847 +*lappend* 'varName value ?value value \...?'+
2849 Treat the variable given by +'varName'+ as a list and append each of
2850 the +'value'+ arguments to that list as a separate element, with spaces
2851 between elements.
2853 If +'varName'+ doesn't exist, it is created as a list with elements given
2854 by the +'value'+ arguments. `lappend` is similar to `append` except that
2855 each +'value'+ is appended as a list element rather than raw text.
2857 This command provides a relatively efficient way to build up large lists.
2858 For example,
2860     lappend a $b
2862 is much more efficient than
2864     set a [concat $a [list $b]]
2866 when +$a+ is long.
2868 lassign
2869 ~~~~~~~
2870 +*lassign* 'list varName ?varName \...?'+
2872 This command treats the value +'list'+ as a list and assigns successive elements from that list to
2873 the variables given by the +'varName'+ arguments in order. If there are more variable names than
2874 list elements, the remaining variables are set to the empty string. If there are more list elements
2875 than variables, a list of unassigned elements is returned.
2877     jim> lassign {1 2 3} a b; puts a=$a,b=$b
2878     3
2879     a=1,b=2
2881 local
2882 ~~~~~
2883 +*local* 'cmd ?arg\...?'+
2885 First, `local` evaluates +'cmd'+ with the given arguments. The return value must
2886 be the name of an existing command, which is marked as having local scope.
2887 This means that when the current procedure exits, the specified
2888 command is deleted. This can be useful with `lambda`, local procedures or
2889 to automatically close a filehandle.
2891 In addition, if a command already exists with the same name,
2892 the existing command will be kept rather than deleted, and may be called
2893 via `upcall`. The previous command will be restored when the current
2894 procedure exits. See `upcall` for more details.
2896 In this example, a local procedure is created. Note that the procedure
2897 continues to have global scope while it is active.
2899     proc outer {} {
2900       # proc ... returns "inner" which is marked local
2901       local proc inner {} {
2902         # will be deleted when 'outer' exits
2903       }
2905       inner
2906       ...
2907     }
2909 In this example, the lambda is deleted at the end of the procedure rather
2910 than waiting until garbage collection.
2912     proc outer {} {
2913       set x [lambda inner {args} {
2914         # will be deleted when 'outer' exits
2915       }]
2916       # Use 'function' here which simply returns $x
2917       local function $x
2919       $x ...
2920       ...
2921     }
2923 loop
2924 ~~~~
2925 +*loop* 'var first limit ?incr? body'+
2927 Similar to `for` except simpler and possibly more efficient.
2928 With a positive increment, equivalent to:
2930   for {set var $first} {$var < $limit} {incr var $incr} $body
2932 If +'incr'+ is not specified, 1 is used.
2933 Note that setting the loop variable inside the loop does not
2934 affect the loop count.
2936 lindex
2937 ~~~~~~
2938 +*lindex* 'list ?index ...?'+
2940 Treats +'list'+ as a Tcl list and returns element +'index'+ from it
2941 (0 refers to the first element of the list).
2942 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2944 In extracting the element, +'lindex'+ observes the same rules concerning
2945 braces and quotes and backslashes as the Tcl command interpreter; however,
2946 variable substitution and command substitution do not occur.
2948 If no index values are given, simply returns +'list'+
2950 If +'index'+ is negative or greater than or equal to the number of elements
2951 in +'list'+, then an empty string is returned.
2953 If additional index arguments are supplied, then each argument is
2954 used in turn to select an element from the previous indexing
2955 operation, allowing the script to select elements from sublists.
2957 linsert
2958 ~~~~~~~
2959 +*linsert* 'list index element ?element element \...?'+
2961 This command produces a new list from +'list'+ by inserting all
2962 of the +'element'+ arguments just before the element +'index'+
2963 of +'list'+. Each +'element'+ argument will become
2964 a separate element of the new list. If +'index'+ is less than
2965 or equal to zero, then the new elements are inserted at the
2966 beginning of the list. If +'index'+ is greater than or equal
2967 to the number of elements in the list, then the new elements are
2968 appended to the list.
2970 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2972 list
2973 ~~~~
2975 +*list* 'arg ?arg \...?'+
2977 This command returns a list comprised of all the arguments, +'arg'+. Braces
2978 and backslashes get added as necessary, so that the `lindex` command
2979 may be used on the result to re-extract the original arguments, and also
2980 so that `eval` may be used to execute the resulting list, with
2981 +'arg1'+ comprising the command's name and the other args comprising
2982 its arguments. `list` produces slightly different results than
2983 `concat`:  `concat` removes one level of grouping before forming
2984 the list, while `list` works directly from the original arguments.
2985 For example, the command
2987     list a b {c d e} {f {g h}}
2989 will return
2991     a b {c d e} {f {g h}}
2993 while `concat` with the same arguments will return
2995     a b c d e f {g h}
2997 llength
2998 ~~~~~~~
2999 +*llength* 'list'+
3001 Treats +'list'+ as a list and returns a decimal string giving
3002 the number of elements in it.
3004 lset
3005 ~~~~
3006 +*lset* 'varName ?index ..? newValue'+
3008 Sets an element in a list.
3010 The `lset` command accepts a parameter, +'varName'+, which it interprets
3011 as the name of a variable containing a Tcl list. It also accepts
3012 zero or more indices into the list. Finally, it accepts a new value
3013 for an element of varName. If no indices are presented, the command
3014 takes the form:
3016     lset varName newValue
3018 In this case, newValue replaces the old value of the variable
3019 varName.
3021 When presented with a single index, the `lset` command
3022 treats the content of the varName variable as a Tcl list. It addresses
3023 the index'th element in it (0 refers to the first element of the
3024 list). When interpreting the list, `lset` observes the same rules
3025 concerning braces and quotes and backslashes as the Tcl command
3026 interpreter; however, variable substitution and command substitution
3027 do not occur. The command constructs a new list in which the
3028 designated element is replaced with newValue. This new list is
3029 stored in the variable varName, and is also the return value from
3030 the `lset` command.
3032 If index is negative or greater than or equal to the number of
3033 elements in $varName, then an error occurs.
3035 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
3037 If additional index arguments are supplied, then each argument is
3038 used in turn to address an element within a sublist designated by
3039 the previous indexing operation, allowing the script to alter
3040 elements in sublists. The command,
3042     lset a 1 2 newValue
3044 replaces element 2 of sublist 1 with +'newValue'+.
3046 The integer appearing in each index argument must be greater than
3047 or equal to zero. The integer appearing in each index argument must
3048 be strictly less than the length of the corresponding list. In other
3049 words, the `lset` command cannot change the size of a list. If an
3050 index is outside the permitted range, an error is reported.
3052 lmap
3053 ~~~~
3055 +*lmap* 'varName list body'+
3057 +*lmap* 'varList list ?varList2 list2 \...? body'+
3059 `lmap` is a "collecting" `foreach` which returns a list of its results.
3061 For example:
3063     jim> lmap i {1 2 3 4 5} {expr $i*$i}
3064     1 4 9 16 25
3065     jim> lmap a {1 2 3} b {A B C} {list $a $b}
3066     {1 A} {2 B} {3 C}
3068 If the body invokes `continue`, no value is added for this iteration.
3069 If the body invokes `break`, the loop ends and no more values are added.
3071 load
3072 ~~~~
3073 +*load* 'filename'+
3075 Loads the dynamic extension, +'filename'+. Generally the filename should have
3076 the extension +.so+. The initialisation function for the module must be based
3077 on the name of the file. For example loading +hwaccess.so+ will invoke
3078 the initialisation function, +Jim_hwaccessInit+. Normally the `load` command
3079 should not be used directly. Instead it is invoked automatically by `package require`.
3081 lrange
3082 ~~~~~~
3083 +*lrange* 'list first last'+
3085 +'list'+ must be a valid Tcl list. This command will return a new
3086 list consisting of elements +'first'+ through +'last'+, inclusive.
3088 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
3090 If +'last'+ is greater than or equal to the number of elements
3091 in the list, then it is treated as if it were +end+.
3093 If +'first'+ is greater than +'last'+ then an empty string
3094 is returned.
3096 Note: +"`lrange` 'list first first'"+ does not always produce the
3097 same result as +"`lindex` 'list first'"+ (although it often does
3098 for simple fields that aren't enclosed in braces); it does, however,
3099 produce exactly the same results as +"`list` [`lindex` 'list first']"+
3101 lreplace
3102 ~~~~~~~~
3104 +*lreplace* 'list first last ?element element \...?'+
3106 Returns a new list formed by replacing one or more elements of
3107 +'list'+ with the +'element'+ arguments.
3109 +'first'+ gives the index in +'list'+ of the first element
3110 to be replaced.
3112 If +'first'+ is less than zero then it refers to the first
3113 element of +'list'+;  the element indicated by +'first'+
3114 must exist in the list.
3116 +'last'+ gives the index in +'list'+ of the last element
3117 to be replaced;  it must be greater than or equal to +'first'+.
3119 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
3121 The +'element'+ arguments specify zero or more new arguments to
3122 be added to the list in place of those that were deleted.
3124 Each +'element'+ argument will become a separate element of
3125 the list.
3127 If no +'element'+ arguments are specified, then the elements
3128 between +'first'+ and +'last'+ are simply deleted.
3130 lrepeat
3131 ~~~~~~~~
3132 +*lrepeat* 'number element1 ?element2 \...?'+
3134 Build a list by repeating elements +'number'+ times (which must be
3135 a positive integer).
3137     jim> lrepeat 3 a b
3138     a b a b a b
3140 lreverse
3141 ~~~~~~~~
3142 +*lreverse* 'list'+
3144 Returns the list in reverse order.
3146     jim> lreverse {1 2 3}
3147     3 2 1
3149 lsearch
3150 ~~~~~~~
3151 +*lsearch* '?options? list pattern'+
3153 This command searches the elements +'list'+ to see if one of them matches +'pattern'+. If so, the
3154 command returns the index of the first matching element (unless the options +-all+, +-inline+ or +-bool+ are
3155 specified.) If not, the command returns -1. The option arguments indicates how the elements of
3156 the list are to be matched against pattern and must have one of the values below:
3158 *Note* that this command is different from Tcl in that default match type is +-exact+ rather than +-glob+.
3160 +*-exact*+::
3161     +'pattern'+ is a literal string that is compared for exact equality against each list element.
3162     This is the default.
3164 +*-glob*+::
3165     +'pattern'+ is a glob-style pattern which is matched against each list element using the same
3166     rules as the string match command.
3168 +*-regexp*+::
3169     +'pattern'+ is treated as a regular expression and matched against each list element using
3170     the rules described by `regexp`.
3172 +*-command* 'cmdname'+::
3173     +'cmdname'+ is a command which is used to match the pattern against each element of the
3174     list. It is invoked as +'cmdname' ?*-nocase*? 'pattern listvalue'+ and should return 1
3175     for a match, or 0 for no match.
3177 +*-all*+::
3178     Changes the result to be the list of all matching indices (or all matching values if
3179     +-inline+ is specified as well). If indices are returned, the indices will be in numeric
3180     order. If values are returned, the order of the values will be the order of those values
3181     within the input list.
3183 +*-inline*+::
3184     The matching value is returned instead of its index (or an empty string if no value
3185     matches). If +-all+ is also specified, then the result of the command is the list of all
3186     values that matched. The +-inline+ and +-bool+ options are mutually exclusive.
3188 +*-bool*+::
3189     Changes the result to '1' if a match was found, or '0' otherwise. If +-all+ is also specified,
3190     the result will be a list of '0' and '1' for each element of the list depending upon whether
3191     the corresponding element matches. The +-inline+ and +-bool+ options are mutually exclusive.
3193 +*-not*+::
3194     This negates the sense of the match, returning the index (or value
3195     if +-inline+ is specified) of the first non-matching value in the
3196     list. If +-bool+ is also specified, the '0' will be returned if a
3197     match is found, or '1' otherwise. If +-all+ is also specified,
3198     non-matches will be returned rather than matches.
3200 +*-nocase*+::
3201     Causes comparisons to be handled in a case-insensitive manner.
3203 lsort
3204 ~~~~~
3205 +*lsort* ?*-index* 'listindex'? ?*-nocase|-integer|-real|-command* 'cmdname'? ?*-unique*? ?*-decreasing*|*-increasing*? 'list'+
3207 Sort the elements of +'list'+, returning a new list in sorted order.
3208 By default, ASCII (or UTF-8) sorting is used, with the result in increasing order.
3210 If +-nocase+ is specified, comparisons are case-insensitive.
3212 If +-integer+ is specified, numeric sorting is used.
3214 If +-real+ is specified, floating point number sorting is used.
3216 If +-command 'cmdname'+ is specified, +'cmdname'+ is treated as a command
3217 name. For each comparison, +'cmdname $value1 $value2+' is called which
3218 should compare the values and return an integer less than, equal
3219 to, or greater than zero if the +'$value1'+ is to be considered less
3220 than, equal to, or greater than +'$value2'+, respectively.
3222 If +-decreasing+ is specified, the resulting list is in the opposite
3223 order to what it would be otherwise. +-increasing+ is the default.
3225 If +-unique+ is specified, then only the last set of duplicate elements found in the list will be retained.
3226 Note that duplicates are determined relative to the comparison used in the sort. Thus if +-index 0+ is used,
3227 +{1 a}+ and +{1 b}+ would be considered duplicates and only the second element, +{1 b}+, would be retained.
3229 If +-index 'listindex'+ is specified, each element of the list is treated as a list and
3230 the given index is extracted from the list for comparison. The list index may
3231 be any valid list index, such as +1+, +end+ or +end-2+.
3233 open
3234 ~~~~
3235 +*open* 'fileName ?access?'+
3237 +*open* '|command-pipeline ?access?'+
3239 Opens a file and returns an identifier
3240 that may be used in future invocations
3241 of commands like `read`, `puts`, and `close`.
3242 +'fileName'+ gives the name of the file to open.
3244 The +'access'+ argument indicates the way in which the file is to be accessed.
3245 It may have any of the following values:
3247 +r+::
3248     Open the file for reading only; the file must already exist.
3250 +r++::
3251     Open the file for both reading and writing; the file must
3252     already exist.
3254 +w+::
3255     Open the file for writing only. Truncate it if it exists. If it doesn't
3256     exist, create a new file.
3258 +w++::
3259     Open the file for reading and writing. Truncate it if it exists.
3260     If it doesn't exist, create a new file.
3262 +a+::
3263     Open the file for writing only. The file must already exist, and the file
3264     is positioned so that new data is appended to the file.
3266 +a++::
3267     Open the file for reading and writing. If the file doesn't
3268     exist, create a new empty file. Set the initial access position
3269     to the end of the file.
3271 +'access'+ defaults to 'r'.
3273 If a file is opened for both reading and writing, then `seek`
3274 must be invoked between a read and a write, or vice versa.
3276 If the first character of +'fileName'+ is "|" then the remaining
3277 characters of +'fileName'+ are treated as a list of arguments that
3278 describe a command pipeline to invoke, in the same style as the
3279 arguments for exec. In this case, the channel identifier returned
3280 by open may be used to write to the command's input pipe or read
3281 from its output pipe, depending on the value of +'access'+. If write-only
3282 access is used (e.g. +'access'+ is 'w'), then standard output for the
3283 pipeline is directed to the current standard output unless overridden
3284 by the command. If read-only access is used (e.g. +'access'+ is r),
3285 standard input for the pipeline is taken from the current standard
3286 input unless overridden by the command.
3288 The `pid` command may be used to return the process ids of the commands
3289 forming the command pipeline.
3291 See also `socket`, `pid`, `exec`
3293 package
3294 ~~~~~~~
3295 +*package provide* 'name ?version?'+
3297 Indicates that the current script provides the package named +'name'+.
3298 If no version is specified, '1.0' is used.
3300 Any script which provides a package may include this statement
3301 as the first statement, although it is not required.
3303 +*package require* 'name ?version?'*+
3305 Searches for the package with the given +'name'+ by examining each path
3306 in '$::auto_path' and trying to load '$path/$name.so' as a dynamic extension,
3307 or '$path/$name.tcl' as a script package.
3309 The first such file which is found is considered to provide the package.
3310 (The version number is ignored).
3312 If '$name.so' exists, it is loaded with the `load` command,
3313 otherwise if '$name.tcl' exists it is loaded with the `source` command.
3315 If `load` or `source` fails, `package require` will fail immediately.
3316 No further attempt will be made to locate the file.
3320 +*pid*+
3322 +*pid* 'fileId'+
3324 The first form returns the process identifier of the current process.
3326 The second form accepts a handle returned by `open` and returns a list
3327 of the process ids forming the pipeline in the same form as `exec ... &`.
3328 If 'fileId' represents a regular file handle rather than a command pipeline,
3329 the empty string is returned instead.
3331 See also `open`, `exec`
3333 proc
3334 ~~~~
3335 +*proc* 'name args ?statics? body'+
3337 The `proc` command creates a new Tcl command procedure, +'name'+.
3338 When the new command is invoked, the contents of +'body'+ will be executed.
3339 Tcl interpreter. +'args'+ specifies the formal arguments to the procedure.
3340 If specified, +'statics'+, declares static variables which are bound to the
3341 procedure.
3343 See PROCEDURES for detailed information about Tcl procedures.
3345 The `proc` command returns +'name'+ (which is useful with `local`).
3347 When a procedure is invoked, the procedure's return value is the
3348 value specified in a `return` command.  If the procedure doesn't
3349 execute an explicit `return`, then its return value is the value
3350 of the last command executed in the procedure's body.
3352 If an error occurs while executing the procedure body, then the
3353 procedure-as-a-whole will return that same error.
3355 puts
3356 ~~~~
3357 +*puts* ?*-nonewline*? '?fileId? string'+
3359 +'fileId' *puts* ?*-nonewline*? 'string'+
3361 Writes the characters given by +'string'+ to the file given
3362 by +'fileId'+. +'fileId'+ must have been the return
3363 value from a previous call to `open`, or it may be
3364 +stdout+ or +stderr+ to refer to one of the standard I/O
3365 channels; it must refer to a file that was opened for
3366 writing.
3368 In the first form, if no +'fileId'+ is specified then it defaults to +stdout+.
3369 `puts` normally outputs a newline character after +'string'+,
3370 but this feature may be suppressed by specifying the +-nonewline+
3371 switch.
3373 Output to files is buffered internally by Tcl; the `flush`
3374 command may be used to force buffered characters to be output.
3378 +*pwd*+
3380 Returns the path name of the current working directory.
3382 rand
3383 ~~~~
3384 +*rand* '?min? ?max?'+
3386 Returns a random integer between +'min'+ (defaults to 0) and +'max'+
3387 (defaults to the maximum integer).
3389 If only one argument is given, it is interpreted as +'max'+.
3391 range
3392 ~~~~
3393 +*range* '?start? end ?step?'+
3395 Returns a list of integers starting at +'start'+ (defaults to 0)
3396 and ranging up to but not including +'end'+ in steps of +'step'+ defaults to 1).
3398     jim> range 5
3399     0 1 2 3 4
3400     jim> range 2 5
3401     2 3 4
3402     jim> range 2 10 4
3403     2 6
3404     jim> range 7 4 -2
3405     7 5
3407 read
3408 ~~~~
3409 +*read* ?*-nonewline*? 'fileId'+
3411 +'fileId' *read* ?*-nonewline*?+
3413 +*read* 'fileId numBytes'+
3415 +'fileId' *read* 'numBytes'+
3418 In the first form, all of the remaining bytes are read from the file
3419 given by +'fileId'+; they are returned as the result of the command.
3420 If the +-nonewline+ switch is specified then the last
3421 character of the file is discarded if it is a newline.
3423 In the second form, the extra argument specifies how many bytes to read;
3424 exactly this many bytes will be read and returned, unless there are fewer than
3425 +'numBytes'+ bytes left in the file; in this case, all the remaining
3426 bytes are returned.
3428 +'fileId'+ must be +stdin+ or the return value from a previous call
3429 to `open`; it must refer to a file that was opened for reading.
3431 regexp
3432 ~~~~~~
3433 +*regexp ?-nocase? ?-line? ?-indices? ?-start* 'offset'? *?-all? ?-inline? ?--?* 'exp string ?matchVar? ?subMatchVar subMatchVar \...?'+
3435 Determines whether the regular expression +'exp'+ matches part or
3436 all of +'string'+ and returns 1 if it does, 0 if it doesn't.
3438 See REGULAR EXPRESSIONS above for complete information on the
3439 syntax of +'exp'+ and how it is matched against +'string'+.
3441 If additional arguments are specified after +'string'+ then they
3442 are treated as the names of variables to use to return
3443 information about which part(s) of +'string'+ matched +'exp'+.
3444 +'matchVar'+ will be set to the range of +'string'+ that
3445 matched all of +'exp'+. The first +'subMatchVar'+ will contain
3446 the characters in +'string'+ that matched the leftmost parenthesized
3447 subexpression within +'exp'+, the next +'subMatchVar'+ will
3448 contain the characters that matched the next parenthesized
3449 subexpression to the right in +'exp'+, and so on.
3451 Normally, +'matchVar'+ and the each +'subMatchVar'+ are set to hold the
3452 matching characters from `string`, however see +-indices+ and
3453 +-inline+ below.
3455 If there are more values for +'subMatchVar'+ than parenthesized subexpressions
3456 within +'exp'+, or if a particular subexpression in +'exp'+ doesn't
3457 match the string (e.g. because it was in a portion of the expression
3458 that wasn't matched), then the corresponding +'subMatchVar'+ will be
3459 set to +"-1 -1"+ if +-indices+ has been specified or to an empty
3460 string otherwise.
3462 The following switches modify the behaviour of +'regexp'+
3464 +*-nocase*+::
3465     Causes upper-case and lower-case characters to be treated as
3466     identical during the matching process.
3468 +*-line*+::
3469     Use newline-sensitive matching. By default, newline
3470     is a completely ordinary character with no special meaning in
3471     either REs or strings. With this flag, +[^+ bracket expressions
3472     and +.+ never match newline, an +^+ anchor matches the null
3473     string after any newline in the string in addition to its normal
3474     function, and the +$+ anchor matches the null string before any
3475     newline in the string in addition to its normal function.
3477 +*-indices*+::
3478     Changes what is stored in the subMatchVars. Instead of
3479     storing the matching characters from string, each variable
3480     will contain a list of two decimal strings giving the indices
3481     in string of the first and last characters in the matching
3482     range of characters.
3484 +*-start* 'offset'+::
3485     Specifies a character index offset into the string at which to start
3486     matching the regular expression. If +-indices+ is
3487     specified, the indices will be indexed starting from the
3488     absolute beginning of the input string. +'offset'+ will be
3489     constrained to the bounds of the input string.
3491 +*-all*+::
3492     Causes the regular expression to be matched as many times as possible
3493     in the string, returning the total number of matches found. If this
3494     is specified with match variables, they will contain information
3495     for the last match only.
3497 +*-inline*+::
3498     Causes the command to return, as a list, the data that would otherwise
3499     be placed in match variables. When using +-inline+, match variables
3500     may not be specified. If used with +-all+, the list will be concatenated
3501     at each iteration, such that a flat list is always returned. For
3502     each match iteration, the command will append the overall match
3503     data, plus one element for each subexpression in the regular
3504     expression.
3506 +*--*+::
3507     Marks the end of switches. The argument following this one will be
3508     treated as +'exp'+ even if it starts with a +-+.
3510 regsub
3511 ~~~~~~
3512 +*regsub ?-nocase? ?-all? ?-line? ?-start* 'offset'? ?*--*? 'exp string subSpec ?varName?'+
3514 This command matches the regular expression +'exp'+ against
3515 +'string'+ using the rules described in REGULAR EXPRESSIONS
3516 above.
3518 If +'varName'+ is specified, the commands stores +'string'+ to +'varName'+
3519 with the substitutions detailed below, and returns the number of
3520 substitutions made (normally 1 unless +-all+ is specified).
3521 This is 0 if there were no matches.
3523 If +'varName'+ is not specified, the substituted string will be returned
3524 instead.
3526 When copying +'string'+, the portion of +'string'+ that
3527 matched +'exp'+ is replaced with +'subSpec'+.
3528 If +'subSpec'+ contains a +&+ or +{backslash}0+, then it is replaced
3529 in the substitution with the portion of +'string'+ that
3530 matched +'exp'+.
3532 If +'subSpec'+ contains a +{backslash}n+, where +'n'+ is a digit
3533 between 1 and 9, then it is replaced in the substitution with
3534 the portion of +'string'+ that matched the +'n'+\'-th
3535 parenthesized subexpression of +'exp'+.
3536 Additional backslashes may be used in +'subSpec'+ to prevent special
3537 interpretation of +&+ or +{backslash}0+ or +{backslash}n+ or
3538 backslash.
3540 The use of backslashes in +'subSpec'+ tends to interact badly
3541 with the Tcl parser's use of backslashes, so it's generally
3542 safest to enclose +'subSpec'+ in braces if it includes
3543 backslashes.
3545 The following switches modify the behaviour of +'regsub'+
3547 +*-nocase*+::
3548     Upper-case characters in +'string'+ are converted to lower-case
3549     before matching against +'exp'+;  however, substitutions
3550     specified by +'subSpec'+ use the original unconverted form
3551     of +'string'+.
3553 +*-all*+::
3554     All ranges in +'string'+ that match +'exp'+ are found and substitution
3555     is performed for each of these ranges, rather than only the
3556     first. The +&+ and +{backslash}n+ sequences are handled for
3557     each substitution using the information from the corresponding
3558     match.
3560 +*-line*+::
3561     Use newline-sensitive matching. By default, newline
3562     is a completely ordinary character with no special meaning in
3563     either REs or strings.  With this flag, +[^+ bracket expressions
3564     and +.+ never match newline, an +^+ anchor matches the null
3565     string after any newline in the string in addition to its normal
3566     function, and the +$+ anchor matches the null string before any
3567     newline in the string in addition to its normal function.
3569 +*-start* 'offset'+::
3570     Specifies a character index offset into the string at which to
3571     start matching the regular expression. +'offset'+ will be
3572     constrained to the bounds of the input string.
3574 +*--*+::
3575     Marks the end of switches. The argument following this one will be
3576     treated as +'exp'+ even if it starts with a +-+.
3580 +*ref* 'string tag ?finalizer?'+
3582 Create a new reference containing +'string'+ of type +'tag'+.
3583 If +'finalizer'+ is specified, it is a command which will be invoked
3584 when the a garbage collection cycle runs and this reference is
3585 no longer accessible.
3587 The finalizer is invoked as:
3589   finalizer reference string
3591 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
3593 rename
3594 ~~~~~~
3595 +*rename* 'oldName newName'+
3597 Rename the command that used to be called +'oldName'+ so that it
3598 is now called +'newName'+.  If +'newName'+ is an empty string
3599 (e.g. {}) then +'oldName'+ is deleted.  The `rename` command
3600 returns an empty string as result.
3602 return
3603 ~~~~~~
3604 +*return* ?*-code* 'code'? ?*-errorinfo* 'stacktrace'? ?*-errorcode* 'errorcode'? ?*-level* 'n'? ?'value'?+
3606 Return immediately from the current procedure (or top-level command
3607 or `source` command), with +'value'+ as the return value.  If +'value'+
3608 is not specified, an empty string will be returned as result.
3610 If +-code+ is specified (as either a number or ok, error, break,
3611 continue, signal, return or exit), this code will be used instead
3612 of +JIM_OK+. This is generally useful when implementing flow of control
3613 commands.
3615 If +-level+ is specified and greater than 1, it has the effect of delaying
3616 the new return code from +-code+. This is useful when rethrowing an error
3617 from `catch`. See the implementation of try/catch in tclcompat.tcl for
3618 an example of how this is done.
3620 Note: The following options are only used when +-code+ is JIM_ERR.
3622 If +-errorinfo+ is specified (as returned from `info stacktrace`)
3623 it is used to initialize the stacktrace.
3625 If +-errorcode+ is specified, it is used to set the global variable $::errorCode.
3627 scan
3628 ~~~~
3629 +*scan* 'string format varName1 ?varName2 \...?'+
3631 This command parses fields from an input string in the same fashion
3632 as the C 'sscanf' procedure.  +'string'+ gives the input to be parsed
3633 and +'format'+ indicates how to parse it, using '%' fields as in
3634 'sscanf'.  All of the 'sscanf' options are valid; see the 'sscanf'
3635 man page for details.  Each +'varName'+ gives the name of a variable;
3636 when a field is scanned from +'string'+, the result is converted back
3637 into a string and assigned to the corresponding +'varName'+.  The
3638 only unusual conversion is for '%c'.  For '%c' conversions a single
3639 character value is converted to a decimal string, which is then
3640 assigned to the corresponding +'varName'+; no field width may be
3641 specified for this conversion.
3643 seek
3644 ~~~~
3645 +*seek* 'fileId offset ?origin?'+
3647 +'fileId' *seek* 'offset ?origin?'+
3649 Change the current access position for +'fileId'+.
3650 The +'offset'+ and +'origin'+ arguments specify the position at
3651 which the next read or write will occur for +'fileId'+.
3652 +'offset'+ must be a number (which may be negative) and +'origin'+
3653 must be one of the following:
3655 +*start*+::
3656     The new access position will be +'offset'+ bytes from the start
3657     of the file.
3659 +*current*+::
3660     The new access position will be +'offset'+ bytes from the current
3661     access position; a negative +'offset'+ moves the access position
3662     backwards in the file.
3664 +*end*+::
3665     The new access position will be +'offset'+ bytes from the end of
3666     the file.  A negative +'offset'+ places the access position before
3667     the end-of-file, and a positive +'offset'+ places the access position
3668     after the end-of-file.
3670 The +'origin'+ argument defaults to +start+.
3672 +'fileId'+ must have been the return value from a previous call to
3673 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
3674 of the standard I/O channels.
3676 This command returns an empty string.
3680 +*set* 'varName ?value?'+
3682 Returns the value of variable +'varName'+.
3684 If +'value'+ is specified, then set the value of +'varName'+ to +'value'+,
3685 creating a new variable if one doesn't already exist, and return
3686 its value.
3688 If +'varName'+ contains an open parenthesis and ends with a
3689 close parenthesis, then it refers to an array element:  the characters
3690 before the open parenthesis are the name of the array, and the characters
3691 between the parentheses are the index within the array.
3692 Otherwise +'varName'+ refers to a scalar variable.
3694 If no procedure is active, then +'varName'+ refers to a global
3695 variable.
3697 If a procedure is active, then +'varName'+ refers to a parameter
3698 or local variable of the procedure, unless the +'global'+ command
3699 has been invoked to declare +'varName'+ to be global.
3701 The +::+ prefix may also be used to explicitly reference a variable
3702 in the global scope.
3704 setref
3705 ~~~~~~
3706 +*setref* 'reference string'+
3708 Store a new string in +'reference'+, replacing the existing string.
3709 The reference must be a valid reference create with the `ref`
3710 command.
3712 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
3714 signal
3715 ~~~~~~
3716 Command for signal handling.
3718 See `kill` for the different forms which may be used to specify signals.
3720 Commands which return a list of signal names do so using the canonical form:
3721 "+SIGINT SIGTERM+".
3723 +*signal handle* ?'signals \...'?+::
3724     If no signals are given, returns a list of all signals which are currently
3725     being handled.
3726     If signals are specified, these are added to the list of signals currently
3727     being handled.
3729 +*signal ignore* ?'signals \...'?+::
3730     If no signals are given, returns a lists all signals which are currently
3731     being ignored.
3732     If signals are specified, these are added to the list of signals
3733     currently being ignored. These signals are still delivered, but
3734     are not considered by `catch -signal` or `try -signal`. Use
3735     `signal check` to determine which signals have occurred but
3736     been ignored.
3738 +*signal default* ?'signals \...'?+::
3739     If no signals are given, returns a lists all signals which are currently have
3740     the default behaviour.
3741     If signals are specified, these are added to the list of signals which have
3742     the default behaviour.
3744 +*signal check ?-clear?* ?'signals \...'?+::
3745     Returns a list of signals which have been delivered to the process
3746     but are 'ignored'. If signals are specified, only that set of signals will
3747     be checked, otherwise all signals will be checked.
3748     If +-clear+ is specified, any signals returned are removed and will not be
3749     returned by subsequent calls to `signal check` unless delivered again.
3751 +*signal throw* ?'signal'?+::
3752     Raises the given signal, which defaults to +SIGINT+ if not specified.
3753     The behaviour is identical to:
3755         kill signal [pid]
3757 Note that `signal handle` and `signal ignore` represent two forms of signal
3758 handling. `signal handle` is used in conjunction with `catch -signal` or `try -signal`
3759 to immediately abort execution when the signal is delivered. Alternatively, `signal ignore`
3760 is used in conjunction with `signal check` to handle signal synchronously. Consider the
3761 two examples below.
3763 Prevent a processing from taking too long
3765     signal handle SIGALRM
3766     alarm 20
3767     try -signal {
3768         .. possibly long running process ..
3769         alarm 0
3770     } on signal {sig} {
3771         puts stderr "Process took too long"
3772     }
3774 Handle SIGHUP to reconfigure:
3776     signal ignore SIGHUP
3777     while {1} {
3778         ... handle configuration/reconfiguration ...
3779         while {[signal check -clear SIGHUP] eq ""} {
3780             ... do processing ..
3781         }
3782         # Received SIGHUP, so reconfigure
3783     }
3785 sleep
3786 ~~~~~
3787 +*sleep* 'seconds'+
3789 Pauses for the given number of seconds, which may be a floating
3790 point value less than one to sleep for less than a second, or an
3791 integer to sleep for one or more seconds.
3793 source
3794 ~~~~~~
3795 +*source* 'fileName'+
3797 Read file +'fileName'+ and pass the contents to the Tcl interpreter
3798 as a sequence of commands to execute in the normal fashion.  The return
3799 value of `source` is the return value of the last command executed
3800 from the file.  If an error occurs in executing the contents of the
3801 file, then the `source` command will return that error.
3803 If a `return` command is invoked from within the file, the remainder of
3804 the file will be skipped and the `source` command will return
3805 normally with the result from the `return` command.
3807 split
3808 ~~~~~
3809 +*split* 'string ?splitChars?'+
3811 Returns a list created by splitting +'string'+ at each character
3812 that is in the +'splitChars'+ argument.
3814 Each element of the result list will consist of the
3815 characters from +'string'+ between instances of the
3816 characters in +'splitChars'+.
3818 Empty list elements will be generated if +'string'+ contains
3819 adjacent characters in +'splitChars'+, or if the first or last
3820 character of +'string'+ is in +'splitChars'+.
3822 If +'splitChars'+ is an empty string then each character of
3823 +'string'+ becomes a separate element of the result list.
3825 +'splitChars'+ defaults to the standard white-space characters.
3826 For example,
3828     split "comp.unix.misc" .
3830 returns +'"comp unix misc"'+ and
3832     split "Hello world" {}
3834 returns +'"H e l l o { } w o r l d"'+.
3836 stackdump
3837 ~~~~~~~~~
3839 +*stackdump* 'stacktrace'+
3841 Creates a human readable representation of a stack trace.
3843 stacktrace
3844 ~~~~~~~~~~
3846 +*stacktrace*+
3848 Returns a live stack trace as a list of +proc file line proc file line \...+.
3849 Iteratively uses `info frame` to create the stack trace. This stack trace is in the
3850 same form as produced by `catch` and `info stacktrace`
3852 See also `stackdump`.
3854 string
3855 ~~~~~~
3857 +*string* 'option arg ?arg \...?'+
3859 Perform one of several string operations, depending on +'option'+.
3860 The legal options (which may be abbreviated) are:
3862 +*string bytelength* 'string'+::
3863     Returns the length of the string in bytes. This will return
3864     the same value as `string length` if UTF-8 support is not enabled,
3865     or if the string is composed entirely of ASCII characters.
3866     See UTF-8 AND UNICODE.
3868 +*string byterange* 'string first last'+::
3869     Like `string range` except works on bytes rather than characters.
3870     These commands are identical if UTF-8 support is not enabled.
3872 +*string cat* '?string1 string2 \...?'+::
3873     Concatenates the given strings into a single string.
3875 +*string compare ?-nocase?* ?*-length* 'len? string1 string2'+::
3876     Perform a character-by-character comparison of strings +'string1'+ and
3877     +'string2'+ in the same way as the C 'strcmp' procedure.  Return
3878     -1, 0, or 1, depending on whether +'string1'+ is lexicographically
3879     less than, equal to, or greater than +'string2'+. If +-length+
3880     is specified, then only the first +'len'+ characters are used
3881     in the comparison.  If +'len'+ is negative, it is ignored.
3882     Performs a case-insensitive comparison if +-nocase+ is specified.
3884 +*string equal ?-nocase?* '?*-length* len?' 'string1 string2'+::
3885     Returns 1 if the strings are equal, or 0 otherwise. If +-length+
3886     is specified, then only the first +'len'+ characters are used
3887     in the comparison.  If +'len'+ is negative, it is ignored.
3888     Performs a case-insensitive comparison if +-nocase+ is specified.
3890 +*string first* 'string1 string2 ?firstIndex?'+::
3891     Search +'string2'+ for a sequence of characters that exactly match
3892     the characters in +'string1'+.  If found, return the index of the
3893     first character in the first such match within +'string2'+.  If not
3894     found, return -1. If +'firstIndex'+ is specified, matching will start
3895     from +'firstIndex'+ of +'string1'+.
3896  ::
3897     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'firstIndex'+.
3899 +*string index* 'string charIndex'+::
3900     Returns the +'charIndex'+'th character of the +'string'+
3901     argument.  A +'charIndex'+ of 0 corresponds to the first
3902     character of the string.
3903     If +'charIndex'+ is less than 0 or greater than
3904     or equal to the length of the string then an empty string is
3905     returned.
3906  ::
3907     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'charIndex'+.
3909 +*string is* 'class' ?*-strict*? 'string'+::
3910     Returns 1 if +'string'+ is a valid member of the specified character
3911     class, otherwise returns 0. If +-strict+ is specified, then an
3912     empty string returns 0, otherwise an empty string will return 1
3913     on any class. The following character classes are recognized
3914     (the class name can be abbreviated):
3915   ::
3916   +alnum+;;  Any alphabet or digit character.
3917   +alpha+;;  Any alphabet character.
3918   +ascii+;;  Any character with a value less than 128 (those that are in the 7-bit ascii range).
3919   +boolean+;;  Any of the valid string formats for a boolean value in Tcl (0, false, no, off, 1, true, yes, on)
3920   +control+;; Any control character.
3921   +digit+;;  Any digit character.
3922   +double+;; Any of the valid forms for a double in Tcl, with optional surrounding whitespace.
3923              In case of under/overflow in the value, 0 is returned.
3924   +graph+;;  Any printing character, except space.
3925   +integer+;; Any of the valid string formats for an integer value in Tcl, with optional surrounding whitespace.
3926   +lower+;;  Any lower case alphabet character.
3927   +print+;;  Any printing character, including space.
3928   +punct+;;  Any punctuation character.
3929   +space+;;  Any space character.
3930   +upper+;;  Any upper case alphabet character.
3931   +xdigit+;; Any hexadecimal digit character ([0-9A-Fa-f]).
3932  ::
3933     Note that string classification does +'not'+ respect UTF-8. See UTF-8 AND UNICODE
3934  ::
3935     Note that only +'lowercase'+ boolean values are recognized (Tcl accepts any case).
3937 +*string last* 'string1 string2 ?lastIndex?'+::
3938     Search +'string2'+ for a sequence of characters that exactly match
3939     the characters in +'string1'+.  If found, return the index of the
3940     first character in the last such match within +'string2'+.  If there
3941     is no match, then return -1. If +'lastIndex'+ is specified, only characters
3942     up to +'lastIndex'+ of +'string2'+ will be considered in the match.
3943  ::
3944     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'lastIndex'+.
3946 +*string length* 'string'+::
3947     Returns a decimal string giving the number of characters in +'string'+.
3948     If UTF-8 support is enabled, this may be different than the number of bytes.
3949     See UTF-8 AND UNICODE
3951 +*string map ?-nocase?* 'mapping string'+::
3952     Replaces substrings in +'string'+ based on the key-value pairs in
3953     +'mapping'+, which is a list of +key value key value \...+ as in the form
3954     returned by `array get`. Each instance of a key in the string will be
3955     replaced with its corresponding value.  If +-nocase+ is specified, then
3956     matching is done without regard to case differences. Both key and value may
3957     be multiple characters.  Replacement is done in an ordered manner, so the
3958     key appearing first in the list will be checked first, and so on. +'string'+ is
3959     only iterated over once, so earlier key replacements will have no affect for
3960     later key matches. For example,
3962       string map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc
3964  ::
3965     will return the string +01321221+.
3966  ::
3967     Note that if an earlier key is a prefix of a later one, it will completely mask the later
3968     one.  So if the previous example is reordered like this,
3970       string map {1 0 ab 2 a 3 abc 1} 1abcaababcabababc
3972  ::
3973     it will return the string +02c322c222c+.
3975 +*string match ?-nocase?* 'pattern string'+::
3976     See if +'pattern'+ matches +'string'+; return 1 if it does, 0
3977     if it doesn't.  Matching is done in a fashion similar to that
3978     used by the C-shell.  For the two strings to match, their contents
3979     must be identical except that the following special sequences
3980     may appear in +'pattern'+:
3982     +*+;;
3983         Matches any sequence of characters in +'string'+,
3984         including a null string.
3986     +?+;;
3987         Matches any single character in +'string'+.
3989     +['chars']+;;
3990         Matches any character in the set given by +'chars'+.
3991         If a sequence of the form +'x-y'+ appears in +'chars'+,
3992         then any character between +'x'+ and +'y'+, inclusive,
3993         will match.
3995     +{backslash}x+;;
3996         Matches the single character +'x'+.  This provides a way of
3997         avoiding the special interpretation of the characters +{backslash}*?[]+
3998         in +'pattern'+.
3999  ::
4000     Performs a case-insensitive comparison if +-nocase+ is specified.
4002 +*string range* 'string first last'+::
4003     Returns a range of consecutive characters from +'string'+, starting
4004     with the character whose index is +'first'+ and ending with the
4005     character whose index is +'last'+.  An index of 0 refers to the
4006     first character of the string.
4007  ::
4008     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
4009  ::
4010     If +'first'+ is less than zero then it is treated as if it were zero, and
4011     if +'last'+ is greater than or equal to the length of the string then
4012     it is treated as if it were +end+.  If +'first'+ is greater than
4013     +'last'+ then an empty string is returned.
4015 +*string repeat* 'string count'+::
4016     Returns a new string consisting of +'string'+ repeated +'count'+ times.
4018 +*string replace* 'string first last ?newstring?'+::
4019     Removes a range of consecutive characters from +'string'+, starting
4020     with the character whose index is +'first'+ and ending with the
4021     character whose index is +'last'+.  If +'newstring'+ is specified,
4022     then it is placed in the removed character range. If +'first'+ is
4023     less than zero then it is treated as if it were zero, and if +'last'+
4024     is greater than or equal to the length of the string then it is
4025     treated as if it were +end+. If +'first'+ is greater than +'last'+
4026     or the length of the initial string, or +'last'+ is less than 0,
4027     then the initial string is returned untouched.
4029 +*string reverse* 'string'+::
4030     Returns a string that is the same length as +'string'+ but
4031     with its characters in the reverse order.
4033 +*string tolower* 'string'+::
4034     Returns a value equal to +'string'+ except that all upper case
4035     letters have been converted to lower case.
4037 +*string totitle* 'string'+::
4038     Returns a value equal to +'string'+ except that the first character
4039     is converted to title case (or upper case if there is no UTF-8 titlecase variant)
4040     and all remaining characters have been converted to lower case.
4042 +*string toupper* 'string'+::
4043     Returns a value equal to +'string'+ except that all lower case
4044     letters have been converted to upper case.
4046 +*string trim* 'string ?chars?'+::
4047     Returns a value equal to +'string'+ except that any leading
4048     or trailing characters from the set given by +'chars'+ are
4049     removed.
4050     If +'chars'+ is not specified then white space is removed
4051     (spaces, tabs, newlines, and carriage returns).
4053 +*string trimleft* 'string ?chars?'+::
4054     Returns a value equal to +'string'+ except that any
4055     leading 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 trimright* 'string ?chars?'+::
4061     Returns a value equal to +'string'+ except that any
4062     trailing 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).
4066     Null characters are always removed.
4068 subst
4069 ~~~~~
4070 +*subst ?-nobackslashes? ?-nocommands? ?-novariables?* 'string'+
4072 This command performs variable substitutions, command substitutions,
4073 and backslash substitutions on its string argument and returns the
4074 fully-substituted result. The substitutions are performed in exactly
4075 the same way as for Tcl commands. As a result, the string argument
4076 is actually substituted twice, once by the Tcl parser in the usual
4077 fashion for Tcl commands, and again by the subst command.
4079 If any of the +-nobackslashes+, +-nocommands+, or +-novariables+ are
4080 specified, then the corresponding substitutions are not performed.
4081 For example, if +-nocommands+ is specified, no command substitution
4082 is performed: open and close brackets are treated as ordinary
4083 characters with no special interpretation.
4085 *Note*: when it performs its substitutions, subst does not give any
4086 special treatment to double quotes or curly braces. For example,
4087 the following script returns +xyz \{44\}+, not +xyz \{$a\}+.
4089     set a 44
4090     subst {xyz {$a}}
4093 switch
4094 ~~~~~~
4095 +*switch* '?options? string pattern body ?pattern body \...?'+
4097 +*switch* '?options? string {pattern body ?pattern body \...?}'+
4099 The `switch` command matches its string argument against each of
4100 the pattern arguments in order. As soon as it finds a pattern that
4101 matches string it evaluates the following body and returns the
4102 result of that evaluation. If the last pattern argument is default
4103 then it matches anything. If no pattern argument matches string and
4104 no default is given, then the `switch` command returns an empty string.
4105 If the initial arguments to switch start with - then they are treated
4106 as options. The following options are currently supported:
4108     +-exact+::
4109         Use exact matching when comparing string to a
4110         pattern. This is the default.
4112     +-glob+::
4113         When matching string to the patterns, use glob-style
4114         matching (i.e. the same as implemented by the string
4115         match command).
4117     +-regexp+::
4118         When matching string to the patterns, use regular
4119         expression matching (i.e. the same as implemented
4120         by the regexp command).
4122     +-command 'commandname'+::
4123         When matching string to the patterns, use the given command, which
4124         must be a single word. The command is invoked as
4125         'commandname pattern string', or 'commandname -nocase pattern string'
4126         and must return 1 if matched, or 0 if not.
4128     +--+::
4129         Marks the end of options. The argument following
4130         this one will be treated as string even if it starts
4131         with a +-+.
4133 Two syntaxes are provided for the pattern and body arguments. The
4134 first uses a separate argument for each of the patterns and commands;
4135 this form is convenient if substitutions are desired on some of the
4136 patterns or commands. The second form places all of the patterns
4137 and commands together into a single argument; the argument must
4138 have proper list structure, with the elements of the list being the
4139 patterns and commands. The second form makes it easy to construct
4140 multi-line `switch` commands, since the braces around the whole list
4141 make it unnecessary to include a backslash at the end of each line.
4142 Since the pattern arguments are in braces in the second form, no
4143 command or variable substitutions are performed on them; this makes
4144 the behaviour of the second form different than the first form in
4145 some cases.
4147 If a body is specified as +-+ it means that the body for the next
4148 pattern should also be used as the body for this pattern (if the
4149 next pattern also has a body of +-+ then the body after that is
4150 used, and so on). This feature makes it possible to share a single
4151 body among several patterns.
4153 Below are some examples of `switch` commands:
4155     switch abc a - b {format 1} abc {format 2} default {format 3}
4157 will return 2,
4159     switch -regexp aaab {
4160            ^a.*b$ -
4161            b {format 1}
4162            a* {format 2}
4163            default {format 3}
4164     }
4166 will return 1, and
4168     switch xyz {
4169            a -
4170            b {format 1}
4171            a* {format 2}
4172            default {format 3}
4173     }
4175 will return 3.
4177 tailcall
4178 ~~~~~~~~
4179 +*tailcall* 'cmd ?arg\...?'+
4181 The `tailcall` command provides an optimised way of invoking a command whilst replacing
4182 the current call frame. This is similar to 'exec' in Bourne Shell.
4184 The following are identical except the first immediately replaces the current call frame.
4186   tailcall a b c
4188   return [uplevel 1 [list a b c]]
4190 `tailcall` is useful as a dispatch mechanism:
4192   proc a {cmd args} {
4193     tailcall sub_$cmd {*}$args
4194   }
4195   proc sub_cmd1 ...
4196   proc sub_cmd2 ...
4198 tell
4199 ~~~~
4200 +*tell* 'fileId'+
4202 +'fileId' *tell*+
4204 Returns a decimal string giving the current access position in
4205 +'fileId'+.
4207 +'fileId'+ must have been the return value from a previous call to
4208 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
4209 of the standard I/O channels.
4211 throw
4212 ~~~~~
4213 +*throw* 'code ?msg?'+
4215 This command throws an exception (return) code along with an optional message.
4216 This command is mostly for convenient usage with `try`.
4218 The command +throw break+ is equivalent to +break+.
4219 The command +throw 20 message+ can be caught with an +on 20 \...+ clause to `try`.
4221 time
4222 ~~~~
4223 +*time* 'command ?count?'+
4225 This command will call the Tcl interpreter +'count'+
4226 times to execute +'command'+ (or once if +'count'+ isn't
4227 specified).  It will then return a string of the form
4229     503 microseconds per iteration
4231 which indicates the average amount of time required per iteration,
4232 in microseconds.
4234 Time is measured in elapsed time, not CPU time.
4238 +*try* '?catchopts? tryscript' ?*on* 'returncodes {?resultvar? ?optsvar?} handlerscript \...'? ?*finally* 'finalscript'?+
4240 The `try` command is provided as a convenience for exception handling.
4242 This interpeter first evaluates +'tryscript'+ under the effect of the catch
4243 options +'catchopts'+ (e.g. +-signal -noexit --+, see `catch`).
4245 It then evaluates the script for the first matching 'on' handler
4246 (there many be zero or more) based on the return code from the `try`
4247 section. For example a normal +JIM_ERR+ error will be matched by
4248 an 'on error' handler.
4250 Finally, any +'finalscript'+ is evaluated.
4252 The result of this command is the result of +'tryscript'+, except in the
4253 case where an exception occurs in a matching 'on' handler script or the 'finally' script,
4254 in which case the result is this new exception.
4256 The specified +'returncodes'+ is a list of return codes either as names ('ok', 'error', 'break', etc.)
4257 or as integers.
4259 If +'resultvar'+ and +'optsvar'+ are specified, they are set as for `catch` before evaluating
4260 the matching handler.
4262 For example:
4264     set f [open input]
4265     try -signal {
4266         process $f
4267     } on {continue break} {} {
4268         error "Unexpected break/continue"
4269     } on error {msg opts} {
4270         puts "Dealing with error"
4271         return {*}$opts $msg
4272     } on signal sig {
4273         puts "Got signal: $sig"
4274     } finally {
4275         $f close
4276     }
4278 If break, continue or error are raised, they are dealt with by the matching
4279 handler.
4281 In any case, the file will be closed via the 'finally' clause.
4283 See also `throw`, `catch`, `return`, `error`.
4285 unknown
4286 ~~~~~~~
4287 +*unknown* 'cmdName ?arg arg ...?'+
4289 This command doesn't actually exist as part of Tcl, but Tcl will
4290 invoke it if it does exist.
4292 If the Tcl interpreter encounters a command name for which there
4293 is not a defined command, then Tcl checks for the existence of
4294 a command named `unknown`.
4296 If there is no such command, then the interpreter returns an
4297 error.
4299 If the `unknown` command exists, then it is invoked with
4300 arguments consisting of the fully-substituted name and arguments
4301 for the original non-existent command.
4303 The `unknown` command typically does things like searching
4304 through library directories for a command procedure with the name
4305 +'cmdName'+, or expanding abbreviated command names to full-length,
4306 or automatically executing unknown commands as UNIX sub-processes.
4308 In some cases (such as expanding abbreviations) `unknown` will
4309 change the original command slightly and then (re-)execute it.
4310 The result of the `unknown` command is used as the result for
4311 the original non-existent command.
4313 unset
4314 ~~~~~
4315 +*unset ?-nocomplain? ?--?* '?name name ...?'+
4317 Remove variables.
4318 Each +'name'+ is a variable name, specified in any of the
4319 ways acceptable to the `set` command.
4321 If a +'name'+ refers to an element of an array, then that
4322 element is removed without affecting the rest of the array.
4324 If a +'name'+ consists of an array name with no parenthesized
4325 index, then the entire array is deleted.
4327 The `unset` command returns an empty string as result.
4329 An error occurs if any of the variables doesn't exist, unless '-nocomplain'
4330 is specified. The '--' argument may be specified to stop option processing
4331 in case the variable name may be '-nocomplain'.
4333 upcall
4334 ~~~~~~~
4335 +*upcall* 'command ?args ...?'+
4337 May be used from within a proc defined as `local` `proc` in order to call
4338 the previous, hidden version of the same command.
4340 If there is no previous definition of the command, an error is returned.
4342 uplevel
4343 ~~~~~~~
4344 +*uplevel* '?level? command ?command ...?'+
4346 All of the +'command'+ arguments are concatenated as if they had
4347 been passed to `concat`; the result is then evaluated in the
4348 variable context indicated by +'level'+.  `uplevel` returns
4349 the result of that evaluation.  If +'level'+ is an integer, then
4350 it gives a distance (up the procedure calling stack) to move before
4351 executing the command.  If +'level'+ consists of +\#+ followed by
4352 a number then the number gives an absolute level number.  If +'level'+
4353 is omitted then it defaults to +1+.  +'level'+ cannot be
4354 defaulted if the first +'command'+ argument starts with a digit or +#+.
4356 For example, suppose that procedure 'a' was invoked
4357 from top-level, and that it called 'b', and that 'b' called 'c'.
4358 Suppose that 'c' invokes the `uplevel` command.  If +'level'+
4359 is +1+ or +#2+  or omitted, then the command will be executed
4360 in the variable context of 'b'.  If +'level'+ is +2+ or +#1+
4361 then the command will be executed in the variable context of 'a'.
4363 If +'level'+ is '3' or +#0+ then the command will be executed
4364 at top-level (only global variables will be visible).
4365 The `uplevel` command causes the invoking procedure to disappear
4366 from the procedure calling stack while the command is being executed.
4367 In the above example, suppose 'c' invokes the command
4369     uplevel 1 {set x 43; d}
4371 where 'd' is another Tcl procedure.  The `set` command will
4372 modify the variable 'x' in 'b's context, and 'd' will execute
4373 at level 3, as if called from 'b'.  If it in turn executes
4374 the command
4376     uplevel {set x 42}
4378 then the `set` command will modify the same variable 'x' in 'b's
4379 context:  the procedure 'c' does not appear to be on the call stack
4380 when 'd' is executing.  The command `info level` may
4381 be used to obtain the level of the current procedure.
4383 `uplevel` makes it possible to implement new control
4384 constructs as Tcl procedures (for example, `uplevel` could
4385 be used to implement the `while` construct as a Tcl procedure).
4387 upvar
4388 ~~~~~
4389 +*upvar* '?level? otherVar myVar ?otherVar myVar ...?'+
4391 This command arranges for one or more local variables in the current
4392 procedure to refer to variables in an enclosing procedure call or
4393 to global variables.
4395 +'level'+ may have any of the forms permitted for the `uplevel`
4396 command, and may be omitted if the first letter of the first +'otherVar'+
4397 isn't +#+ or a digit (it defaults to '1').
4399 For each +'otherVar'+ argument, `upvar` makes the variable
4400 by that name in the procedure frame given by +'level'+ (or at
4401 global level, if +'level'+ is +#0+) accessible
4402 in the current procedure by the name given in the corresponding
4403 +'myVar'+ argument.
4405 The variable named by +'otherVar'+ need not exist at the time of the
4406 call;  it will be created the first time +'myVar'+ is referenced, just like
4407 an ordinary variable.
4409 `upvar` may only be invoked from within procedures.
4411 `upvar` returns an empty string.
4413 The `upvar` command simplifies the implementation of call-by-name
4414 procedure calling and also makes it easier to build new control constructs
4415 as Tcl procedures.
4416 For example, consider the following procedure:
4418     proc add2 name {
4419         upvar $name x
4420         set x [expr $x+2]
4421     }
4423 'add2' is invoked with an argument giving the name of a variable,
4424 and it adds two to the value of that variable.
4425 Although 'add2' could have been implemented using `uplevel`
4426 instead of `upvar`, `upvar` makes it simpler for 'add2'
4427 to access the variable in the caller's procedure frame.
4429 while
4430 ~~~~~
4431 +*while* 'test body'+
4433 The +'while'+ command evaluates +'test'+ as an expression
4434 (in the same way that `expr` evaluates its argument).
4435 The value of the expression must be numeric; if it is non-zero
4436 then +'body'+ is executed by passing it to the Tcl interpreter.
4438 Once +'body'+ has been executed then +'test'+ is evaluated
4439 again, and the process repeats until eventually +'test'+
4440 evaluates to a zero numeric value.  `continue`
4441 commands may be executed inside +'body'+ to terminate the current
4442 iteration of the loop, and `break`
4443 commands may be executed inside +'body'+ to cause immediate
4444 termination of the `while` command.
4446 The `while` command always returns an empty string.
4448 OPTIONAL-EXTENSIONS
4449 -------------------
4451 The following extensions may or may not be available depending upon
4452 what options were selected when Jim Tcl was built.
4454 [[cmd_1]]
4455 posix: os.fork, os.wait, os.gethostname, os.getids, os.uptime
4456 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4457 +*os.fork*+::
4458     Invokes 'fork(2)' and returns the result.
4460 +*os.wait -nohang* 'pid'+::
4461     Invokes waitpid(2), with WNOHANG if +-nohang+ is specified.
4462     Returns a list of 3 elements.
4464    {0 none 0} if -nohang is specified, and the process is still alive.
4466    {-1 error <error-description>} if the process does not exist or has already been waited for.
4468    {<pid> exit <exit-status>} if the process exited normally.
4470    {<pid> signal <signal-number>} if the process terminated on a signal.
4472    {<pid> other 0} otherwise (core dump, stopped, continued, etc.)
4474 +*os.gethostname*+::
4475     Invokes 'gethostname(3)' and returns the result.
4477 +*os.getids*+::
4478     Returns the various user/group ids for the current process.
4480     jim> os.getids
4481     uid 1000 euid 1000 gid 100 egid 100
4483 +*os.uptime*+::
4484     Returns the number of seconds since system boot. See description of 'uptime' in 'sysinfo(2)'.
4486 ANSI I/O (aio) and EVENTLOOP API
4487 --------------------------------
4488 Jim provides an alternative object-based API for I/O.
4490 See `open` and `socket` for commands which return an I/O handle.
4494 +$handle *accept* ?addrvar?+::
4495     Server socket only: Accept a connection and return stream.
4496     If +'addrvar'+ is specified, the address of the connected client is stored
4497     in the named variable in the form 'addr:port'. See `socket` for details.
4499 +$handle *buffering none|line|full*+::
4500     Sets the buffering mode of the stream.
4502 +$handle *close* ?r(ead)|w(rite)?+::
4503     Closes the stream.
4504     The  two-argument form is a "half-close" on a socket. See the +shutdown(2)+ man page.
4506 +$handle *copyto* 'tofd ?size?'+::
4507     Copy bytes to the file descriptor +'tofd'+. If +'size'+ is specified, at most
4508     that many bytes will be copied. Otherwise copying continues until the end
4509     of the input file. Returns the number of bytes actually copied.
4511 +$handle *eof*+::
4512     Returns 1 if stream is at eof
4514 +$handle *filename*+::
4515     Returns the original filename associated with the handle.
4516     Handles returned by `socket` give the socket type instead of a filename.
4518 +$handle *flush*+::
4519     Flush the stream
4521 +$handle *gets* '?var?'+::
4522     Read one line and return it or store it in the var
4524 +$handle *isatty*+::
4525     Returns 1 if the stream is a tty device.
4527 +$handle *lock*+::
4528     Apply a POSIX lock to the open file associated with the handle using
4529     fcntl(2).
4530     The handle must be open for write access.
4531     Returns 1 if the lock was successfully obtained, 0 otherwise.
4532     An error occurs if the handle is not suitable for locking (e.g.
4533     if it is not open for write)
4535 +$handle *ndelay ?0|1?*+::
4536     Set O_NDELAY (if arg). Returns current/new setting.
4537     Note that in general ANSI I/O interacts badly with non-blocking I/O.
4538     Use with care.
4540 +$handle *puts ?-nonewline?* 'str'+::
4541     Write the string, with newline unless -nonewline
4543 +$handle *read ?-nonewline?* '?len?'+::
4544     Read and return bytes from the stream. To eof if no len.
4546 +$handle *recvfrom* 'maxlen ?addrvar?'+::
4547     Receives a message from the handle via recvfrom(2) and returns it.
4548     At most +'maxlen'+ bytes are read.
4549     If +'addrvar'+ is specified, the sending address of the message is stored in
4550     the named variable in the form 'addr:port'. See `socket` for details.
4552 +$handle *seek* 'offset' *?start|current|end?*+::
4553     Seeks in the stream (default 'current')
4555 +$handle *sendto* 'str ?addr:?port'+::
4556     Sends the string, +'str'+, to the given address via the socket using sendto(2).
4557     This is intended for udp/dgram sockets and may give an error or behave in unintended
4558     ways for other handle types.
4559     Returns the number of bytes written.
4561 +$handle *sync*+::
4562     Flush the stream, then fsync(2) to commit any changes to storage.
4563     Only available on platforms that support fsync(2).
4565 +$handle *tell*+::
4566     Returns the current seek position
4568 +$handle *ssl* *?-server cert priv?*+::
4569     Initiates a SSL/TLS session and returns a new stream
4571 +$handle *unlock*+::
4572     Release a POSIX lock previously acquired by `aio lock`.
4574 +$handle *verify*+::
4575     Verifies the certificate of a SSL/TLS stream peer
4577 +*load_ssl_certs* 'dir'+::
4578     Loads SSL/TLS CA certificates for use during verification
4580 fconfigure
4581 ~~~~~~~~~~
4582 +*fconfigure* 'handle' *?-blocking 0|1? ?-buffering noneline|full? ?-translation* 'mode'?+::
4583     For compatibility with Tcl, a limited form of the `fconfigure`
4584     command is supported.
4585     * `fconfigure ... -blocking` maps to `aio ndelay`
4586     * `fconfigure ... -buffering` maps to `aio buffering`
4587     * `fconfigure ... -translation` is accepted but ignored
4589 [[cmd_2]]
4590 eventloop: after, vwait, update
4591 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4593 The following commands allow a script to be invoked when the given condition occurs.
4594 If no script is given, returns the current script. If the given script is the empty, the
4595 handler is removed.
4597 +$handle *readable* '?readable-script?'+::
4598     Sets or returns the script for when the socket is readable.
4600 +$handle *writable* '?writable-script?'+::
4601     Sets or returns the script for when the socket is writable.
4603 +$handle *onexception* '?exception-script?'+::
4604     Sets or returns the script for when oob data received.
4606 For compatibility with 'Tcl', these may be prefixed with `fileevent`.  e.g.
4608  ::
4609     +fileevent $handle *readable* '\...'+
4611 Time-based execution is also available via the eventloop API.
4613 +*after* 'ms'+::
4614     Sleeps for the given number of milliseconds. No events are
4615     processed during this time.
4617 +*after* 'ms'|*idle* 'script ?script \...?'+::
4618     The scripts are concatenated and executed after the given
4619     number of milliseconds have elapsed.  If 'idle' is specified,
4620     the script will run the next time the event loop is processed
4621     with `vwait` or `update`. The script is only run once and
4622     then removed.  Returns an event id.
4624 +*after cancel* 'id|command'+::
4625     Cancels an `after` event with the given event id or matching
4626     command (script).  Returns the number of milliseconds
4627     remaining until the event would have fired.  Returns the
4628     empty string if no matching event is found.
4630 +*after info* '?id?'+::
4631     If +'id'+ is not given, returns a list of current `after`
4632     events.  If +'id'+ is given, returns a list containing the
4633     associated script and either 'timer' or 'idle' to indicated
4634     the type of the event. An error occurs if +'id'+ does not
4635     match an event.
4637 +*vwait* 'variable'+::
4638     A call to `vwait` enters the eventloop. `vwait` processes
4639     events until the named (global) variable changes or all
4640     event handlers are removed. The variable need not exist
4641     beforehand.  If there are no event handlers defined, `vwait`
4642     returns immediately.
4644 +*update ?idletasks?*+::
4645     A call to `update` enters the eventloop to process expired events, but
4646     no new events. If 'idletasks' is specified, only expired time events are handled,
4647     not file events.
4648     Returns once handlers have been run for all expired events.
4650 Scripts are executed at the global scope. If an error occurs during a handler script,
4651 an attempt is made to call (the user-defined command) `bgerror` with the details of the error.
4652 If the `bgerror` command does not exist, the error message details are printed to stderr instead.
4654 If a file event handler script generates an error, the handler is automatically removed
4655 to prevent infinite errors. (A time event handler is always removed after execution).
4657 +*bgerror* 'msg'+::
4658     Called when an event handler script generates an error. Note that the normal command resolution
4659     rules are used for bgerror. First the name is resolved in the current namespace, then in the
4660     global scope.
4662 socket
4663 ~~~~~~
4664 Various socket types may be created.
4666 +*socket unix* 'path'+::
4667     A unix domain socket client.
4669 +*socket unix.server* 'path'+::
4670     A unix domain socket server.
4672 +*socket ?-ipv6? stream* 'addr:port'+::
4673     A TCP socket client. (See the forms for +'addr'+ below)
4675 +*socket ?-ipv6? stream.server* '?addr:?port'+::
4676     A TCP socket server (+'addr'+ defaults to +0.0.0.0+ for IPv4 or +[::]+ for IPv6).
4678 +*socket ?-ipv6? dgram* ?'addr:port'?+::
4679     A UDP socket client. If the address is not specified,
4680     the client socket will be unbound and 'sendto' must be used
4681     to indicated the destination.
4683 +*socket ?-ipv6? dgram.server* 'addr:port'+::
4684     A UDP socket server.
4686 +*socket pipe*+::
4687     A pipe. Note that unlike all other socket types, this command returns
4688     a list of two channels: {read write}
4690 +*socket pair*+::
4691     A socketpair (see socketpair(2)). Like `socket pipe`, this command returns
4692     a list of two channels: {s1 s2}. These channels are both readable and writable.
4694 This command creates a socket connected (client) or bound (server) to the given
4695 address.
4697 The returned value is channel and may generally be used with the various file I/O
4698 commands (gets, puts, read, etc.), either as object-based syntax or Tcl-compatible syntax.
4700     . set f [socket stream www.google.com:80]
4701     aio.sockstream1
4702     . $f puts -nonewline "GET / HTTP/1.0\r\n\r\n"
4703     . $f gets
4704     HTTP/1.0 302 Found
4705     . $f close
4707 Server sockets, however support only 'accept', which is most useful in conjunction with
4708 the EVENTLOOP API.
4710     set f [socket stream.server 80]
4711     $f readable {
4712         set client [$f accept]
4713         $client gets $buf
4714         ...
4715         $client puts -nonewline "HTTP/1.1 404 Not found\r\n"
4716         $client close
4717     }
4718     vwait done
4720 The address, +'addr'+, can be given in one of the following forms:
4722 1. For IPv4 socket types, an IPv4 address such as 192.168.1.1
4723 2. For IPv6 socket types, an IPv6 address such as [fe80::1234] or [::]
4724 3. A hostname
4726 Note that on many systems, listening on an IPv6 address such as [::] will
4727 also accept requests via IPv4.
4729 Where a hostname is specified, the +'first'+ returned address is used
4730 which matches the socket type is used.
4732 The special type 'pipe' isn't really a socket.
4734     lassign [socket pipe] r w
4736     # Must close $w after exec
4737     exec ps >@$w &
4738     $w close
4740     $r readable ...
4742 syslog
4743 ~~~~~~
4744 +*syslog* '?options? ?priority? message'+
4746 This  command sends message to system syslog facility with given
4747 priority. Valid priorities are:
4749     emerg, alert, crit, err, error, warning, notice, info, debug
4751 If a message is specified, but no priority is specified, then a
4752 priority of info is used.
4754 By default, facility user is used and the value of global tcl variable
4755 argv0 is used as ident string. However, any of the following options
4756 may be specified before priority to control these parameters:
4758 +*-facility* 'value'+::
4759     Use specified facility instead of user. The following
4760     values for facility are recognized:
4762     authpriv, cron, daemon, kernel, lpr, mail, news, syslog, user,
4763     uucp, local0-local7
4765 +*-ident* 'string'+::
4766     Use given string instead of argv0 variable for ident string.
4768 +*-options* 'integer'+::
4769     Set syslog options such as +LOG_CONS+, +LOG_NDELAY+. You should
4770     use numeric values of those from your system syslog.h file,
4771     because I haven't got time to implement yet another hash
4772     table.
4774 pack: pack, unpack
4775 ~~~~~~~~~~~~~~~~~~
4776 The optional 'pack' extension provides commands to encode and decode binary strings.
4778 +*pack* 'varName value' *-intle|-intbe|-floatle|-floatbe|-str* 'bitwidth ?bitoffset?'+::
4779     Packs the binary representation of +'value'+ into the variable
4780     +'varName'+. The value is packed according to the given type
4781     (integer/floating point/string, big-endian/little-endian), width and bit offset.
4782     The variable is created if necessary (like `append`).
4783     The variable is expanded if necessary.
4785 +*unpack* 'binvalue' *-intbe|-intle|-uintbe|-uintle|-floatbe|-floatle|-str* 'bitpos bitwidth'+::
4786     Unpacks bits from +'binvalue'+ at bit position +'bitpos'+ and with +'bitwidth'+.
4787     Interprets the value according to the type (integer/floating point/string, big-endian/little-endian
4788     and signed/unsigned) and returns it. For integer types, +'bitwidth'+
4789     may be up to the size of a Jim Tcl integer (typically 64 bits). For floating point types,
4790     +'bitwidth'+ may be 32 bits (for single precision numbers) or 64 bits (for double precision).
4791     For the string type, both the width and the offset must be on a byte boundary (multiple of 8). Attempting to
4792     access outside the length of the value will return 0 for integer types, 0.0 for floating point types
4793     or the empty string for the string type.
4795 zlib
4796 ~~~~
4797 The optional 'zlib' extension provides a Tcl-compatible subset of the `zlib` command.
4799 +*crc32* 'data' '?startValue?'+::
4800     Returns the CRC32 checksum of a buffer. Optionally, an initial value may be specified; this is most useful
4801     for calculating the checksum of chunked data read from a stream (for instance, a pipe).
4803 +*deflate* 'string' '?level?'+::
4804     Compresses a buffer and outputs a raw, Deflate-compressed stream. Optionally, a compression level (1-9) may
4805     be specified to choose the desired speed vs. compression rate ratio.
4807 +*inflate* 'data' '?bufferSize?'+::
4808     Decompresses a raw, Deflate-compressed stream. When the uncompressed data size is known and specified, memory
4809     allocation is more efficient. Otherwise, decomperssion is chunked and therefore slower.
4811 +*gzip* 'string' '?-level level?'+::
4812     Compresses a buffer and adds a gzip header.
4814 +*gunzip* 'data' '?-buffersize size?'+::
4815     Decompresses a gzip-compressed buffer. Decompression is chunked, with a default, small buffer size of 64K
4816     which guarantees lower memory footprint at the cost of speed. It is recommended to use a bigger size, on
4817     systems without a severe memory constraint.
4819 binary
4820 ~~~~~~
4821 The optional, pure-Tcl 'binary' extension provides the Tcl-compatible `binary scan` and `binary format`
4822 commands based on the low-level `pack` and `unpack` commands.
4824 See the Tcl documentation at: http://www.tcl.tk/man/tcl8.5/TclCmd/binary.htm
4826 Note that 'binary format' with f/r/R specifiers (single-precision float) uses the value of Infinity
4827  in case of overflow.
4829 oo: class, super
4830 ~~~~~~~~~~~~~~~~
4831 The optional, pure-Tcl 'oo' extension provides object-oriented (OO) support for Jim Tcl.
4833 See the online documentation (http://jim.tcl.tk/index.html/doc/www/www/documentation/oo/) for more details.
4835 +*class* 'classname ?baseclasses? classvars'+::
4836     Create a new class, +'classname'+, with the given dictionary
4837     (+'classvars'+) as class variables. These are the initial variables
4838     which all newly created objects of this class are initialised with.
4839     If a list of baseclasses is given, methods and instance variables
4840     are inherited.
4842 +*super* 'method ?args \...?'+::
4843     From within a method, invokes the given method on the base class.
4844     Note that this will only call the last baseclass given.
4846 tree
4847 ~~~~
4848 The optional, pure-Tcl 'tree' extension implements an OO, general purpose tree structure
4849 similar to that provided by tcllib ::struct::tree (http://core.tcl.tk/tcllib/doc/trunk/embedded/www/tcllib/files/modules/struct/struct_tree.html)
4851 A tree is a collection of nodes, where each node (except the root node) has a single parent
4852 and zero or more child nodes (ordered), as well as zero or more attribute/value pairs.
4854 +*tree*+::
4855     Creates and returns a new tree object with a single node named "root".
4856     All operations on the tree are invoked through this object.
4858 +$tree *destroy*+::
4859     Destroy the tree and all it's nodes. (Note that the tree will also
4860     be automatically garbage collected once it goes out of scope).
4862 +$tree *set* 'nodename key value'+::
4863     Set the value for the given attribute key.
4865 +$tree *lappend* 'nodename key value \...'+::
4866     Append to the (list) value(s) for the given attribute key, or set if not yet set.
4868 +$tree *keyexists* 'nodename key'+::
4869     Returns 1 if the given attribute key exists.
4871 +$tree *get* 'nodename key'+::
4872     Returns the value associated with the given attribute key.
4874 +$tree *getall* 'nodename'+::
4875     Returns the entire attribute dictionary associated with the given key.
4877 +$tree *depth* 'nodename'+::
4878     Returns the depth of the given node. The depth of "root" is 0.
4880 +$tree *parent* 'nodename'+::
4881     Returns the node name of the parent node, or "" for the root node.
4883 +$tree *numchildren* 'nodename'+::
4884     Returns the number of child nodes.
4886 +$tree *children* 'nodename'+::
4887     Returns a list of the child nodes.
4889 +$tree *next* 'nodename'+::
4890     Returns the next sibling node, or "" if none.
4892 +$tree *insert* 'nodename ?index?'+::
4893     Add a new child node to the given node. The index is a list index
4894     such as +3+ or +end-2+. The default index is +end+.
4895     Returns the name of the newly added node.
4897 +$tree *walk* 'nodename' *dfs|bfs* {'actionvar nodevar'} 'script'+::
4898     Walks the tree starting from the given node, either breadth first (+bfs+)
4899     depth first (+dfs+).
4900     The value +"enter"+ or +"exit"+ is stored in variable +'actionvar'+.
4901     The name of each node is stored in +'nodevar'+.
4902     The script is evaluated twice for each node, on entry and exit.
4904 +$tree *dump*+::
4905     Dumps the tree contents to stdout
4907 tcl::prefix
4908 ~~~~~~~~~~~
4909 The optional tclprefix extension provides the Tcl8.6-compatible 'tcl::prefix' command
4910 (http://www.tcl.tk/man/tcl8.6/TclCmd/prefix.htm) for matching strings against a table
4911 of possible values (typically commands or options).
4913 +*tcl::prefix all* 'table string'+::
4914     Returns a list of all elements in +'table'+ that begin with the prefix +'string'+.
4916 +*tcl::prefix longest* 'table string'+::
4917     Returns the longest common prefix of all elements in +'table'+ that begin with the prefix +'string'+.
4919 +*tcl::prefix match* '?options? table string'+::
4920     If +'string'+ equals one element in +'table'+ or is a prefix to
4921     exactly one element, the matched element is returned. If not, the
4922     result depends on the +-error+ option.
4924     * +*-exact*+ Accept only exact matches.
4925     * +*-message* 'string'+ Use +'string'+ in the error message at a mismatch. Default is "option".
4926     * +*-error* 'options'+ The options are used when no match is found. If +'options'+ is
4927       empty, no error is generated and an empty string is returned.
4928       Otherwise the options are used as return options when
4929       generating the error message. The default corresponds to
4930       setting +-level 0+.
4932 history
4933 ~~~~~~~
4934 The optional history extension provides script access to the command line editing
4935 and history support available in 'jimsh'. See 'examples/jtclsh.tcl' for an example.
4936 Note: if line editing support is not available, `history getline` acts like `gets` and
4937 the remaining subcommands do nothing.
4939 +*history load* 'filename'+::
4940     Load history from a (text) file. If the file does not exist or is not readable,
4941     it is ignored.
4943 +*history getline* 'prompt ?varname?'+::
4944     Displays the given prompt and allows a line to be entered. Similarly to `gets`,
4945     if +'varname'+ is given, it receives the line and the length of the line is returned,
4946     or -1 on EOF. If +'varname'+ is not given, the line is returned directly.
4948 +*history add* 'line'+::
4949     Adds the given line to the history buffer.
4951 +*history save* 'filename'+::
4952     Saves the current history buffer to the given file.
4954 +*history show*+::
4955     Displays the current history buffer to standard output.
4957 namespace
4958 ~~~~~~~~~
4959 Provides namespace-related functions. See also: http://www.tcl.tk/man/tcl8.6/TclCmd/namespace.htm
4961 +*namespace code* 'script'+::
4962     Captures the current namespace context for later execution of
4963     the script +'script'+. It returns a new script in which script has
4964     been wrapped in a +*namespace inscope*+ command.
4966 +*namespace current*+::
4967     Returns the fully-qualified name for the current namespace.
4969 +*namespace delete* '?namespace ...?'+::
4970     Deletes all commands and variables with the given namespace prefixes.
4972 +*namespace eval* 'namespace arg ?arg...?'+::
4973     Activates a namespace called +'namespace'+ and evaluates some code in that context.
4975 +*namespace origin* 'command'+::
4976     Returns the fully-qualified name of the original command to which the imported command +'command'+ refers.
4978 +*namespace parent* ?namespace?+::
4979     Returns the fully-qualified name of the parent namespace for namespace +'namespace'+, if given, otherwise
4980     for the current namespace.
4982 +*namespace qualifiers* 'string'+::
4983     Returns any leading namespace qualifiers for +'string'+
4985 +*namespace tail* 'string'+::
4986     Returns the simple name at the end of a qualified string.
4988 +*namespace upvar* 'namespace ?arg...?'+::
4989     This command arranges for zero or more local variables in the current procedure to refer to variables in +'namespace'+
4991 +*namespace which* '?-command|-variable? name'+::
4992     Looks up +'name'+ as either a command (the default) or variable and returns its fully-qualified name.
4994 interp
4995 ~~~~~~
4996 The optional 'interp' command allows sub-interpreters to be created where commands may be run
4997 independently (but synchronously) of the main interpreter.
4999 +*interp*+::
5000     Creates and returns a new interpreter object (command).
5001         The created interpeter contains any built-in commands along with static extensions,
5002         but does not include any dynamically loaded commands (package require, load).
5003         These must be reloaded in the child interpreter if required.
5005 +*$interp delete*+::
5006     Deletes the interpeter object.
5008 +*$interp eval* 'script' ...+::
5009         Evaluates a script in the context for the child interpreter, in the same way as 'eval'.
5011 +*$interp alias* 'alias childcmd parentcmd ?arg ...?'+::
5012         Similar to 'alias', but creates a command, +'childcmd'+, in the child interpreter that is an
5013         alias for +'parentcmd'+ in the parent interpreter, with the given, fixed arguments. 
5014         The alias may be deleted in the child with 'rename'.
5016 [[BuiltinVariables]]
5017 BUILT-IN VARIABLES
5018 ------------------
5020 The following global variables are created automatically
5021 by the Tcl library.
5023 +*env*+::
5024     This variable is set by Jim as an array
5025     whose elements are the environment variables for the process.
5026     Reading an element will return the value of the corresponding
5027     environment variable.
5028     This array is initialised at startup from the `env` command.
5029     It may be modified and will affect the environment passed to
5030     commands invoked with `exec`.
5032 +*platform_tcl*+::
5033     This variable is set by Jim as an array containing information
5034     about the platform on which Jim was built. Currently this includes
5035     'os' and 'platform'.
5037 +*auto_path*+::
5038     This variable contains a list of paths to search for packages.
5039     It defaults to a location based on where jim is installed
5040     (e.g. +/usr/local/lib/jim+), but may be changed by +jimsh+
5041     or the embedding application. Note that +jimsh+ will consider
5042     the environment variable +$JIMLIB+ to be a list of colon-separated
5043     list of paths to add to +*auto_path*+.
5045 +*errorCode*+::
5046     This variable holds the value of the -errorcode return
5047     option set by the most recent error that occurred in this
5048     interpreter. This list value represents additional information
5049     about the error in a form that is easy to process with
5050     programs. The first element of the list identifies a general
5051     class of errors, and determines the format of the rest of
5052     the list. The following formats for -errorcode return options
5053     are used by the Tcl core; individual applications may define
5054     additional formats. Currently only `exec` sets this variable.
5055     Otherwise it will be +NONE+.
5057 The following global variables are set by jimsh.
5059 +*tcl_interactive*+::
5060     This variable is set to 1 if jimsh is started in interactive mode
5061     or 0 otherwise.
5063 +*tcl_platform*+::
5064     This variable is set by Jim as an array containing information
5065     about the platform upon which Jim was built. The following is an
5066     example of the contents of this array.
5068     tcl_platform(byteOrder)     = littleEndian
5069     tcl_platform(engine)        = Jim
5070     tcl_platform(os)            = Darwin
5071     tcl_platform(platform)      = unix
5072     tcl_platform(pointerSize)   = 8
5073     tcl_platform(threaded)      = 0
5074     tcl_platform(wordSize)      = 8
5075     tcl_platform(pathSeparator) = :
5077 +*argv0*+::
5078     If jimsh is invoked to run a script, this variable contains the name
5079     of the script.
5081 +*argv*+::
5082     If jimsh is invoked to run a script, this variable contains a list
5083     of any arguments supplied to the script.
5085 +*argc*+::
5086     If jimsh is invoked to run a script, this variable contains the number
5087     of arguments supplied to the script.
5089 +*jim::argv0*+::
5090     The value of argv[0] when jimsh was invoked.
5092 CHANGES IN PREVIOUS RELEASES
5093 ----------------------------
5095 === In v0.70 ===
5097 1. +platform_tcl()+ settings are now automatically determined
5098 2. Add aio `$handle filename`
5099 3. Add `info channels`
5100 4. The 'bio' extension is gone. Now `aio` supports 'copyto'.
5101 5. Add `exists` command
5102 6. Add the pure-Tcl 'oo' extension
5103 7. The `exec` command now only uses vfork(), not fork()
5104 8. Unit test framework is less verbose and more Tcl-compatible
5105 9. Optional UTF-8 support
5106 10. Optional built-in regexp engine for better Tcl compatibility and UTF-8 support
5107 11. Command line editing in interactive mode, e.g. 'jimsh'
5109 === In v0.63 ===
5111 1. `source` now checks that a script is complete (.i.e. not missing a brace)
5112 2. 'info complete' now uses the real parser and so is 100% accurate
5113 3. Better access to live stack frames with 'info frame', `stacktrace` and `stackdump`
5114 4. `tailcall` no longer loses stack trace information
5115 5. Add `alias` and `curry`
5116 6. `lambda`, `alias` and `curry` are implemented via `tailcall` for efficiency
5117 7. `local` allows procedures to be deleted automatically at the end of the current procedure
5118 8. udp sockets are now supported for both clients and servers.
5119 9. vfork-based exec is now working correctly
5120 10. Add 'file tempfile'
5121 11. Add 'socket pipe'
5122 12. Enhance 'try ... on ... finally' to be more Tcl 8.6 compatible
5123 13. It is now possible to `return` from within `try`
5124 14. IPv6 support is now included
5125 15. Add 'string is'
5126 16. Event handlers works better if an error occurs. eof handler has been removed.
5127 17. `exec` now sets $::errorCode, and catch sets opts(-errorcode) for exit status
5128 18. Command pipelines via open "|..." are now supported
5129 19. `pid` can now return pids of a command pipeline
5130 20. Add 'info references'
5131 21. Add support for 'after +'ms'+', 'after idle', 'after info', `update`
5132 22. `exec` now sets environment based on $::env
5133 23. Add 'dict keys'
5134 24. Add support for 'lsort -index'
5136 === In v0.62 ===
5138 1. Add support to `exec` for '>&', '>>&', '|&', '2>@1'
5139 2. Fix `exec` error messages when special token (e.g. '>') is the last token
5140 3. Fix `subst` handling of backslash escapes.
5141 4. Allow abbreviated options for `subst`
5142 5. Add support for `return`, `break`, `continue` in subst
5143 6. Many `expr` bug fixes
5144 7. Add support for functions in `expr` (e.g. int(), abs()), and also 'in', 'ni' list operations
5145 8. The variable name argument to `regsub` is now optional
5146 9. Add support for 'unset -nocomplain'
5147 10. Add support for list commands: `lassign`, `lrepeat`
5148 11. Fully-functional `lsearch` is now implemented
5149 12. Add 'info nameofexecutable' and 'info returncodes'
5150 13. Allow `catch` to determine what return codes are caught
5151 14. Allow `incr` to increment an unset variable by first setting to 0
5152 15. Allow 'args' and optional arguments to the left or required arguments in `proc`
5153 16. Add 'file copy'
5154 17. Add 'try ... finally' command
5157 LICENCE
5158 -------
5160  Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
5161  Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
5162  Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
5163  Copyright 2008 oharboe - Oyvind Harboe - oyvind.harboe@zylin.com
5164  Copyright 2008 Andrew Lunn <andrew@lunn.ch>
5165  Copyright 2008 Duane Ellis <openocd@duaneellis.com>
5166  Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
5167  Copyright 2009 Steve Bennett <steveb@workware.net.au>
5169 [literal]
5170  Redistribution and use in source and binary forms, with or without
5171  modification, are permitted provided that the following conditions
5172  are met:
5173  1. Redistributions of source code must retain the above copyright
5174     notice, this list of conditions and the following disclaimer.
5175  2. Redistributions in binary form must reproduce the above
5176     copyright notice, this list of conditions and the following
5177     disclaimer in the documentation and/or other materials
5178     provided with the distribution.
5180  THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
5181  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
5182  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
5183  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
5184  JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
5185  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
5186  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
5187  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
5188  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
5189  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
5190  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
5191  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5193  The views and conclusions contained in the software and documentation
5194  are those of the authors and should not be interpreted as representing
5195  official policies, either expressed or implied, of the Jim Tcl Project.