docs: Update documentation for recent changes
[jimtcl.git] / jim_tcl.txt
blob7a736c1cb8108f143ae74cb787dfad97471191a0
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
18   jimsh --help
21 .Quick Index
22 * <<CommandIndex,Command Reference>>
23 * <<OperatorPrecedence,Operator Precedence>>
24 * <<BuiltinVariables, Builtin Variables>>
25 * <<BackslashSequences, Backslash Sequences>>
27 INTRODUCTION
28 ------------
29 Jim Tcl is a small footprint reimplementation of the Tcl scripting language.
30 The core language engine is compatible with Tcl 8.5+, while implementing
31 a significant subset of the Tcl 8.6 command set, plus additional features
32 available only in Jim Tcl.
34 Some notable differences with Tcl 8.5/8.6 are:
36 1. Object-based I/O (aio), but with a Tcl-compatibility layer
37 2. I/O: Support for sockets and pipes including udp, unix domain sockets and IPv6
38 3. Integers are 64bit
39 4. Support for references (`ref`/`getref`/`setref`) and garbage collection
40 5. Builtin dictionary type (`dict`) with some limitations compared to Tcl 8.6
41 6. `env` command to access environment variables
42 7. Operating system features: `os.fork`, `os.wait`, `os.uptime`, `signal`, `alarm`, `sleep`
43 8. Much better error reporting. `info stacktrace` as a replacement for '$errorInfo', '$errorCode'
44 9. Support for "static" variables in procedures
45 10. Threads and coroutines are not supported
46 11. Command and variable traces are not supported
47 12. Built-in command line editing
48 13. Expression shorthand syntax: +$(...)+
49 14. Modular build allows many features to be omitted or built as dynamic, loadable modules
50 15. Highly suitable for use in an embedded environment
51 16. Support for UDP, IPv6, Unix-Domain sockets in addition to TCP sockets
53 RECENT CHANGES
54 --------------
55 Changes between 0.77 and 0.78
56 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
57 1. Add serial/tty support with `aio tty`
58 2. Add support for 'jimsh -'
59 3. Add hidden '-commands' option to many commands
60 4. Add scriptable autocompletion support in interactive mode with `tcl::autocomplete`
61 5. Add `aio sockopt`
62 6. Add scriptable autocompletion support with `history completion`
64 Changes between 0.76 and 0.77
65 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
66 1. Add support for `aio sync`
67 2. Add SSL and TLS support in aio
68 3. Added `zlib`
69 4. Added support for boolean constants in `expr`
70 5. `string is` now supports 'boolean' class
71 6. Add support for `aio lock` and `aio unlock`
72 7. Add new `interp` command
74 Changes between 0.75 and 0.76
75 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
76 1. `glob` now supports the +-tails+ option
77 2. Add support for `string cat`
78 3. Allow `info source` to add source info
80 Changes between 0.74 and 0.75
81 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
82 1. `binary`, `pack` and `unpack` now support floating point
83 2. `file copy` +-force+ handles source and target as the same file
84 3. `format` now supports +%b+ for binary conversion
85 4. `lsort` now supports +-unique+ and +-real+
86 5. Add support for half-close with `aio close` +?r|w?+
87 6. Add `socket pair` for a bidirectional pipe
88 7. Add '--random-hash' to randomise hash tables for greater security
89 8. `dict` now supports 'for', 'values', 'incr', 'append', 'lappend', 'update', 'info' and 'replace'
90 9. `file stat` no longer requires the variable name
91 10. Add support for `file link`
93 Changes between 0.73 and 0.74
94 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
95 1. Numbers with leading zeros are treated as decimal, not octal
96 2. Add `aio isatty`
97 3. Add LFS (64 bit) support for `aio seek`, `aio tell`, `aio copyto`, `file copy`
98 4. `string compare` and `string equal` now support '-length'
99 5. `glob` now supports '-directory'
101 Changes between 0.72 and 0.73
102 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
103 1. Built-in regexp now support non-capturing parentheses: (?:...)
104 2. Add `string replace`
105 3. Add `string totitle`
106 4. Add `info statics`
107 5. Add +build-jim-ext+ for easy separate building of loadable modules (extensions)
108 6. `local` now works with any command, not just procs
109 7. Add `info alias` to access the target of an alias
110 8. UTF-8 encoding past the basic multilingual plane (BMP) is supported
111 9. Add `tcl::prefix`
112 10. Add `history`
113 11. Most extensions are now enabled by default
114 12. Add support for namespaces and the `namespace` command
115 13. Add `apply`
117 Changes between 0.71 and 0.72
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119 1. procs now allow 'args' and optional parameters in any position
120 2. Add Tcl-compatible expr functions, `rand()`, `srand()` and `pow()`
121 3. Add support for the '-force' option to `file delete`
122 4. Better diagnostics when `source` fails to load a script with a missing quote or bracket
123 5. New +tcl_platform(pathSeparator)+
124 6. Add support settings the modification time with `file mtime`
125 7. `exec` is now fully supported on win32 (mingw32)
126 8. `file join`, `pwd`, `glob` etc. now work for mingw32
127 9. Line editing is now supported for the win32 console (mingw32)
128 10. Add `aio listen` command
130 Changes between 0.70 and 0.71
131 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
132 1. Allow 'args' to be renamed in procs
133 2. Add +$(...)+ shorthand syntax for expressions
134 3. Add automatic reference variables in procs with +&var+ syntax
135 4. Support +jimsh --version+
136 5. Additional variables in +tcl_platform()+
137 6. `local` procs now push existing commands and `upcall` can call them
138 7. Add `loop` command (TclX compatible)
139 8. Add `aio buffering` command
140 9. `info complete` can now return the missing character
141 10. `binary format` and `binary scan` are now (optionally) supported
142 11. Add `string byterange`
143 12. Built-in regexp now support non-greedy repetition (*?, +?, ??)
145 TCL INTRODUCTION
146 -----------------
147 Tcl stands for 'tool command language' and is pronounced
148 'http://www.oxforddictionaries.com/definition/american_english/tickle[tickle]'.
149 It is actually two things: a language and a library.
151 First, Tcl is a simple textual language, intended primarily for
152 issuing commands to interactive programs such as text editors,
153 debuggers, illustrators, and shells.  It has a simple syntax and is also
154 programmable, so Tcl users can write command procedures to provide more
155 powerful commands than those in the built-in set.
157 Second, Tcl is a library package that can be embedded in application
158 programs.  The Tcl library consists of a parser for the Tcl language,
159 routines to implement the Tcl built-in commands, and procedures that
160 allow each application to extend Tcl with additional commands specific
161 to that application.  The application program generates Tcl commands and
162 passes them to the Tcl parser for execution.  Commands may be generated
163 by reading characters from an input source, or by associating command
164 strings with elements of the application's user interface, such as menu
165 entries, buttons, or keystrokes.
167 When the Tcl library receives commands it parses them into component
168 fields and executes built-in commands directly.  For commands implemented
169 by the application, Tcl calls back to the application to execute the
170 commands.  In many cases commands will invoke recursive invocations of the
171 Tcl interpreter by passing in additional strings to execute (procedures,
172 looping commands, and conditional commands all work in this way).
174 An application program gains three advantages by using Tcl for its command
175 language.  First, Tcl provides a standard syntax:  once users know Tcl,
176 they will be able to issue commands easily to any Tcl-based application.
177 Second, Tcl provides programmability.  All a Tcl application needs
178 to do is to implement a few application-specific low-level commands.
179 Tcl provides many utility commands plus a general programming interface
180 for building up complex command procedures.  By using Tcl, applications
181 need not re-implement these features.
183 Third, Tcl can be used as a common language for communicating between
184 applications.  Inter-application communication is not built into the
185 Tcl core described here, but various add-on libraries, such as the Tk
186 toolkit, allow applications to issue commands to each other.  This makes
187 it possible for applications to work together in much more powerful ways
188 than was previously possible.
190 Fourth, Jim Tcl includes a command processor, +jimsh+, which can be
191 used to run standalone Tcl scripts, or to run Tcl commands interactively.
193 This manual page focuses primarily on the Tcl language.  It describes
194 the language syntax and the built-in commands that will be available
195 in any application based on Tcl.  The individual library procedures are
196 described in more detail in separate manual pages, one per procedure.
198 JIMSH COMMAND INTERPRETER
199 -------------------------
200 A simple, but powerful command processor, +jimsh+, is part of Jim Tcl.
201 It may be invoked in interactive mode as:
203   jimsh
205 or to process the Tcl script in a file with:
207   jimsh filename
209 or to process the Tcl script from standard input:
211   jimsh -
213 It may also be invoked to execute an immediate script with:
215   jimsh -e "script"
217 Interactive Mode
218 ~~~~~~~~~~~~~~~~
219 Interactive mode reads Tcl commands from standard input, evaluates
220 those commands and prints the results.
222   $ jimsh
223   Welcome to Jim version 0.73, Copyright (c) 2005-8 Salvatore Sanfilippo
224   . info version
225   0.73
226   . lsort [info commands p*]
227   package parray pid popen proc puts pwd
228   . foreach i {a b c} {
229   {> puts $i
230   {> }
231   a
232   b
233   c
234   . bad
235   invalid command name "bad"
236   [error] . exit
237   $
239 If +jimsh+ is configured with line editing (it is by default) and a VT-100-compatible
240 terminal is detected, Emacs-style line editing commands are available, including:
241 arrow keys, +\^W+ to erase a word, +\^U+ to erase the line, +^R+ for reverse incremental search
242 in history. Additionally, the +h+ command may be used to display the command history.
244 Command line history is automatically saved and loaded from +~/.jim_history+
246 In interactive mode, +jimsh+ automatically runs the script +~/.jimrc+ at startup
247 if it exists.
249 INTERPRETERS
250 ------------
251 The central data structure in Tcl is an interpreter (C type 'Jim_Interp').
252 An interpreter consists of a set of command bindings, a set of variable
253 values, and a few other miscellaneous pieces of state.  Each Tcl command
254 is interpreted in the context of a particular interpreter.
256 Some Tcl-based applications will maintain multiple interpreters
257 simultaneously, each associated with a different widget or portion of
258 the application.  Interpreters are relatively lightweight structures.
259 They can be created and deleted quickly, so application programmers should
260 feel free to use multiple interpreters if that simplifies the application.
262 DATA TYPES
263 ----------
264 Tcl supports only one type of data:  strings.  All commands, all arguments
265 to commands, all command results, and all variable values are strings.
267 Where commands require numeric arguments or return numeric results,
268 the arguments and results are passed as strings.  Many commands expect
269 their string arguments to have certain formats, but this interpretation
270 is up to the individual commands.  For example, arguments often contain
271 Tcl command strings, which may get executed as part of the commands.
272 The easiest way to understand the Tcl interpreter is to remember that
273 everything is just an operation on a string.  In many cases Tcl constructs
274 will look similar to more structured constructs from other languages.
275 However, the Tcl constructs are not structured at all; they are just
276 strings of characters, and this gives them a different behaviour than
277 the structures they may look like.
279 Although the exact interpretation of a Tcl string depends on who is doing
280 the interpretation, there are three common forms that strings take:
281 commands, expressions, and lists.  The major sections below discuss
282 these three forms in more detail.
284 BASIC COMMAND SYNTAX
285 --------------------
286 The Tcl language has syntactic similarities to both the Unix shells
287 and Lisp.  However, the interpretation of commands is different
288 in Tcl than in either of those other two systems.
289 A Tcl command string consists of one or more commands separated
290 by newline characters or semi-colons.
291 Each command consists of a collection of fields separated by
292 white space (spaces or tabs).
293 The first field must be the name of a command, and the
294 additional fields, if any, are arguments that will be passed to
295 that command.  For example, the command:
297     set a 22
299 has three fields:  the first, `set`, is the name of a Tcl command, and
300 the last two, 'a' and '22', will be passed as arguments to
301 the `set` command.  The command name may refer either to a built-in
302 Tcl command, an application-specific command bound in with the library
303 procedure 'Jim_CreateCommand', or a command procedure defined with the
304 `proc` built-in command.
306 Arguments are passed literally as text strings.  Individual commands may
307 interpret those strings in any fashion they wish.  The `set` command,
308 for example, will treat its first argument as the name of a variable
309 and its second argument as a string value to assign to that variable.
310 For other commands arguments may be interpreted as integers, lists,
311 file names, or Tcl commands.
313 Command names should normally be typed completely (e.g. no abbreviations).
314 However, if the Tcl interpreter cannot locate a command it invokes a
315 special command named `unknown` which attempts to find or create the
316 command.
318 For example, at many sites `unknown` will search through library
319 directories for the desired command and create it as a Tcl procedure if
320 it is found.  The `unknown` command often provides automatic completion
321 of abbreviated commands, but usually only for commands that were typed
322 interactively.
324 It's probably a bad idea to use abbreviations in command scripts and
325 other forms that will be re-used over time:  changes to the command set
326 may cause abbreviations to become ambiguous, resulting in scripts that
327 no longer work.
329 COMMENTS
330 --------
331 If the first non-blank character in a command is +\#+, then everything
332 from the +#+ up through the next newline character is treated as
333 a comment and ignored.  When comments are embedded inside nested
334 commands (e.g. fields enclosed in braces) they must have properly-matched
335 braces (this is necessary because when Tcl parses the top-level command
336 it doesn't yet know that the nested field will be used as a command so
337 it cannot process the nested comment character as a comment).
339 GROUPING ARGUMENTS WITH DOUBLE-QUOTES
340 -------------------------------------
341 Normally each argument field ends at the next white space, but
342 double-quotes may be used to create arguments with embedded space.
344 If an argument field begins with a double-quote, then the argument isn't
345 terminated by white space (including newlines) or a semi-colon (see below
346 for information on semi-colons); instead it ends at the next double-quote
347 character.  The double-quotes are not included in the resulting argument.
348 For example, the command
350     set a "This is a single argument"
352 will pass two arguments to `set`:  'a' and 'This is a single argument'.
354 Within double-quotes, command substitutions, variable substitutions,
355 and backslash substitutions still occur, as described below.  If the
356 first character of a command field is not a quote, then quotes receive
357 no special interpretation in the parsing of that field.
359 GROUPING ARGUMENTS WITH BRACES
360 ------------------------------
361 Curly braces may also be used for grouping arguments.  They are similar
362 to quotes except for two differences.  First, they nest; this makes them
363 easier to use for complicated arguments like nested Tcl command strings.
364 Second, the substitutions described below for commands, variables, and
365 backslashes do *not* occur in arguments enclosed in braces, so braces
366 can be used to prevent substitutions where they are undesirable.
368 If an argument field begins with a left brace, then the argument ends
369 at the matching right brace.  Tcl will strip off the outermost layer
370 of braces and pass the information between the braces to the command
371 without any further modification.  For example, in the command
373     set a {xyz a {b c d}}
375 the `set` command will receive two arguments: 'a'
376 and 'xyz a {b c d}'.
378 When braces or quotes are in effect, the matching brace or quote need
379 not be on the same line as the starting quote or brace; in this case
380 the newline will be included in the argument field along with any other
381 characters up to the matching brace or quote.  For example, the `eval`
382 command takes one argument, which is a command string; `eval` invokes
383 the Tcl interpreter to execute the command string.  The command
385     eval {
386       set a 22
387       set b 33
388     }
390 will assign the value '22' to 'a' and '33' to 'b'.
392 If the first character of a command field is not a left
393 brace, then neither left nor right
394 braces in the field will be treated specially (except as part of
395 variable substitution; see below).
397 COMMAND SUBSTITUTION WITH BRACKETS
398 ----------------------------------
399 If an open bracket occurs in a field of a command, then command
400 substitution occurs (except for fields enclosed in braces).  All of the
401 text up to the matching close bracket is treated as a Tcl command and
402 executed immediately.  Then the result of that command is substituted
403 for the bracketed text.  For example, consider the command
405     set a [set b]
407 When the `set` command has only a single argument, it is the name of a
408 variable and `set` returns the contents of that variable.  In this case,
409 if variable 'b' has the value 'foo', then the command above is equivalent
410 to the command
412     set a foo
414 Brackets can be used in more complex ways.  For example, if the variable
415 'b' has the value 'foo' and the variable 'c' has the value 'gorp',
416 then the command
418     set a xyz[set b].[set c]
420 is equivalent to the command
422     set a xyzfoo.gorp
425 A bracketed command may contain multiple commands separated by newlines
426 or semi-colons in the usual fashion.  In this case the value of the last
427 command is used for substitution.  For example, the command
429     set a x[set b 22
430     expr $b+2]x
432 is equivalent to the command
434     set a x24x
437 If a field is enclosed in braces then the brackets and the characters
438 between them are not interpreted specially; they are passed through to
439 the argument verbatim.
441 VARIABLE SUBSTITUTION WITH $
442 ----------------------------
443 The dollar sign (+$+) may be used as a special shorthand form for
444 substituting variable values.  If +$+ appears in an argument that isn't
445 enclosed in braces then variable substitution will occur.  The characters
446 after the +$+, up to the first character that isn't a number, letter,
447 or underscore, are taken as a variable name and the string value of that
448 variable is substituted for the name.
450 For example, if variable 'foo' has the value 'test', then the command
452     set a $foo.c
454 is equivalent to the command
456     set a test.c
458 There are two special forms for variable substitution.  If the next
459 character after the name of the variable is an open parenthesis, then
460 the variable is assumed to be an array name, and all of the characters
461 between the open parenthesis and the next close parenthesis are taken as
462 an index into the array.  Command substitutions and variable substitutions
463 are performed on the information between the parentheses before it is
464 used as an index.
466 For example, if the variable 'x' is an array with one element named
467 'first' and value '87' and another element named '14' and value 'more',
468 then the command
470     set a xyz$x(first)zyx
472 is equivalent to the command
474     set a xyz87zyx
476 If the variable 'index' has the value '14', then the command
478     set a xyz$x($index)zyx
480 is equivalent to the command
482     set a xyzmorezyx
484 For more information on arrays, see VARIABLES AND ARRAYS below.
486 The second special form for variables occurs when the dollar sign is
487 followed by an open curly brace.  In this case the variable name consists
488 of all the characters up to the next curly brace.
490 Array references are not possible in this form:  the name between braces
491 is assumed to refer to a scalar variable.  For example, if variable
492 'foo' has the value 'test', then the command
494     set a abc${foo}bar
496 is equivalent to the command
498     set a abctestbar
501 Variable substitution does not occur in arguments that are enclosed in
502 braces:  the dollar sign and variable name are passed through to the
503 argument verbatim.
505 The dollar sign abbreviation is simply a shorthand form.  +$a+ is
506 completely equivalent to +[set a]+; it is provided as a convenience
507 to reduce typing.
509 SEPARATING COMMANDS WITH SEMI-COLONS
510 ------------------------------------
511 Normally, each command occupies one line (the command is terminated by a
512 newline character).  However, semi-colon (+;+) is treated as a command
513 separator character; multiple commands may be placed on one line by
514 separating them with a semi-colon.  Semi-colons are not treated as
515 command separators if they appear within curly braces or double-quotes.
517 BACKSLASH SUBSTITUTION
518 ----------------------
519 Backslashes may be used to insert non-printing characters into command
520 fields and also to insert special characters like braces and brackets
521 into fields without them being interpreted specially as described above.
523 The backslash sequences understood by the Tcl interpreter are
524 listed below.  In each case, the backslash
525 sequence is replaced by the given character:
526 [[BackslashSequences]]
527 +{backslash}b+::
528     Backspace (0x8)
530 +{backslash}f+::
531     Form feed (0xc)
533 +{backslash}n+::
534     Newline (0xa)
536 +{backslash}r+::
537     Carriage-return (0xd).
539 +{backslash}t+::
540     Tab (0x9).
542 +{backslash}v+::
543     Vertical tab (0xb).
545 +{backslash}{+::
546     Left brace ({).
548 +{backslash}}+::
549     Right brace (}).
551 +{backslash}[+::
552     Open bracket ([).
554 +{backslash}]+::
555     Close bracket (]).
557 +{backslash}$+::
558     Dollar sign ($).
560 +{backslash}<space>+::
561     Space ( ): doesn't terminate argument.
563 +{backslash};+::
564     Semi-colon: doesn't terminate command.
566 +{backslash}"+::
567     Double-quote.
569 +{backslash}<newline>+::
570     Nothing:  this joins two lines together
571     into a single line.  This backslash feature is unique in that
572     it will be applied even when the sequence occurs within braces.
574 +{backslash}{backslash}+::
575     Backslash ('{backslash}').
577 +{backslash}ddd+::
578     The digits +'ddd'+ (one, two, or three of them) give the octal value of
579     the character.  Note that Jim supports null characters in strings.
581 +{backslash}unnnn+::
582 +{backslash}u\{nnn\}+::
583 +{backslash}Unnnnnnnn+::
584     The UTF-8 encoding of the unicode codepoint represented by the hex digits, +'nnnn'+, is inserted.
585     The 'u' form allows for one to four hex digits.
586     The 'U' form allows for one to eight hex digits.
587     The 'u\{nnn\}' form allows for one to eight hex digits, but makes it easier to insert
588     characters UTF-8 characters which are followed by a hex digit.
590 For example, in the command
592     set a \{x\[\ yz\141
594 the second argument to `set` will be +{x[ yza+.
596 If a backslash is followed by something other than one of the options
597 described above, then the backslash is transmitted to the argument
598 field without any special processing, and the Tcl scanner continues
599 normal processing with the next character.  For example, in the
600 command
602     set \*a \\\{foo
604 The first argument to `set` will be +{backslash}*a+ and the second
605 argument will be +{backslash}{foo+.
607 If an argument is enclosed in braces, then backslash sequences inside
608 the argument are parsed but no substitution occurs (except for
609 backslash-newline):  the backslash
610 sequence is passed through to the argument as is, without making
611 any special interpretation of the characters in the backslash sequence.
612 In particular, backslashed braces are not counted in locating the
613 matching right brace that terminates the argument.
614 For example, in the
615 command
617     set a {\{abc}
619 the second argument to `set` will be +{backslash}{abc+.
621 This backslash mechanism is not sufficient to generate absolutely
622 any argument structure; it only covers the
623 most common cases.  To produce particularly complicated arguments
624 it is probably easiest to use the `format` command along with
625 command substitution.
627 STRING AND LIST INDEX SPECIFICATIONS
628 ------------------------------------
630 Many string and list commands take one or more 'index' parameters which
631 specify a position in the string relative to the start or end of the string/list.
633 The index may be one of the following forms:
635 +integer+::
636     A simple integer, where '0' refers to the first element of the string
637     or list.
639 +integer+integer+ or::
640 +integer-integer+::
641     The sum or difference of the two integers. e.g. +2+3+ refers to the 5th element.
642     This is useful when used with (e.g.) +$i+1+ rather than the more verbose
643     +[expr {$i+1\}]+
645 +end+::
646     The last element of the string or list.
648 +end-integer+::
649     The 'nth-from-last' element of the string or list.
651 COMMAND SUMMARY
652 ---------------
653 1. A command is just a string.
654 2. Within a string commands are separated by newlines or semi-colons
655    (unless the newline or semi-colon is within braces or brackets
656    or is backslashed).
657 3. A command consists of fields.  The first field is the name of the command.
658    The other fields are strings that are passed to that command as arguments.
659 4. Fields are normally separated by white space.
660 5. Double-quotes allow white space and semi-colons to appear within
661    a single argument.
662    Command substitution, variable substitution, and backslash substitution
663    still occur inside quotes.
664 6. Braces defer interpretation of special characters.
665    If a field begins with a left brace, then it consists of everything
666    between the left brace and the matching right brace. The
667    braces themselves are not included in the argument.
668    No further processing is done on the information between the braces
669    except that backslash-newline sequences are eliminated.
670 7. If a field doesn't begin with a brace then backslash,
671    variable, and command substitution are done on the field.  Only a
672    single level of processing is done:  the results of one substitution
673    are not scanned again for further substitutions or any other
674    special treatment.  Substitution can
675    occur on any field of a command, including the command name
676    as well as the arguments.
677 8. If the first non-blank character of a command is a +\#+, everything
678    from the +#+ up through the next newline is treated as a comment
679    and ignored.
681 EXPRESSIONS
682 -----------
683 The second major interpretation applied to strings in Tcl is
684 as expressions.  Several commands, such as `expr`, `for`,
685 and `if`, treat one or more of their arguments as expressions
686 and call the Tcl expression processors ('Jim_ExprLong',
687 'Jim_ExprBoolean', etc.) to evaluate them.
689 The operators permitted in Tcl expressions are a subset of
690 the operators permitted in C expressions, and they have the
691 same meaning and precedence as the corresponding C operators.
692 Expressions almost always yield numeric results
693 (integer or floating-point values).
694 For example, the expression
696     8.2 + 6
698 evaluates to 14.2.
700 Tcl expressions differ from C expressions in the way that
701 operands are specified, and in that Tcl expressions support
702 non-numeric operands and string comparisons.
704 A Tcl expression consists of a combination of operands, operators,
705 and parentheses.
707 White space may be used between the operands and operators and
708 parentheses; it is ignored by the expression processor.
709 Where possible, operands are interpreted as integer values.
711 Integer values may be specified in decimal (the normal case) or in
712 hexadecimal (if the first two characters of the operand are '0x').
713 Note that Jim Tcl does *not* treat numbers with leading zeros as octal.
715 If an operand does not have one of the integer formats given
716 above, then it is treated as a floating-point number if that is
717 possible.  Floating-point numbers may be specified in any of the
718 ways accepted by an ANSI-compliant C compiler (except that the
719 'f', 'F', 'l', and 'L' suffixes will not be permitted in
720 most installations).  For example, all of the
721 following are valid floating-point numbers:  2.1, 3., 6e4, 7.91e+16.
723 If no numeric interpretation is possible, then an operand is left
724 as a string (and only a limited set of operators may be applied to
725 it).
727 String constants representing boolean constants
728 (+'0'+, +'1'+, +'false'+, +'off'+, +'no'+, +'true'+, +'on'+, +'yes'+)
729 are also recognized and can be used in logical operations.
731 1. Operands may be specified in any of the following ways:
733 2. As a numeric value, either integer or floating-point.
735 3. As one of valid boolean constants
737 4. As a Tcl variable, using standard '$' notation.
738 The variable's value will be used as the operand.
740 5. As a string enclosed in double-quotes.
741 The expression parser will perform backslash, variable, and
742 command substitutions on the information between the quotes,
743 and use the resulting value as the operand
745 6. As a string enclosed in braces.
746 The characters between the open brace and matching close brace
747 will be used as the operand without any substitutions.
749 7. As a Tcl command enclosed in brackets.
750 The command will be executed and its result will be used as
751 the operand.
753 Where substitutions occur above (e.g. inside quoted strings), they
754 are performed by the expression processor.
755 However, an additional layer of substitution may already have
756 been performed by the command parser before the expression
757 processor was called.
759 As discussed below, it is usually best to enclose expressions
760 in braces to prevent the command parser from performing substitutions
761 on the contents.
763 For some examples of simple expressions, suppose the variable 'a' has
764 the value 3 and the variable 'b' has the value 6.  Then the expression
765 on the left side of each of the lines below will evaluate to the value
766 on the right side of the line:
768     $a + 3.1                6.1
769     2 + "$a.$b"             5.6
770     4*[llength "6 2"]       8
771     {word one} < "word $a"  0
773 The valid operators are listed below, grouped in decreasing order
774 of precedence:
775 [[OperatorPrecedence]]
776 +int() double() round() abs(), rand(), srand()+::
777     Unary functions (except rand() which takes no arguments)
778     * +'int()'+ converts the numeric argument to an integer by truncating down.
779     * +'double()'+ converts the numeric argument to floating point.
780     * +'round()'+ converts the numeric argument to the closest integer value.
781     * +'abs()'+ takes the absolute value of the numeric argument.
782     * +'rand()'+ returns a pseudo-random floating-point value in the range (0,1).
783     * +'srand()'+ takes an integer argument to (re)seed the random number generator. Returns the first random number from that seed.
785 +sin() cos() tan() asin() acos() atan() sinh() cosh() tanh() ceil() floor() exp() log() log10() sqrt()+::
786     Unary math functions.
787     If Jim is compiled with math support, these functions are available.
789 +- + ~ !+::
790     Unary minus, unary plus, bit-wise NOT, logical NOT.  None of these operands
791     may be applied to string operands, and bit-wise NOT may be
792     applied only to integers.
794 +** pow(x,y)+::
795     Power. e.g. 'x^y^'. If Jim is compiled with math support, supports doubles and
796     integers. Otherwise supports integers only. (Note that the math-function form
797     has the same highest precedence)
799 +* / %+::
800     Multiply, divide, remainder.  None of these operands may be
801     applied to string operands, and remainder may be applied only
802     to integers.
804 ++ -+::
805     Add and subtract.  Valid for any numeric operands.
807 +<<  >> <<< >>>+::
808     Left and right shift, left and right rotate.  Valid for integer operands only.
810 +<  >  \<=  >=+::
811     Boolean less, greater, less than or equal, and greater than or equal.
812     Each operator produces 1 if the condition is true, 0 otherwise.
813     These operators may be applied to strings as well as numeric operands,
814     in which case string comparison is used.
816 +==  !=+::
817     Boolean equal and not equal.  Each operator produces a zero/one result.
818     Valid for all operand types. *Note* that values will be converted to integers
819     if possible, then floating point types, and finally strings will be compared.
820     It is recommended that 'eq' and 'ne' should be used for string comparison.
822 +eq ne+::
823     String equal and not equal.  Uses the string value directly without
824     attempting to convert to a number first.
826 +in ni+::
827     String in list and not in list. For 'in', result is 1 if the left operand (as a string)
828     is contained in the right operand (as a list), or 0 otherwise. The result for
829     +{$a ni $list}+ is equivalent to +{!($a in $list)}+.
831 +&+::
832     Bit-wise AND.  Valid for integer operands only.
834 +|+::
835     Bit-wise OR.  Valid for integer operands only.
837 +^+::
838     Bit-wise exclusive OR.  Valid for integer operands only.
840 +&&+::
841     Logical AND.  Produces a 1 result if both operands are non-zero, 0 otherwise.
842     Valid for numeric operands only (integers or floating-point).
844 +||+::
845     Logical OR.  Produces a 0 result if both operands are zero, 1 otherwise.
846     Valid for numeric operands only (integers or floating-point).
848 +x ? y : z+::
849     If-then-else, as in C.  If +'x'+
850     evaluates to non-zero, then the result is the value of +'y'+.
851     Otherwise the result is the value of +'z'+.
852     The +'x'+ operand must have a numeric value, while +'y'+ and +'z'+ can
853     be of any type.
855 See the C manual for more details on the results
856 produced by each operator.
857 All of the binary operators group left-to-right within the same
858 precedence level.  For example, the expression
860     4*2 < 7
862 evaluates to 0.
864 The +&&+, +||+, and +?:+ operators have 'lazy evaluation', just as
865 in C, which means that operands are not evaluated if they are not
866 needed to determine the outcome.  For example, in
868     $v ? [a] : [b]
870 only one of +[a]+ or +[b]+ will actually be evaluated,
871 depending on the value of +$v+.
873 All internal computations involving integers are done with the C
874 type 'long long' if available, or 'long' otherwise, and all internal
875 computations involving floating-point are done with the C type
876 'double'.
878 When converting a string to floating-point, exponent overflow is
879 detected and results in a Tcl error.
880 For conversion to integer from string, detection of overflow depends
881 on the behaviour of some routines in the local C library, so it should
882 be regarded as unreliable.
883 In any case, overflow and underflow are generally not detected
884 reliably for intermediate results.
886 Conversion among internal representations for integer, floating-point,
887 string operands is done automatically as needed.
888 For arithmetic computations, integers are used until some
889 floating-point number is introduced, after which floating-point is used.
890 For example,
892     5 / 4
894 yields the result 1, while
896     5 / 4.0
897     5 / ( [string length "abcd"] + 0.0 )
899 both yield the result 1.25.
901 String values may be used as operands of the comparison operators,
902 although the expression evaluator tries to do comparisons as integer
903 or floating-point when it can.
904 If one of the operands of a comparison is a string and the other
905 has a numeric value, the numeric operand is converted back to
906 a string using the C 'sprintf' format specifier
907 '%d' for integers and '%g' for floating-point values.
908 For example, the expressions
910     "0x03" > "2"
911     "0y" < "0x12"
913 both evaluate to 1.  The first comparison is done using integer
914 comparison, and the second is done using string comparison after
915 the second operand is converted to the string '18'.
917 In general it is safest to enclose an expression in braces when
918 entering it in a command:  otherwise, if the expression contains
919 any white space then the Tcl interpreter will split it
920 among several arguments.  For example, the command
922     expr $a + $b
924 results in three arguments being passed to `expr`:  +$a+,
925 \+, and +$b+.  In addition, if the expression isn't in braces
926 then the Tcl interpreter will perform variable and command substitution
927 immediately (it will happen in the command parser rather than in
928 the expression parser).  In many cases the expression is being
929 passed to a command that will evaluate the expression later (or
930 even many times if, for example, the expression is to be used to
931 decide when to exit a loop).  Usually the desired goal is to re-do
932 the variable or command substitutions each time the expression is
933 evaluated, rather than once and for all at the beginning.  For example,
934 the command
936     for {set i 1} $i<=10 {incr i} {...}        ** WRONG **
938 is probably intended to iterate over all values of +i+ from 1 to 10.
939 After each iteration of the body of the loop, `for` will pass
940 its second argument to the expression evaluator to see whether or not
941 to continue processing.  Unfortunately, in this case the value of +i+
942 in the second argument will be substituted once and for all when the
943 `for` command is parsed.  If +i+ was 0 before the `for`
944 command was invoked then the second argument of `for` will be +0\<=10+
945 which will always evaluate to 1, even though +i+ eventually
946 becomes greater than 10.  In the above case the loop will never
947 terminate.  Instead, the expression should be placed in braces:
949     for {set i 1} {$i<=10} {incr i} {...}      ** RIGHT **
951 This causes the substitution of 'i'
952 to be delayed; it will be re-done each time the expression is
953 evaluated, which is the desired result.
955 LISTS
956 -----
957 The third major way that strings are interpreted in Tcl is as lists.
958 A list is just a string with a list-like structure
959 consisting of fields separated by white space.  For example, the
960 string
962     Al Sue Anne John
964 is a list with four elements or fields.
965 Lists have the same basic structure as command strings, except
966 that a newline character in a list is treated as a field separator
967 just like space or tab.  Conventions for braces and quotes
968 and backslashes are the same for lists as for commands.  For example,
969 the string
971     a b\ c {d e {f g h}}
973 is a list with three elements:  +a+, +b c+, and +d e {f g h}+.
975 Whenever an element is extracted from a list, the same rules about
976 braces and quotes and backslashes are applied as for commands.  Thus in
977 the example above when the third element is extracted from the list,
978 the result is
980     d e {f g h}
982 (when the field was extracted, all that happened was to strip off
983 the outermost layer of braces).  Command substitution and
984 variable substitution are never
985 made on a list (at least, not by the list-processing commands; the
986 list can always be passed to the Tcl interpreter for evaluation).
988 The Tcl commands `concat`, `foreach`, `lappend`, `lindex`, `linsert`,
989 `list`, `llength`, `lrange`, `lreplace`, `lsearch`, and `lsort` allow
990 you to build lists, extract elements from them, search them, and perform
991 other list-related functions.
993 Advanced list commands include `lrepeat`, `lreverse`, `lmap`, `lassign`, `lset`.
995 LIST EXPANSION
996 --------------
998 A new addition to Tcl 8.5 is the ability to expand a list into separate
999 arguments. Support for this feature is also available in Jim.
1001 Consider the following attempt to exec a list:
1003     set cmd {ls -l}
1004     exec $cmd
1006 This will attempt to exec a command named "ls -l", which will clearly not
1007 work. Typically eval and concat are required to solve this problem, however
1008 it can be solved much more easily with +\{*\}+.
1010     exec {*}$cmd
1012 This will expand the following argument into individual elements and then evaluate
1013 the resulting command.
1015 Note that the official Tcl syntax is +\{*\}+, however +\{expand\}+ is retained
1016 for backward compatibility with experimental versions of this feature.
1018 REGULAR EXPRESSIONS
1019 -------------------
1020 Tcl provides two commands that support string matching using regular
1021 expressions, `regexp` and `regsub`, as well as `switch -regexp` and
1022 `lsearch -regexp`.
1024 Regular expressions may be implemented one of two ways. Either using the system's C library
1025 POSIX regular expression support, or using the built-in regular expression engine.
1026 The differences between these are described below.
1028 *NOTE* Tcl 7.x and 8.x use perl-style Advanced Regular Expressions (+ARE+).
1030 POSIX Regular Expressions
1031 ~~~~~~~~~~~~~~~~~~~~~~~~~
1032 If the system supports POSIX regular expressions, and UTF-8 support is not enabled,
1033 this support will be used by default. The type of regular expressions supported are
1034 Extended Regular Expressions (+ERE+) rather than Basic Regular Expressions (+BRE+).
1035 See REG_EXTENDED in the documentation.
1037 Using the system-supported POSIX regular expressions will typically
1038 make for the smallest code size, but some features such as UTF-8
1039 and +{backslash}w+, +{backslash}d+, +{backslash}s+ are not supported, and null characters
1040 in strings are not supported.
1042 See regex(3) and regex(7) for full details.
1044 Jim built-in Regular Expressions
1045 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1046 The Jim built-in regular expression engine may be selected with +./configure --with-jim-regexp+
1047 or it will be selected automatically if UTF-8 support is enabled.
1049 This engine supports UTF-8 as well as some +ARE+ features. The differences with both Tcl 7.x/8.x
1050 and POSIX are highlighted below.
1052 1. UTF-8 strings and patterns are both supported
1053 2. All Tcl character classes are supported (e.g. +[:alnum:]+, +[:digit:]+, +[:space:]+), but...
1054 3. Character classes apply to ASCII characters only
1055 4. Supported shorthand character classes: +{backslash}w+ = +[:alnum:]+, +{backslash}W+ = +^[:alnum:]+, +{backslash}d+ = +[:digit:],+ +{backslash}D+ = +^[:digit:],+ +{backslash}s+ = +[:space:]+, + +{backslash}S+ = +^[:space:]+
1056 5. Supported constraint escapes: +{backslash}m+ = +{backslash}<+ = start of word, +{backslash}M+ = +{backslash}>+ = end of word
1057 6. Backslash escapes may be used within regular expressions, such as +{backslash}n+ = newline, +{backslash}uNNNN+ = unicode
1058 7. Partially supported constraint escapes: +{backslash}A+ = start of string, +{backslash}Z+ = end of string
1059 8. Support for the +?+ non-greedy quantifier. e.g. +*?+
1060 9. Support for non-capturing parentheses +(?:...)+
1061 10. Jim Tcl considers that both patterns and strings end at a null character (+\x00+)
1063 COMMAND RESULTS
1064 ---------------
1065 Each command produces two results:  a code and a string.  The
1066 code indicates whether the command completed successfully or not,
1067 and the string gives additional information.  The valid codes are
1068 defined in jim.h, and are:
1070 +JIM_OK(0)+::
1071     This is the normal return code, and indicates that the command completed
1072     successfully.  The string gives the command's return value.
1074 +JIM_ERR(1)+::
1075     Indicates that an error occurred; the string gives a message describing
1076     the error.
1078 +JIM_RETURN(2)+::
1079     Indicates that the `return` command has been invoked, and that the
1080     current procedure (or top-level command or `source` command)
1081     should return immediately.  The
1082     string gives the return value for the procedure or command.
1084 +JIM_BREAK(3)+::
1085     Indicates that the `break` command has been invoked, so the
1086     innermost loop should abort immediately.  The string should always
1087     be empty.
1089 +JIM_CONTINUE(4)+::
1090     Indicates that the `continue` command has been invoked, so the
1091     innermost loop should go on to the next iteration.  The string
1092     should always be empty.
1094 +JIM_SIGNAL(5)+::
1095     Indicates that a signal was caught while executing a commands.
1096     The string contains the name of the signal caught.
1097     See the `signal` and `catch` commands.
1099 +JIM_EXIT(6)+::
1100     Indicates that the command called the `exit` command.
1101     The string contains the exit code.
1103 Tcl programmers do not normally need to think about return codes,
1104 since +JIM_OK+ is almost always returned.  If anything else is returned
1105 by a command, then the Tcl interpreter immediately stops processing
1106 commands and returns to its caller.  If there are several nested
1107 invocations of the Tcl interpreter in progress, then each nested
1108 command will usually return the error to its caller, until eventually
1109 the error is reported to the top-level application code.  The
1110 application will then display the error message for the user.
1112 In a few cases, some commands will handle certain `error` conditions
1113 themselves and not return them upwards.  For example, the `for`
1114 command checks for the +JIM_BREAK+ code; if it occurs, then `for`
1115 stops executing the body of the loop and returns +JIM_OK+ to its
1116 caller.  The `for` command also handles +JIM_CONTINUE+ codes and the
1117 procedure interpreter handles +JIM_RETURN+ codes.  The `catch`
1118 command allows Tcl programs to catch errors and handle them without
1119 aborting command interpretation any further.
1121 The `info returncodes` command may be used to programmatically map between
1122 return codes and names.
1124 PROCEDURES
1125 ----------
1126 Tcl allows you to extend the command interface by defining
1127 procedures.  A Tcl procedure can be invoked just like any other Tcl
1128 command (it has a name and it receives one or more arguments).
1129 The only difference is that its body isn't a piece of C code linked
1130 into the program; it is a string containing one or more other
1131 Tcl commands.
1133 The `proc` command is used to create a new Tcl command procedure:
1135 +*proc* 'name arglist ?statics? body'+
1137 The new command is named +'name'+, and it replaces any existing command
1138 there may have been by that name. Whenever the new command is
1139 invoked, the contents of +'body'+ will be executed by the Tcl
1140 interpreter.
1142 +'arglist'+ specifies the formal arguments to the procedure.
1143 It consists of a list, possibly empty, of the following
1144 argument specifiers:
1146 +name+::
1147     Required Argument - A simple argument name.
1149 +{name default}+::
1150     Optional Argument - A two-element list consisting of the
1151     argument name, followed by the default value, which will
1152     be used if the corresponding argument is not supplied.
1154 +&name+::
1155     Reference Argument - The caller is expected to pass the name of
1156     an existing variable. An implicit +`upvar` 1 origname name+ is done
1157     to make the variable available in the proc scope.
1159 +*args*+::
1160     Variable Argument - The special name +'args'+, which is
1161     assigned all remaining arguments (including none) as a list. The
1162     variable argument may only be specified once. Note that
1163     the syntax +{args newname}+ may be used to retain the special
1164     behaviour of +'args'+ with a different local name. In this case,
1165     the variable is named +'newname'+ rather than +'args'+.
1167 When the command is invoked, a local variable will be created for each of
1168 the formal arguments to the procedure; its value will be the value
1169 of corresponding argument in the invoking command or the argument's
1170 default value.
1172 Arguments with default values need not be specified in a procedure
1173 invocation.  However, there must be enough actual arguments for all
1174 required arguments, and there must not be any extra actual arguments
1175 (unless the Variable Argument is specified).
1177 Actual arguments are assigned to formal arguments as in left-to-right
1178 order with the following precedence.
1180 1. Required Arguments (including Reference Arguments)
1181 2. Optional Arguments
1182 3. Variable Argument
1184 The following example illustrates precedence. Assume a procedure declaration:
1186     proc p {{a A} args b {c C} d} {...}
1188 This procedure requires at least two arguments, but can accept an unlimited number.
1189 The following table shows how various numbers of arguments are assigned.
1190 Values marked as +-+ are assigned the default value.
1192 [width="40%",frame="topbot",options="header"]
1193 |==============
1194 |Number of arguments|a|args|b|c|d
1195 |2|-|-|1|-|2
1196 |3|1|-|2|-|3
1197 |4|1|-|2|3|4
1198 |5|1|2|3|4|5
1199 |6|1|2,3|4|5|6
1200 |==============
1202 When +'body'+ is being executed, variable names normally refer to local
1203 variables, which are created automatically when referenced and deleted
1204 when the procedure returns.  One local variable is automatically created
1205 for each of the procedure's arguments.  Global variables can be
1206 accessed by invoking the `global` command or via the +::+ prefix.
1208 New in Jim
1209 ~~~~~~~~~~
1210 In addition to procedure arguments, Jim procedures may declare static variables.
1211 These variables scoped to the procedure and initialised at procedure definition.
1212 Either from the static variable definition, or from the enclosing scope.
1214 Consider the following example:
1216     jim> set a 1
1217     jim> proc a {} {a {b 2}} {
1218         set c 1
1219         puts "$a $b $c"
1220         incr a
1221         incr b
1222         incr c
1223     }
1224     jim> a
1225     1 2 1
1226     jim> a
1227     2 3 1
1229 The static variable +'a'+ has no initialiser, so it is initialised from
1230 the enclosing scope with the value 1. (Note that it is an error if there
1231 is no variable with the same name in the enclosing scope). However +'b'+
1232 has an initialiser, so it is initialised to 2.
1234 Unlike a local variable, the value of a static variable is retained across
1235 invocations of the procedure.
1237 See the `proc` command for information on how to define procedures
1238 and what happens when they are invoked. See also NAMESPACES.
1240 VARIABLES - SCALARS AND ARRAYS
1241 ------------------------------
1242 Tcl allows the definition of variables and the use of their values
1243 either through '$'-style variable substitution, the `set`
1244 command, or a few other mechanisms.
1246 Variables need not be declared:  a new variable will automatically
1247 be created each time a new variable name is used.
1249 Tcl supports two types of variables:  scalars and arrays.
1250 A scalar variable has a single value, whereas an array variable
1251 can have any number of elements, each with a name (called
1252 its 'index') and a value.
1254 Array indexes may be arbitrary strings; they need not be numeric.
1255 Parentheses are used refer to array elements in Tcl commands.
1256 For example, the command
1258     set x(first) 44
1260 will modify the element of 'x' whose index is 'first'
1261 so that its new value is '44'.
1263 Two-dimensional arrays can be simulated in Tcl by using indexes
1264 that contain multiple concatenated values.
1265 For example, the commands
1267     set a(2,3) 1
1268     set a(3,6) 2
1270 set the elements of 'a' whose indexes are '2,3' and '3,6'.
1272 In general, array elements may be used anywhere in Tcl that scalar
1273 variables may be used.
1275 If an array is defined with a particular name, then there may
1276 not be a scalar variable with the same name.
1278 Similarly, if there is a scalar variable with a particular
1279 name then it is not possible to make array references to the
1280 variable.
1282 To convert a scalar variable to an array or vice versa, remove
1283 the existing variable with the `unset` command.
1285 The `array` command provides several features for dealing
1286 with arrays, such as querying the names of all the elements of
1287 the array and converting between an array and a list.
1289 Variables may be either global or local.  If a variable
1290 name is used when a procedure isn't being executed, then it
1291 automatically refers to a global variable.  Variable names used
1292 within a procedure normally refer to local variables associated with that
1293 invocation of the procedure.  Local variables are deleted whenever
1294 a procedure exits.  Either `global` command may be used to request
1295 that a name refer to a global variable for the duration of the current
1296 procedure (this is somewhat analogous to 'extern' in C), or the variable
1297 may be explicitly scoped with the +::+ prefix. For example
1299     set a 1
1300     set b 2
1301     proc p {} {
1302         set c 3
1303         global a
1305         puts "$a $::b $c"
1306     }
1307     p
1309 will output:
1311     1 2 3
1313 ARRAYS AS LISTS IN JIM
1314 ----------------------
1315 Unlike Tcl, Jim can automatically convert between a list (with an even
1316 number of elements) and an array value. This is similar to the way Tcl
1317 can convert between a string and a list.
1319 For example:
1321   set a {1 one 2 two}
1322   puts $a(2)
1324 will output:
1326   two
1328 Thus `array set` is equivalent to `set` when the variable does not
1329 exist or is empty.
1331 The reverse is also true where an array will be converted into
1332 a list.
1334   set a(1) one; set a(2) two
1335   puts $a
1337 will output:
1339   1 one 2 two
1341 DICTIONARY VALUES
1342 -----------------
1343 Tcl 8.5 introduced the dict command, and Jim Tcl has added a version
1344 of this command. Dictionaries provide efficient access to key-value
1345 pairs, just like arrays, but dictionaries are pure values. This
1346 means that you can pass them to a procedure just as a list or a
1347 string. Tcl dictionaries are therefore much more like Tcl lists,
1348 except that they represent a mapping from keys to values, rather
1349 than an ordered sequence.
1351 You can nest dictionaries, so that the value for a particular key
1352 consists of another dictionary. That way you can elegantly build
1353 complicated data structures, such as hierarchical databases. You
1354 can also combine dictionaries with other Tcl data structures. For
1355 instance, you can build a list of dictionaries that themselves
1356 contain lists.
1358 Dictionaries are values that contain an efficient, order-preserving
1359 mapping from arbitrary keys to arbitrary values. Each key in the
1360 dictionary maps to a single value. They have a textual format that
1361 is exactly that of any list with an even number of elements, with
1362 each mapping in the dictionary being represented as two items in
1363 the list. When a command takes a dictionary and produces a new
1364 dictionary based on it (either returning it or writing it back into
1365 the variable that the starting dictionary was read from) the new
1366 dictionary will have the same order of keys, modulo any deleted
1367 keys and with new keys added on to the end. When a string is
1368 interpreted as a dictionary and it would otherwise have duplicate
1369 keys, only the last value for a particular key is used; the others
1370 are ignored, meaning that, "apple banana" and "apple carrot apple
1371 banana" are equivalent dictionaries (with different string
1372 representations).
1374 Note that in Jim, arrays are implemented as dictionaries.
1375 Thus automatic conversion between lists and dictionaries applies
1376 as it does for arrays.
1378   jim> dict set a 1 one
1379   1 one
1380   jim> dict set a 2 two
1381   1 one 2 two
1382   jim> puts $a
1383   1 one 2 two
1384   jim> puts $a(2)
1385   two
1386   jim> dict set a 3 T three
1387   1 one 2 two 3 {T three}
1389 See the `dict` command for more details.
1391 NAMESPACES
1392 ----------
1393 Tcl added namespaces as a mechanism avoiding name clashes, especially in applications
1394 including a number of 3rd party components. While there is less need for namespaces
1395 in Jim Tcl (which does not strive to support large applications), it is convenient to
1396 provide a subset of the support for namespaces to easy porting code from Tcl.
1398 Jim Tcl currently supports "light-weight" namespaces which should be adequate for most
1399 purposes. This feature is currently experimental. See README.namespaces for more information
1400 and the documentation of the `namespace` command.
1402 GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION
1403 -----------------------------------------------
1404 Unlike Tcl, Jim has some sophisticated support for functional programming.
1405 These are described briefly below.
1407 More information may be found at http://wiki.tcl.tk/13847
1409 References
1410 ~~~~~~~~~~
1411 A reference can be thought of as holding a value with one level of indirection,
1412 where the value may be garbage collected when unreferenced.
1413 Consider the following example:
1415     jim> set r [ref "One String" test]
1416     <reference.<test___>.00000000000000000000>
1417     jim> getref $r
1418     One String
1420 The operation `ref` creates a references to the value specified by the
1421 first argument. (The second argument is a "type" used for documentation purposes).
1423 The operation `getref` is the dereferencing operation which retrieves the value
1424 stored in the reference.
1426     jim> setref $r "New String"
1427     New String
1428     jim> getref $r
1429     New String
1431 The operation `setref` replaces the value stored by the reference. If the old value
1432 is no longer accessible by any reference, it will eventually be automatically be garbage
1433 collected.
1435 Garbage Collection
1436 ~~~~~~~~~~~~~~~~~~
1437 Normally, all values in Tcl are passed by value. As such values are copied and released
1438 automatically as necessary.
1440 With the introduction of references, it is possible to create values whose lifetime
1441 transcend their scope. To support this, case, the Jim system will periodically identify
1442 and discard objects which are no longer accessible by any reference.
1444 The `collect` command may be used to force garbage collection.  Consider a reference created
1445 with a finalizer:
1447     jim> proc f {ref value} { puts "Finaliser called for $ref,$value" }
1448     jim> set r [ref "One String" test f]
1449     <reference.<test___>.00000000000
1450     jim> collect
1451     0
1452     jim> set r ""
1453     jim> collect
1454     Finaliser called for <reference.<test___>.00000000000,One String
1455     1
1457 Note that once the reference, 'r', was modified so that it no longer
1458 contained a reference to the value, the garbage collector discarded
1459 the value (after calling the finalizer).
1461 The finalizer for a reference may be examined or changed with the `finalize` command
1463     jim> finalize $r
1464     f
1465     jim> finalize $r newf
1466     newf
1468 Lambda Function
1469 ~~~~~~~~~~~~~~~
1470 Jim provides a garbage collected `lambda` function. This is a procedure
1471 which is able to create an anonymous procedure.  Consider:
1473     jim> set f [lambda {a} {{x 0}} { incr x $a }]
1474     jim> $f 1
1475     1
1476     jim> $f 2
1477     3
1478     jim> set f ""
1480 This create an anonymous procedure (with the name stored in 'f'), with a static variable
1481 which is incremented by the supplied value and the result returned.
1483 Once the procedure name is no longer accessible, it will automatically be deleted
1484 when the garbage collector runs.
1486 The procedure may also be delete immediately by renaming it "". e.g.
1488     jim> rename $f ""
1490 UTF-8 AND UNICODE
1491 -----------------
1492 If Jim is built with UTF-8 support enabled (configure --enable-utf),
1493 then most string-related commands become UTF-8 aware.  These include,
1494 but are not limited to, `string match`, `split`, `glob`, `scan` and
1495 `format`.
1497 UTF-8 encoding has many advantages, but one of the complications is that
1498 characters can take a variable number of bytes. Thus the addition of
1499 `string bytelength` which returns the number of bytes in a string,
1500 while `string length` returns the number of characters.
1502 If UTF-8 support is not enabled, all commands treat bytes as characters
1503 and `string bytelength` returns the same value as `string length`.
1505 Note that even if UTF-8 support is not enabled, the +{backslash}uNNNN+ and related syntax
1506 is still available to embed UTF-8 sequences.
1508 Jim Tcl supports all currently defined unicode codepoints. That is 21 bits, up to +'U+1FFFFF'.
1510 String Matching
1511 ~~~~~~~~~~~~~~~
1512 Commands such as `string match`, `lsearch -glob`, `array names` and others use string
1513 pattern matching rules. These commands support UTF-8. For example:
1515   string match a\[\ua0-\ubf\]b "a\u00a3b"
1517 format and scan
1518 ~~~~~~~~~~~~~~~
1519 +format %c+ allows a unicode codepoint to be be encoded. For example, the following will return
1520 a string with two bytes and one character. The same as +{backslash}ub5+
1522   format %c 0xb5
1524 `format` respects widths as character widths, not byte widths. For example, the following will
1525 return a string with three characters, not three bytes.
1527   format %.3s \ub5\ub6\ub7\ub8
1529 Similarly, +scan ... %c+ allows a UTF-8 to be decoded to a unicode codepoint. The following will set
1530 +'a'+ to 181 (0xb5) and +'b'+ to 65 (0x41).
1532   scan \u00b5A %c%c a b
1534 `scan %s` will also accept a character class, including unicode ranges.
1536 String Classes
1537 ~~~~~~~~~~~~~~
1538 `string is` has *not* been extended to classify UTF-8 characters. Therefore, the following
1539 will return 0, even though the string may be considered to be alphabetic.
1541   string is alpha \ub5Test
1543 This does not affect the string classes 'ascii', 'control', 'digit', 'double', 'integer' or 'xdigit'.
1545 Case Mapping and Conversion
1546 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1547 Jim provides a simplified unicode case mapping. This means that case conversion
1548 and comparison will not increase or decrease the number of characters in a string.
1549 (Although it may change the number of bytes).
1551 `string toupper` will convert any lowercase letters to their uppercase equivalent.
1552 Any character which is not a letter or has no uppercase equivalent is left unchanged.
1553 Similarly for `string tolower` and `string totitle`.
1555 Commands which perform case insensitive matches, such as `string compare -nocase`
1556 and `lsearch -nocase` fold both strings to uppercase before comparison.
1558 Invalid UTF-8 Sequences
1559 ~~~~~~~~~~~~~~~~~~~~~~~
1560 Some UTF-8 character sequences are invalid, such as those beginning with '0xff',
1561 those which represent character sequences longer than 3 bytes (greater than U+FFFF),
1562 and those which end prematurely, such as a lone '0xc2'.
1564 In these situations, the offending bytes are treated as single characters. For example,
1565 the following returns 2.
1567   string bytelength \xff\xff
1569 Regular Expressions
1570 ~~~~~~~~~~~~~~~~~~~
1571 If UTF-8 support is enabled, the built-in regular expression engine will be
1572 selected which supports UTF-8 strings and patterns.
1574 See REGULAR EXPRESSIONS
1576 BUILT-IN COMMANDS
1577 -----------------
1578 The Tcl library provides the following built-in commands, which will
1579 be available in any application using Tcl.  In addition to these
1580 built-in commands, there may be additional commands defined by each
1581 application, plus commands defined as Tcl procedures.
1583 In the command syntax descriptions below, words in +*boldface*+ are
1584 literals that you type verbatim to Tcl.
1586 Words in +'italics'+ are meta-symbols; they serve as names for any of
1587 a range of values that you can type.
1589 Optional arguments or groups of arguments are indicated by enclosing them
1590 in +?question-marks?+.
1592 Ellipses (+\...+) indicate that any number of additional
1593 arguments or groups of arguments may appear, in the same format
1594 as the preceding argument(s).
1596 [[CommandIndex]]
1597 Command Index
1598 ~~~~~~~~~~~~~
1599 @INSERTINDEX@
1601 alarm
1602 ~~~~~
1603 +*alarm* 'seconds'+
1605 Delivers the +SIGALRM+ signal to the process after the given
1606 number of seconds. If the platform supports 'ualarm(3)' then
1607 the argument may be a floating point value. Otherwise it must
1608 be an integer.
1610 Note that unless a signal handler for +SIGALRM+ has been installed
1611 (see `signal`), the process will exit on this signal.
1613 alias
1614 ~~~~~
1615 +*alias* 'name args\...'+
1617 Creates a single word alias (command) for one or more words. For example,
1618 the following creates an alias for the command `info exists`.
1620     alias e info exists
1621     if {[e var]} {
1622       ...
1623     }
1625 `alias` returns +'name'+, allowing it to be used with `local`.
1627 See also `proc`, `curry`, `lambda`, `local`, `info alias`, `exists -alias`
1629 append
1630 ~~~~~~
1631 +*append* 'varName value ?value value ...?'+
1633 Append all of the +'value'+ arguments to the current value
1634 of variable +'varName'+.  If +'varName'+ doesn't exist,
1635 it is given a value equal to the concatenation of all the
1636 +'value'+ arguments.
1638 This command provides an efficient way to build up long
1639 variables incrementally.
1640 For example, "`append a $b`" is much more efficient than
1641 "`set a $a$b`" if +$a+ is long.
1643 apply
1644 ~~~~~~
1645 +*apply* 'lambdaExpr ?arg1 arg2 \...?'+
1647 The command `apply` provides for anonymous procedure calls,
1648 similar to `lambda`, but without command name being created, even temporarily.
1650 The function  +'lambdaExpr'+ is a two element list +{args body}+
1651 or a three element list +{args body namespace}+. The first element
1652 args specifies the formal arguments, in the same form as the `proc` and `lambda` commands.
1654 array
1655 ~~~~~
1656 +*array* 'option arrayName ?arg\...?'+
1658 This command performs one of several operations on the
1659 variable given by +'arrayName'+.
1661 Note that in general, if the named array does not exist, the +'array'+ command behaves
1662 as though the array exists but is empty.
1664 The +'option'+ argument determines what action is carried out by the
1665 command.  The legal +'options'+ (which may be abbreviated) are:
1667 +*array exists* 'arrayName'+::
1668     Returns 1 if arrayName is an array variable, 0 if there is
1669     no variable by that name.
1671 +*array get* 'arrayName ?pattern?'+::
1672     Returns a list containing pairs of elements. The first
1673     element in each pair is the name of an element in arrayName
1674     and the second element of each pair is the value of the
1675     array element. The order of the pairs is undefined. If
1676     pattern is not specified, then all of the elements of the
1677     array are included in the result. If pattern is specified,
1678     then only those elements whose names match pattern (using
1679     the matching rules of string match) are included. If arrayName
1680     isn't the name of an array variable, or if the array contains
1681     no elements, then an empty list is returned.
1683 +*array names* 'arrayName ?pattern?'+::
1684     Returns a list containing the names of all of the elements
1685     in the array that match pattern. If pattern is omitted then
1686     the command returns all of the element names in the array.
1687     If pattern is specified, then only those elements whose
1688     names match pattern (using the matching rules of string
1689     match) are included. If there are no (matching) elements
1690     in the array, or if arrayName isn't the name of an array
1691     variable, then an empty string is returned.
1693 +*array set* 'arrayName list'+::
1694     Sets the values of one or more elements in arrayName. list
1695     must have a form like that returned by array get, consisting
1696     of an even number of elements. Each odd-numbered element
1697     in list is treated as an element name within arrayName, and
1698     the following element in list is used as a new value for
1699     that array element. If the variable arrayName does not
1700     already exist and list is empty, arrayName is created with
1701     an empty array value.
1703 +*array size* 'arrayName'+::
1704     Returns the number of elements in the array. If arrayName
1705     isn't the name of an array then 0 is returned.
1707 +*array unset* 'arrayName ?pattern?'+::
1708     Unsets all of the elements in the array that match pattern
1709     (using the matching rules of string match). If arrayName
1710     isn't the name of an array variable or there are no matching
1711     elements in the array, no error will be raised. If pattern
1712     is omitted and arrayName is an array variable, then the
1713     command unsets the entire array. The command always returns
1714     an empty string.
1716 break
1717 ~~~~~
1718 +*break*+
1720 This command may be invoked only inside the body of a loop command
1721 such as `for` or `foreach` or `while`.  It returns a +JIM_BREAK+ code
1722 to signal the innermost containing loop command to return immediately.
1724 case
1725 ~~~~
1726 +*case* 'string' ?in? 'patList body ?patList body ...?'+
1728 +*case* 'string' ?in? {'patList body ?patList body ...?'}+
1730 *Note* that the `switch` command should generally be preferred unless compatibility
1731 with Tcl 6.x is desired.
1733 Match +'string'+ against each of the +'patList'+ arguments
1734 in order.  If one matches, then evaluate the following +'body'+ argument
1735 by passing it recursively to the Tcl interpreter, and return the result
1736 of that evaluation.  Each +'patList'+ argument consists of a single
1737 pattern or list of patterns.  Each pattern may contain any of the wild-cards
1738 described under `string match`.
1740 If a +'patList'+ argument is +default+, the corresponding body will be
1741 evaluated if no +'patList'+ matches +'string'+.  If no +'patList'+ argument
1742 matches +'string'+ and no default is given, then the `case` command returns
1743 an empty string.
1745 Two syntaxes are provided.
1747 The first uses a separate argument for each of the patterns and commands;
1748 this form is convenient if substitutions are desired on some of the
1749 patterns or commands.
1751 The second form places all of the patterns and commands together into
1752 a single argument; the argument must have proper list structure, with
1753 the elements of the list being the patterns and commands.
1755 The second form makes it easy to construct multi-line case commands,
1756 since the braces around the whole list make it unnecessary to include a
1757 backslash at the end of each line.
1759 Since the +'patList'+ arguments are in braces in the second form,
1760 no command or variable substitutions are performed on them;  this makes
1761 the behaviour of the second form different than the first form in some
1762 cases.
1764 Below are some examples of `case` commands:
1766     case abc in {a b} {format 1} default {format 2} a* {format 3}
1768 will return '3',
1770     case a in {
1771         {a b} {format 1}
1772         default {format 2}
1773         a* {format 3}
1774     }
1776 will return '1', and
1778     case xyz {
1779         {a b}
1780             {format 1}
1781         default
1782             {format 2}
1783         a*
1784             {format 3}
1785     }
1787 will return '2'.
1789 catch
1790 ~~~~~
1791 +*catch* ?-?no?'code \...'? ?--? 'command ?resultVarName? ?optionsVarName?'+
1793 The `catch` command may be used to prevent errors from aborting
1794 command interpretation.  `catch` evaluates +'command'+, and returns a
1795 +JIM_OK+ code, regardless of any errors that might occur while
1796 executing +'command'+ (with the possible exception of +JIM_SIGNAL+ -
1797 see below).
1799 The return value from `catch` is a decimal string giving the code
1800 returned by the Tcl interpreter after executing +'command'+.  This
1801 will be '0' (+JIM_OK+) if there were no errors in +'command'+; otherwise
1802 it will have a non-zero value corresponding to one of the exceptional
1803 return codes (see jim.h for the definitions of code values, or the
1804 `info returncodes` command).
1806 If the +'resultVarName'+ argument is given, then it gives the name
1807 of a variable; `catch` will set the value of the variable to the
1808 string returned from +'command'+ (either a result or an error message).
1810 If the +'optionsVarName'+ argument is given, then it gives the name
1811 of a variable; `catch` will set the value of the variable to a
1812 dictionary. For any return code other than +JIM_RETURN+, the value
1813 for the key +-code+ will be set to the return code. For +JIM_RETURN+
1814 it will be set to the code given in `return -code`. Additionally,
1815 for the return code +JIM_ERR+, the value of the key +-errorinfo+
1816 will contain the current stack trace (the same result as `info stacktrace`),
1817 the value of the key +-errorcode+ will contain the
1818 same value as the global variable $::errorCode, and the value of
1819 the key +-level+ will be the current return level (see `return -level`).
1820 This can be useful to rethrow an error:
1822     if {[catch {...} msg opts]} {
1823         ...maybe do something with the error...
1824         incr opts(-level)
1825         return {*}$opts $msg
1826     }
1828 Normally `catch` will +'not'+ catch any of the codes +JIM_EXIT+, +JIM_EVAL+ or +JIM_SIGNAL+.
1829 The set of codes which will be caught may be modified by specifying the one more codes before
1830 +'command'+.
1832 e.g. To catch +JIM_EXIT+ but not +JIM_BREAK+ or +JIM_CONTINUE+
1834     catch -exit -nobreak -nocontinue -- { ... }
1836 The use of +--+ is optional. It signifies that no more return code options follow.
1838 Note that if a signal marked as `signal handle` is caught with `catch -signal`, the return value
1839 (stored in +'resultVarName'+) is name of the signal caught.
1843 +*cd* 'dirName'+
1845 Change the current working directory to +'dirName'+.
1847 Returns an empty string.
1849 This command can potentially be disruptive to an application, so it may
1850 be removed in some applications.
1852 clock
1853 ~~~~~
1854 +*clock seconds*+::
1855     Returns the current time as seconds since the epoch.
1857 +*clock clicks*+::
1858     Returns the current time in `clicks'.
1860 +*clock microseconds*+::
1861     Returns the current time in microseconds.
1863 +*clock milliseconds*+::
1864     Returns the current time in milliseconds.
1866 +*clock format* 'seconds' ?*-format* 'format?'+::
1867     Format the given time (seconds since the epoch) according to the given
1868     format. See strftime(3) for supported formats.
1869     If no format is supplied, "%c" is used.
1871 +*clock scan* 'str' *-format* 'format'+::
1872     Scan the given time string using the given format string.
1873     See strptime(3) for supported formats.
1875 close
1876 ~~~~~
1877 +*close* 'fileId'+
1879 +'fileId' *close*+
1881 Closes the file given by +'fileId'+.
1882 +'fileId'+ must be the return value from a previous invocation
1883 of the `open` command; after this command, it should not be
1884 used anymore.
1886 collect
1887 ~~~~~~~
1888 +*collect*+
1890 Normally reference garbage collection is automatically performed periodically.
1891 However it may be run immediately with the `collect` command.
1893 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
1895 concat
1896 ~~~~~~
1897 +*concat* 'arg ?arg \...?'+
1899 This command treats each argument as a list and concatenates them
1900 into a single list.  It permits any number of arguments.  For example,
1901 the command
1903     concat a b {c d e} {f {g h}}
1905 will return
1907     a b c d e f {g h}
1909 as its result.
1911 continue
1912 ~~~~~~~~
1913 +*continue*+
1915 This command may be invoked only inside the body of a loop command such
1916 as `for` or `foreach` or `while`.  It returns a  +JIM_CONTINUE+ code to
1917 signal the innermost containing loop command to skip the remainder of
1918 the loop's body but continue with the next iteration of the loop.
1920 curry
1921 ~~~~~
1922 +*alias* 'args\...'+
1924 Similar to `alias` except it creates an anonymous procedure (lambda) instead of
1925 a named procedure.
1927 the following creates a local, unnamed alias for the command `info exists`.
1929     set e [local curry info exists]
1930     if {[$e var]} {
1931       ...
1932     }
1934 `curry` returns the name of the procedure.
1936 See also `proc`, `alias`, `lambda`, `local`.
1938 dict
1939 ~~~~
1940 +*dict* 'option ?arg\...?'+
1942 Performs one of several operations on dictionary values.
1944 The +'option'+ argument determines what action is carried out by the
1945 command.  The legal +'options'+ are:
1947 +*dict create* '?key value \...?'+::
1948     Create and return a new dictionary value that contains each of
1949     the key/value mappings listed as  arguments (keys and values
1950     alternating, with each key being followed by its associated
1951     value.)
1953 +*dict exists* 'dictionary key ?key \...?'+::
1954     Returns a boolean value indicating whether the given key (or path
1955     of keys through a set of nested dictionaries) exists in the given
1956     dictionary value.  This returns a true value exactly when `dict get`
1957     on that path will succeed.
1959 +*dict get* 'dictionary ?key \...?'+::
1960     Given a dictionary value (first argument) and a key (second argument),
1961     this will retrieve the value for that key. Where several keys are
1962     supplied, the behaviour of the command shall be as if the result
1963     of "`dict get $dictVal $key`" was passed as the first argument to
1964     dict get with the remaining arguments as second (and possibly
1965     subsequent) arguments. This facilitates lookups in nested dictionaries.
1966     If no keys are provided, dict would return a list containing pairs
1967     of elements in a manner similar to array get. That is, the first
1968     element of each pair would be the key and the second element would
1969     be the value for that key.  It is an error to attempt to retrieve
1970     a value for a key that is not present in the dictionary.
1972 +*dict keys* 'dictionary ?pattern?'+::
1973     Returns a list of the keys in the dictionary.
1974     If pattern is specified, then only those keys whose
1975     names match +'pattern'+ (using the matching rules of string
1976     match) are included.
1978 +*dict merge* ?'dictionary \...'?+::
1979     Return a dictionary that contains the contents of each of the
1980     +'dictionary'+ arguments. Where two (or more) dictionaries
1981     contain a mapping for the same key, the resulting dictionary
1982     maps that key to the value according to the last dictionary on
1983     the command line containing a mapping for that key.
1985 +*dict set* 'dictionaryName key ?key \...? value'+::
1986     This operation takes the +'name'+ of a variable containing a dictionary
1987     value and places an updated dictionary value in that variable
1988     containing a mapping from the given key to the given value. When
1989     multiple keys are present, this operation creates or updates a chain
1990     of nested dictionaries.
1992 +*dict size* 'dictionary'+::
1993     Return the number of key/value mappings in the given dictionary value.
1995 +*dict unset* 'dictionaryName key ?key \...? value'+::
1996     This operation (the companion to `dict set`) takes the name of a
1997     variable containing a dictionary value and places an updated
1998     dictionary value in that variable that does not contain a mapping
1999     for the given key. Where multiple keys are present, this describes
2000     a path through nested dictionaries to the mapping to remove. At
2001     least one key must be specified, but the last key on the key-path
2002     need not exist. All other components on the path must exist.
2004 +*dict with* 'dictionaryName key ?key \...? script'+::
2005     Execute the Tcl script in +'script'+ with the value for each
2006     key in +'dictionaryName'+ mapped to a variable with the same
2007     name. Where one or more keys are given, these indicate a chain
2008     of nested dictionaries, with the innermost dictionary being the
2009     one opened out for the execution of body. Making +'dictionaryName'+
2010     unreadable will make the updates to the dictionary be discarded,
2011     and this also happens if the contents of +'dictionaryName'+ are
2012     adjusted so that the chain of dictionaries no longer exists.
2013     The result of `dict with` is (unless some kind of error occurs)
2014     the result of the evaluation of body.
2015  ::
2016     The variables are mapped in the scope enclosing the `dict with`;
2017     it is recommended that this command only be used in a local
2018     scope (procedure). Because of this, the variables set by
2019     `dict with` will continue to exist after the command finishes (unless
2020     explicitly unset). Note that changes to the contents of +'dictionaryName'+
2021     only happen when +'script'+ terminates.
2023 +*dict for, values, incr, append, lappend, update, info, replace*+ to be documented...
2027 +*env* '?name? ?default?'+
2029 If +'name'+ is supplied, returns the value of +'name'+ from the initial
2030 environment (see getenv(3)). An error is returned if +'name'+ does not
2031 exist in the environment, unless +'default'+ is supplied - in which case
2032 that value is returned instead.
2034 If no arguments are supplied, returns a list of all environment variables
2035 and their values as +{name value \...}+
2037 See also the global variable +::env+
2041 +*eof* 'fileId'+
2043 +'fileId' *eof*+
2045 Returns 1 if an end-of-file condition has occurred on +'fileId'+,
2046 0 otherwise.
2048 +'fileId'+ must have been the return value from a previous call to `open`,
2049 or it may be +stdin+, +stdout+, or +stderr+ to refer to one of the
2050 standard I/O channels.
2052 error
2053 ~~~~~
2054 +*error* 'message ?stacktrace?'+
2056 Returns a +JIM_ERR+ code, which causes command interpretation to be
2057 unwound.  +'message'+ is a string that is returned to the application
2058 to indicate what went wrong.
2060 If the +'stacktrace'+ argument is provided and is non-empty,
2061 it is used to initialize the stacktrace.
2063 This feature is most useful in conjunction with the `catch` command:
2064 if a caught error cannot be handled successfully, +'stacktrace'+ can be used
2065 to return a stack trace reflecting the original point of occurrence
2066 of the error:
2068     catch {...} errMsg
2069     ...
2070     error $errMsg [info stacktrace]
2072 See also `errorInfo`, `info stacktrace`, `catch` and `return`
2074 errorInfo
2075 ~~~~~~~~~
2076 +*errorInfo* 'error ?stacktrace?'+
2078 Returns a human-readable representation of the given error message and stack trace.
2079 Typical usage is:
2081     if {[catch {...} error]} {
2082         puts stderr [errorInfo $error [info stacktrace]]
2083         exit 1
2084     }
2086 See also `error`.
2088 eval
2089 ~~~~
2090 +*eval* 'arg ?arg\...?'+
2092 `eval` takes one or more arguments, which together comprise a Tcl
2093 command (or collection of Tcl commands separated by newlines in the
2094 usual way).  `eval` concatenates all its arguments in the same
2095 fashion as the `concat` command, passes the concatenated string to the
2096 Tcl interpreter recursively, and returns the result of that
2097 evaluation (or any error generated by it).
2099 exec
2100 ~~~~
2101 +*exec* 'arg ?arg\...?'+
2103 This command treats its arguments as the specification
2104 of one or more UNIX commands to execute as subprocesses.
2105 The commands take the form of a standard shell pipeline;
2106 +|+ arguments separate commands in the
2107 pipeline and cause standard output of the preceding command
2108 to be piped into standard input of the next command (or +|&+ for
2109 both standard output and standard error).
2111 Under normal conditions the result of the `exec` command
2112 consists of the standard output produced by the last command
2113 in the pipeline followed by the standard error output.
2115 If any of the commands writes to its standard error file,
2116 then this will be included in the result after the standard output
2117 of the last command.
2119 Note that unlike Tcl, data written to standard error does not cause
2120 `exec` to return an error.
2122 If any of the commands in the pipeline exit abnormally or
2123 are killed or suspended, then `exec` will return an error.
2124 If no standard error output was produced, or is redirected,
2125 the error message will include the normal result, as above,
2126 followed by error messages describing the abnormal terminations.
2128 If any standard error output was produced, these abnormal termination
2129 messages are suppressed.
2131 If the last character of the result or error message
2132 is a newline then that character is deleted from the result
2133 or error message for consistency with normal
2134 Tcl return values.
2136 An +'arg'+ may have one of the following special forms:
2138 +>filename+::
2139     The standard output of the last command in the pipeline
2140     is redirected to the file.  In this situation `exec`
2141     will normally return an empty string.
2143 +>>filename+::
2144     As above, but append to the file.
2146 +>@fileId+::
2147     The standard output of the last command in the pipeline is
2148     redirected to the given (writable) file descriptor (e.g. stdout,
2149     stderr, or the result of `open`). In this situation `exec`
2150     will normally return an empty string.
2152 +2>filename+::
2153     The standard error of the last command in the pipeline
2154     is redirected to the file.
2156 +2>>filename+::
2157     As above, but append to the file.
2159 +2>@fileId+::
2160     The standard error of the last command in the pipeline is
2161     redirected to the given (writable) file descriptor.
2163 +2>@1+::
2164     The standard error of the last command in the pipeline is
2165     redirected to the same file descriptor as the standard output.
2167 +>&filename+::
2168     Both the standard output and standard error of the last command
2169     in the pipeline is redirected to the file.
2171 +>>&filename+::
2172     As above, but append to the file.
2174 +<filename+::
2175     The standard input of the first command in the pipeline
2176     is taken from the file.
2178 +<<string+::
2179     The standard input of the first command is taken as the
2180     given immediate value.
2182 +<@fileId+::
2183     The standard input of the first command in the pipeline
2184     is taken from the given (readable) file descriptor.
2186 If there is no redirection of standard input, standard error
2187 or standard output, these are connected to the corresponding
2188 input or output of the application.
2190 If the last +'arg'+ is +&+ then the command will be
2191 executed in background.
2192 In this case the standard output from the last command
2193 in the pipeline will
2194 go to the application's standard output unless
2195 redirected in the command, and error output from all
2196 the commands in the pipeline will go to the application's
2197 standard error file. The return value of exec in this case
2198 is a list of process ids (pids) in the pipeline.
2200 Each +'arg'+ becomes one word for a command, except for
2201 +|+, +<+, +<<+, +>+, and +&+ arguments, and the
2202 arguments that follow +<+, +<<+, and +>+.
2204 The first word in each command is taken as the command name;
2205 the directories in the PATH environment variable are searched for
2206 an executable by the given name.
2208 No `glob` expansion or other shell-like substitutions
2209 are performed on the arguments to commands.
2211 If the command fails, the global $::errorCode (and the -errorcode
2212 option in `catch`) will be set to a list, as follows:
2214 +*CHILDKILLED* 'pid sigName msg'+::
2215         This format is used when a child process has been killed
2216         because of a signal. The pid element will be the process's
2217         identifier (in decimal). The sigName element will be the
2218         symbolic name of the signal that caused the process to
2219         terminate; it will be one of the names from the include
2220         file signal.h, such as SIGPIPE. The msg element will be a
2221         short human-readable message describing the signal, such
2222         as "write on pipe with no readers" for SIGPIPE.
2224 +*CHILDSUSP* 'pid sigName msg'+::
2225         This format is used when a child process has been suspended
2226         because of a signal. The pid element will be the process's
2227         identifier, in decimal. The sigName element will be the
2228         symbolic name of the signal that caused the process to
2229         suspend; this will be one of the names from the include
2230         file signal.h, such as SIGTTIN. The msg element will be a
2231         short human-readable message describing the signal, such
2232         as "background tty read" for SIGTTIN.
2234 +*CHILDSTATUS* 'pid code'+::
2235         This format is used when a child process has exited with a
2236         non-zero exit status. The pid element will be the process's
2237         identifier (in decimal) and the code element will be the
2238         exit code returned by the process (also in decimal).
2240 The environment for the executed command is set from $::env (unless
2241 this variable is unset, in which case the original environment is used).
2243 exists
2244 ~~~~~~
2245 +*exists ?-var|-proc|-command|-alias?* 'name'+
2247 Checks the existence of the given variable, procedure, command
2248 or alias respectively and returns 1 if it exists or 0 if not.  This command
2249 provides a more simplified/convenient version of `info exists`,
2250 `info procs` and `info commands`.
2252 If the type is omitted, a type of '-var' is used. The type may be abbreviated.
2254 exit
2255 ~~~~
2256 +*exit* '?returnCode?'+
2258 Terminate the process, returning +'returnCode'+ to the
2259 parent as the exit status.
2261 If +'returnCode'+ isn't specified then it defaults
2262 to 0.
2264 Note that exit can be caught with `catch`.
2266 expr
2267 ~~~~
2268 +*expr* 'arg'+
2270 Calls the expression processor to evaluate +'arg'+, and returns
2271 the result as a string.  See the section EXPRESSIONS above.
2273 Note that Jim supports a shorthand syntax for `expr` as +$(\...)+
2274 The following two are identical.
2276   set x [expr {3 * 2 + 1}]
2277   set x $(3 * 2 + 1)
2279 file
2280 ~~~~
2281 +*file* 'option name ?arg\...?'+
2283 Operate on a file or a file name.  +'name'+ is the name of a file.
2285 +'option'+ indicates what to do with the file name.  Any unique
2286 abbreviation for +'option'+ is acceptable.  The valid options are:
2288 +*file atime* 'name'+::
2289     Return a decimal string giving the time at which file +'name'+
2290     was last accessed.  The time is measured in the standard UNIX
2291     fashion as seconds from a fixed starting time (often January 1, 1970).
2292     If the file doesn't exist or its access time cannot be queried then an
2293     error is generated.
2295 +*file copy ?-force?* 'source target'+::
2296     Copies file +'source'+ to file +'target'+. The source file must exist.
2297     The target file must not exist, unless +-force+ is specified.
2299 +*file delete ?-force? ?--?* 'name\...'+::
2300     Deletes file or directory +'name'+. If the file or directory doesn't exist, nothing happens.
2301     If it can't be deleted, an error is generated. Non-empty directories will not be deleted
2302     unless the +-force+ options is given. In this case no errors will be generated, even
2303     if the file/directory can't be deleted. Use +'--'+ if there is any possibility of
2304     the first name being +'-force'+.
2306 +*file dirname* 'name'+::
2307     Return all of the characters in +'name'+ up to but not including
2308     the last slash character.  If there are no slashes in +'name'+
2309     then return +.+ (a single dot).  If the last slash in +'name'+ is its first
2310     character, then return +/+.
2312 +*file executable* 'name'+::
2313     Return '1' if file +'name'+ is executable by
2314     the current user, '0' otherwise.
2316 +*file exists* 'name'+::
2317     Return '1' if file +'name'+ exists and the current user has
2318     search privileges for the directories leading to it, '0' otherwise.
2320 +*file extension* 'name'+::
2321     Return all of the characters in +'name'+ after and including the
2322     last dot in +'name'+.  If there is no dot in +'name'+ then return
2323     the empty string.
2325 +*file isdirectory* 'name'+::
2326     Return '1' if file +'name'+ is a directory,
2327     '0' otherwise.
2329 +*file isfile* 'name'+::
2330     Return '1' if file +'name'+ is a regular file,
2331     '0' otherwise.
2333 +*file join* 'arg\...'+::
2334     Joins multiple path components. Note that if any components is
2335     an absolute path, the preceding components are ignored.
2336     Thus +"`file` join /tmp /root"+ returns +"/root"+.
2338 +*file link* ?*-hard|-symbolic*? 'newname target'+::
2339     Creates a hard link (default) or symbolic link from +'newname'+ to +'target'+.
2340     Note that the sense of this command is the opposite of `file rename` and `file copy`
2341     and also of `ln`, but this is compatible with Tcl.
2342     An error is returned if +'target'+ doesn't exist or +'newname'+ already exists.
2344 +*file lstat* 'name varName'+::
2345     Same as 'stat' option (see below) except uses the +'lstat'+
2346     kernel call instead of +'stat'+.  This means that if +'name'+
2347     refers to a symbolic link the information returned in +'varName'+
2348     is for the link rather than the file it refers to.  On systems that
2349     don't support symbolic links this option behaves exactly the same
2350     as the 'stat' option.
2352 +*file mkdir* 'dir1 ?dir2\...?'+::
2353     Creates each directory specified. For each pathname +'dir'+ specified,
2354     this command will create all non-existing parent directories
2355     as well as +'dir'+ itself. If an existing directory is specified,
2356     then no action is taken and no error is returned. Trying to
2357     overwrite an existing file with a directory will result in an
2358     error.  Arguments are processed in the order specified, halting
2359     at the first error, if any.
2361 +*file mtime* 'name ?time?'+::
2362     Return a decimal string giving the time at which file +'name'+
2363     was last modified.  The time is measured in the standard UNIX
2364     fashion as seconds from a fixed starting time (often January 1, 1970).
2365     If the file doesn't exist or its modified time cannot be queried then an
2366     error is generated. If +'time'+ is given, sets the modification time
2367     of the file to the given value.
2369 +*file normalize* 'name'+::
2370     Return the normalized path of +'name'+. See 'realpath(3)'.
2372 +*file owned* 'name'+::
2373     Return '1' if file +'name'+ is owned by the current user,
2374     '0' otherwise.
2376 +*file readable* 'name'+::
2377     Return '1' if file +'name'+ is readable by
2378     the current user, '0' otherwise.
2380 +*file readlink* 'name'+::
2381     Returns the value of the symbolic link given by +'name'+ (i.e. the
2382     name of the file it points to).  If
2383     +'name'+ isn't a symbolic link or its value cannot be read, then
2384     an error is returned.  On systems that don't support symbolic links
2385     this option is undefined.
2387 +*file rename* ?*-force*? 'oldname' 'newname'+::
2388     Renames the file from the old name to the new name.
2389     If +'newname'+ already exists, an error is returned unless +'-force'+ is
2390     specified.
2392 +*file rootname* 'name'+::
2393     Return all of the characters in +'name'+ up to but not including
2394     the last '.' character in the name.  If +'name'+ doesn't contain
2395     a dot, then return +'name'+.
2397 +*file size* 'name'+::
2398     Return a decimal string giving the size of file +'name'+ in bytes.
2399     If the file doesn't exist or its size cannot be queried then an
2400     error is generated.
2402 +*file stat* 'name ?varName?'+::
2403     Invoke the 'stat' kernel call on +'name'+, and return the result
2404     as a dictionary with the following keys: 'atime',
2405     'ctime', 'dev', 'gid', 'ino', 'mode', 'mtime',
2406     'nlink', 'size', 'type', 'uid'.
2407     Each element except 'type' is a decimal string with the value of
2408     the corresponding field from the 'stat' return structure; see the
2409     manual entry for 'stat' for details on the meanings of the values.
2410     The 'type' element gives the type of the file in the same form
2411     returned by the command `file type`.
2412     If +'varName'+ is specified, it is taken to be the name of an array
2413     variable and the values are also stored into the array.
2415 +*file tail* 'name'+::
2416     Return all of the characters in +'name'+ after the last slash.
2417     If +'name'+ contains no slashes then return +'name'+.
2419 +*file tempfile* '?template?'+::
2420     Creates and returns the name of a unique temporary file. If +'template'+ is omitted, a
2421     default template will be used to place the file in /tmp. See 'mkstemp(3)' for
2422     the format of the template and security concerns.
2424 +*file type* 'name'+::
2425     Returns a string giving the type of file +'name'+, which will be
2426     one of +file+, +directory+, +characterSpecial+,
2427     +blockSpecial+, +fifo+, +link+, or +socket+.
2429 +*file writable* 'name'+::
2430     Return '1' if file +'name'+ is writable by
2431     the current user, '0' otherwise.
2433 The `file` commands that return 0/1 results are often used in
2434 conditional or looping commands, for example:
2436     if {![file exists foo]} {
2437         error {bad file name}
2438     } else {
2439         ...
2440     }
2442 finalize
2443 ~~~~~~~~
2444 +*finalize* 'reference ?command?'+
2446 If +'command'+ is omitted, returns the finalizer command for the given reference.
2448 Otherwise, sets a new finalizer command for the given reference. +'command'+ may be
2449 the empty string to remove the current finalizer.
2451 The reference must be a valid reference create with the `ref`
2452 command.
2454 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2456 flush
2457 ~~~~~
2458 +*flush* 'fileId'+
2460 +'fileId' *flush*+
2462 Flushes any output that has been buffered for +'fileId'+.  +'fileId'+ must
2463 have been the return value from a previous call to `open`, or it may be
2464 +stdout+ or +stderr+ to access one of the standard I/O streams; it must
2465 refer to a file that was opened for writing.  This command returns an
2466 empty string.
2470 +*for* 'start test next body'+
2472 `for` is a looping command, similar in structure to the C `for` statement.
2473 The +'start'+, +'next'+, and +'body'+ arguments must be Tcl command strings,
2474 and +'test'+ is an expression string.
2476 The `for` command first invokes the Tcl interpreter to execute +'start'+.
2477 Then it repeatedly evaluates +'test'+ as an expression; if the result is
2478 non-zero it invokes the Tcl interpreter on +'body'+, then invokes the Tcl
2479 interpreter on +'next'+, then repeats the loop.  The command terminates
2480 when +'test'+ evaluates to 0.
2482 If a `continue` command is invoked within +'body'+ then any remaining
2483 commands in the current execution of +'body'+ are skipped; processing
2484 continues by invoking the Tcl interpreter on +'next'+, then evaluating
2485 +'test'+, and so on.
2487 If a `break` command is invoked within +'body'+ or +'next'+, then the `for`
2488 command will return immediately.
2490 The operation of `break` and `continue` are similar to the corresponding
2491 statements in C.
2493 `for` returns an empty string.
2495 foreach
2496 ~~~~~~~
2497 +*foreach* 'varName list body'+
2499 +*foreach* 'varList list ?varList2 list2 \...? body'+
2501 In this command, +'varName'+ is the name of a variable, +'list'+
2502 is a list of values to assign to +'varName'+, and +'body'+ is a
2503 collection of Tcl commands.
2505 For each field in +'list'+ (in order from left to right), `foreach` assigns
2506 the contents of the field to +'varName'+ (as if the `lindex` command
2507 had been used to extract the field), then calls the Tcl interpreter to
2508 execute +'body'+.
2510 If instead of being a simple name, +'varList'+ is used, multiple assignments
2511 are made each time through the loop, one for each element of +'varList'+.
2513 For example, if there are two elements in +'varList'+ and six elements in
2514 the list, the loop will be executed three times.
2516 If the length of the list doesn't evenly divide by the number of elements
2517 in +'varList'+, the value of the remaining variables in the last iteration
2518 of the loop are undefined.
2520 The `break` and `continue` statements may be invoked inside +'body'+,
2521 with the same effect as in the `for` command.
2523 `foreach` returns an empty string.
2525 format
2526 ~~~~~~
2527 +*format* 'formatString ?arg \...?'+
2529 This command generates a formatted string in the same way as the
2530 C 'sprintf' procedure (it uses 'sprintf' in its
2531 implementation).  +'formatString'+ indicates how to format
2532 the result, using +%+ fields as in 'sprintf', and the additional
2533 arguments, if any, provide values to be substituted into the result.
2535 All of the 'sprintf' options are valid; see the 'sprintf'
2536 man page for details.  Each +'arg'+ must match the expected type
2537 from the +%+ field in +'formatString'+; the `format` command
2538 converts each argument to the correct type (floating, integer, etc.)
2539 before passing it to 'sprintf' for formatting.
2541 The only unusual conversion is for +%c+; in this case the argument
2542 must be a decimal string, which will then be converted to the corresponding
2543 ASCII (or UTF-8) character value.
2545 In addition, Jim Tcl provides basic support for conversion to binary with +%b+.
2547 `format` does backslash substitution on its +'formatString'+
2548 argument, so backslash sequences in +'formatString'+ will be handled
2549 correctly even if the argument is in braces.
2551 The return value from `format` is the formatted string.
2553 getref
2554 ~~~~~~
2555 +*getref* 'reference'+
2557 Returns the string associated with +'reference'+. The reference must
2558 be a valid reference create with the `ref` command.
2560 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2562 gets
2563 ~~~~
2564 +*gets* 'fileId ?varName?'+
2566 +'fileId' *gets* '?varName?'+
2568 Reads the next line from the file given by +'fileId'+ and discards
2569 the terminating newline character.
2571 If +'varName'+ is specified, then the line is placed in the variable
2572 by that name and the return value is a count of the number of characters
2573 read (not including the newline).
2575 If the end of the file is reached before reading
2576 any characters then -1 is returned and +'varName'+ is set to an
2577 empty string.
2579 If +'varName'+ is not specified then the return value will be
2580 the line (minus the newline character) or an empty string if
2581 the end of the file is reached before reading any characters.
2583 An empty string will also be returned if a line contains no characters
2584 except the newline, so `eof` may have to be used to determine
2585 what really happened.
2587 If the last character in the file is not a newline character, then
2588 `gets` behaves as if there were an additional newline character
2589 at the end of the file.
2591 +'fileId'+ must be +stdin+ or the return value from a previous
2592 call to `open`; it must refer to a file that was opened
2593 for reading.
2595 glob
2596 ~~~~
2597 +*glob* ?*-nocomplain*? ?*-directory* 'dir'? ?*-tails*? ?*--*? 'pattern ?pattern \...?'+
2599 This command performs filename globbing, using csh rules.  The returned
2600 value from `glob` is the list of expanded filenames.
2602 If +-nocomplain+ is specified as the first argument then an empty
2603 list may be returned;  otherwise an error is returned if the expanded
2604 list is empty.  The +-nocomplain+ argument must be provided
2605 exactly: an abbreviation will not be accepted.
2607 If +-directory+ is given, the +'dir'+ is understood to contain a
2608 directory name to search in. This allows globbing inside directories
2609 whose names may contain glob-sensitive characters. The returned names
2610 include the directory name unless +'-tails'+ is specified.
2612 If +'-tails'+ is specified, along with +-directory+, the returned names
2613 are relative to the given directory.
2615 global
2616 ~~~~~~
2618 +*global* 'varName ?varName \...?'+
2620 This command is ignored unless a Tcl procedure is being interpreted.
2621 If so, then it declares each given +'varName'+ to be a global variable
2622 rather than a local one.  For the duration of the current procedure
2623 (and only while executing in the current procedure), any reference to
2624 +'varName'+ will be bound to a global variable instead
2625 of a local one.
2627 An alternative to using `global` is to use the +::+ prefix
2628 to explicitly name a variable in the global scope.
2632 +*if* 'expr1' ?*then*? 'body1' *elseif* 'expr2' ?*then*? 'body2' *elseif* \... ?*else*? ?'bodyN'?+
2634 The `if` command evaluates +'expr1'+ as an expression (in the same way
2635 that `expr` evaluates its argument).  The value of the expression must
2636 be numeric; if it is non-zero then +'body1'+ is executed by passing it to
2637 the Tcl interpreter.
2639 Otherwise +'expr2'+ is evaluated as an expression and if it is non-zero
2640 then +'body2'+ is executed, and so on.
2642 If none of the expressions evaluates to non-zero then +'bodyN'+ is executed.
2644 The +then+ and +else+ arguments are optional "noise words" to make the
2645 command easier to read.
2647 There may be any number of +elseif+ clauses, including zero.  +'bodyN'+
2648 may also be omitted as long as +else+ is omitted too.
2650 The return value from the command is the result of the body script that
2651 was executed, or an empty string if none of the expressions was non-zero
2652 and there was no +'bodyN'+.
2654 incr
2655 ~~~~
2656 +*incr* 'varName ?increment?'+
2658 Increment the value stored in the variable whose name is +'varName'+.
2659 The value of the variable must be integral.
2661 If +'increment'+ is supplied then its value (which must be an
2662 integer) is added to the value of variable +'varName'+;  otherwise
2663 1 is added to +'varName'+.
2665 The new value is stored as a decimal string in variable +'varName'+
2666 and also returned as result.
2668 If the variable does not exist, the variable is implicitly created
2669 and set to +0+ first.
2671 info
2672 ~~~~
2674 +*info* 'option ?arg\...?'+::
2676 Provide information about various internals to the Tcl interpreter.
2677 The legal +'option'+'s (which may be abbreviated) are:
2679 +*info args* 'procname'+::
2680     Returns a list containing the names of the arguments to procedure
2681     +'procname'+, in order.  +'procname'+ must be the name of a
2682     Tcl command procedure.
2684 +*info alias* 'command'+::
2685     +'command'+ must be an alias created with `alias`. In which case the target
2686     command and arguments, as passed to `alias` are returned. See `exists -alias`
2688 +*info body* 'procname'+::
2689     Returns the body of procedure +'procname'+.  +'procname'+ must be
2690     the name of a Tcl command procedure.
2692 +*info channels*+::
2693     Returns a list of all open file handles from `open` or `socket`
2695 +*info commands* ?'pattern'?+::
2696     If +'pattern'+ isn't specified, returns a list of names of all the
2697     Tcl commands, including both the built-in commands written in C and
2698     the command procedures defined using the `proc` command.
2699     If +'pattern'+ is specified, only those names matching +'pattern'+
2700     are returned.  Matching is determined using the same rules as for
2701     `string match`.
2703 +*info complete* 'command' ?'missing'?+::
2704     Returns 1 if +'command'+ is a complete Tcl command in the sense of
2705     having no unclosed quotes, braces, brackets or array element names,
2706     If the command doesn't appear to be complete then 0 is returned.
2707     This command is typically used in line-oriented input environments
2708     to allow users to type in commands that span multiple lines;  if the
2709     command isn't complete, the script can delay evaluating it until additional
2710     lines have been typed to complete the command. If +'varName'+ is specified, the
2711     missing character is stored in the variable with that name.
2713 +*info exists* 'varName'+::
2714     Returns '1' if the variable named +'varName'+ exists in the
2715     current context (either as a global or local variable), returns '0'
2716     otherwise.
2718 +*info frame* ?'number'?+::
2719     If +'number'+ is not specified, this command returns a number
2720     which is the same result as `info level` - the current stack frame level.
2721     If +'number'+ is specified, then the result is a list consisting of the procedure,
2722     filename and line number for the procedure call at level +'number'+ on the stack.
2723     If +'number'+ is positive then it selects a particular stack level (1 refers
2724     to the top-most active procedure, 2 to the procedure it called, and
2725     so on); otherwise it gives a level relative to the current level
2726     (0 refers to the current procedure, -1 to its caller, and so on).
2727     The level has an identical meaning to `info level`.
2729 +*info globals* ?'pattern'?+::
2730     If +'pattern'+ isn't specified, returns a list of all the names
2731     of currently-defined global variables.
2732     If +'pattern'+ is specified, only those names matching +'pattern'+
2733     are returned.  Matching is determined using the same rules as for
2734     `string match`.
2736 +*info hostname*+::
2737     An alias for `os.gethostname` for compatibility with Tcl 6.x
2739 +*info level* ?'number'?+::
2740     If +'number'+ is not specified, this command returns a number
2741     giving the stack level of the invoking procedure, or 0 if the
2742     command is invoked at top-level.  If +'number'+ is specified,
2743     then the result is a list consisting of the name and arguments for the
2744     procedure call at level +'number'+ on the stack.  If +'number'+
2745     is positive then it selects a particular stack level (1 refers
2746     to the top-most active procedure, 2 to the procedure it called, and
2747     so on); otherwise it gives a level relative to the current level
2748     (0 refers to the current procedure, -1 to its caller, and so on).
2749     See the `uplevel` command for more information on what stack
2750     levels mean.
2752 +*info locals* ?'pattern'?+::
2753     If +'pattern'+ isn't specified, returns a list of all the names
2754     of currently-defined local variables, including arguments to the
2755     current procedure, if any.  Variables defined with the `global`
2756     and `upvar` commands will not be returned.  If +'pattern'+ is
2757     specified, only those names matching +'pattern'+ are returned.
2758     Matching is determined using the same rules as for `string match`.
2760 +*info nameofexecutable*+::
2761     Returns the name of the binary file from which the application
2762     was invoked. A full path will be returned, unless the path
2763     can't be determined, in which case the empty string will be returned.
2765 +*info procs* ?'pattern'?+::
2766     If +'pattern'+ isn't specified, returns a list of all the
2767     names of Tcl command procedures.
2768     If +'pattern'+ is specified, only those names matching +'pattern'+
2769     are returned.  Matching is determined using the same rules as for
2770     `string match`.
2772 +*info references*+::
2773     Returns a list of all references which have not yet been garbage
2774     collected.
2776 +*info returncodes* ?'code'?+::
2777     Returns a list representing the mapping of standard return codes
2778     to names. e.g. +{0 ok 1 error 2 return \...}+. If a code is given,
2779     instead returns the name for the given code.
2781 +*info script*+::
2782     If a Tcl script file is currently being evaluated (i.e. there is a
2783     call to 'Jim_EvalFile' active or there is an active invocation
2784     of the `source` command), then this command returns the name
2785     of the innermost file being processed.  Otherwise the command returns an
2786     empty string.
2788 +*info source* 'script ?filename line?'+::
2789     With a single argument, returns the original source location of the given script as a list of
2790     +{filename linenumber}+. If the source location can't be determined, the
2791     list +{{} 0}+ is returned. If +'filename'+ and +'line'+ are given, returns a copy
2792     of +'script'+ with the associate source information. This can be useful to produce
2793     useful messages from `eval`, etc. if the original source information may be lost.
2795 +*info stacktrace*+::
2796     After an error is caught with `catch`, returns the stack trace as a list
2797     of +{procedure filename line \...}+.
2799 +*info statics* 'procname'+::
2800     Returns a dictionary of the static variables of procedure
2801     +'procname'+.  +'procname'+ must be the name of a Tcl command
2802     procedure. An empty dictionary is returned if the procedure has
2803     no static variables.
2805 +*info version*+::
2806     Returns the version number for this version of Jim in the form +*x.yy*+.
2808 +*info vars* ?'pattern'?+::
2809     If +'pattern'+ isn't specified,
2810     returns a list of all the names of currently-visible variables, including
2811     both locals and currently-visible globals.
2812     If +'pattern'+ is specified, only those names matching +'pattern'+
2813     are returned.  Matching is determined using the same rules as for
2814     `string match`.
2816 join
2817 ~~~~
2818 +*join* 'list ?joinString?'+
2820 The +'list'+ argument must be a valid Tcl list.  This command returns the
2821 string formed by joining all of the elements of +'list'+ together with
2822 +'joinString'+ separating each adjacent pair of elements.
2824 The +'joinString'+ argument defaults to a space character.
2826 kill
2827 ~~~~
2828 +*kill* ?'SIG'|*-0*? 'pid'+
2830 Sends the given signal to the process identified by +'pid'+.
2832 The signal may be specified by name or number in one of the following forms:
2834 * +TERM+
2835 * +SIGTERM+
2836 * +-TERM+
2837 * +15+
2838 * +-15+
2840 The signal name may be in either upper or lower case.
2842 The special signal name +-0+ simply checks that a signal +'could'+ be sent.
2844 If no signal is specified, SIGTERM is used.
2846 An error is raised if the signal could not be delivered.
2848 lambda
2849 ~~~~~~
2850 +*lambda* 'args ?statics? body'+
2852 The `lambda` command is identical to `proc`, except rather than
2853 creating a named procedure, it creates an anonymous procedure and returns
2854 the name of the procedure.
2856 See `proc` and GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2858 lappend
2859 ~~~~~~~
2860 +*lappend* 'varName value ?value value \...?'+
2862 Treat the variable given by +'varName'+ as a list and append each of
2863 the +'value'+ arguments to that list as a separate element, with spaces
2864 between elements.
2866 If +'varName'+ doesn't exist, it is created as a list with elements given
2867 by the +'value'+ arguments. `lappend` is similar to `append` except that
2868 each +'value'+ is appended as a list element rather than raw text.
2870 This command provides a relatively efficient way to build up large lists.
2871 For example,
2873     lappend a $b
2875 is much more efficient than
2877     set a [concat $a [list $b]]
2879 when +$a+ is long.
2881 lassign
2882 ~~~~~~~
2883 +*lassign* 'list varName ?varName \...?'+
2885 This command treats the value +'list'+ as a list and assigns successive elements from that list to
2886 the variables given by the +'varName'+ arguments in order. If there are more variable names than
2887 list elements, the remaining variables are set to the empty string. If there are more list elements
2888 than variables, a list of unassigned elements is returned.
2890     jim> lassign {1 2 3} a b; puts a=$a,b=$b
2891     3
2892     a=1,b=2
2894 local
2895 ~~~~~
2896 +*local* 'cmd ?arg\...?'+
2898 First, `local` evaluates +'cmd'+ with the given arguments. The return value must
2899 be the name of an existing command, which is marked as having local scope.
2900 This means that when the current procedure exits, the specified
2901 command is deleted. This can be useful with `lambda`, local procedures or
2902 to automatically close a filehandle.
2904 In addition, if a command already exists with the same name,
2905 the existing command will be kept rather than deleted, and may be called
2906 via `upcall`. The previous command will be restored when the current
2907 procedure exits. See `upcall` for more details.
2909 In this example, a local procedure is created. Note that the procedure
2910 continues to have global scope while it is active.
2912     proc outer {} {
2913       # proc ... returns "inner" which is marked local
2914       local proc inner {} {
2915         # will be deleted when 'outer' exits
2916       }
2918       inner
2919       ...
2920     }
2922 In this example, the lambda is deleted at the end of the procedure rather
2923 than waiting until garbage collection.
2925     proc outer {} {
2926       set x [lambda inner {args} {
2927         # will be deleted when 'outer' exits
2928       }]
2929       # Use 'function' here which simply returns $x
2930       local function $x
2932       $x ...
2933       ...
2934     }
2936 loop
2937 ~~~~
2938 +*loop* 'var first limit ?incr? body'+
2940 Similar to `for` except simpler and possibly more efficient.
2941 With a positive increment, equivalent to:
2943   for {set var $first} {$var < $limit} {incr var $incr} $body
2945 If +'incr'+ is not specified, 1 is used.
2946 Note that setting the loop variable inside the loop does not
2947 affect the loop count.
2949 lindex
2950 ~~~~~~
2951 +*lindex* 'list ?index ...?'+
2953 Treats +'list'+ as a Tcl list and returns element +'index'+ from it
2954 (0 refers to the first element of the list).
2955 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2957 In extracting the element, +'lindex'+ observes the same rules concerning
2958 braces and quotes and backslashes as the Tcl command interpreter; however,
2959 variable substitution and command substitution do not occur.
2961 If no index values are given, simply returns +'list'+
2963 If +'index'+ is negative or greater than or equal to the number of elements
2964 in +'list'+, then an empty string is returned.
2966 If additional index arguments are supplied, then each argument is
2967 used in turn to select an element from the previous indexing
2968 operation, allowing the script to select elements from sublists.
2970 linsert
2971 ~~~~~~~
2972 +*linsert* 'list index element ?element element \...?'+
2974 This command produces a new list from +'list'+ by inserting all
2975 of the +'element'+ arguments just before the element +'index'+
2976 of +'list'+. Each +'element'+ argument will become
2977 a separate element of the new list. If +'index'+ is less than
2978 or equal to zero, then the new elements are inserted at the
2979 beginning of the list. If +'index'+ is greater than or equal
2980 to the number of elements in the list, then the new elements are
2981 appended to the list.
2983 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2985 list
2986 ~~~~
2988 +*list* 'arg ?arg \...?'+
2990 This command returns a list comprised of all the arguments, +'arg'+. Braces
2991 and backslashes get added as necessary, so that the `lindex` command
2992 may be used on the result to re-extract the original arguments, and also
2993 so that `eval` may be used to execute the resulting list, with
2994 +'arg1'+ comprising the command's name and the other args comprising
2995 its arguments. `list` produces slightly different results than
2996 `concat`:  `concat` removes one level of grouping before forming
2997 the list, while `list` works directly from the original arguments.
2998 For example, the command
3000     list a b {c d e} {f {g h}}
3002 will return
3004     a b {c d e} {f {g h}}
3006 while `concat` with the same arguments will return
3008     a b c d e f {g h}
3010 llength
3011 ~~~~~~~
3012 +*llength* 'list'+
3014 Treats +'list'+ as a list and returns a decimal string giving
3015 the number of elements in it.
3017 lset
3018 ~~~~
3019 +*lset* 'varName ?index ..? newValue'+
3021 Sets an element in a list.
3023 The `lset` command accepts a parameter, +'varName'+, which it interprets
3024 as the name of a variable containing a Tcl list. It also accepts
3025 zero or more indices into the list. Finally, it accepts a new value
3026 for an element of varName. If no indices are presented, the command
3027 takes the form:
3029     lset varName newValue
3031 In this case, newValue replaces the old value of the variable
3032 varName.
3034 When presented with a single index, the `lset` command
3035 treats the content of the varName variable as a Tcl list. It addresses
3036 the index'th element in it (0 refers to the first element of the
3037 list). When interpreting the list, `lset` observes the same rules
3038 concerning braces and quotes and backslashes as the Tcl command
3039 interpreter; however, variable substitution and command substitution
3040 do not occur. The command constructs a new list in which the
3041 designated element is replaced with newValue. This new list is
3042 stored in the variable varName, and is also the return value from
3043 the `lset` command.
3045 If index is negative or greater than or equal to the number of
3046 elements in $varName, then an error occurs.
3048 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
3050 If additional index arguments are supplied, then each argument is
3051 used in turn to address an element within a sublist designated by
3052 the previous indexing operation, allowing the script to alter
3053 elements in sublists. The command,
3055     lset a 1 2 newValue
3057 replaces element 2 of sublist 1 with +'newValue'+.
3059 The integer appearing in each index argument must be greater than
3060 or equal to zero. The integer appearing in each index argument must
3061 be strictly less than the length of the corresponding list. In other
3062 words, the `lset` command cannot change the size of a list. If an
3063 index is outside the permitted range, an error is reported.
3065 lmap
3066 ~~~~
3068 +*lmap* 'varName list body'+
3070 +*lmap* 'varList list ?varList2 list2 \...? body'+
3072 `lmap` is a "collecting" `foreach` which returns a list of its results.
3074 For example:
3076     jim> lmap i {1 2 3 4 5} {expr $i*$i}
3077     1 4 9 16 25
3078     jim> lmap a {1 2 3} b {A B C} {list $a $b}
3079     {1 A} {2 B} {3 C}
3081 If the body invokes `continue`, no value is added for this iteration.
3082 If the body invokes `break`, the loop ends and no more values are added.
3084 load
3085 ~~~~
3086 +*load* 'filename'+
3088 Loads the dynamic extension, +'filename'+. Generally the filename should have
3089 the extension +.so+. The initialisation function for the module must be based
3090 on the name of the file. For example loading +hwaccess.so+ will invoke
3091 the initialisation function, +Jim_hwaccessInit+. Normally the `load` command
3092 should not be used directly. Instead it is invoked automatically by `package require`.
3094 lrange
3095 ~~~~~~
3096 +*lrange* 'list first last'+
3098 +'list'+ must be a valid Tcl list. This command will return a new
3099 list consisting of elements +'first'+ through +'last'+, inclusive.
3101 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
3103 If +'last'+ is greater than or equal to the number of elements
3104 in the list, then it is treated as if it were +end+.
3106 If +'first'+ is greater than +'last'+ then an empty string
3107 is returned.
3109 Note: +"`lrange` 'list first first'"+ does not always produce the
3110 same result as +"`lindex` 'list first'"+ (although it often does
3111 for simple fields that aren't enclosed in braces); it does, however,
3112 produce exactly the same results as +"`list` [`lindex` 'list first']"+
3114 lreplace
3115 ~~~~~~~~
3117 +*lreplace* 'list first last ?element element \...?'+
3119 Returns a new list formed by replacing one or more elements of
3120 +'list'+ with the +'element'+ arguments.
3122 +'first'+ gives the index in +'list'+ of the first element
3123 to be replaced.
3125 If +'first'+ is less than zero then it refers to the first
3126 element of +'list'+;  the element indicated by +'first'+
3127 must exist in the list.
3129 +'last'+ gives the index in +'list'+ of the last element
3130 to be replaced;  it must be greater than or equal to +'first'+.
3132 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
3134 The +'element'+ arguments specify zero or more new arguments to
3135 be added to the list in place of those that were deleted.
3137 Each +'element'+ argument will become a separate element of
3138 the list.
3140 If no +'element'+ arguments are specified, then the elements
3141 between +'first'+ and +'last'+ are simply deleted.
3143 lrepeat
3144 ~~~~~~~~
3145 +*lrepeat* 'number element1 ?element2 \...?'+
3147 Build a list by repeating elements +'number'+ times (which must be
3148 a positive integer).
3150     jim> lrepeat 3 a b
3151     a b a b a b
3153 lreverse
3154 ~~~~~~~~
3155 +*lreverse* 'list'+
3157 Returns the list in reverse order.
3159     jim> lreverse {1 2 3}
3160     3 2 1
3162 lsearch
3163 ~~~~~~~
3164 +*lsearch* '?options? list pattern'+
3166 This command searches the elements +'list'+ to see if one of them matches +'pattern'+. If so, the
3167 command returns the index of the first matching element (unless the options +-all+, +-inline+ or +-bool+ are
3168 specified.) If not, the command returns -1. The option arguments indicates how the elements of
3169 the list are to be matched against pattern and must have one of the values below:
3171 *Note* that this command is different from Tcl in that default match type is +-exact+ rather than +-glob+.
3173 +*-exact*+::
3174     +'pattern'+ is a literal string that is compared for exact equality against each list element.
3175     This is the default.
3177 +*-glob*+::
3178     +'pattern'+ is a glob-style pattern which is matched against each list element using the same
3179     rules as the string match command.
3181 +*-regexp*+::
3182     +'pattern'+ is treated as a regular expression and matched against each list element using
3183     the rules described by `regexp`.
3185 +*-command* 'cmdname'+::
3186     +'cmdname'+ is a command which is used to match the pattern against each element of the
3187     list. It is invoked as +'cmdname' ?*-nocase*? 'pattern listvalue'+ and should return 1
3188     for a match, or 0 for no match.
3190 +*-all*+::
3191     Changes the result to be the list of all matching indices (or all matching values if
3192     +-inline+ is specified as well). If indices are returned, the indices will be in numeric
3193     order. If values are returned, the order of the values will be the order of those values
3194     within the input list.
3196 +*-inline*+::
3197     The matching value is returned instead of its index (or an empty string if no value
3198     matches). If +-all+ is also specified, then the result of the command is the list of all
3199     values that matched. The +-inline+ and +-bool+ options are mutually exclusive.
3201 +*-bool*+::
3202     Changes the result to '1' if a match was found, or '0' otherwise. If +-all+ is also specified,
3203     the result will be a list of '0' and '1' for each element of the list depending upon whether
3204     the corresponding element matches. The +-inline+ and +-bool+ options are mutually exclusive.
3206 +*-not*+::
3207     This negates the sense of the match, returning the index (or value
3208     if +-inline+ is specified) of the first non-matching value in the
3209     list. If +-bool+ is also specified, the '0' will be returned if a
3210     match is found, or '1' otherwise. If +-all+ is also specified,
3211     non-matches will be returned rather than matches.
3213 +*-nocase*+::
3214     Causes comparisons to be handled in a case-insensitive manner.
3216 lsort
3217 ~~~~~
3218 +*lsort* ?*-index* 'listindex'? ?*-nocase|-integer|-real|-command* 'cmdname'? ?*-unique*? ?*-decreasing*|*-increasing*? 'list'+
3220 Sort the elements of +'list'+, returning a new list in sorted order.
3221 By default, ASCII (or UTF-8) sorting is used, with the result in increasing order.
3223 If +-nocase+ is specified, comparisons are case-insensitive.
3225 If +-integer+ is specified, numeric sorting is used.
3227 If +-real+ is specified, floating point number sorting is used.
3229 If +-command 'cmdname'+ is specified, +'cmdname'+ is treated as a command
3230 name. For each comparison, +'cmdname $value1 $value2+' is called which
3231 should compare the values and return an integer less than, equal
3232 to, or greater than zero if the +'$value1'+ is to be considered less
3233 than, equal to, or greater than +'$value2'+, respectively.
3235 If +-decreasing+ is specified, the resulting list is in the opposite
3236 order to what it would be otherwise. +-increasing+ is the default.
3238 If +-unique+ is specified, then only the last set of duplicate elements found in the list will be retained.
3239 Note that duplicates are determined relative to the comparison used in the sort. Thus if +-index 0+ is used,
3240 +{1 a}+ and +{1 b}+ would be considered duplicates and only the second element, +{1 b}+, would be retained.
3242 If +-index 'listindex'+ is specified, each element of the list is treated as a list and
3243 the given index is extracted from the list for comparison. The list index may
3244 be any valid list index, such as +1+, +end+ or +end-2+.
3246 open
3247 ~~~~
3248 +*open* 'fileName ?access?'+
3250 +*open* '|command-pipeline ?access?'+
3252 Opens a file and returns an identifier
3253 that may be used in future invocations
3254 of commands like `read`, `puts`, and `close`.
3255 +'fileName'+ gives the name of the file to open.
3257 The +'access'+ argument indicates the way in which the file is to be accessed.
3258 It may have any of the following values:
3260 +r+::
3261     Open the file for reading only; the file must already exist.
3263 +r++::
3264     Open the file for both reading and writing; the file must
3265     already exist.
3267 +w+::
3268     Open the file for writing only. Truncate it if it exists. If it doesn't
3269     exist, create a new file.
3271 +w++::
3272     Open the file for reading and writing. Truncate it if it exists.
3273     If it doesn't exist, create a new file.
3275 +a+::
3276     Open the file for writing only. The file must already exist, and the file
3277     is positioned so that new data is appended to the file.
3279 +a++::
3280     Open the file for reading and writing. If the file doesn't
3281     exist, create a new empty file. Set the initial access position
3282     to the end of the file.
3284 +'access'+ defaults to 'r'.
3286 If a file is opened for both reading and writing, then `seek`
3287 must be invoked between a read and a write, or vice versa.
3289 If the first character of +'fileName'+ is "|" then the remaining
3290 characters of +'fileName'+ are treated as a list of arguments that
3291 describe a command pipeline to invoke, in the same style as the
3292 arguments for exec. In this case, the channel identifier returned
3293 by open may be used to write to the command's input pipe or read
3294 from its output pipe, depending on the value of +'access'+. If write-only
3295 access is used (e.g. +'access'+ is 'w'), then standard output for the
3296 pipeline is directed to the current standard output unless overridden
3297 by the command. If read-only access is used (e.g. +'access'+ is r),
3298 standard input for the pipeline is taken from the current standard
3299 input unless overridden by the command.
3301 The `pid` command may be used to return the process ids of the commands
3302 forming the command pipeline.
3304 See also `socket`, `pid`, `exec`
3306 package
3307 ~~~~~~~
3308 +*package provide* 'name ?version?'+
3310 Indicates that the current script provides the package named +'name'+.
3311 If no version is specified, '1.0' is used.
3313 Any script which provides a package may include this statement
3314 as the first statement, although it is not required.
3316 +*package require* 'name ?version?'*+
3318 Searches for the package with the given +'name'+ by examining each path
3319 in '$::auto_path' and trying to load '$path/$name.so' as a dynamic extension,
3320 or '$path/$name.tcl' as a script package.
3322 The first such file which is found is considered to provide the package.
3323 (The version number is ignored).
3325 If '$name.so' exists, it is loaded with the `load` command,
3326 otherwise if '$name.tcl' exists it is loaded with the `source` command.
3328 If `load` or `source` fails, `package require` will fail immediately.
3329 No further attempt will be made to locate the file.
3333 +*pid*+
3335 +*pid* 'fileId'+
3337 The first form returns the process identifier of the current process.
3339 The second form accepts a handle returned by `open` and returns a list
3340 of the process ids forming the pipeline in the same form as `exec ... &`.
3341 If 'fileId' represents a regular file handle rather than a command pipeline,
3342 the empty string is returned instead.
3344 See also `open`, `exec`
3346 proc
3347 ~~~~
3348 +*proc* 'name args ?statics? body'+
3350 The `proc` command creates a new Tcl command procedure, +'name'+.
3351 When the new command is invoked, the contents of +'body'+ will be executed.
3352 Tcl interpreter. +'args'+ specifies the formal arguments to the procedure.
3353 If specified, +'statics'+, declares static variables which are bound to the
3354 procedure.
3356 See PROCEDURES for detailed information about Tcl procedures.
3358 The `proc` command returns +'name'+ (which is useful with `local`).
3360 When a procedure is invoked, the procedure's return value is the
3361 value specified in a `return` command.  If the procedure doesn't
3362 execute an explicit `return`, then its return value is the value
3363 of the last command executed in the procedure's body.
3365 If an error occurs while executing the procedure body, then the
3366 procedure-as-a-whole will return that same error.
3368 puts
3369 ~~~~
3370 +*puts* ?*-nonewline*? '?fileId? string'+
3372 +'fileId' *puts* ?*-nonewline*? 'string'+
3374 Writes the characters given by +'string'+ to the file given
3375 by +'fileId'+. +'fileId'+ must have been the return
3376 value from a previous call to `open`, or it may be
3377 +stdout+ or +stderr+ to refer to one of the standard I/O
3378 channels; it must refer to a file that was opened for
3379 writing.
3381 In the first form, if no +'fileId'+ is specified then it defaults to +stdout+.
3382 `puts` normally outputs a newline character after +'string'+,
3383 but this feature may be suppressed by specifying the +-nonewline+
3384 switch.
3386 Output to files is buffered internally by Tcl; the `flush`
3387 command may be used to force buffered characters to be output.
3391 +*pwd*+
3393 Returns the path name of the current working directory.
3395 rand
3396 ~~~~
3397 +*rand* '?min? ?max?'+
3399 Returns a random integer between +'min'+ (defaults to 0) and +'max'+
3400 (defaults to the maximum integer).
3402 If only one argument is given, it is interpreted as +'max'+.
3404 range
3405 ~~~~
3406 +*range* '?start? end ?step?'+
3408 Returns a list of integers starting at +'start'+ (defaults to 0)
3409 and ranging up to but not including +'end'+ in steps of +'step'+ defaults to 1).
3411     jim> range 5
3412     0 1 2 3 4
3413     jim> range 2 5
3414     2 3 4
3415     jim> range 2 10 4
3416     2 6
3417     jim> range 7 4 -2
3418     7 5
3420 read
3421 ~~~~
3422 +*read* ?*-nonewline*? 'fileId'+
3424 +'fileId' *read* ?*-nonewline*?+
3426 +*read* 'fileId numBytes'+
3428 +'fileId' *read* 'numBytes'+
3431 In the first form, all of the remaining bytes are read from the file
3432 given by +'fileId'+; they are returned as the result of the command.
3433 If the +-nonewline+ switch is specified then the last
3434 character of the file is discarded if it is a newline.
3436 In the second form, the extra argument specifies how many bytes to read;
3437 exactly this many bytes will be read and returned, unless there are fewer than
3438 +'numBytes'+ bytes left in the file; in this case, all the remaining
3439 bytes are returned.
3441 +'fileId'+ must be +stdin+ or the return value from a previous call
3442 to `open`; it must refer to a file that was opened for reading.
3444 regexp
3445 ~~~~~~
3446 +*regexp ?-nocase? ?-line? ?-indices? ?-start* 'offset'? *?-all? ?-inline? ?--?* 'exp string ?matchVar? ?subMatchVar subMatchVar \...?'+
3448 Determines whether the regular expression +'exp'+ matches part or
3449 all of +'string'+ and returns 1 if it does, 0 if it doesn't.
3451 See REGULAR EXPRESSIONS above for complete information on the
3452 syntax of +'exp'+ and how it is matched against +'string'+.
3454 If additional arguments are specified after +'string'+ then they
3455 are treated as the names of variables to use to return
3456 information about which part(s) of +'string'+ matched +'exp'+.
3457 +'matchVar'+ will be set to the range of +'string'+ that
3458 matched all of +'exp'+. The first +'subMatchVar'+ will contain
3459 the characters in +'string'+ that matched the leftmost parenthesized
3460 subexpression within +'exp'+, the next +'subMatchVar'+ will
3461 contain the characters that matched the next parenthesized
3462 subexpression to the right in +'exp'+, and so on.
3464 Normally, +'matchVar'+ and the each +'subMatchVar'+ are set to hold the
3465 matching characters from `string`, however see +-indices+ and
3466 +-inline+ below.
3468 If there are more values for +'subMatchVar'+ than parenthesized subexpressions
3469 within +'exp'+, or if a particular subexpression in +'exp'+ doesn't
3470 match the string (e.g. because it was in a portion of the expression
3471 that wasn't matched), then the corresponding +'subMatchVar'+ will be
3472 set to +"-1 -1"+ if +-indices+ has been specified or to an empty
3473 string otherwise.
3475 The following switches modify the behaviour of +'regexp'+
3477 +*-nocase*+::
3478     Causes upper-case and lower-case characters to be treated as
3479     identical during the matching process.
3481 +*-line*+::
3482     Use newline-sensitive matching. By default, newline
3483     is a completely ordinary character with no special meaning in
3484     either REs or strings. With this flag, +[^+ bracket expressions
3485     and +.+ never match newline, an +^+ anchor matches the null
3486     string after any newline in the string in addition to its normal
3487     function, and the +$+ anchor matches the null string before any
3488     newline in the string in addition to its normal function.
3490 +*-indices*+::
3491     Changes what is stored in the subMatchVars. Instead of
3492     storing the matching characters from string, each variable
3493     will contain a list of two decimal strings giving the indices
3494     in string of the first and last characters in the matching
3495     range of characters.
3497 +*-start* 'offset'+::
3498     Specifies a character index offset into the string at which to start
3499     matching the regular expression. If +-indices+ is
3500     specified, the indices will be indexed starting from the
3501     absolute beginning of the input string. +'offset'+ will be
3502     constrained to the bounds of the input string.
3504 +*-all*+::
3505     Causes the regular expression to be matched as many times as possible
3506     in the string, returning the total number of matches found. If this
3507     is specified with match variables, they will contain information
3508     for the last match only.
3510 +*-inline*+::
3511     Causes the command to return, as a list, the data that would otherwise
3512     be placed in match variables. When using +-inline+, match variables
3513     may not be specified. If used with +-all+, the list will be concatenated
3514     at each iteration, such that a flat list is always returned. For
3515     each match iteration, the command will append the overall match
3516     data, plus one element for each subexpression in the regular
3517     expression.
3519 +*--*+::
3520     Marks the end of switches. The argument following this one will be
3521     treated as +'exp'+ even if it starts with a +-+.
3523 regsub
3524 ~~~~~~
3525 +*regsub ?-nocase? ?-all? ?-line? ?-start* 'offset'? ?*--*? 'exp string subSpec ?varName?'+
3527 This command matches the regular expression +'exp'+ against
3528 +'string'+ using the rules described in REGULAR EXPRESSIONS
3529 above.
3531 If +'varName'+ is specified, the commands stores +'string'+ to +'varName'+
3532 with the substitutions detailed below, and returns the number of
3533 substitutions made (normally 1 unless +-all+ is specified).
3534 This is 0 if there were no matches.
3536 If +'varName'+ is not specified, the substituted string will be returned
3537 instead.
3539 When copying +'string'+, the portion of +'string'+ that
3540 matched +'exp'+ is replaced with +'subSpec'+.
3541 If +'subSpec'+ contains a +&+ or +{backslash}0+, then it is replaced
3542 in the substitution with the portion of +'string'+ that
3543 matched +'exp'+.
3545 If +'subSpec'+ contains a +{backslash}n+, where +'n'+ is a digit
3546 between 1 and 9, then it is replaced in the substitution with
3547 the portion of +'string'+ that matched the +'n'+\'-th
3548 parenthesized subexpression of +'exp'+.
3549 Additional backslashes may be used in +'subSpec'+ to prevent special
3550 interpretation of +&+ or +{backslash}0+ or +{backslash}n+ or
3551 backslash.
3553 The use of backslashes in +'subSpec'+ tends to interact badly
3554 with the Tcl parser's use of backslashes, so it's generally
3555 safest to enclose +'subSpec'+ in braces if it includes
3556 backslashes.
3558 The following switches modify the behaviour of +'regsub'+
3560 +*-nocase*+::
3561     Upper-case characters in +'string'+ are converted to lower-case
3562     before matching against +'exp'+;  however, substitutions
3563     specified by +'subSpec'+ use the original unconverted form
3564     of +'string'+.
3566 +*-all*+::
3567     All ranges in +'string'+ that match +'exp'+ are found and substitution
3568     is performed for each of these ranges, rather than only the
3569     first. The +&+ and +{backslash}n+ sequences are handled for
3570     each substitution using the information from the corresponding
3571     match.
3573 +*-line*+::
3574     Use newline-sensitive matching. By default, newline
3575     is a completely ordinary character with no special meaning in
3576     either REs or strings.  With this flag, +[^+ bracket expressions
3577     and +.+ never match newline, an +^+ anchor matches the null
3578     string after any newline in the string in addition to its normal
3579     function, and the +$+ anchor matches the null string before any
3580     newline in the string in addition to its normal function.
3582 +*-start* 'offset'+::
3583     Specifies a character index offset into the string at which to
3584     start matching the regular expression. +'offset'+ will be
3585     constrained to the bounds of the input string.
3587 +*--*+::
3588     Marks the end of switches. The argument following this one will be
3589     treated as +'exp'+ even if it starts with a +-+.
3593 +*ref* 'string tag ?finalizer?'+
3595 Create a new reference containing +'string'+ of type +'tag'+.
3596 If +'finalizer'+ is specified, it is a command which will be invoked
3597 when the a garbage collection cycle runs and this reference is
3598 no longer accessible.
3600 The finalizer is invoked as:
3602   finalizer reference string
3604 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
3606 rename
3607 ~~~~~~
3608 +*rename* 'oldName newName'+
3610 Rename the command that used to be called +'oldName'+ so that it
3611 is now called +'newName'+.  If +'newName'+ is an empty string
3612 (e.g. {}) then +'oldName'+ is deleted.  The `rename` command
3613 returns an empty string as result.
3615 return
3616 ~~~~~~
3617 +*return* ?*-code* 'code'? ?*-errorinfo* 'stacktrace'? ?*-errorcode* 'errorcode'? ?*-level* 'n'? ?'value'?+
3619 Return immediately from the current procedure (or top-level command
3620 or `source` command), with +'value'+ as the return value.  If +'value'+
3621 is not specified, an empty string will be returned as result.
3623 If +-code+ is specified (as either a number or ok, error, break,
3624 continue, signal, return or exit), this code will be used instead
3625 of +JIM_OK+. This is generally useful when implementing flow of control
3626 commands.
3628 If +-level+ is specified and greater than 1, it has the effect of delaying
3629 the new return code from +-code+. This is useful when rethrowing an error
3630 from `catch`. See the implementation of try/catch in tclcompat.tcl for
3631 an example of how this is done.
3633 Note: The following options are only used when +-code+ is JIM_ERR.
3635 If +-errorinfo+ is specified (as returned from `info stacktrace`)
3636 it is used to initialize the stacktrace.
3638 If +-errorcode+ is specified, it is used to set the global variable $::errorCode.
3640 scan
3641 ~~~~
3642 +*scan* 'string format varName1 ?varName2 \...?'+
3644 This command parses fields from an input string in the same fashion
3645 as the C 'sscanf' procedure.  +'string'+ gives the input to be parsed
3646 and +'format'+ indicates how to parse it, using '%' fields as in
3647 'sscanf'.  All of the 'sscanf' options are valid; see the 'sscanf'
3648 man page for details.  Each +'varName'+ gives the name of a variable;
3649 when a field is scanned from +'string'+, the result is converted back
3650 into a string and assigned to the corresponding +'varName'+.  The
3651 only unusual conversion is for '%c'.  For '%c' conversions a single
3652 character value is converted to a decimal string, which is then
3653 assigned to the corresponding +'varName'+; no field width may be
3654 specified for this conversion.
3656 seek
3657 ~~~~
3658 +*seek* 'fileId offset ?origin?'+
3660 +'fileId' *seek* 'offset ?origin?'+
3662 Change the current access position for +'fileId'+.
3663 The +'offset'+ and +'origin'+ arguments specify the position at
3664 which the next read or write will occur for +'fileId'+.
3665 +'offset'+ must be a number (which may be negative) and +'origin'+
3666 must be one of the following:
3668 +*start*+::
3669     The new access position will be +'offset'+ bytes from the start
3670     of the file.
3672 +*current*+::
3673     The new access position will be +'offset'+ bytes from the current
3674     access position; a negative +'offset'+ moves the access position
3675     backwards in the file.
3677 +*end*+::
3678     The new access position will be +'offset'+ bytes from the end of
3679     the file.  A negative +'offset'+ places the access position before
3680     the end-of-file, and a positive +'offset'+ places the access position
3681     after the end-of-file.
3683 The +'origin'+ argument defaults to +start+.
3685 +'fileId'+ must have been the return value from a previous call to
3686 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
3687 of the standard I/O channels.
3689 This command returns an empty string.
3693 +*set* 'varName ?value?'+
3695 Returns the value of variable +'varName'+.
3697 If +'value'+ is specified, then set the value of +'varName'+ to +'value'+,
3698 creating a new variable if one doesn't already exist, and return
3699 its value.
3701 If +'varName'+ contains an open parenthesis and ends with a
3702 close parenthesis, then it refers to an array element:  the characters
3703 before the open parenthesis are the name of the array, and the characters
3704 between the parentheses are the index within the array.
3705 Otherwise +'varName'+ refers to a scalar variable.
3707 If no procedure is active, then +'varName'+ refers to a global
3708 variable.
3710 If a procedure is active, then +'varName'+ refers to a parameter
3711 or local variable of the procedure, unless the +'global'+ command
3712 has been invoked to declare +'varName'+ to be global.
3714 The +::+ prefix may also be used to explicitly reference a variable
3715 in the global scope.
3717 setref
3718 ~~~~~~
3719 +*setref* 'reference string'+
3721 Store a new string in +'reference'+, replacing the existing string.
3722 The reference must be a valid reference create with the `ref`
3723 command.
3725 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
3727 signal
3728 ~~~~~~
3729 Command for signal handling.
3731 See `kill` for the different forms which may be used to specify signals.
3733 Commands which return a list of signal names do so using the canonical form:
3734 "+SIGINT SIGTERM+".
3736 +*signal handle* ?'signals \...'?+::
3737     If no signals are given, returns a list of all signals which are currently
3738     being handled.
3739     If signals are specified, these are added to the list of signals currently
3740     being handled.
3742 +*signal ignore* ?'signals \...'?+::
3743     If no signals are given, returns a lists all signals which are currently
3744     being ignored.
3745     If signals are specified, these are added to the list of signals
3746     currently being ignored. These signals are still delivered, but
3747     are not considered by `catch -signal` or `try -signal`. Use
3748     `signal check` to determine which signals have occurred but
3749     been ignored.
3751 +*signal default* ?'signals \...'?+::
3752     If no signals are given, returns a lists all signals which are currently have
3753     the default behaviour.
3754     If signals are specified, these are added to the list of signals which have
3755     the default behaviour.
3757 +*signal check ?-clear?* ?'signals \...'?+::
3758     Returns a list of signals which have been delivered to the process
3759     but are 'ignored'. If signals are specified, only that set of signals will
3760     be checked, otherwise all signals will be checked.
3761     If +-clear+ is specified, any signals returned are removed and will not be
3762     returned by subsequent calls to `signal check` unless delivered again.
3764 +*signal throw* ?'signal'?+::
3765     Raises the given signal, which defaults to +SIGINT+ if not specified.
3766     The behaviour is identical to:
3768         kill signal [pid]
3770 Note that `signal handle` and `signal ignore` represent two forms of signal
3771 handling. `signal handle` is used in conjunction with `catch -signal` or `try -signal`
3772 to immediately abort execution when the signal is delivered. Alternatively, `signal ignore`
3773 is used in conjunction with `signal check` to handle signal synchronously. Consider the
3774 two examples below.
3776 Prevent a processing from taking too long
3778     signal handle SIGALRM
3779     alarm 20
3780     try -signal {
3781         .. possibly long running process ..
3782         alarm 0
3783     } on signal {sig} {
3784         puts stderr "Process took too long"
3785     }
3787 Handle SIGHUP to reconfigure:
3789     signal ignore SIGHUP
3790     while {1} {
3791         ... handle configuration/reconfiguration ...
3792         while {[signal check -clear SIGHUP] eq ""} {
3793             ... do processing ..
3794         }
3795         # Received SIGHUP, so reconfigure
3796     }
3798 Note: signal handling is currently not supported in child interpreters.
3799 In these interpreters, the signal command does not exist.
3801 sleep
3802 ~~~~~
3803 +*sleep* 'seconds'+
3805 Pauses for the given number of seconds, which may be a floating
3806 point value less than one to sleep for less than a second, or an
3807 integer to sleep for one or more seconds.
3809 source
3810 ~~~~~~
3811 +*source* 'fileName'+
3813 Read file +'fileName'+ and pass the contents to the Tcl interpreter
3814 as a sequence of commands to execute in the normal fashion.  The return
3815 value of `source` is the return value of the last command executed
3816 from the file.  If an error occurs in executing the contents of the
3817 file, then the `source` command will return that error.
3819 If a `return` command is invoked from within the file, the remainder of
3820 the file will be skipped and the `source` command will return
3821 normally with the result from the `return` command.
3823 split
3824 ~~~~~
3825 +*split* 'string ?splitChars?'+
3827 Returns a list created by splitting +'string'+ at each character
3828 that is in the +'splitChars'+ argument.
3830 Each element of the result list will consist of the
3831 characters from +'string'+ between instances of the
3832 characters in +'splitChars'+.
3834 Empty list elements will be generated if +'string'+ contains
3835 adjacent characters in +'splitChars'+, or if the first or last
3836 character of +'string'+ is in +'splitChars'+.
3838 If +'splitChars'+ is an empty string then each character of
3839 +'string'+ becomes a separate element of the result list.
3841 +'splitChars'+ defaults to the standard white-space characters.
3842 For example,
3844     split "comp.unix.misc" .
3846 returns +'"comp unix misc"'+ and
3848     split "Hello world" {}
3850 returns +'"H e l l o { } w o r l d"'+.
3852 stackdump
3853 ~~~~~~~~~
3855 +*stackdump* 'stacktrace'+
3857 Creates a human readable representation of a stack trace.
3859 stacktrace
3860 ~~~~~~~~~~
3862 +*stacktrace*+
3864 Returns a live stack trace as a list of +proc file line proc file line \...+.
3865 Iteratively uses `info frame` to create the stack trace. This stack trace is in the
3866 same form as produced by `catch` and `info stacktrace`
3868 See also `stackdump`.
3870 string
3871 ~~~~~~
3873 +*string* 'option arg ?arg \...?'+
3875 Perform one of several string operations, depending on +'option'+.
3876 The legal options (which may be abbreviated) are:
3878 +*string bytelength* 'string'+::
3879     Returns the length of the string in bytes. This will return
3880     the same value as `string length` if UTF-8 support is not enabled,
3881     or if the string is composed entirely of ASCII characters.
3882     See UTF-8 AND UNICODE.
3884 +*string byterange* 'string first last'+::
3885     Like `string range` except works on bytes rather than characters.
3886     These commands are identical if UTF-8 support is not enabled.
3888 +*string cat* '?string1 string2 \...?'+::
3889     Concatenates the given strings into a single string.
3891 +*string compare ?-nocase?* ?*-length* 'len? string1 string2'+::
3892     Perform a character-by-character comparison of strings +'string1'+ and
3893     +'string2'+ in the same way as the C 'strcmp' procedure.  Return
3894     -1, 0, or 1, depending on whether +'string1'+ is lexicographically
3895     less than, equal to, or greater than +'string2'+. If +-length+
3896     is specified, then only the first +'len'+ characters are used
3897     in the comparison.  If +'len'+ is negative, it is ignored.
3898     Performs a case-insensitive comparison if +-nocase+ is specified.
3900 +*string equal ?-nocase?* '?*-length* len?' 'string1 string2'+::
3901     Returns 1 if the strings are equal, or 0 otherwise. If +-length+
3902     is specified, then only the first +'len'+ characters are used
3903     in the comparison.  If +'len'+ is negative, it is ignored.
3904     Performs a case-insensitive comparison if +-nocase+ is specified.
3906 +*string first* 'string1 string2 ?firstIndex?'+::
3907     Search +'string2'+ for a sequence of characters that exactly match
3908     the characters in +'string1'+.  If found, return the index of the
3909     first character in the first such match within +'string2'+.  If not
3910     found, return -1. If +'firstIndex'+ is specified, matching will start
3911     from +'firstIndex'+ of +'string1'+.
3912  ::
3913     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'firstIndex'+.
3915 +*string index* 'string charIndex'+::
3916     Returns the +'charIndex'+'th character of the +'string'+
3917     argument.  A +'charIndex'+ of 0 corresponds to the first
3918     character of the string.
3919     If +'charIndex'+ is less than 0 or greater than
3920     or equal to the length of the string then an empty string is
3921     returned.
3922  ::
3923     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'charIndex'+.
3925 +*string is* 'class' ?*-strict*? 'string'+::
3926     Returns 1 if +'string'+ is a valid member of the specified character
3927     class, otherwise returns 0. If +-strict+ is specified, then an
3928     empty string returns 0, otherwise an empty string will return 1
3929     on any class. The following character classes are recognized
3930     (the class name can be abbreviated):
3931   ::
3932   +alnum+;;  Any alphabet or digit character.
3933   +alpha+;;  Any alphabet character.
3934   +ascii+;;  Any character with a value less than 128 (those that are in the 7-bit ascii range).
3935   +boolean+;;  Any of the valid string formats for a boolean value in Tcl (0, false, no, off, 1, true, yes, on)
3936   +control+;; Any control character.
3937   +digit+;;  Any digit character.
3938   +double+;; Any of the valid forms for a double in Tcl, with optional surrounding whitespace.
3939              In case of under/overflow in the value, 0 is returned.
3940   +graph+;;  Any printing character, except space.
3941   +integer+;; Any of the valid string formats for an integer value in Tcl, with optional surrounding whitespace.
3942   +lower+;;  Any lower case alphabet character.
3943   +print+;;  Any printing character, including space.
3944   +punct+;;  Any punctuation character.
3945   +space+;;  Any space character.
3946   +upper+;;  Any upper case alphabet character.
3947   +xdigit+;; Any hexadecimal digit character ([0-9A-Fa-f]).
3948  ::
3949     Note that string classification does +'not'+ respect UTF-8. See UTF-8 AND UNICODE
3950  ::
3951     Note that only +'lowercase'+ boolean values are recognized (Tcl accepts any case).
3953 +*string last* 'string1 string2 ?lastIndex?'+::
3954     Search +'string2'+ for a sequence of characters that exactly match
3955     the characters in +'string1'+.  If found, return the index of the
3956     first character in the last such match within +'string2'+.  If there
3957     is no match, then return -1. If +'lastIndex'+ is specified, only characters
3958     up to +'lastIndex'+ of +'string2'+ will be considered in the match.
3959  ::
3960     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'lastIndex'+.
3962 +*string length* 'string'+::
3963     Returns a decimal string giving the number of characters in +'string'+.
3964     If UTF-8 support is enabled, this may be different than the number of bytes.
3965     See UTF-8 AND UNICODE
3967 +*string map ?-nocase?* 'mapping string'+::
3968     Replaces substrings in +'string'+ based on the key-value pairs in
3969     +'mapping'+, which is a list of +key value key value \...+ as in the form
3970     returned by `array get`. Each instance of a key in the string will be
3971     replaced with its corresponding value.  If +-nocase+ is specified, then
3972     matching is done without regard to case differences. Both key and value may
3973     be multiple characters.  Replacement is done in an ordered manner, so the
3974     key appearing first in the list will be checked first, and so on. +'string'+ is
3975     only iterated over once, so earlier key replacements will have no affect for
3976     later key matches. For example,
3978       string map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc
3980  ::
3981     will return the string +01321221+.
3982  ::
3983     Note that if an earlier key is a prefix of a later one, it will completely mask the later
3984     one.  So if the previous example is reordered like this,
3986       string map {1 0 ab 2 a 3 abc 1} 1abcaababcabababc
3988  ::
3989     it will return the string +02c322c222c+.
3991 +*string match ?-nocase?* 'pattern string'+::
3992     See if +'pattern'+ matches +'string'+; return 1 if it does, 0
3993     if it doesn't.  Matching is done in a fashion similar to that
3994     used by the C-shell.  For the two strings to match, their contents
3995     must be identical except that the following special sequences
3996     may appear in +'pattern'+:
3998     +*+;;
3999         Matches any sequence of characters in +'string'+,
4000         including a null string.
4002     +?+;;
4003         Matches any single character in +'string'+.
4005     +['chars']+;;
4006         Matches any character in the set given by +'chars'+.
4007         If a sequence of the form +'x-y'+ appears in +'chars'+,
4008         then any character between +'x'+ and +'y'+, inclusive,
4009         will match.
4011     +{backslash}x+;;
4012         Matches the single character +'x'+.  This provides a way of
4013         avoiding the special interpretation of the characters +{backslash}*?[]+
4014         in +'pattern'+.
4015  ::
4016     Performs a case-insensitive comparison if +-nocase+ is specified.
4018 +*string range* 'string first last'+::
4019     Returns 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'+.  An index of 0 refers to the
4022     first character of the string.
4023  ::
4024     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
4025  ::
4026     If +'first'+ is less than zero then it is treated as if it were zero, and
4027     if +'last'+ is greater than or equal to the length of the string then
4028     it is treated as if it were +end+.  If +'first'+ is greater than
4029     +'last'+ then an empty string is returned.
4031 +*string repeat* 'string count'+::
4032     Returns a new string consisting of +'string'+ repeated +'count'+ times.
4034 +*string replace* 'string first last ?newstring?'+::
4035     Removes a range of consecutive characters from +'string'+, starting
4036     with the character whose index is +'first'+ and ending with the
4037     character whose index is +'last'+.  If +'newstring'+ is specified,
4038     then it is placed in the removed character range. If +'first'+ is
4039     less than zero then it is treated as if it were zero, and if +'last'+
4040     is greater than or equal to the length of the string then it is
4041     treated as if it were +end+. If +'first'+ is greater than +'last'+
4042     or the length of the initial string, or +'last'+ is less than 0,
4043     then the initial string is returned untouched.
4045 +*string reverse* 'string'+::
4046     Returns a string that is the same length as +'string'+ but
4047     with its characters in the reverse order.
4049 +*string tolower* 'string'+::
4050     Returns a value equal to +'string'+ except that all upper case
4051     letters have been converted to lower case.
4053 +*string totitle* 'string'+::
4054     Returns a value equal to +'string'+ except that the first character
4055     is converted to title case (or upper case if there is no UTF-8 titlecase variant)
4056     and all remaining characters have been converted to lower case.
4058 +*string toupper* 'string'+::
4059     Returns a value equal to +'string'+ except that all lower case
4060     letters have been converted to upper case.
4062 +*string trim* 'string ?chars?'+::
4063     Returns a value equal to +'string'+ except that any leading
4064     or trailing characters from the set given by +'chars'+ are
4065     removed.
4066     If +'chars'+ is not specified then white space is removed
4067     (spaces, tabs, newlines, and carriage returns).
4069 +*string trimleft* 'string ?chars?'+::
4070     Returns a value equal to +'string'+ except that any
4071     leading characters from the set given by +'chars'+ are
4072     removed.
4073     If +'chars'+ is not specified then white space is removed
4074     (spaces, tabs, newlines, and carriage returns).
4076 +*string trimright* 'string ?chars?'+::
4077     Returns a value equal to +'string'+ except that any
4078     trailing characters from the set given by +'chars'+ are
4079     removed.
4080     If +'chars'+ is not specified then white space is removed
4081     (spaces, tabs, newlines, and carriage returns).
4082     Null characters are always removed.
4084 subst
4085 ~~~~~
4086 +*subst ?-nobackslashes? ?-nocommands? ?-novariables?* 'string'+
4088 This command performs variable substitutions, command substitutions,
4089 and backslash substitutions on its string argument and returns the
4090 fully-substituted result. The substitutions are performed in exactly
4091 the same way as for Tcl commands. As a result, the string argument
4092 is actually substituted twice, once by the Tcl parser in the usual
4093 fashion for Tcl commands, and again by the subst command.
4095 If any of the +-nobackslashes+, +-nocommands+, or +-novariables+ are
4096 specified, then the corresponding substitutions are not performed.
4097 For example, if +-nocommands+ is specified, no command substitution
4098 is performed: open and close brackets are treated as ordinary
4099 characters with no special interpretation.
4101 *Note*: when it performs its substitutions, subst does not give any
4102 special treatment to double quotes or curly braces. For example,
4103 the following script returns +xyz \{44\}+, not +xyz \{$a\}+.
4105     set a 44
4106     subst {xyz {$a}}
4109 switch
4110 ~~~~~~
4111 +*switch* '?options? string pattern body ?pattern body \...?'+
4113 +*switch* '?options? string {pattern body ?pattern body \...?}'+
4115 The `switch` command matches its string argument against each of
4116 the pattern arguments in order. As soon as it finds a pattern that
4117 matches string it evaluates the following body and returns the
4118 result of that evaluation. If the last pattern argument is default
4119 then it matches anything. If no pattern argument matches string and
4120 no default is given, then the `switch` command returns an empty string.
4121 If the initial arguments to switch start with - then they are treated
4122 as options. The following options are currently supported:
4124     +-exact+::
4125         Use exact matching when comparing string to a
4126         pattern. This is the default.
4128     +-glob+::
4129         When matching string to the patterns, use glob-style
4130         matching (i.e. the same as implemented by the string
4131         match command).
4133     +-regexp+::
4134         When matching string to the patterns, use regular
4135         expression matching (i.e. the same as implemented
4136         by the regexp command).
4138     +-command 'commandname'+::
4139         When matching string to the patterns, use the given command, which
4140         must be a single word. The command is invoked as
4141         'commandname pattern string', or 'commandname -nocase pattern string'
4142         and must return 1 if matched, or 0 if not.
4144     +--+::
4145         Marks the end of options. The argument following
4146         this one will be treated as string even if it starts
4147         with a +-+.
4149 Two syntaxes are provided for the pattern and body arguments. The
4150 first uses a separate argument for each of the patterns and commands;
4151 this form is convenient if substitutions are desired on some of the
4152 patterns or commands. The second form places all of the patterns
4153 and commands together into a single argument; the argument must
4154 have proper list structure, with the elements of the list being the
4155 patterns and commands. The second form makes it easy to construct
4156 multi-line `switch` commands, since the braces around the whole list
4157 make it unnecessary to include a backslash at the end of each line.
4158 Since the pattern arguments are in braces in the second form, no
4159 command or variable substitutions are performed on them; this makes
4160 the behaviour of the second form different than the first form in
4161 some cases.
4163 If a body is specified as +-+ it means that the body for the next
4164 pattern should also be used as the body for this pattern (if the
4165 next pattern also has a body of +-+ then the body after that is
4166 used, and so on). This feature makes it possible to share a single
4167 body among several patterns.
4169 Below are some examples of `switch` commands:
4171     switch abc a - b {format 1} abc {format 2} default {format 3}
4173 will return 2,
4175     switch -regexp aaab {
4176            ^a.*b$ -
4177            b {format 1}
4178            a* {format 2}
4179            default {format 3}
4180     }
4182 will return 1, and
4184     switch xyz {
4185            a -
4186            b {format 1}
4187            a* {format 2}
4188            default {format 3}
4189     }
4191 will return 3.
4193 tailcall
4194 ~~~~~~~~
4195 +*tailcall* 'cmd ?arg\...?'+
4197 The `tailcall` command provides an optimised way of invoking a command whilst replacing
4198 the current call frame. This is similar to 'exec' in Bourne Shell.
4200 The following are identical except the first immediately replaces the current call frame.
4202   tailcall a b c
4204   return [uplevel 1 [list a b c]]
4206 `tailcall` is useful as a dispatch mechanism:
4208   proc a {cmd args} {
4209     tailcall sub_$cmd {*}$args
4210   }
4211   proc sub_cmd1 ...
4212   proc sub_cmd2 ...
4214 tell
4215 ~~~~
4216 +*tell* 'fileId'+
4218 +'fileId' *tell*+
4220 Returns a decimal string giving the current access position in
4221 +'fileId'+.
4223 +'fileId'+ must have been the return value from a previous call to
4224 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
4225 of the standard I/O channels.
4227 throw
4228 ~~~~~
4229 +*throw* 'code ?msg?'+
4231 This command throws an exception (return) code along with an optional message.
4232 This command is mostly for convenient usage with `try`.
4234 The command +throw break+ is equivalent to +break+.
4235 The command +throw 20 message+ can be caught with an +on 20 \...+ clause to `try`.
4237 time
4238 ~~~~
4239 +*time* 'command ?count?'+
4241 This command will call the Tcl interpreter +'count'+
4242 times to execute +'command'+ (or once if +'count'+ isn't
4243 specified).  It will then return a string of the form
4245     503 microseconds per iteration
4247 which indicates the average amount of time required per iteration,
4248 in microseconds.
4250 Time is measured in elapsed time, not CPU time.
4254 +*try* '?catchopts? tryscript' ?*on* 'returncodes {?resultvar? ?optsvar?} handlerscript \...'? ?*finally* 'finalscript'?+
4256 The `try` command is provided as a convenience for exception handling.
4258 This interpeter first evaluates +'tryscript'+ under the effect of the catch
4259 options +'catchopts'+ (e.g. +-signal -noexit --+, see `catch`).
4261 It then evaluates the script for the first matching 'on' handler
4262 (there many be zero or more) based on the return code from the `try`
4263 section. For example a normal +JIM_ERR+ error will be matched by
4264 an 'on error' handler.
4266 Finally, any +'finalscript'+ is evaluated.
4268 The result of this command is the result of +'tryscript'+, except in the
4269 case where an exception occurs in a matching 'on' handler script or the 'finally' script,
4270 in which case the result is this new exception.
4272 The specified +'returncodes'+ is a list of return codes either as names ('ok', 'error', 'break', etc.)
4273 or as integers.
4275 If +'resultvar'+ and +'optsvar'+ are specified, they are set as for `catch` before evaluating
4276 the matching handler.
4278 For example:
4280     set f [open input]
4281     try -signal {
4282         process $f
4283     } on {continue break} {} {
4284         error "Unexpected break/continue"
4285     } on error {msg opts} {
4286         puts "Dealing with error"
4287         return {*}$opts $msg
4288     } on signal sig {
4289         puts "Got signal: $sig"
4290     } finally {
4291         $f close
4292     }
4294 If break, continue or error are raised, they are dealt with by the matching
4295 handler.
4297 In any case, the file will be closed via the 'finally' clause.
4299 See also `throw`, `catch`, `return`, `error`.
4301 unknown
4302 ~~~~~~~
4303 +*unknown* 'cmdName ?arg arg ...?'+
4305 This command doesn't actually exist as part of Tcl, but Tcl will
4306 invoke it if it does exist.
4308 If the Tcl interpreter encounters a command name for which there
4309 is not a defined command, then Tcl checks for the existence of
4310 a command named `unknown`.
4312 If there is no such command, then the interpreter returns an
4313 error.
4315 If the `unknown` command exists, then it is invoked with
4316 arguments consisting of the fully-substituted name and arguments
4317 for the original non-existent command.
4319 The `unknown` command typically does things like searching
4320 through library directories for a command procedure with the name
4321 +'cmdName'+, or expanding abbreviated command names to full-length,
4322 or automatically executing unknown commands as UNIX sub-processes.
4324 In some cases (such as expanding abbreviations) `unknown` will
4325 change the original command slightly and then (re-)execute it.
4326 The result of the `unknown` command is used as the result for
4327 the original non-existent command.
4329 unset
4330 ~~~~~
4331 +*unset ?-nocomplain? ?--?* '?name name ...?'+
4333 Remove variables.
4334 Each +'name'+ is a variable name, specified in any of the
4335 ways acceptable to the `set` command.
4337 If a +'name'+ refers to an element of an array, then that
4338 element is removed without affecting the rest of the array.
4340 If a +'name'+ consists of an array name with no parenthesized
4341 index, then the entire array is deleted.
4343 The `unset` command returns an empty string as result.
4345 An error occurs if any of the variables doesn't exist, unless '-nocomplain'
4346 is specified. The '--' argument may be specified to stop option processing
4347 in case the variable name may be '-nocomplain'.
4349 upcall
4350 ~~~~~~~
4351 +*upcall* 'command ?args ...?'+
4353 May be used from within a proc defined as `local` `proc` in order to call
4354 the previous, hidden version of the same command.
4356 If there is no previous definition of the command, an error is returned.
4358 uplevel
4359 ~~~~~~~
4360 +*uplevel* '?level? command ?command ...?'+
4362 All of the +'command'+ arguments are concatenated as if they had
4363 been passed to `concat`; the result is then evaluated in the
4364 variable context indicated by +'level'+.  `uplevel` returns
4365 the result of that evaluation.  If +'level'+ is an integer, then
4366 it gives a distance (up the procedure calling stack) to move before
4367 executing the command.  If +'level'+ consists of +\#+ followed by
4368 a number then the number gives an absolute level number.  If +'level'+
4369 is omitted then it defaults to +1+.  +'level'+ cannot be
4370 defaulted if the first +'command'+ argument starts with a digit or +#+.
4372 For example, suppose that procedure 'a' was invoked
4373 from top-level, and that it called 'b', and that 'b' called 'c'.
4374 Suppose that 'c' invokes the `uplevel` command.  If +'level'+
4375 is +1+ or +#2+  or omitted, then the command will be executed
4376 in the variable context of 'b'.  If +'level'+ is +2+ or +#1+
4377 then the command will be executed in the variable context of 'a'.
4379 If +'level'+ is '3' or +#0+ then the command will be executed
4380 at top-level (only global variables will be visible).
4381 The `uplevel` command causes the invoking procedure to disappear
4382 from the procedure calling stack while the command is being executed.
4383 In the above example, suppose 'c' invokes the command
4385     uplevel 1 {set x 43; d}
4387 where 'd' is another Tcl procedure.  The `set` command will
4388 modify the variable 'x' in 'b's context, and 'd' will execute
4389 at level 3, as if called from 'b'.  If it in turn executes
4390 the command
4392     uplevel {set x 42}
4394 then the `set` command will modify the same variable 'x' in 'b's
4395 context:  the procedure 'c' does not appear to be on the call stack
4396 when 'd' is executing.  The command `info level` may
4397 be used to obtain the level of the current procedure.
4399 `uplevel` makes it possible to implement new control
4400 constructs as Tcl procedures (for example, `uplevel` could
4401 be used to implement the `while` construct as a Tcl procedure).
4403 upvar
4404 ~~~~~
4405 +*upvar* '?level? otherVar myVar ?otherVar myVar ...?'+
4407 This command arranges for one or more local variables in the current
4408 procedure to refer to variables in an enclosing procedure call or
4409 to global variables.
4411 +'level'+ may have any of the forms permitted for the `uplevel`
4412 command, and may be omitted if the first letter of the first +'otherVar'+
4413 isn't +#+ or a digit (it defaults to '1').
4415 For each +'otherVar'+ argument, `upvar` makes the variable
4416 by that name in the procedure frame given by +'level'+ (or at
4417 global level, if +'level'+ is +#0+) accessible
4418 in the current procedure by the name given in the corresponding
4419 +'myVar'+ argument.
4421 The variable named by +'otherVar'+ need not exist at the time of the
4422 call;  it will be created the first time +'myVar'+ is referenced, just like
4423 an ordinary variable.
4425 `upvar` may only be invoked from within procedures.
4427 `upvar` returns an empty string.
4429 The `upvar` command simplifies the implementation of call-by-name
4430 procedure calling and also makes it easier to build new control constructs
4431 as Tcl procedures.
4432 For example, consider the following procedure:
4434     proc add2 name {
4435         upvar $name x
4436         set x [expr $x+2]
4437     }
4439 'add2' is invoked with an argument giving the name of a variable,
4440 and it adds two to the value of that variable.
4441 Although 'add2' could have been implemented using `uplevel`
4442 instead of `upvar`, `upvar` makes it simpler for 'add2'
4443 to access the variable in the caller's procedure frame.
4445 while
4446 ~~~~~
4447 +*while* 'test body'+
4449 The +'while'+ command evaluates +'test'+ as an expression
4450 (in the same way that `expr` evaluates its argument).
4451 The value of the expression must be numeric; if it is non-zero
4452 then +'body'+ is executed by passing it to the Tcl interpreter.
4454 Once +'body'+ has been executed then +'test'+ is evaluated
4455 again, and the process repeats until eventually +'test'+
4456 evaluates to a zero numeric value.  `continue`
4457 commands may be executed inside +'body'+ to terminate the current
4458 iteration of the loop, and `break`
4459 commands may be executed inside +'body'+ to cause immediate
4460 termination of the `while` command.
4462 The `while` command always returns an empty string.
4464 OPTIONAL-EXTENSIONS
4465 -------------------
4467 The following extensions may or may not be available depending upon
4468 what options were selected when Jim Tcl was built.
4470 [[cmd_1]]
4471 posix: os.fork, os.wait, os.gethostname, os.getids, os.uptime
4472 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4473 +*os.fork*+::
4474     Invokes 'fork(2)' and returns the result.
4476 +*os.wait -nohang* 'pid'+::
4477     Invokes waitpid(2), with WNOHANG if +-nohang+ is specified.
4478     Returns a list of 3 elements.
4480    {0 none 0} if -nohang is specified, and the process is still alive.
4482    {-1 error <error-description>} if the process does not exist or has already been waited for.
4484    {<pid> exit <exit-status>} if the process exited normally.
4486    {<pid> signal <signal-number>} if the process terminated on a signal.
4488    {<pid> other 0} otherwise (core dump, stopped, continued, etc.)
4490 +*os.gethostname*+::
4491     Invokes 'gethostname(3)' and returns the result.
4493 +*os.getids*+::
4494     Returns the various user/group ids for the current process.
4496     jim> os.getids
4497     uid 1000 euid 1000 gid 100 egid 100
4499 +*os.uptime*+::
4500     Returns the number of seconds since system boot. See description of 'uptime' in 'sysinfo(2)'.
4502 ANSI I/O (aio) and EVENTLOOP API
4503 --------------------------------
4504 Jim provides an alternative object-based API for I/O.
4506 See `open` and `socket` for commands which return an I/O handle.
4510 +$handle *accept* ?addrvar?+::
4511     Server socket only: Accept a connection and return stream.
4512     If +'addrvar'+ is specified, the address of the connected client is stored
4513     in the named variable in the form 'addr:port'. See `socket` for details.
4515 +$handle *buffering none|line|full*+::
4516     Sets the buffering mode of the stream.
4518 +$handle *close* ?r(ead)|w(rite)?+::
4519     Closes the stream.
4520     The  two-argument form is a "half-close" on a socket. See the +shutdown(2)+ man page.
4522 +$handle *copyto* 'tofd ?size?'+::
4523     Copy bytes to the file descriptor +'tofd'+. If +'size'+ is specified, at most
4524     that many bytes will be copied. Otherwise copying continues until the end
4525     of the input file. Returns the number of bytes actually copied.
4527 +$handle *eof*+::
4528     Returns 1 if stream is at eof
4530 +$handle *filename*+::
4531     Returns the original filename associated with the handle.
4532     Handles returned by `socket` give the socket type instead of a filename.
4534 +$handle *flush*+::
4535     Flush the stream
4537 +$handle *gets* '?var?'+::
4538     Read one line and return it or store it in the var
4540 +$handle *isatty*+::
4541     Returns 1 if the stream is a tty device.
4543 +$handle *lock*+::
4544     Apply a POSIX lock to the open file associated with the handle using
4545     fcntl(2).
4546     The handle must be open for write access.
4547     Returns 1 if the lock was successfully obtained, 0 otherwise.
4548     An error occurs if the handle is not suitable for locking (e.g.
4549     if it is not open for write)
4551 +$handle *ndelay ?0|1?*+::
4552     Set O_NDELAY (if arg). Returns current/new setting.
4553     Note that in general ANSI I/O interacts badly with non-blocking I/O.
4554     Use with care.
4556 +$handle *puts ?-nonewline?* 'str'+::
4557     Write the string, with newline unless -nonewline
4559 +$handle *read ?-nonewline?* '?len?'+::
4560     Read and return bytes from the stream. To eof if no len.
4562 +$handle *recvfrom* 'maxlen ?addrvar?'+::
4563     Receives a message from the handle via recvfrom(2) and returns it.
4564     At most +'maxlen'+ bytes are read.
4565     If +'addrvar'+ is specified, the sending address of the message is stored in
4566     the named variable in the form 'addr:port'. See `socket` for details.
4568 +$handle *seek* 'offset' *?start|current|end?*+::
4569     Seeks in the stream (default 'current')
4571 +$handle *sendto* 'str ?addr:?port'+::
4572     Sends the string, +'str'+, to the given address via the socket using sendto(2).
4573     This is intended for udp/dgram sockets and may give an error or behave in unintended
4574     ways for other handle types.
4575     Returns the number of bytes written.
4577 +$handle *sockopt* '?name value?'+::
4578     With no arguments, returns a dictionary of socket options currently set for the handle
4579         (will be empty for a non-socket). With +'name'+ and +'value'+, sets the socket option
4580         to the given value. Currently supports the following boolean socket options:
4581         +broadcast, debug, keepalive, nosigpipe, oobinline, tcp_nodelay+, and the following
4582         integer socket options: +sndbuf, rcvbuf+
4584 +$handle *sync*+::
4585     Flush the stream, then fsync(2) to commit any changes to storage.
4586     Only available on platforms that support fsync(2).
4588 +$handle *tell*+::
4589     Returns the current seek position
4591 +$handle *tty* ?settings?+::
4592         If no arguments are given, returns a dictionary containing the tty settings for the stream.
4593         If arguments are given, they must either be a dictionary, or +setting value \...+
4594         Abbrevations are supported for both settings and values, so the following is acceptable:
4595         +$f tty parity e input c out raw+.
4596     Only available on platforms that support termios(3). Supported settings are:
4598     +*baud* 'rate'+;;
4599         Baud rate. e.g. 115200
4601     +*data 5|6|7|8*+;;
4602         Number of data bits
4604     +*stop 1|2*+;;
4605         Number of stop bits
4607     +*parity even|odd|none*+;;
4608         Parity setting
4610     +*handshake xonxoff|rtscts|none*+;;
4611                 Handshaking type
4613     +*input raw|cooked*+;;
4614                 Input character processing. In raw mode, the usual key sequences such as ^C do
4615                 not generate signals.
4617     +*output raw|cooked*+;;
4618                 Output character processing. Typically CR -> CRNL is disabled in raw mode.
4620     +*vmin* 'numchars'+;;
4621                 Minimum number of characters to read.
4623     +*vtime* 'time'+;;
4624                 Timeout for noncanonical read (units of 0.1 seconds)
4626 +$handle *ssl* *?-server cert priv?*+::
4627     Initiates a SSL/TLS session and returns a new stream
4629 +$handle *unlock*+::
4630     Release a POSIX lock previously acquired by `aio lock`.
4632 +$handle *verify*+::
4633     Verifies the certificate of a SSL/TLS stream peer
4635 +*load_ssl_certs* 'dir'+::
4636     Loads SSL/TLS CA certificates for use during verification
4638 fconfigure
4639 ~~~~~~~~~~
4640 +*fconfigure* 'handle' *?-blocking 0|1? ?-buffering noneline|full? ?-translation* 'mode'?+::
4641     For compatibility with Tcl, a limited form of the `fconfigure`
4642     command is supported.
4643     * `fconfigure ... -blocking` maps to `aio ndelay`
4644     * `fconfigure ... -buffering` maps to `aio buffering`
4645     * `fconfigure ... -translation` is accepted but ignored
4647 [[cmd_2]]
4648 eventloop: after, vwait, update
4649 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4651 The following commands allow a script to be invoked when the given condition occurs.
4652 If no script is given, returns the current script. If the given script is the empty, the
4653 handler is removed.
4655 +$handle *readable* '?readable-script?'+::
4656     Sets or returns the script for when the socket is readable.
4658 +$handle *writable* '?writable-script?'+::
4659     Sets or returns the script for when the socket is writable.
4661 +$handle *onexception* '?exception-script?'+::
4662     Sets or returns the script for when oob data received.
4664 For compatibility with 'Tcl', these may be prefixed with `fileevent`.  e.g.
4666  ::
4667     +fileevent $handle *readable* '\...'+
4669 Time-based execution is also available via the eventloop API.
4671 +*after* 'ms'+::
4672     Sleeps for the given number of milliseconds. No events are
4673     processed during this time.
4675 +*after* 'ms'|*idle* 'script ?script \...?'+::
4676     The scripts are concatenated and executed after the given
4677     number of milliseconds have elapsed.  If 'idle' is specified,
4678     the script will run the next time the event loop is processed
4679     with `vwait` or `update`. The script is only run once and
4680     then removed.  Returns an event id.
4682 +*after cancel* 'id|command'+::
4683     Cancels an `after` event with the given event id or matching
4684     command (script).  Returns the number of milliseconds
4685     remaining until the event would have fired.  Returns the
4686     empty string if no matching event is found.
4688 +*after info* '?id?'+::
4689     If +'id'+ is not given, returns a list of current `after`
4690     events.  If +'id'+ is given, returns a list containing the
4691     associated script and either 'timer' or 'idle' to indicated
4692     the type of the event. An error occurs if +'id'+ does not
4693     match an event.
4695 +*vwait* 'variable'+::
4696     A call to `vwait` enters the eventloop. `vwait` processes
4697     events until the named (global) variable changes or all
4698     event handlers are removed. The variable need not exist
4699     beforehand.  If there are no event handlers defined, `vwait`
4700     returns immediately.
4702 +*update ?idletasks?*+::
4703     A call to `update` enters the eventloop to process expired events, but
4704     no new events. If 'idletasks' is specified, only expired time events are handled,
4705     not file events.
4706     Returns once handlers have been run for all expired events.
4708 Scripts are executed at the global scope. If an error occurs during a handler script,
4709 an attempt is made to call (the user-defined command) `bgerror` with the details of the error.
4710 If the `bgerror` command does not exist, the error message details are printed to stderr instead.
4712 If a file event handler script generates an error, the handler is automatically removed
4713 to prevent infinite errors. (A time event handler is always removed after execution).
4715 +*bgerror* 'msg'+::
4716     Called when an event handler script generates an error. Note that the normal command resolution
4717     rules are used for bgerror. First the name is resolved in the current namespace, then in the
4718     global scope.
4720 socket
4721 ~~~~~~
4722 Various socket types may be created.
4724 +*socket unix* 'path'+::
4725     A unix domain socket client.
4727 +*socket unix.server* 'path'+::
4728     A unix domain socket server.
4730 +*socket ?-ipv6? stream* 'addr:port'+::
4731     A TCP socket client. (See the forms for +'addr'+ below)
4733 +*socket ?-ipv6? stream.server* '?addr:?port'+::
4734     A TCP socket server (+'addr'+ defaults to +0.0.0.0+ for IPv4 or +[::]+ for IPv6).
4736 +*socket ?-ipv6? dgram* ?'addr:port'?+::
4737     A UDP socket client. If the address is not specified,
4738     the client socket will be unbound and 'sendto' must be used
4739     to indicated the destination.
4741 +*socket ?-ipv6? dgram.server* 'addr:port'+::
4742     A UDP socket server.
4744 +*socket pipe*+::
4745     A pipe. Note that unlike all other socket types, this command returns
4746     a list of two channels: {read write}
4748 +*socket pair*+::
4749     A socketpair (see socketpair(2)). Like `socket pipe`, this command returns
4750     a list of two channels: {s1 s2}. These channels are both readable and writable.
4752 This command creates a socket connected (client) or bound (server) to the given
4753 address.
4755 The returned value is channel and may generally be used with the various file I/O
4756 commands (gets, puts, read, etc.), either as object-based syntax or Tcl-compatible syntax.
4758     . set f [socket stream www.google.com:80]
4759     aio.sockstream1
4760     . $f puts -nonewline "GET / HTTP/1.0\r\n\r\n"
4761     . $f gets
4762     HTTP/1.0 302 Found
4763     . $f close
4765 Server sockets, however support only 'accept', which is most useful in conjunction with
4766 the EVENTLOOP API.
4768     set f [socket stream.server 80]
4769     $f readable {
4770         set client [$f accept]
4771         $client gets $buf
4772         ...
4773         $client puts -nonewline "HTTP/1.1 404 Not found\r\n"
4774         $client close
4775     }
4776     vwait done
4778 The address, +'addr'+, can be given in one of the following forms:
4780 1. For IPv4 socket types, an IPv4 address such as 192.168.1.1
4781 2. For IPv6 socket types, an IPv6 address such as [fe80::1234] or [::]
4782 3. A hostname
4784 Note that on many systems, listening on an IPv6 address such as [::] will
4785 also accept requests via IPv4.
4787 Where a hostname is specified, the +'first'+ returned address is used
4788 which matches the socket type is used.
4790 The special type 'pipe' isn't really a socket.
4792     lassign [socket pipe] r w
4794     # Must close $w after exec
4795     exec ps >@$w &
4796     $w close
4798     $r readable ...
4800 syslog
4801 ~~~~~~
4802 +*syslog* '?options? ?priority? message'+
4804 This  command sends message to system syslog facility with given
4805 priority. Valid priorities are:
4807     emerg, alert, crit, err, error, warning, notice, info, debug
4809 If a message is specified, but no priority is specified, then a
4810 priority of info is used.
4812 By default, facility user is used and the value of global tcl variable
4813 argv0 is used as ident string. However, any of the following options
4814 may be specified before priority to control these parameters:
4816 +*-facility* 'value'+::
4817     Use specified facility instead of user. The following
4818     values for facility are recognized:
4820     authpriv, cron, daemon, kernel, lpr, mail, news, syslog, user,
4821     uucp, local0-local7
4823 +*-ident* 'string'+::
4824     Use given string instead of argv0 variable for ident string.
4826 +*-options* 'integer'+::
4827     Set syslog options such as +LOG_CONS+, +LOG_NDELAY+. You should
4828     use numeric values of those from your system syslog.h file,
4829     because I haven't got time to implement yet another hash
4830     table.
4832 pack: pack, unpack
4833 ~~~~~~~~~~~~~~~~~~
4834 The optional 'pack' extension provides commands to encode and decode binary strings.
4836 +*pack* 'varName value' *-intle|-intbe|-floatle|-floatbe|-str* 'bitwidth ?bitoffset?'+::
4837     Packs the binary representation of +'value'+ into the variable
4838     +'varName'+. The value is packed according to the given type
4839     (integer/floating point/string, big-endian/little-endian), width and bit offset.
4840     The variable is created if necessary (like `append`).
4841     The variable is expanded if necessary.
4843 +*unpack* 'binvalue' *-intbe|-intle|-uintbe|-uintle|-floatbe|-floatle|-str* 'bitpos bitwidth'+::
4844     Unpacks bits from +'binvalue'+ at bit position +'bitpos'+ and with +'bitwidth'+.
4845     Interprets the value according to the type (integer/floating point/string, big-endian/little-endian
4846     and signed/unsigned) and returns it. For integer types, +'bitwidth'+
4847     may be up to the size of a Jim Tcl integer (typically 64 bits). For floating point types,
4848     +'bitwidth'+ may be 32 bits (for single precision numbers) or 64 bits (for double precision).
4849     For the string type, both the width and the offset must be on a byte boundary (multiple of 8). Attempting to
4850     access outside the length of the value will return 0 for integer types, 0.0 for floating point types
4851     or the empty string for the string type.
4853 zlib
4854 ~~~~
4855 The optional 'zlib' extension provides a Tcl-compatible subset of the `zlib` command.
4857 +*crc32* 'data' '?startValue?'+::
4858     Returns the CRC32 checksum of a buffer. Optionally, an initial value may be specified; this is most useful
4859     for calculating the checksum of chunked data read from a stream (for instance, a pipe).
4861 +*deflate* 'string' '?level?'+::
4862     Compresses a buffer and outputs a raw, Deflate-compressed stream. Optionally, a compression level (1-9) may
4863     be specified to choose the desired speed vs. compression rate ratio.
4865 +*inflate* 'data' '?bufferSize?'+::
4866     Decompresses a raw, Deflate-compressed stream. When the uncompressed data size is known and specified, memory
4867     allocation is more efficient. Otherwise, decomperssion is chunked and therefore slower.
4869 +*gzip* 'string' '?-level level?'+::
4870     Compresses a buffer and adds a gzip header.
4872 +*gunzip* 'data' '?-buffersize size?'+::
4873     Decompresses a gzip-compressed buffer. Decompression is chunked, with a default, small buffer size of 64K
4874     which guarantees lower memory footprint at the cost of speed. It is recommended to use a bigger size, on
4875     systems without a severe memory constraint.
4877 binary
4878 ~~~~~~
4879 The optional, pure-Tcl 'binary' extension provides the Tcl-compatible `binary scan` and `binary format`
4880 commands based on the low-level `pack` and `unpack` commands.
4882 See the Tcl documentation at: http://www.tcl.tk/man/tcl8.5/TclCmd/binary.htm
4884 Note that 'binary format' with f/r/R specifiers (single-precision float) uses the value of Infinity
4885  in case of overflow.
4887 oo: class, super
4888 ~~~~~~~~~~~~~~~~
4889 The optional, pure-Tcl 'oo' extension provides object-oriented (OO) support for Jim Tcl.
4891 See the online documentation (http://jim.tcl.tk/index.html/doc/www/www/documentation/oo/) for more details.
4893 +*class* 'classname ?baseclasses? classvars'+::
4894     Create a new class, +'classname'+, with the given dictionary
4895     (+'classvars'+) as class variables. These are the initial variables
4896     which all newly created objects of this class are initialised with.
4897     If a list of baseclasses is given, methods and instance variables
4898     are inherited.
4900 +*super* 'method ?args \...?'+::
4901     From within a method, invokes the given method on the base class.
4902     Note that this will only call the last baseclass given.
4904 tree
4905 ~~~~
4906 The optional, pure-Tcl 'tree' extension implements an OO, general purpose tree structure
4907 similar to that provided by tcllib ::struct::tree (http://core.tcl.tk/tcllib/doc/trunk/embedded/www/tcllib/files/modules/struct/struct_tree.html)
4909 A tree is a collection of nodes, where each node (except the root node) has a single parent
4910 and zero or more child nodes (ordered), as well as zero or more attribute/value pairs.
4912 +*tree*+::
4913     Creates and returns a new tree object with a single node named "root".
4914     All operations on the tree are invoked through this object.
4916 +$tree *destroy*+::
4917     Destroy the tree and all it's nodes. (Note that the tree will also
4918     be automatically garbage collected once it goes out of scope).
4920 +$tree *set* 'nodename key value'+::
4921     Set the value for the given attribute key.
4923 +$tree *lappend* 'nodename key value \...'+::
4924     Append to the (list) value(s) for the given attribute key, or set if not yet set.
4926 +$tree *keyexists* 'nodename key'+::
4927     Returns 1 if the given attribute key exists.
4929 +$tree *get* 'nodename key'+::
4930     Returns the value associated with the given attribute key.
4932 +$tree *getall* 'nodename'+::
4933     Returns the entire attribute dictionary associated with the given key.
4935 +$tree *depth* 'nodename'+::
4936     Returns the depth of the given node. The depth of "root" is 0.
4938 +$tree *parent* 'nodename'+::
4939     Returns the node name of the parent node, or "" for the root node.
4941 +$tree *numchildren* 'nodename'+::
4942     Returns the number of child nodes.
4944 +$tree *children* 'nodename'+::
4945     Returns a list of the child nodes.
4947 +$tree *next* 'nodename'+::
4948     Returns the next sibling node, or "" if none.
4950 +$tree *insert* 'nodename ?index?'+::
4951     Add a new child node to the given node. The index is a list index
4952     such as +3+ or +end-2+. The default index is +end+.
4953     Returns the name of the newly added node.
4955 +$tree *walk* 'nodename' *dfs|bfs* {'actionvar nodevar'} 'script'+::
4956     Walks the tree starting from the given node, either breadth first (+bfs+)
4957     depth first (+dfs+).
4958     The value +"enter"+ or +"exit"+ is stored in variable +'actionvar'+.
4959     The name of each node is stored in +'nodevar'+.
4960     The script is evaluated twice for each node, on entry and exit.
4962 +$tree *dump*+::
4963     Dumps the tree contents to stdout
4965 tcl::prefix
4966 ~~~~~~~~~~~
4967 The optional tclprefix extension provides the Tcl8.6-compatible `tcl::prefix` command
4968 (http://www.tcl.tk/man/tcl8.6/TclCmd/prefix.htm) for matching strings against a table
4969 of possible values (typically commands or options).
4971 +*tcl::prefix all* 'table string'+::
4972     Returns a list of all elements in +'table'+ that begin with the prefix +'string'+.
4974 +*tcl::prefix longest* 'table string'+::
4975     Returns the longest common prefix of all elements in +'table'+ that begin with the prefix +'string'+.
4977 +*tcl::prefix match* '?options? table string'+::
4978     If +'string'+ equals one element in +'table'+ or is a prefix to
4979     exactly one element, the matched element is returned. If not, the
4980     result depends on the +-error+ option.
4982     * +*-exact*+ Accept only exact matches.
4983     * +*-message* 'string'+ Use +'string'+ in the error message at a mismatch. Default is "option".
4984     * +*-error* 'options'+ The options are used when no match is found. If +'options'+ is
4985       empty, no error is generated and an empty string is returned.
4986       Otherwise the options are used as return options when
4987       generating the error message. The default corresponds to
4988       setting +-level 0+.
4990 tcl::autocomplete
4991 ~~~~~~~~~~~~~~~~~
4992 Scriptable command line completion is supported in the interactive shell, 'jimsh', through
4993 the `tcl::autocomplete` callback. A simple implementation is provided, however this may
4994 be replaced with a custom command instead if desired.
4996 In the interactive shell, press <TAB> to activate command line completion.
4998 +*tcl::autocomplete* 'commandline'+::
4999         This command is called with the current command line when the user presses <TAB>.
5000         The command should return a list of all possible command lines that match the current command line.
5001         For example if +*pr*+ is the current command line, the list +*{prefix proc}*+ may be returned.
5003 history
5004 ~~~~~~~
5005 The optional history extension provides script access to the command line editing
5006 and history support available in 'jimsh'. See 'examples/jtclsh.tcl' for an example.
5007 Note: if line editing support is not available, `history getline` acts like `gets` and
5008 the remaining subcommands do nothing.
5010 +*history load* 'filename'+::
5011     Load history from a (text) file. If the file does not exist or is not readable,
5012     it is ignored.
5014 +*history getline* 'prompt ?varname?'+::
5015     Displays the given prompt and allows a line to be entered. Similarly to `gets`,
5016     if +'varname'+ is given, it receives the line and the length of the line is returned,
5017     or -1 on EOF. If +'varname'+ is not given, the line is returned directly.
5019 +*history completion* 'command'+::
5020     Sets an autocompletion command (see `tcl::autocomplete`) that is active during `history getline`.
5021         If the command is empty, autocompletion is disabled.
5023 +*history add* 'line'+::
5024     Adds the given line to the history buffer.
5026 +*history save* 'filename'+::
5027     Saves the current history buffer to the given file.
5029 +*history show*+::
5030     Displays the current history buffer to standard output.
5032 namespace
5033 ~~~~~~~~~
5034 Provides namespace-related functions. See also: http://www.tcl.tk/man/tcl8.6/TclCmd/namespace.htm
5036 +*namespace code* 'script'+::
5037     Captures the current namespace context for later execution of
5038     the script +'script'+. It returns a new script in which script has
5039     been wrapped in a +*namespace inscope*+ command.
5041 +*namespace current*+::
5042     Returns the fully-qualified name for the current namespace.
5044 +*namespace delete* '?namespace ...?'+::
5045     Deletes all commands and variables with the given namespace prefixes.
5047 +*namespace eval* 'namespace arg ?arg...?'+::
5048     Activates a namespace called +'namespace'+ and evaluates some code in that context.
5050 +*namespace origin* 'command'+::
5051     Returns the fully-qualified name of the original command to which the imported command +'command'+ refers.
5053 +*namespace parent* ?namespace?+::
5054     Returns the fully-qualified name of the parent namespace for namespace +'namespace'+, if given, otherwise
5055     for the current namespace.
5057 +*namespace qualifiers* 'string'+::
5058     Returns any leading namespace qualifiers for +'string'+
5060 +*namespace tail* 'string'+::
5061     Returns the simple name at the end of a qualified string.
5063 +*namespace upvar* 'namespace ?arg...?'+::
5064     This command arranges for zero or more local variables in the current procedure to refer to variables in +'namespace'+
5066 +*namespace which* '?-command|-variable? name'+::
5067     Looks up +'name'+ as either a command (the default) or variable and returns its fully-qualified name.
5069 interp
5070 ~~~~~~
5071 The optional 'interp' command allows sub-interpreters to be created where commands may be run
5072 independently (but synchronously) of the main interpreter.
5074 +*interp*+::
5075     Creates and returns a new interpreter object (command).
5076         The created interpeter contains any built-in commands along with static extensions,
5077         but does not include any dynamically loaded commands (package require, load).
5078         These must be reloaded in the child interpreter if required.
5080 +*$interp delete*+::
5081     Deletes the interpeter object.
5083 +*$interp eval* 'script' ...+::
5084         Evaluates a script in the context for the child interpreter, in the same way as 'eval'.
5086 +*$interp alias* 'alias childcmd parentcmd ?arg ...?'+::
5087         Similar to 'alias', but creates a command, +'childcmd'+, in the child interpreter that is an
5088         alias for +'parentcmd'+ in the parent interpreter, with the given, fixed arguments.
5089         The alias may be deleted in the child with 'rename'.
5091 [[BuiltinVariables]]
5092 BUILT-IN VARIABLES
5093 ------------------
5095 The following global variables are created automatically
5096 by the Tcl library.
5098 +*env*+::
5099     This variable is set by Jim as an array
5100     whose elements are the environment variables for the process.
5101     Reading an element will return the value of the corresponding
5102     environment variable.
5103     This array is initialised at startup from the `env` command.
5104     It may be modified and will affect the environment passed to
5105     commands invoked with `exec`.
5107 +*platform_tcl*+::
5108     This variable is set by Jim as an array containing information
5109     about the platform on which Jim was built. Currently this includes
5110     'os' and 'platform'.
5112 +*auto_path*+::
5113     This variable contains a list of paths to search for packages.
5114     It defaults to a location based on where jim is installed
5115     (e.g. +/usr/local/lib/jim+), but may be changed by +jimsh+
5116     or the embedding application. Note that +jimsh+ will consider
5117     the environment variable +$JIMLIB+ to be a list of colon-separated
5118     list of paths to add to +*auto_path*+.
5120 +*errorCode*+::
5121     This variable holds the value of the -errorcode return
5122     option set by the most recent error that occurred in this
5123     interpreter. This list value represents additional information
5124     about the error in a form that is easy to process with
5125     programs. The first element of the list identifies a general
5126     class of errors, and determines the format of the rest of
5127     the list. The following formats for -errorcode return options
5128     are used by the Tcl core; individual applications may define
5129     additional formats. Currently only `exec` sets this variable.
5130     Otherwise it will be +NONE+.
5132 The following global variables are set by jimsh.
5134 +*tcl_interactive*+::
5135     This variable is set to 1 if jimsh is started in interactive mode
5136     or 0 otherwise.
5138 +*tcl_platform*+::
5139     This variable is set by Jim as an array containing information
5140     about the platform upon which Jim was built. The following is an
5141     example of the contents of this array.
5143     tcl_platform(byteOrder)     = littleEndian
5144     tcl_platform(engine)        = Jim
5145     tcl_platform(os)            = Darwin
5146     tcl_platform(platform)      = unix
5147     tcl_platform(pointerSize)   = 8
5148     tcl_platform(threaded)      = 0
5149     tcl_platform(wordSize)      = 8
5150     tcl_platform(pathSeparator) = :
5152 +*argv0*+::
5153     If jimsh is invoked to run a script, this variable contains the name
5154     of the script.
5156 +*argv*+::
5157     If jimsh is invoked to run a script, this variable contains a list
5158     of any arguments supplied to the script.
5160 +*argc*+::
5161     If jimsh is invoked to run a script, this variable contains the number
5162     of arguments supplied to the script.
5164 +*jim::argv0*+::
5165     The value of argv[0] when jimsh was invoked.
5167 CHANGES IN PREVIOUS RELEASES
5168 ----------------------------
5170 === In v0.70 ===
5172 1. +platform_tcl()+ settings are now automatically determined
5173 2. Add aio `$handle filename`
5174 3. Add `info channels`
5175 4. The 'bio' extension is gone. Now `aio` supports 'copyto'.
5176 5. Add `exists` command
5177 6. Add the pure-Tcl 'oo' extension
5178 7. The `exec` command now only uses vfork(), not fork()
5179 8. Unit test framework is less verbose and more Tcl-compatible
5180 9. Optional UTF-8 support
5181 10. Optional built-in regexp engine for better Tcl compatibility and UTF-8 support
5182 11. Command line editing in interactive mode, e.g. 'jimsh'
5184 === In v0.63 ===
5186 1. `source` now checks that a script is complete (.i.e. not missing a brace)
5187 2. 'info complete' now uses the real parser and so is 100% accurate
5188 3. Better access to live stack frames with 'info frame', `stacktrace` and `stackdump`
5189 4. `tailcall` no longer loses stack trace information
5190 5. Add `alias` and `curry`
5191 6. `lambda`, `alias` and `curry` are implemented via `tailcall` for efficiency
5192 7. `local` allows procedures to be deleted automatically at the end of the current procedure
5193 8. udp sockets are now supported for both clients and servers.
5194 9. vfork-based exec is now working correctly
5195 10. Add 'file tempfile'
5196 11. Add 'socket pipe'
5197 12. Enhance 'try ... on ... finally' to be more Tcl 8.6 compatible
5198 13. It is now possible to `return` from within `try`
5199 14. IPv6 support is now included
5200 15. Add 'string is'
5201 16. Event handlers works better if an error occurs. eof handler has been removed.
5202 17. `exec` now sets $::errorCode, and catch sets opts(-errorcode) for exit status
5203 18. Command pipelines via open "|..." are now supported
5204 19. `pid` can now return pids of a command pipeline
5205 20. Add 'info references'
5206 21. Add support for 'after +'ms'+', 'after idle', 'after info', `update`
5207 22. `exec` now sets environment based on $::env
5208 23. Add 'dict keys'
5209 24. Add support for 'lsort -index'
5211 === In v0.62 ===
5213 1. Add support to `exec` for '>&', '>>&', '|&', '2>@1'
5214 2. Fix `exec` error messages when special token (e.g. '>') is the last token
5215 3. Fix `subst` handling of backslash escapes.
5216 4. Allow abbreviated options for `subst`
5217 5. Add support for `return`, `break`, `continue` in subst
5218 6. Many `expr` bug fixes
5219 7. Add support for functions in `expr` (e.g. int(), abs()), and also 'in', 'ni' list operations
5220 8. The variable name argument to `regsub` is now optional
5221 9. Add support for 'unset -nocomplain'
5222 10. Add support for list commands: `lassign`, `lrepeat`
5223 11. Fully-functional `lsearch` is now implemented
5224 12. Add 'info nameofexecutable' and 'info returncodes'
5225 13. Allow `catch` to determine what return codes are caught
5226 14. Allow `incr` to increment an unset variable by first setting to 0
5227 15. Allow 'args' and optional arguments to the left or required arguments in `proc`
5228 16. Add 'file copy'
5229 17. Add 'try ... finally' command
5232 LICENCE
5233 -------
5235  Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
5236  Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
5237  Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
5238  Copyright 2008 oharboe - Oyvind Harboe - oyvind.harboe@zylin.com
5239  Copyright 2008 Andrew Lunn <andrew@lunn.ch>
5240  Copyright 2008 Duane Ellis <openocd@duaneellis.com>
5241  Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
5242  Copyright 2009 Steve Bennett <steveb@workware.net.au>
5244 [literal]
5245  Redistribution and use in source and binary forms, with or without
5246  modification, are permitted provided that the following conditions
5247  are met:
5248  1. Redistributions of source code must retain the above copyright
5249     notice, this list of conditions and the following disclaimer.
5250  2. Redistributions in binary form must reproduce the above
5251     copyright notice, this list of conditions and the following
5252     disclaimer in the documentation and/or other materials
5253     provided with the distribution.
5255  THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
5256  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
5257  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
5258  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
5259  JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
5260  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
5261  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
5262  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
5263  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
5264  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
5265  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
5266  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5268  The views and conclusions contained in the software and documentation
5269  are those of the authors and should not be interpreted as representing
5270  official policies, either expressed or implied, of the Jim Tcl Project.