format: Validate too many flags in format string
[jimtcl.git] / jim_tcl.txt
blobcce8369190a040c8acd777f7c04140fa2b15da70
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`
62 Changes between 0.76 and 0.77
63 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
64 1. Add support for `aio sync`
65 2. Add SSL and TLS support in aio
66 3. Added `zlib`
67 4. Added support for boolean constants in `expr`
68 5. `string is` now supports 'boolean' class
69 6. Add support for `aio lock` and `aio unlock`
70 7. Add new `interp` command
72 Changes between 0.75 and 0.76
73 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
74 1. `glob` now supports the +-tails+ option
75 2. Add support for `string cat`
76 3. Allow `info source` to add source info
78 Changes between 0.74 and 0.75
79 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
80 1. `binary`, `pack` and `unpack` now support floating point
81 2. `file copy` +-force+ handles source and target as the same file
82 3. `format` now supports +%b+ for binary conversion
83 4. `lsort` now supports +-unique+ and +-real+
84 5. Add support for half-close with `aio close` +?r|w?+
85 6. Add `socket pair` for a bidirectional pipe
86 7. Add '--random-hash' to randomise hash tables for greater security
87 8. `dict` now supports 'for', 'values', 'incr', 'append', 'lappend', 'update', 'info' and 'replace'
88 9. `file stat` no longer requires the variable name
89 10. Add support for `file link`
91 Changes between 0.73 and 0.74
92 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
93 1. Numbers with leading zeros are treated as decimal, not octal
94 2. Add `aio isatty`
95 3. Add LFS (64 bit) support for `aio seek`, `aio tell`, `aio copyto`, `file copy`
96 4. `string compare` and `string equal` now support '-length'
97 5. `glob` now supports '-directory'
99 Changes between 0.72 and 0.73
100 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
101 1. Built-in regexp now support non-capturing parentheses: (?:...)
102 2. Add `string replace`
103 3. Add `string totitle`
104 4. Add `info statics`
105 5. Add +build-jim-ext+ for easy separate building of loadable modules (extensions)
106 6. `local` now works with any command, not just procs
107 7. Add `info alias` to access the target of an alias
108 8. UTF-8 encoding past the basic multilingual plane (BMP) is supported
109 9. Add `tcl::prefix`
110 10. Add `history`
111 11. Most extensions are now enabled by default
112 12. Add support for namespaces and the `namespace` command
113 13. Add `apply`
115 Changes between 0.71 and 0.72
116 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
117 1. procs now allow 'args' and optional parameters in any position
118 2. Add Tcl-compatible expr functions, `rand()`, `srand()` and `pow()`
119 3. Add support for the '-force' option to `file delete`
120 4. Better diagnostics when `source` fails to load a script with a missing quote or bracket
121 5. New +tcl_platform(pathSeparator)+
122 6. Add support settings the modification time with `file mtime`
123 7. `exec` is now fully supported on win32 (mingw32)
124 8. `file join`, `pwd`, `glob` etc. now work for mingw32
125 9. Line editing is now supported for the win32 console (mingw32)
126 10. Add `aio listen` command
128 Changes between 0.70 and 0.71
129 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
130 1. Allow 'args' to be renamed in procs
131 2. Add +$(...)+ shorthand syntax for expressions
132 3. Add automatic reference variables in procs with +&var+ syntax
133 4. Support +jimsh --version+
134 5. Additional variables in +tcl_platform()+
135 6. `local` procs now push existing commands and `upcall` can call them
136 7. Add `loop` command (TclX compatible)
137 8. Add `aio buffering` command
138 9. `info complete` can now return the missing character
139 10. `binary format` and `binary scan` are now (optionally) supported
140 11. Add `string byterange`
141 12. Built-in regexp now support non-greedy repetition (*?, +?, ??)
143 TCL INTRODUCTION
144 -----------------
145 Tcl stands for 'tool command language' and is pronounced
146 'http://www.oxforddictionaries.com/definition/american_english/tickle[tickle]'.
147 It is actually two things: a language and a library.
149 First, Tcl is a simple textual language, intended primarily for
150 issuing commands to interactive programs such as text editors,
151 debuggers, illustrators, and shells.  It has a simple syntax and is also
152 programmable, so Tcl users can write command procedures to provide more
153 powerful commands than those in the built-in set.
155 Second, Tcl is a library package that can be embedded in application
156 programs.  The Tcl library consists of a parser for the Tcl language,
157 routines to implement the Tcl built-in commands, and procedures that
158 allow each application to extend Tcl with additional commands specific
159 to that application.  The application program generates Tcl commands and
160 passes them to the Tcl parser for execution.  Commands may be generated
161 by reading characters from an input source, or by associating command
162 strings with elements of the application's user interface, such as menu
163 entries, buttons, or keystrokes.
165 When the Tcl library receives commands it parses them into component
166 fields and executes built-in commands directly.  For commands implemented
167 by the application, Tcl calls back to the application to execute the
168 commands.  In many cases commands will invoke recursive invocations of the
169 Tcl interpreter by passing in additional strings to execute (procedures,
170 looping commands, and conditional commands all work in this way).
172 An application program gains three advantages by using Tcl for its command
173 language.  First, Tcl provides a standard syntax:  once users know Tcl,
174 they will be able to issue commands easily to any Tcl-based application.
175 Second, Tcl provides programmability.  All a Tcl application needs
176 to do is to implement a few application-specific low-level commands.
177 Tcl provides many utility commands plus a general programming interface
178 for building up complex command procedures.  By using Tcl, applications
179 need not re-implement these features.
181 Third, Tcl can be used as a common language for communicating between
182 applications.  Inter-application communication is not built into the
183 Tcl core described here, but various add-on libraries, such as the Tk
184 toolkit, allow applications to issue commands to each other.  This makes
185 it possible for applications to work together in much more powerful ways
186 than was previously possible.
188 Fourth, Jim Tcl includes a command processor, +jimsh+, which can be
189 used to run standalone Tcl scripts, or to run Tcl commands interactively.
191 This manual page focuses primarily on the Tcl language.  It describes
192 the language syntax and the built-in commands that will be available
193 in any application based on Tcl.  The individual library procedures are
194 described in more detail in separate manual pages, one per procedure.
196 JIMSH COMMAND INTERPRETER
197 -------------------------
198 A simple, but powerful command processor, +jimsh+, is part of Jim Tcl.
199 It may be invoked in interactive mode as:
201   jimsh
203 or to process the Tcl script in a file with:
205   jimsh filename
207 or to process the Tcl script from standard input:
209   jimsh -
211 It may also be invoked to execute an immediate script with:
213   jimsh -e "script"
215 Interactive Mode
216 ~~~~~~~~~~~~~~~~
217 Interactive mode reads Tcl commands from standard input, evaluates
218 those commands and prints the results.
220   $ jimsh
221   Welcome to Jim version 0.73, Copyright (c) 2005-8 Salvatore Sanfilippo
222   . info version
223   0.73
224   . lsort [info commands p*]
225   package parray pid popen proc puts pwd
226   . foreach i {a b c} {
227   {> puts $i
228   {> }
229   a
230   b
231   c
232   . bad
233   invalid command name "bad"
234   [error] . exit
235   $
237 If +jimsh+ is configured with line editing (it is by default) and a VT-100-compatible
238 terminal is detected, Emacs-style line editing commands are available, including:
239 arrow keys, +\^W+ to erase a word, +\^U+ to erase the line, +^R+ for reverse incremental search
240 in history. Additionally, the +h+ command may be used to display the command history.
242 Command line history is automatically saved and loaded from +~/.jim_history+
244 In interactive mode, +jimsh+ automatically runs the script +~/.jimrc+ at startup
245 if it exists.
247 INTERPRETERS
248 ------------
249 The central data structure in Tcl is an interpreter (C type 'Jim_Interp').
250 An interpreter consists of a set of command bindings, a set of variable
251 values, and a few other miscellaneous pieces of state.  Each Tcl command
252 is interpreted in the context of a particular interpreter.
254 Some Tcl-based applications will maintain multiple interpreters
255 simultaneously, each associated with a different widget or portion of
256 the application.  Interpreters are relatively lightweight structures.
257 They can be created and deleted quickly, so application programmers should
258 feel free to use multiple interpreters if that simplifies the application.
260 DATA TYPES
261 ----------
262 Tcl supports only one type of data:  strings.  All commands, all arguments
263 to commands, all command results, and all variable values are strings.
265 Where commands require numeric arguments or return numeric results,
266 the arguments and results are passed as strings.  Many commands expect
267 their string arguments to have certain formats, but this interpretation
268 is up to the individual commands.  For example, arguments often contain
269 Tcl command strings, which may get executed as part of the commands.
270 The easiest way to understand the Tcl interpreter is to remember that
271 everything is just an operation on a string.  In many cases Tcl constructs
272 will look similar to more structured constructs from other languages.
273 However, the Tcl constructs are not structured at all; they are just
274 strings of characters, and this gives them a different behaviour than
275 the structures they may look like.
277 Although the exact interpretation of a Tcl string depends on who is doing
278 the interpretation, there are three common forms that strings take:
279 commands, expressions, and lists.  The major sections below discuss
280 these three forms in more detail.
282 BASIC COMMAND SYNTAX
283 --------------------
284 The Tcl language has syntactic similarities to both the Unix shells
285 and Lisp.  However, the interpretation of commands is different
286 in Tcl than in either of those other two systems.
287 A Tcl command string consists of one or more commands separated
288 by newline characters or semi-colons.
289 Each command consists of a collection of fields separated by
290 white space (spaces or tabs).
291 The first field must be the name of a command, and the
292 additional fields, if any, are arguments that will be passed to
293 that command.  For example, the command:
295     set a 22
297 has three fields:  the first, `set`, is the name of a Tcl command, and
298 the last two, 'a' and '22', will be passed as arguments to
299 the `set` command.  The command name may refer either to a built-in
300 Tcl command, an application-specific command bound in with the library
301 procedure 'Jim_CreateCommand', or a command procedure defined with the
302 `proc` built-in command.
304 Arguments are passed literally as text strings.  Individual commands may
305 interpret those strings in any fashion they wish.  The `set` command,
306 for example, will treat its first argument as the name of a variable
307 and its second argument as a string value to assign to that variable.
308 For other commands arguments may be interpreted as integers, lists,
309 file names, or Tcl commands.
311 Command names should normally be typed completely (e.g. no abbreviations).
312 However, if the Tcl interpreter cannot locate a command it invokes a
313 special command named `unknown` which attempts to find or create the
314 command.
316 For example, at many sites `unknown` will search through library
317 directories for the desired command and create it as a Tcl procedure if
318 it is found.  The `unknown` command often provides automatic completion
319 of abbreviated commands, but usually only for commands that were typed
320 interactively.
322 It's probably a bad idea to use abbreviations in command scripts and
323 other forms that will be re-used over time:  changes to the command set
324 may cause abbreviations to become ambiguous, resulting in scripts that
325 no longer work.
327 COMMENTS
328 --------
329 If the first non-blank character in a command is +\#+, then everything
330 from the +#+ up through the next newline character is treated as
331 a comment and ignored.  When comments are embedded inside nested
332 commands (e.g. fields enclosed in braces) they must have properly-matched
333 braces (this is necessary because when Tcl parses the top-level command
334 it doesn't yet know that the nested field will be used as a command so
335 it cannot process the nested comment character as a comment).
337 GROUPING ARGUMENTS WITH DOUBLE-QUOTES
338 -------------------------------------
339 Normally each argument field ends at the next white space, but
340 double-quotes may be used to create arguments with embedded space.
342 If an argument field begins with a double-quote, then the argument isn't
343 terminated by white space (including newlines) or a semi-colon (see below
344 for information on semi-colons); instead it ends at the next double-quote
345 character.  The double-quotes are not included in the resulting argument.
346 For example, the command
348     set a "This is a single argument"
350 will pass two arguments to `set`:  'a' and 'This is a single argument'.
352 Within double-quotes, command substitutions, variable substitutions,
353 and backslash substitutions still occur, as described below.  If the
354 first character of a command field is not a quote, then quotes receive
355 no special interpretation in the parsing of that field.
357 GROUPING ARGUMENTS WITH BRACES
358 ------------------------------
359 Curly braces may also be used for grouping arguments.  They are similar
360 to quotes except for two differences.  First, they nest; this makes them
361 easier to use for complicated arguments like nested Tcl command strings.
362 Second, the substitutions described below for commands, variables, and
363 backslashes do *not* occur in arguments enclosed in braces, so braces
364 can be used to prevent substitutions where they are undesirable.
366 If an argument field begins with a left brace, then the argument ends
367 at the matching right brace.  Tcl will strip off the outermost layer
368 of braces and pass the information between the braces to the command
369 without any further modification.  For example, in the command
371     set a {xyz a {b c d}}
373 the `set` command will receive two arguments: 'a'
374 and 'xyz a {b c d}'.
376 When braces or quotes are in effect, the matching brace or quote need
377 not be on the same line as the starting quote or brace; in this case
378 the newline will be included in the argument field along with any other
379 characters up to the matching brace or quote.  For example, the `eval`
380 command takes one argument, which is a command string; `eval` invokes
381 the Tcl interpreter to execute the command string.  The command
383     eval {
384       set a 22
385       set b 33
386     }
388 will assign the value '22' to 'a' and '33' to 'b'.
390 If the first character of a command field is not a left
391 brace, then neither left nor right
392 braces in the field will be treated specially (except as part of
393 variable substitution; see below).
395 COMMAND SUBSTITUTION WITH BRACKETS
396 ----------------------------------
397 If an open bracket occurs in a field of a command, then command
398 substitution occurs (except for fields enclosed in braces).  All of the
399 text up to the matching close bracket is treated as a Tcl command and
400 executed immediately.  Then the result of that command is substituted
401 for the bracketed text.  For example, consider the command
403     set a [set b]
405 When the `set` command has only a single argument, it is the name of a
406 variable and `set` returns the contents of that variable.  In this case,
407 if variable 'b' has the value 'foo', then the command above is equivalent
408 to the command
410     set a foo
412 Brackets can be used in more complex ways.  For example, if the variable
413 'b' has the value 'foo' and the variable 'c' has the value 'gorp',
414 then the command
416     set a xyz[set b].[set c]
418 is equivalent to the command
420     set a xyzfoo.gorp
423 A bracketed command may contain multiple commands separated by newlines
424 or semi-colons in the usual fashion.  In this case the value of the last
425 command is used for substitution.  For example, the command
427     set a x[set b 22
428     expr $b+2]x
430 is equivalent to the command
432     set a x24x
435 If a field is enclosed in braces then the brackets and the characters
436 between them are not interpreted specially; they are passed through to
437 the argument verbatim.
439 VARIABLE SUBSTITUTION WITH $
440 ----------------------------
441 The dollar sign (+$+) may be used as a special shorthand form for
442 substituting variable values.  If +$+ appears in an argument that isn't
443 enclosed in braces then variable substitution will occur.  The characters
444 after the +$+, up to the first character that isn't a number, letter,
445 or underscore, are taken as a variable name and the string value of that
446 variable is substituted for the name.
448 For example, if variable 'foo' has the value 'test', then the command
450     set a $foo.c
452 is equivalent to the command
454     set a test.c
456 There are two special forms for variable substitution.  If the next
457 character after the name of the variable is an open parenthesis, then
458 the variable is assumed to be an array name, and all of the characters
459 between the open parenthesis and the next close parenthesis are taken as
460 an index into the array.  Command substitutions and variable substitutions
461 are performed on the information between the parentheses before it is
462 used as an index.
464 For example, if the variable 'x' is an array with one element named
465 'first' and value '87' and another element named '14' and value 'more',
466 then the command
468     set a xyz$x(first)zyx
470 is equivalent to the command
472     set a xyz87zyx
474 If the variable 'index' has the value '14', then the command
476     set a xyz$x($index)zyx
478 is equivalent to the command
480     set a xyzmorezyx
482 For more information on arrays, see VARIABLES AND ARRAYS below.
484 The second special form for variables occurs when the dollar sign is
485 followed by an open curly brace.  In this case the variable name consists
486 of all the characters up to the next curly brace.
488 Array references are not possible in this form:  the name between braces
489 is assumed to refer to a scalar variable.  For example, if variable
490 'foo' has the value 'test', then the command
492     set a abc${foo}bar
494 is equivalent to the command
496     set a abctestbar
499 Variable substitution does not occur in arguments that are enclosed in
500 braces:  the dollar sign and variable name are passed through to the
501 argument verbatim.
503 The dollar sign abbreviation is simply a shorthand form.  +$a+ is
504 completely equivalent to +[set a]+; it is provided as a convenience
505 to reduce typing.
507 SEPARATING COMMANDS WITH SEMI-COLONS
508 ------------------------------------
509 Normally, each command occupies one line (the command is terminated by a
510 newline character).  However, semi-colon (+;+) is treated as a command
511 separator character; multiple commands may be placed on one line by
512 separating them with a semi-colon.  Semi-colons are not treated as
513 command separators if they appear within curly braces or double-quotes.
515 BACKSLASH SUBSTITUTION
516 ----------------------
517 Backslashes may be used to insert non-printing characters into command
518 fields and also to insert special characters like braces and brackets
519 into fields without them being interpreted specially as described above.
521 The backslash sequences understood by the Tcl interpreter are
522 listed below.  In each case, the backslash
523 sequence is replaced by the given character:
524 [[BackslashSequences]]
525 +{backslash}b+::
526     Backspace (0x8)
528 +{backslash}f+::
529     Form feed (0xc)
531 +{backslash}n+::
532     Newline (0xa)
534 +{backslash}r+::
535     Carriage-return (0xd).
537 +{backslash}t+::
538     Tab (0x9).
540 +{backslash}v+::
541     Vertical tab (0xb).
543 +{backslash}{+::
544     Left brace ({).
546 +{backslash}}+::
547     Right brace (}).
549 +{backslash}[+::
550     Open bracket ([).
552 +{backslash}]+::
553     Close bracket (]).
555 +{backslash}$+::
556     Dollar sign ($).
558 +{backslash}<space>+::
559     Space ( ): doesn't terminate argument.
561 +{backslash};+::
562     Semi-colon: doesn't terminate command.
564 +{backslash}"+::
565     Double-quote.
567 +{backslash}<newline>+::
568     Nothing:  this joins two lines together
569     into a single line.  This backslash feature is unique in that
570     it will be applied even when the sequence occurs within braces.
572 +{backslash}{backslash}+::
573     Backslash ('{backslash}').
575 +{backslash}ddd+::
576     The digits +'ddd'+ (one, two, or three of them) give the octal value of
577     the character.  Note that Jim supports null characters in strings.
579 +{backslash}unnnn+::
580 +{backslash}u\{nnn\}+::
581 +{backslash}Unnnnnnnn+::
582     The UTF-8 encoding of the unicode codepoint represented by the hex digits, +'nnnn'+, is inserted.
583     The 'u' form allows for one to four hex digits.
584     The 'U' form allows for one to eight hex digits.
585     The 'u\{nnn\}' form allows for one to eight hex digits, but makes it easier to insert
586     characters UTF-8 characters which are followed by a hex digit.
588 For example, in the command
590     set a \{x\[\ yz\141
592 the second argument to `set` will be +{x[ yza+.
594 If a backslash is followed by something other than one of the options
595 described above, then the backslash is transmitted to the argument
596 field without any special processing, and the Tcl scanner continues
597 normal processing with the next character.  For example, in the
598 command
600     set \*a \\\{foo
602 The first argument to `set` will be +{backslash}*a+ and the second
603 argument will be +{backslash}{foo+.
605 If an argument is enclosed in braces, then backslash sequences inside
606 the argument are parsed but no substitution occurs (except for
607 backslash-newline):  the backslash
608 sequence is passed through to the argument as is, without making
609 any special interpretation of the characters in the backslash sequence.
610 In particular, backslashed braces are not counted in locating the
611 matching right brace that terminates the argument.
612 For example, in the
613 command
615     set a {\{abc}
617 the second argument to `set` will be +{backslash}{abc+.
619 This backslash mechanism is not sufficient to generate absolutely
620 any argument structure; it only covers the
621 most common cases.  To produce particularly complicated arguments
622 it is probably easiest to use the `format` command along with
623 command substitution.
625 STRING AND LIST INDEX SPECIFICATIONS
626 ------------------------------------
628 Many string and list commands take one or more 'index' parameters which
629 specify a position in the string relative to the start or end of the string/list.
631 The index may be one of the following forms:
633 +integer+::
634     A simple integer, where '0' refers to the first element of the string
635     or list.
637 +integer+integer+ or::
638 +integer-integer+::
639     The sum or difference of the two integers. e.g. +2+3+ refers to the 5th element.
640     This is useful when used with (e.g.) +$i+1+ rather than the more verbose
641     +[expr {$i+1\}]+
643 +end+::
644     The last element of the string or list.
646 +end-integer+::
647     The 'nth-from-last' element of the string or list.
649 COMMAND SUMMARY
650 ---------------
651 1. A command is just a string.
652 2. Within a string commands are separated by newlines or semi-colons
653    (unless the newline or semi-colon is within braces or brackets
654    or is backslashed).
655 3. A command consists of fields.  The first field is the name of the command.
656    The other fields are strings that are passed to that command as arguments.
657 4. Fields are normally separated by white space.
658 5. Double-quotes allow white space and semi-colons to appear within
659    a single argument.
660    Command substitution, variable substitution, and backslash substitution
661    still occur inside quotes.
662 6. Braces defer interpretation of special characters.
663    If a field begins with a left brace, then it consists of everything
664    between the left brace and the matching right brace. The
665    braces themselves are not included in the argument.
666    No further processing is done on the information between the braces
667    except that backslash-newline sequences are eliminated.
668 7. If a field doesn't begin with a brace then backslash,
669    variable, and command substitution are done on the field.  Only a
670    single level of processing is done:  the results of one substitution
671    are not scanned again for further substitutions or any other
672    special treatment.  Substitution can
673    occur on any field of a command, including the command name
674    as well as the arguments.
675 8. If the first non-blank character of a command is a +\#+, everything
676    from the +#+ up through the next newline is treated as a comment
677    and ignored.
679 EXPRESSIONS
680 -----------
681 The second major interpretation applied to strings in Tcl is
682 as expressions.  Several commands, such as `expr`, `for`,
683 and `if`, treat one or more of their arguments as expressions
684 and call the Tcl expression processors ('Jim_ExprLong',
685 'Jim_ExprBoolean', etc.) to evaluate them.
687 The operators permitted in Tcl expressions are a subset of
688 the operators permitted in C expressions, and they have the
689 same meaning and precedence as the corresponding C operators.
690 Expressions almost always yield numeric results
691 (integer or floating-point values).
692 For example, the expression
694     8.2 + 6
696 evaluates to 14.2.
698 Tcl expressions differ from C expressions in the way that
699 operands are specified, and in that Tcl expressions support
700 non-numeric operands and string comparisons.
702 A Tcl expression consists of a combination of operands, operators,
703 and parentheses.
705 White space may be used between the operands and operators and
706 parentheses; it is ignored by the expression processor.
707 Where possible, operands are interpreted as integer values.
709 Integer values may be specified in decimal (the normal case) or in
710 hexadecimal (if the first two characters of the operand are '0x').
711 Note that Jim Tcl does *not* treat numbers with leading zeros as octal.
713 If an operand does not have one of the integer formats given
714 above, then it is treated as a floating-point number if that is
715 possible.  Floating-point numbers may be specified in any of the
716 ways accepted by an ANSI-compliant C compiler (except that the
717 'f', 'F', 'l', and 'L' suffixes will not be permitted in
718 most installations).  For example, all of the
719 following are valid floating-point numbers:  2.1, 3., 6e4, 7.91e+16.
721 If no numeric interpretation is possible, then an operand is left
722 as a string (and only a limited set of operators may be applied to
723 it).
725 String constants representing boolean constants
726 (+'0'+, +'1'+, +'false'+, +'off'+, +'no'+, +'true'+, +'on'+, +'yes'+)
727 are also recognized and can be used in logical operations.
729 1. Operands may be specified in any of the following ways:
731 2. As a numeric value, either integer or floating-point.
733 3. As one of valid boolean constants
735 4. As a Tcl variable, using standard '$' notation.
736 The variable's value will be used as the operand.
738 5. As a string enclosed in double-quotes.
739 The expression parser will perform backslash, variable, and
740 command substitutions on the information between the quotes,
741 and use the resulting value as the operand
743 6. As a string enclosed in braces.
744 The characters between the open brace and matching close brace
745 will be used as the operand without any substitutions.
747 7. As a Tcl command enclosed in brackets.
748 The command will be executed and its result will be used as
749 the operand.
751 Where substitutions occur above (e.g. inside quoted strings), they
752 are performed by the expression processor.
753 However, an additional layer of substitution may already have
754 been performed by the command parser before the expression
755 processor was called.
757 As discussed below, it is usually best to enclose expressions
758 in braces to prevent the command parser from performing substitutions
759 on the contents.
761 For some examples of simple expressions, suppose the variable 'a' has
762 the value 3 and the variable 'b' has the value 6.  Then the expression
763 on the left side of each of the lines below will evaluate to the value
764 on the right side of the line:
766     $a + 3.1                6.1
767     2 + "$a.$b"             5.6
768     4*[llength "6 2"]       8
769     {word one} < "word $a"  0
771 The valid operators are listed below, grouped in decreasing order
772 of precedence:
773 [[OperatorPrecedence]]
774 +int() double() round() abs(), rand(), srand()+::
775     Unary functions (except rand() which takes no arguments)
776     * +'int()'+ converts the numeric argument to an integer by truncating down.
777     * +'double()'+ converts the numeric argument to floating point.
778     * +'round()'+ converts the numeric argument to the closest integer value.
779     * +'abs()'+ takes the absolute value of the numeric argument.
780     * +'rand()'+ returns a pseudo-random floating-point value in the range (0,1).
781     * +'srand()'+ takes an integer argument to (re)seed the random number generator. Returns the first random number from that seed.
783 +sin() cos() tan() asin() acos() atan() sinh() cosh() tanh() ceil() floor() exp() log() log10() sqrt()+::
784     Unary math functions.
785     If Jim is compiled with math support, these functions are available.
787 +- + ~ !+::
788     Unary minus, unary plus, bit-wise NOT, logical NOT.  None of these operands
789     may be applied to string operands, and bit-wise NOT may be
790     applied only to integers.
792 +** pow(x,y)+::
793     Power. e.g. 'x^y^'. If Jim is compiled with math support, supports doubles and
794     integers. Otherwise supports integers only. (Note that the math-function form
795     has the same highest precedence)
797 +* / %+::
798     Multiply, divide, remainder.  None of these operands may be
799     applied to string operands, and remainder may be applied only
800     to integers.
802 ++ -+::
803     Add and subtract.  Valid for any numeric operands.
805 +<<  >> <<< >>>+::
806     Left and right shift, left and right rotate.  Valid for integer operands only.
808 +<  >  \<=  >=+::
809     Boolean less, greater, less than or equal, and greater than or equal.
810     Each operator produces 1 if the condition is true, 0 otherwise.
811     These operators may be applied to strings as well as numeric operands,
812     in which case string comparison is used.
814 +==  !=+::
815     Boolean equal and not equal.  Each operator produces a zero/one result.
816     Valid for all operand types. *Note* that values will be converted to integers
817     if possible, then floating point types, and finally strings will be compared.
818     It is recommended that 'eq' and 'ne' should be used for string comparison.
820 +eq ne+::
821     String equal and not equal.  Uses the string value directly without
822     attempting to convert to a number first.
824 +in ni+::
825     String in list and not in list. For 'in', result is 1 if the left operand (as a string)
826     is contained in the right operand (as a list), or 0 otherwise. The result for
827     +{$a ni $list}+ is equivalent to +{!($a in $list)}+.
829 +&+::
830     Bit-wise AND.  Valid for integer operands only.
832 +|+::
833     Bit-wise OR.  Valid for integer operands only.
835 +^+::
836     Bit-wise exclusive OR.  Valid for integer operands only.
838 +&&+::
839     Logical AND.  Produces a 1 result if both operands are non-zero, 0 otherwise.
840     Valid for numeric operands only (integers or floating-point).
842 +||+::
843     Logical OR.  Produces a 0 result if both operands are zero, 1 otherwise.
844     Valid for numeric operands only (integers or floating-point).
846 +x ? y : z+::
847     If-then-else, as in C.  If +'x'+
848     evaluates to non-zero, then the result is the value of +'y'+.
849     Otherwise the result is the value of +'z'+.
850     The +'x'+ operand must have a numeric value, while +'y'+ and +'z'+ can
851     be of any type.
853 See the C manual for more details on the results
854 produced by each operator.
855 All of the binary operators group left-to-right within the same
856 precedence level.  For example, the expression
858     4*2 < 7
860 evaluates to 0.
862 The +&&+, +||+, and +?:+ operators have 'lazy evaluation', just as
863 in C, which means that operands are not evaluated if they are not
864 needed to determine the outcome.  For example, in
866     $v ? [a] : [b]
868 only one of +[a]+ or +[b]+ will actually be evaluated,
869 depending on the value of +$v+.
871 All internal computations involving integers are done with the C
872 type 'long long' if available, or 'long' otherwise, and all internal
873 computations involving floating-point are done with the C type
874 'double'.
876 When converting a string to floating-point, exponent overflow is
877 detected and results in a Tcl error.
878 For conversion to integer from string, detection of overflow depends
879 on the behaviour of some routines in the local C library, so it should
880 be regarded as unreliable.
881 In any case, overflow and underflow are generally not detected
882 reliably for intermediate results.
884 Conversion among internal representations for integer, floating-point,
885 string operands is done automatically as needed.
886 For arithmetic computations, integers are used until some
887 floating-point number is introduced, after which floating-point is used.
888 For example,
890     5 / 4
892 yields the result 1, while
894     5 / 4.0
895     5 / ( [string length "abcd"] + 0.0 )
897 both yield the result 1.25.
899 String values may be used as operands of the comparison operators,
900 although the expression evaluator tries to do comparisons as integer
901 or floating-point when it can.
902 If one of the operands of a comparison is a string and the other
903 has a numeric value, the numeric operand is converted back to
904 a string using the C 'sprintf' format specifier
905 '%d' for integers and '%g' for floating-point values.
906 For example, the expressions
908     "0x03" > "2"
909     "0y" < "0x12"
911 both evaluate to 1.  The first comparison is done using integer
912 comparison, and the second is done using string comparison after
913 the second operand is converted to the string '18'.
915 In general it is safest to enclose an expression in braces when
916 entering it in a command:  otherwise, if the expression contains
917 any white space then the Tcl interpreter will split it
918 among several arguments.  For example, the command
920     expr $a + $b
922 results in three arguments being passed to `expr`:  +$a+,
923 \+, and +$b+.  In addition, if the expression isn't in braces
924 then the Tcl interpreter will perform variable and command substitution
925 immediately (it will happen in the command parser rather than in
926 the expression parser).  In many cases the expression is being
927 passed to a command that will evaluate the expression later (or
928 even many times if, for example, the expression is to be used to
929 decide when to exit a loop).  Usually the desired goal is to re-do
930 the variable or command substitutions each time the expression is
931 evaluated, rather than once and for all at the beginning.  For example,
932 the command
934     for {set i 1} $i<=10 {incr i} {...}        ** WRONG **
936 is probably intended to iterate over all values of +i+ from 1 to 10.
937 After each iteration of the body of the loop, `for` will pass
938 its second argument to the expression evaluator to see whether or not
939 to continue processing.  Unfortunately, in this case the value of +i+
940 in the second argument will be substituted once and for all when the
941 `for` command is parsed.  If +i+ was 0 before the `for`
942 command was invoked then the second argument of `for` will be +0\<=10+
943 which will always evaluate to 1, even though +i+ eventually
944 becomes greater than 10.  In the above case the loop will never
945 terminate.  Instead, the expression should be placed in braces:
947     for {set i 1} {$i<=10} {incr i} {...}      ** RIGHT **
949 This causes the substitution of 'i'
950 to be delayed; it will be re-done each time the expression is
951 evaluated, which is the desired result.
953 LISTS
954 -----
955 The third major way that strings are interpreted in Tcl is as lists.
956 A list is just a string with a list-like structure
957 consisting of fields separated by white space.  For example, the
958 string
960     Al Sue Anne John
962 is a list with four elements or fields.
963 Lists have the same basic structure as command strings, except
964 that a newline character in a list is treated as a field separator
965 just like space or tab.  Conventions for braces and quotes
966 and backslashes are the same for lists as for commands.  For example,
967 the string
969     a b\ c {d e {f g h}}
971 is a list with three elements:  +a+, +b c+, and +d e {f g h}+.
973 Whenever an element is extracted from a list, the same rules about
974 braces and quotes and backslashes are applied as for commands.  Thus in
975 the example above when the third element is extracted from the list,
976 the result is
978     d e {f g h}
980 (when the field was extracted, all that happened was to strip off
981 the outermost layer of braces).  Command substitution and
982 variable substitution are never
983 made on a list (at least, not by the list-processing commands; the
984 list can always be passed to the Tcl interpreter for evaluation).
986 The Tcl commands `concat`, `foreach`, `lappend`, `lindex`, `linsert`,
987 `list`, `llength`, `lrange`, `lreplace`, `lsearch`, and `lsort` allow
988 you to build lists, extract elements from them, search them, and perform
989 other list-related functions.
991 Advanced list commands include `lrepeat`, `lreverse`, `lmap`, `lassign`, `lset`.
993 LIST EXPANSION
994 --------------
996 A new addition to Tcl 8.5 is the ability to expand a list into separate
997 arguments. Support for this feature is also available in Jim.
999 Consider the following attempt to exec a list:
1001     set cmd {ls -l}
1002     exec $cmd
1004 This will attempt to exec a command named "ls -l", which will clearly not
1005 work. Typically eval and concat are required to solve this problem, however
1006 it can be solved much more easily with +\{*\}+.
1008     exec {*}$cmd
1010 This will expand the following argument into individual elements and then evaluate
1011 the resulting command.
1013 Note that the official Tcl syntax is +\{*\}+, however +\{expand\}+ is retained
1014 for backward compatibility with experimental versions of this feature.
1016 REGULAR EXPRESSIONS
1017 -------------------
1018 Tcl provides two commands that support string matching using regular
1019 expressions, `regexp` and `regsub`, as well as `switch -regexp` and
1020 `lsearch -regexp`.
1022 Regular expressions may be implemented one of two ways. Either using the system's C library
1023 POSIX regular expression support, or using the built-in regular expression engine.
1024 The differences between these are described below.
1026 *NOTE* Tcl 7.x and 8.x use perl-style Advanced Regular Expressions (+ARE+).
1028 POSIX Regular Expressions
1029 ~~~~~~~~~~~~~~~~~~~~~~~~~
1030 If the system supports POSIX regular expressions, and UTF-8 support is not enabled,
1031 this support will be used by default. The type of regular expressions supported are
1032 Extended Regular Expressions (+ERE+) rather than Basic Regular Expressions (+BRE+).
1033 See REG_EXTENDED in the documentation.
1035 Using the system-supported POSIX regular expressions will typically
1036 make for the smallest code size, but some features such as UTF-8
1037 and +{backslash}w+, +{backslash}d+, +{backslash}s+ are not supported, and null characters
1038 in strings are not supported.
1040 See regex(3) and regex(7) for full details.
1042 Jim built-in Regular Expressions
1043 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1044 The Jim built-in regular expression engine may be selected with +./configure --with-jim-regexp+
1045 or it will be selected automatically if UTF-8 support is enabled.
1047 This engine supports UTF-8 as well as some +ARE+ features. The differences with both Tcl 7.x/8.x
1048 and POSIX are highlighted below.
1050 1. UTF-8 strings and patterns are both supported
1051 2. All Tcl character classes are supported (e.g. +[:alnum:]+, +[:digit:]+, +[:space:]+), but...
1052 3. Character classes apply to ASCII characters only
1053 4. Supported shorthand character classes: +{backslash}w+ = +[:alnum:]+, +{backslash}W+ = +^[:alnum:]+, +{backslash}d+ = +[:digit:],+ +{backslash}D+ = +^[:digit:],+ +{backslash}s+ = +[:space:]+, + +{backslash}S+ = +^[:space:]+
1054 5. Supported constraint escapes: +{backslash}m+ = +{backslash}<+ = start of word, +{backslash}M+ = +{backslash}>+ = end of word
1055 6. Backslash escapes may be used within regular expressions, such as +{backslash}n+ = newline, +{backslash}uNNNN+ = unicode
1056 7. Partially supported constraint escapes: +{backslash}A+ = start of string, +{backslash}Z+ = end of string
1057 8. Support for the +?+ non-greedy quantifier. e.g. +*?+
1058 9. Support for non-capturing parentheses +(?:...)+
1059 10. Jim Tcl considers that both patterns and strings end at a null character (+\x00+)
1061 COMMAND RESULTS
1062 ---------------
1063 Each command produces two results:  a code and a string.  The
1064 code indicates whether the command completed successfully or not,
1065 and the string gives additional information.  The valid codes are
1066 defined in jim.h, and are:
1068 +JIM_OK(0)+::
1069     This is the normal return code, and indicates that the command completed
1070     successfully.  The string gives the command's return value.
1072 +JIM_ERR(1)+::
1073     Indicates that an error occurred; the string gives a message describing
1074     the error.
1076 +JIM_RETURN(2)+::
1077     Indicates that the `return` command has been invoked, and that the
1078     current procedure (or top-level command or `source` command)
1079     should return immediately.  The
1080     string gives the return value for the procedure or command.
1082 +JIM_BREAK(3)+::
1083     Indicates that the `break` command has been invoked, so the
1084     innermost loop should abort immediately.  The string should always
1085     be empty.
1087 +JIM_CONTINUE(4)+::
1088     Indicates that the `continue` command has been invoked, so the
1089     innermost loop should go on to the next iteration.  The string
1090     should always be empty.
1092 +JIM_SIGNAL(5)+::
1093     Indicates that a signal was caught while executing a commands.
1094     The string contains the name of the signal caught.
1095     See the `signal` and `catch` commands.
1097 +JIM_EXIT(6)+::
1098     Indicates that the command called the `exit` command.
1099     The string contains the exit code.
1101 Tcl programmers do not normally need to think about return codes,
1102 since +JIM_OK+ is almost always returned.  If anything else is returned
1103 by a command, then the Tcl interpreter immediately stops processing
1104 commands and returns to its caller.  If there are several nested
1105 invocations of the Tcl interpreter in progress, then each nested
1106 command will usually return the error to its caller, until eventually
1107 the error is reported to the top-level application code.  The
1108 application will then display the error message for the user.
1110 In a few cases, some commands will handle certain `error` conditions
1111 themselves and not return them upwards.  For example, the `for`
1112 command checks for the +JIM_BREAK+ code; if it occurs, then `for`
1113 stops executing the body of the loop and returns +JIM_OK+ to its
1114 caller.  The `for` command also handles +JIM_CONTINUE+ codes and the
1115 procedure interpreter handles +JIM_RETURN+ codes.  The `catch`
1116 command allows Tcl programs to catch errors and handle them without
1117 aborting command interpretation any further.
1119 The `info returncodes` command may be used to programmatically map between
1120 return codes and names.
1122 PROCEDURES
1123 ----------
1124 Tcl allows you to extend the command interface by defining
1125 procedures.  A Tcl procedure can be invoked just like any other Tcl
1126 command (it has a name and it receives one or more arguments).
1127 The only difference is that its body isn't a piece of C code linked
1128 into the program; it is a string containing one or more other
1129 Tcl commands.
1131 The `proc` command is used to create a new Tcl command procedure:
1133 +*proc* 'name arglist ?statics? body'+
1135 The new command is named +'name'+, and it replaces any existing command
1136 there may have been by that name. Whenever the new command is
1137 invoked, the contents of +'body'+ will be executed by the Tcl
1138 interpreter.
1140 +'arglist'+ specifies the formal arguments to the procedure.
1141 It consists of a list, possibly empty, of the following
1142 argument specifiers:
1144 +name+::
1145     Required Argument - A simple argument name.
1147 +{name default}+::
1148     Optional Argument - A two-element list consisting of the
1149     argument name, followed by the default value, which will
1150     be used if the corresponding argument is not supplied.
1152 +&name+::
1153     Reference Argument - The caller is expected to pass the name of
1154     an existing variable. An implicit +`upvar` 1 origname name+ is done
1155     to make the variable available in the proc scope.
1157 +*args*+::
1158     Variable Argument - The special name +'args'+, which is
1159     assigned all remaining arguments (including none) as a list. The
1160     variable argument may only be specified once. Note that
1161     the syntax +{args newname}+ may be used to retain the special
1162     behaviour of +'args'+ with a different local name. In this case,
1163     the variable is named +'newname'+ rather than +'args'+.
1165 When the command is invoked, a local variable will be created for each of
1166 the formal arguments to the procedure; its value will be the value
1167 of corresponding argument in the invoking command or the argument's
1168 default value.
1170 Arguments with default values need not be specified in a procedure
1171 invocation.  However, there must be enough actual arguments for all
1172 required arguments, and there must not be any extra actual arguments
1173 (unless the Variable Argument is specified).
1175 Actual arguments are assigned to formal arguments as in left-to-right
1176 order with the following precedence.
1178 1. Required Arguments (including Reference Arguments)
1179 2. Optional Arguments
1180 3. Variable Argument
1182 The following example illustrates precedence. Assume a procedure declaration:
1184     proc p {{a A} args b {c C} d} {...}
1186 This procedure requires at least two arguments, but can accept an unlimited number.
1187 The following table shows how various numbers of arguments are assigned.
1188 Values marked as +-+ are assigned the default value.
1190 [width="40%",frame="topbot",options="header"]
1191 |==============
1192 |Number of arguments|a|args|b|c|d
1193 |2|-|-|1|-|2
1194 |3|1|-|2|-|3
1195 |4|1|-|2|3|4
1196 |5|1|2|3|4|5
1197 |6|1|2,3|4|5|6
1198 |==============
1200 When +'body'+ is being executed, variable names normally refer to local
1201 variables, which are created automatically when referenced and deleted
1202 when the procedure returns.  One local variable is automatically created
1203 for each of the procedure's arguments.  Global variables can be
1204 accessed by invoking the `global` command or via the +::+ prefix.
1206 New in Jim
1207 ~~~~~~~~~~
1208 In addition to procedure arguments, Jim procedures may declare static variables.
1209 These variables scoped to the procedure and initialised at procedure definition.
1210 Either from the static variable definition, or from the enclosing scope.
1212 Consider the following example:
1214     jim> set a 1
1215     jim> proc a {} {a {b 2}} {
1216         set c 1
1217         puts "$a $b $c"
1218         incr a
1219         incr b
1220         incr c
1221     }
1222     jim> a
1223     1 2 1
1224     jim> a
1225     2 3 1
1227 The static variable +'a'+ has no initialiser, so it is initialised from
1228 the enclosing scope with the value 1. (Note that it is an error if there
1229 is no variable with the same name in the enclosing scope). However +'b'+
1230 has an initialiser, so it is initialised to 2.
1232 Unlike a local variable, the value of a static variable is retained across
1233 invocations of the procedure.
1235 See the `proc` command for information on how to define procedures
1236 and what happens when they are invoked. See also NAMESPACES.
1238 VARIABLES - SCALARS AND ARRAYS
1239 ------------------------------
1240 Tcl allows the definition of variables and the use of their values
1241 either through '$'-style variable substitution, the `set`
1242 command, or a few other mechanisms.
1244 Variables need not be declared:  a new variable will automatically
1245 be created each time a new variable name is used.
1247 Tcl supports two types of variables:  scalars and arrays.
1248 A scalar variable has a single value, whereas an array variable
1249 can have any number of elements, each with a name (called
1250 its 'index') and a value.
1252 Array indexes may be arbitrary strings; they need not be numeric.
1253 Parentheses are used refer to array elements in Tcl commands.
1254 For example, the command
1256     set x(first) 44
1258 will modify the element of 'x' whose index is 'first'
1259 so that its new value is '44'.
1261 Two-dimensional arrays can be simulated in Tcl by using indexes
1262 that contain multiple concatenated values.
1263 For example, the commands
1265     set a(2,3) 1
1266     set a(3,6) 2
1268 set the elements of 'a' whose indexes are '2,3' and '3,6'.
1270 In general, array elements may be used anywhere in Tcl that scalar
1271 variables may be used.
1273 If an array is defined with a particular name, then there may
1274 not be a scalar variable with the same name.
1276 Similarly, if there is a scalar variable with a particular
1277 name then it is not possible to make array references to the
1278 variable.
1280 To convert a scalar variable to an array or vice versa, remove
1281 the existing variable with the `unset` command.
1283 The `array` command provides several features for dealing
1284 with arrays, such as querying the names of all the elements of
1285 the array and converting between an array and a list.
1287 Variables may be either global or local.  If a variable
1288 name is used when a procedure isn't being executed, then it
1289 automatically refers to a global variable.  Variable names used
1290 within a procedure normally refer to local variables associated with that
1291 invocation of the procedure.  Local variables are deleted whenever
1292 a procedure exits.  Either `global` command may be used to request
1293 that a name refer to a global variable for the duration of the current
1294 procedure (this is somewhat analogous to 'extern' in C), or the variable
1295 may be explicitly scoped with the +::+ prefix. For example
1297     set a 1
1298     set b 2
1299     proc p {} {
1300         set c 3
1301         global a
1303         puts "$a $::b $c"
1304     }
1305     p
1307 will output:
1309     1 2 3
1311 ARRAYS AS LISTS IN JIM
1312 ----------------------
1313 Unlike Tcl, Jim can automatically convert between a list (with an even
1314 number of elements) and an array value. This is similar to the way Tcl
1315 can convert between a string and a list.
1317 For example:
1319   set a {1 one 2 two}
1320   puts $a(2)
1322 will output:
1324   two
1326 Thus `array set` is equivalent to `set` when the variable does not
1327 exist or is empty.
1329 The reverse is also true where an array will be converted into
1330 a list.
1332   set a(1) one; set a(2) two
1333   puts $a
1335 will output:
1337   1 one 2 two
1339 DICTIONARY VALUES
1340 -----------------
1341 Tcl 8.5 introduced the dict command, and Jim Tcl has added a version
1342 of this command. Dictionaries provide efficient access to key-value
1343 pairs, just like arrays, but dictionaries are pure values. This
1344 means that you can pass them to a procedure just as a list or a
1345 string. Tcl dictionaries are therefore much more like Tcl lists,
1346 except that they represent a mapping from keys to values, rather
1347 than an ordered sequence.
1349 You can nest dictionaries, so that the value for a particular key
1350 consists of another dictionary. That way you can elegantly build
1351 complicated data structures, such as hierarchical databases. You
1352 can also combine dictionaries with other Tcl data structures. For
1353 instance, you can build a list of dictionaries that themselves
1354 contain lists.
1356 Dictionaries are values that contain an efficient, order-preserving
1357 mapping from arbitrary keys to arbitrary values. Each key in the
1358 dictionary maps to a single value. They have a textual format that
1359 is exactly that of any list with an even number of elements, with
1360 each mapping in the dictionary being represented as two items in
1361 the list. When a command takes a dictionary and produces a new
1362 dictionary based on it (either returning it or writing it back into
1363 the variable that the starting dictionary was read from) the new
1364 dictionary will have the same order of keys, modulo any deleted
1365 keys and with new keys added on to the end. When a string is
1366 interpreted as a dictionary and it would otherwise have duplicate
1367 keys, only the last value for a particular key is used; the others
1368 are ignored, meaning that, "apple banana" and "apple carrot apple
1369 banana" are equivalent dictionaries (with different string
1370 representations).
1372 Note that in Jim, arrays are implemented as dictionaries.
1373 Thus automatic conversion between lists and dictionaries applies
1374 as it does for arrays.
1376   jim> dict set a 1 one
1377   1 one
1378   jim> dict set a 2 two
1379   1 one 2 two
1380   jim> puts $a
1381   1 one 2 two
1382   jim> puts $a(2)
1383   two
1384   jim> dict set a 3 T three
1385   1 one 2 two 3 {T three}
1387 See the `dict` command for more details.
1389 NAMESPACES
1390 ----------
1391 Tcl added namespaces as a mechanism avoiding name clashes, especially in applications
1392 including a number of 3rd party components. While there is less need for namespaces
1393 in Jim Tcl (which does not strive to support large applications), it is convenient to
1394 provide a subset of the support for namespaces to easy porting code from Tcl.
1396 Jim Tcl currently supports "light-weight" namespaces which should be adequate for most
1397 purposes. This feature is currently experimental. See README.namespaces for more information
1398 and the documentation of the `namespace` command.
1400 GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION
1401 -----------------------------------------------
1402 Unlike Tcl, Jim has some sophisticated support for functional programming.
1403 These are described briefly below.
1405 More information may be found at http://wiki.tcl.tk/13847
1407 References
1408 ~~~~~~~~~~
1409 A reference can be thought of as holding a value with one level of indirection,
1410 where the value may be garbage collected when unreferenced.
1411 Consider the following example:
1413     jim> set r [ref "One String" test]
1414     <reference.<test___>.00000000000000000000>
1415     jim> getref $r
1416     One String
1418 The operation `ref` creates a references to the value specified by the
1419 first argument. (The second argument is a "type" used for documentation purposes).
1421 The operation `getref` is the dereferencing operation which retrieves the value
1422 stored in the reference.
1424     jim> setref $r "New String"
1425     New String
1426     jim> getref $r
1427     New String
1429 The operation `setref` replaces the value stored by the reference. If the old value
1430 is no longer accessible by any reference, it will eventually be automatically be garbage
1431 collected.
1433 Garbage Collection
1434 ~~~~~~~~~~~~~~~~~~
1435 Normally, all values in Tcl are passed by value. As such values are copied and released
1436 automatically as necessary.
1438 With the introduction of references, it is possible to create values whose lifetime
1439 transcend their scope. To support this, case, the Jim system will periodically identify
1440 and discard objects which are no longer accessible by any reference.
1442 The `collect` command may be used to force garbage collection.  Consider a reference created
1443 with a finalizer:
1445     jim> proc f {ref value} { puts "Finaliser called for $ref,$value" }
1446     jim> set r [ref "One String" test f]
1447     <reference.<test___>.00000000000
1448     jim> collect
1449     0
1450     jim> set r ""
1451     jim> collect
1452     Finaliser called for <reference.<test___>.00000000000,One String
1453     1
1455 Note that once the reference, 'r', was modified so that it no longer
1456 contained a reference to the value, the garbage collector discarded
1457 the value (after calling the finalizer).
1459 The finalizer for a reference may be examined or changed with the `finalize` command
1461     jim> finalize $r
1462     f
1463     jim> finalize $r newf
1464     newf
1466 Lambda Function
1467 ~~~~~~~~~~~~~~~
1468 Jim provides a garbage collected `lambda` function. This is a procedure
1469 which is able to create an anonymous procedure.  Consider:
1471     jim> set f [lambda {a} {{x 0}} { incr x $a }]
1472     jim> $f 1
1473     1
1474     jim> $f 2
1475     3
1476     jim> set f ""
1478 This create an anonymous procedure (with the name stored in 'f'), with a static variable
1479 which is incremented by the supplied value and the result returned.
1481 Once the procedure name is no longer accessible, it will automatically be deleted
1482 when the garbage collector runs.
1484 The procedure may also be delete immediately by renaming it "". e.g.
1486     jim> rename $f ""
1488 UTF-8 AND UNICODE
1489 -----------------
1490 If Jim is built with UTF-8 support enabled (configure --enable-utf),
1491 then most string-related commands become UTF-8 aware.  These include,
1492 but are not limited to, `string match`, `split`, `glob`, `scan` and
1493 `format`.
1495 UTF-8 encoding has many advantages, but one of the complications is that
1496 characters can take a variable number of bytes. Thus the addition of
1497 `string bytelength` which returns the number of bytes in a string,
1498 while `string length` returns the number of characters.
1500 If UTF-8 support is not enabled, all commands treat bytes as characters
1501 and `string bytelength` returns the same value as `string length`.
1503 Note that even if UTF-8 support is not enabled, the +{backslash}uNNNN+ and related syntax
1504 is still available to embed UTF-8 sequences.
1506 Jim Tcl supports all currently defined unicode codepoints. That is 21 bits, up to +'U+1FFFFF'.
1508 String Matching
1509 ~~~~~~~~~~~~~~~
1510 Commands such as `string match`, `lsearch -glob`, `array names` and others use string
1511 pattern matching rules. These commands support UTF-8. For example:
1513   string match a\[\ua0-\ubf\]b "a\u00a3b"
1515 format and scan
1516 ~~~~~~~~~~~~~~~
1517 +format %c+ allows a unicode codepoint to be be encoded. For example, the following will return
1518 a string with two bytes and one character. The same as +{backslash}ub5+
1520   format %c 0xb5
1522 `format` respects widths as character widths, not byte widths. For example, the following will
1523 return a string with three characters, not three bytes.
1525   format %.3s \ub5\ub6\ub7\ub8
1527 Similarly, +scan ... %c+ allows a UTF-8 to be decoded to a unicode codepoint. The following will set
1528 +'a'+ to 181 (0xb5) and +'b'+ to 65 (0x41).
1530   scan \u00b5A %c%c a b
1532 `scan %s` will also accept a character class, including unicode ranges.
1534 String Classes
1535 ~~~~~~~~~~~~~~
1536 `string is` has *not* been extended to classify UTF-8 characters. Therefore, the following
1537 will return 0, even though the string may be considered to be alphabetic.
1539   string is alpha \ub5Test
1541 This does not affect the string classes 'ascii', 'control', 'digit', 'double', 'integer' or 'xdigit'.
1543 Case Mapping and Conversion
1544 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1545 Jim provides a simplified unicode case mapping. This means that case conversion
1546 and comparison will not increase or decrease the number of characters in a string.
1547 (Although it may change the number of bytes).
1549 `string toupper` will convert any lowercase letters to their uppercase equivalent.
1550 Any character which is not a letter or has no uppercase equivalent is left unchanged.
1551 Similarly for `string tolower` and `string totitle`.
1553 Commands which perform case insensitive matches, such as `string compare -nocase`
1554 and `lsearch -nocase` fold both strings to uppercase before comparison.
1556 Invalid UTF-8 Sequences
1557 ~~~~~~~~~~~~~~~~~~~~~~~
1558 Some UTF-8 character sequences are invalid, such as those beginning with '0xff',
1559 those which represent character sequences longer than 3 bytes (greater than U+FFFF),
1560 and those which end prematurely, such as a lone '0xc2'.
1562 In these situations, the offending bytes are treated as single characters. For example,
1563 the following returns 2.
1565   string bytelength \xff\xff
1567 Regular Expressions
1568 ~~~~~~~~~~~~~~~~~~~
1569 If UTF-8 support is enabled, the built-in regular expression engine will be
1570 selected which supports UTF-8 strings and patterns.
1572 See REGULAR EXPRESSIONS
1574 BUILT-IN COMMANDS
1575 -----------------
1576 The Tcl library provides the following built-in commands, which will
1577 be available in any application using Tcl.  In addition to these
1578 built-in commands, there may be additional commands defined by each
1579 application, plus commands defined as Tcl procedures.
1581 In the command syntax descriptions below, words in +*boldface*+ are
1582 literals that you type verbatim to Tcl.
1584 Words in +'italics'+ are meta-symbols; they serve as names for any of
1585 a range of values that you can type.
1587 Optional arguments or groups of arguments are indicated by enclosing them
1588 in +?question-marks?+.
1590 Ellipses (+\...+) indicate that any number of additional
1591 arguments or groups of arguments may appear, in the same format
1592 as the preceding argument(s).
1594 [[CommandIndex]]
1595 Command Index
1596 ~~~~~~~~~~~~~
1597 @INSERTINDEX@
1599 alarm
1600 ~~~~~
1601 +*alarm* 'seconds'+
1603 Delivers the +SIGALRM+ signal to the process after the given
1604 number of seconds. If the platform supports 'ualarm(3)' then
1605 the argument may be a floating point value. Otherwise it must
1606 be an integer.
1608 Note that unless a signal handler for +SIGALRM+ has been installed
1609 (see `signal`), the process will exit on this signal.
1611 alias
1612 ~~~~~
1613 +*alias* 'name args\...'+
1615 Creates a single word alias (command) for one or more words. For example,
1616 the following creates an alias for the command `info exists`.
1618     alias e info exists
1619     if {[e var]} {
1620       ...
1621     }
1623 `alias` returns +'name'+, allowing it to be used with `local`.
1625 See also `proc`, `curry`, `lambda`, `local`, `info alias`, `exists -alias`
1627 append
1628 ~~~~~~
1629 +*append* 'varName value ?value value ...?'+
1631 Append all of the +'value'+ arguments to the current value
1632 of variable +'varName'+.  If +'varName'+ doesn't exist,
1633 it is given a value equal to the concatenation of all the
1634 +'value'+ arguments.
1636 This command provides an efficient way to build up long
1637 variables incrementally.
1638 For example, "`append a $b`" is much more efficient than
1639 "`set a $a$b`" if +$a+ is long.
1641 apply
1642 ~~~~~~
1643 +*apply* 'lambdaExpr ?arg1 arg2 \...?'+
1645 The command `apply` provides for anonymous procedure calls,
1646 similar to `lambda`, but without command name being created, even temporarily.
1648 The function  +'lambdaExpr'+ is a two element list +{args body}+
1649 or a three element list +{args body namespace}+. The first element
1650 args specifies the formal arguments, in the same form as the `proc` and `lambda` commands.
1652 array
1653 ~~~~~
1654 +*array* 'option arrayName ?arg\...?'+
1656 This command performs one of several operations on the
1657 variable given by +'arrayName'+.
1659 Note that in general, if the named array does not exist, the +'array'+ command behaves
1660 as though the array exists but is empty.
1662 The +'option'+ argument determines what action is carried out by the
1663 command.  The legal +'options'+ (which may be abbreviated) are:
1665 +*array exists* 'arrayName'+::
1666     Returns 1 if arrayName is an array variable, 0 if there is
1667     no variable by that name.
1669 +*array get* 'arrayName ?pattern?'+::
1670     Returns a list containing pairs of elements. The first
1671     element in each pair is the name of an element in arrayName
1672     and the second element of each pair is the value of the
1673     array element. The order of the pairs is undefined. If
1674     pattern is not specified, then all of the elements of the
1675     array are included in the result. If pattern is specified,
1676     then only those elements whose names match pattern (using
1677     the matching rules of string match) are included. If arrayName
1678     isn't the name of an array variable, or if the array contains
1679     no elements, then an empty list is returned.
1681 +*array names* 'arrayName ?pattern?'+::
1682     Returns a list containing the names of all of the elements
1683     in the array that match pattern. If pattern is omitted then
1684     the command returns all of the element names in the array.
1685     If pattern is specified, then only those elements whose
1686     names match pattern (using the matching rules of string
1687     match) are included. If there are no (matching) elements
1688     in the array, or if arrayName isn't the name of an array
1689     variable, then an empty string is returned.
1691 +*array set* 'arrayName list'+::
1692     Sets the values of one or more elements in arrayName. list
1693     must have a form like that returned by array get, consisting
1694     of an even number of elements. Each odd-numbered element
1695     in list is treated as an element name within arrayName, and
1696     the following element in list is used as a new value for
1697     that array element. If the variable arrayName does not
1698     already exist and list is empty, arrayName is created with
1699     an empty array value.
1701 +*array size* 'arrayName'+::
1702     Returns the number of elements in the array. If arrayName
1703     isn't the name of an array then 0 is returned.
1705 +*array unset* 'arrayName ?pattern?'+::
1706     Unsets all of the elements in the array that match pattern
1707     (using the matching rules of string match). If arrayName
1708     isn't the name of an array variable or there are no matching
1709     elements in the array, no error will be raised. If pattern
1710     is omitted and arrayName is an array variable, then the
1711     command unsets the entire array. The command always returns
1712     an empty string.
1714 break
1715 ~~~~~
1716 +*break*+
1718 This command may be invoked only inside the body of a loop command
1719 such as `for` or `foreach` or `while`.  It returns a +JIM_BREAK+ code
1720 to signal the innermost containing loop command to return immediately.
1722 case
1723 ~~~~
1724 +*case* 'string' ?in? 'patList body ?patList body ...?'+
1726 +*case* 'string' ?in? {'patList body ?patList body ...?'}+
1728 *Note* that the `switch` command should generally be preferred unless compatibility
1729 with Tcl 6.x is desired.
1731 Match +'string'+ against each of the +'patList'+ arguments
1732 in order.  If one matches, then evaluate the following +'body'+ argument
1733 by passing it recursively to the Tcl interpreter, and return the result
1734 of that evaluation.  Each +'patList'+ argument consists of a single
1735 pattern or list of patterns.  Each pattern may contain any of the wild-cards
1736 described under `string match`.
1738 If a +'patList'+ argument is +default+, the corresponding body will be
1739 evaluated if no +'patList'+ matches +'string'+.  If no +'patList'+ argument
1740 matches +'string'+ and no default is given, then the `case` command returns
1741 an empty string.
1743 Two syntaxes are provided.
1745 The first uses a separate argument for each of the patterns and commands;
1746 this form is convenient if substitutions are desired on some of the
1747 patterns or commands.
1749 The second form places all of the patterns and commands together into
1750 a single argument; the argument must have proper list structure, with
1751 the elements of the list being the patterns and commands.
1753 The second form makes it easy to construct multi-line case commands,
1754 since the braces around the whole list make it unnecessary to include a
1755 backslash at the end of each line.
1757 Since the +'patList'+ arguments are in braces in the second form,
1758 no command or variable substitutions are performed on them;  this makes
1759 the behaviour of the second form different than the first form in some
1760 cases.
1762 Below are some examples of `case` commands:
1764     case abc in {a b} {format 1} default {format 2} a* {format 3}
1766 will return '3',
1768     case a in {
1769         {a b} {format 1}
1770         default {format 2}
1771         a* {format 3}
1772     }
1774 will return '1', and
1776     case xyz {
1777         {a b}
1778             {format 1}
1779         default
1780             {format 2}
1781         a*
1782             {format 3}
1783     }
1785 will return '2'.
1787 catch
1788 ~~~~~
1789 +*catch* ?-?no?'code \...'? ?--? 'command ?resultVarName? ?optionsVarName?'+
1791 The `catch` command may be used to prevent errors from aborting
1792 command interpretation.  `catch` evaluates +'command'+, and returns a
1793 +JIM_OK+ code, regardless of any errors that might occur while
1794 executing +'command'+ (with the possible exception of +JIM_SIGNAL+ -
1795 see below).
1797 The return value from `catch` is a decimal string giving the code
1798 returned by the Tcl interpreter after executing +'command'+.  This
1799 will be '0' (+JIM_OK+) if there were no errors in +'command'+; otherwise
1800 it will have a non-zero value corresponding to one of the exceptional
1801 return codes (see jim.h for the definitions of code values, or the
1802 `info returncodes` command).
1804 If the +'resultVarName'+ argument is given, then it gives the name
1805 of a variable; `catch` will set the value of the variable to the
1806 string returned from +'command'+ (either a result or an error message).
1808 If the +'optionsVarName'+ argument is given, then it gives the name
1809 of a variable; `catch` will set the value of the variable to a
1810 dictionary. For any return code other than +JIM_RETURN+, the value
1811 for the key +-code+ will be set to the return code. For +JIM_RETURN+
1812 it will be set to the code given in `return -code`. Additionally,
1813 for the return code +JIM_ERR+, the value of the key +-errorinfo+
1814 will contain the current stack trace (the same result as `info stacktrace`),
1815 the value of the key +-errorcode+ will contain the
1816 same value as the global variable $::errorCode, and the value of
1817 the key +-level+ will be the current return level (see `return -level`).
1818 This can be useful to rethrow an error:
1820     if {[catch {...} msg opts]} {
1821         ...maybe do something with the error...
1822         incr opts(-level)
1823         return {*}$opts $msg
1824     }
1826 Normally `catch` will +'not'+ catch any of the codes +JIM_EXIT+, +JIM_EVAL+ or +JIM_SIGNAL+.
1827 The set of codes which will be caught may be modified by specifying the one more codes before
1828 +'command'+.
1830 e.g. To catch +JIM_EXIT+ but not +JIM_BREAK+ or +JIM_CONTINUE+
1832     catch -exit -nobreak -nocontinue -- { ... }
1834 The use of +--+ is optional. It signifies that no more return code options follow.
1836 Note that if a signal marked as `signal handle` is caught with `catch -signal`, the return value
1837 (stored in +'resultVarName'+) is name of the signal caught.
1841 +*cd* 'dirName'+
1843 Change the current working directory to +'dirName'+.
1845 Returns an empty string.
1847 This command can potentially be disruptive to an application, so it may
1848 be removed in some applications.
1850 clock
1851 ~~~~~
1852 +*clock seconds*+::
1853     Returns the current time as seconds since the epoch.
1855 +*clock clicks*+::
1856     Returns the current time in `clicks'.
1858 +*clock microseconds*+::
1859     Returns the current time in microseconds.
1861 +*clock milliseconds*+::
1862     Returns the current time in milliseconds.
1864 +*clock format* 'seconds' ?*-format* 'format?'+::
1865     Format the given time (seconds since the epoch) according to the given
1866     format. See strftime(3) for supported formats.
1867     If no format is supplied, "%c" is used.
1869 +*clock scan* 'str' *-format* 'format'+::
1870     Scan the given time string using the given format string.
1871     See strptime(3) for supported formats.
1873 close
1874 ~~~~~
1875 +*close* 'fileId'+
1877 +'fileId' *close*+
1879 Closes the file given by +'fileId'+.
1880 +'fileId'+ must be the return value from a previous invocation
1881 of the `open` command; after this command, it should not be
1882 used anymore.
1884 collect
1885 ~~~~~~~
1886 +*collect*+
1888 Normally reference garbage collection is automatically performed periodically.
1889 However it may be run immediately with the `collect` command.
1891 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
1893 concat
1894 ~~~~~~
1895 +*concat* 'arg ?arg \...?'+
1897 This command treats each argument as a list and concatenates them
1898 into a single list.  It permits any number of arguments.  For example,
1899 the command
1901     concat a b {c d e} {f {g h}}
1903 will return
1905     a b c d e f {g h}
1907 as its result.
1909 continue
1910 ~~~~~~~~
1911 +*continue*+
1913 This command may be invoked only inside the body of a loop command such
1914 as `for` or `foreach` or `while`.  It returns a  +JIM_CONTINUE+ code to
1915 signal the innermost containing loop command to skip the remainder of
1916 the loop's body but continue with the next iteration of the loop.
1918 curry
1919 ~~~~~
1920 +*alias* 'args\...'+
1922 Similar to `alias` except it creates an anonymous procedure (lambda) instead of
1923 a named procedure.
1925 the following creates a local, unnamed alias for the command `info exists`.
1927     set e [local curry info exists]
1928     if {[$e var]} {
1929       ...
1930     }
1932 `curry` returns the name of the procedure.
1934 See also `proc`, `alias`, `lambda`, `local`.
1936 dict
1937 ~~~~
1938 +*dict* 'option ?arg\...?'+
1940 Performs one of several operations on dictionary values.
1942 The +'option'+ argument determines what action is carried out by the
1943 command.  The legal +'options'+ are:
1945 +*dict create* '?key value \...?'+::
1946     Create and return a new dictionary value that contains each of
1947     the key/value mappings listed as  arguments (keys and values
1948     alternating, with each key being followed by its associated
1949     value.)
1951 +*dict exists* 'dictionary key ?key \...?'+::
1952     Returns a boolean value indicating whether the given key (or path
1953     of keys through a set of nested dictionaries) exists in the given
1954     dictionary value.  This returns a true value exactly when `dict get`
1955     on that path will succeed.
1957 +*dict get* 'dictionary ?key \...?'+::
1958     Given a dictionary value (first argument) and a key (second argument),
1959     this will retrieve the value for that key. Where several keys are
1960     supplied, the behaviour of the command shall be as if the result
1961     of "`dict get $dictVal $key`" was passed as the first argument to
1962     dict get with the remaining arguments as second (and possibly
1963     subsequent) arguments. This facilitates lookups in nested dictionaries.
1964     If no keys are provided, dict would return a list containing pairs
1965     of elements in a manner similar to array get. That is, the first
1966     element of each pair would be the key and the second element would
1967     be the value for that key.  It is an error to attempt to retrieve
1968     a value for a key that is not present in the dictionary.
1970 +*dict keys* 'dictionary ?pattern?'+::
1971     Returns a list of the keys in the dictionary.
1972     If pattern is specified, then only those keys whose
1973     names match +'pattern'+ (using the matching rules of string
1974     match) are included.
1976 +*dict merge* ?'dictionary \...'?+::
1977     Return a dictionary that contains the contents of each of the
1978     +'dictionary'+ arguments. Where two (or more) dictionaries
1979     contain a mapping for the same key, the resulting dictionary
1980     maps that key to the value according to the last dictionary on
1981     the command line containing a mapping for that key.
1983 +*dict set* 'dictionaryName key ?key \...? value'+::
1984     This operation takes the +'name'+ of a variable containing a dictionary
1985     value and places an updated dictionary value in that variable
1986     containing a mapping from the given key to the given value. When
1987     multiple keys are present, this operation creates or updates a chain
1988     of nested dictionaries.
1990 +*dict size* 'dictionary'+::
1991     Return the number of key/value mappings in the given dictionary value.
1993 +*dict unset* 'dictionaryName key ?key \...? value'+::
1994     This operation (the companion to `dict set`) takes the name of a
1995     variable containing a dictionary value and places an updated
1996     dictionary value in that variable that does not contain a mapping
1997     for the given key. Where multiple keys are present, this describes
1998     a path through nested dictionaries to the mapping to remove. At
1999     least one key must be specified, but the last key on the key-path
2000     need not exist. All other components on the path must exist.
2002 +*dict with* 'dictionaryName key ?key \...? script'+::
2003     Execute the Tcl script in +'script'+ with the value for each
2004     key in +'dictionaryName'+ mapped to a variable with the same
2005     name. Where one or more keys are given, these indicate a chain
2006     of nested dictionaries, with the innermost dictionary being the
2007     one opened out for the execution of body. Making +'dictionaryName'+
2008     unreadable will make the updates to the dictionary be discarded,
2009     and this also happens if the contents of +'dictionaryName'+ are
2010     adjusted so that the chain of dictionaries no longer exists.
2011     The result of `dict with` is (unless some kind of error occurs)
2012     the result of the evaluation of body.
2013  ::
2014     The variables are mapped in the scope enclosing the `dict with`;
2015     it is recommended that this command only be used in a local
2016     scope (procedure). Because of this, the variables set by
2017     `dict with` will continue to exist after the command finishes (unless
2018     explicitly unset). Note that changes to the contents of +'dictionaryName'+
2019     only happen when +'script'+ terminates.
2021 +*dict for, values, incr, append, lappend, update, info, replace*+ to be documented...
2025 +*env* '?name? ?default?'+
2027 If +'name'+ is supplied, returns the value of +'name'+ from the initial
2028 environment (see getenv(3)). An error is returned if +'name'+ does not
2029 exist in the environment, unless +'default'+ is supplied - in which case
2030 that value is returned instead.
2032 If no arguments are supplied, returns a list of all environment variables
2033 and their values as +{name value \...}+
2035 See also the global variable +::env+
2039 +*eof* 'fileId'+
2041 +'fileId' *eof*+
2043 Returns 1 if an end-of-file condition has occurred on +'fileId'+,
2044 0 otherwise.
2046 +'fileId'+ must have been the return value from a previous call to `open`,
2047 or it may be +stdin+, +stdout+, or +stderr+ to refer to one of the
2048 standard I/O channels.
2050 error
2051 ~~~~~
2052 +*error* 'message ?stacktrace?'+
2054 Returns a +JIM_ERR+ code, which causes command interpretation to be
2055 unwound.  +'message'+ is a string that is returned to the application
2056 to indicate what went wrong.
2058 If the +'stacktrace'+ argument is provided and is non-empty,
2059 it is used to initialize the stacktrace.
2061 This feature is most useful in conjunction with the `catch` command:
2062 if a caught error cannot be handled successfully, +'stacktrace'+ can be used
2063 to return a stack trace reflecting the original point of occurrence
2064 of the error:
2066     catch {...} errMsg
2067     ...
2068     error $errMsg [info stacktrace]
2070 See also `errorInfo`, `info stacktrace`, `catch` and `return`
2072 errorInfo
2073 ~~~~~~~~~
2074 +*errorInfo* 'error ?stacktrace?'+
2076 Returns a human-readable representation of the given error message and stack trace.
2077 Typical usage is:
2079     if {[catch {...} error]} {
2080         puts stderr [errorInfo $error [info stacktrace]]
2081         exit 1
2082     }
2084 See also `error`.
2086 eval
2087 ~~~~
2088 +*eval* 'arg ?arg\...?'+
2090 `eval` takes one or more arguments, which together comprise a Tcl
2091 command (or collection of Tcl commands separated by newlines in the
2092 usual way).  `eval` concatenates all its arguments in the same
2093 fashion as the `concat` command, passes the concatenated string to the
2094 Tcl interpreter recursively, and returns the result of that
2095 evaluation (or any error generated by it).
2097 exec
2098 ~~~~
2099 +*exec* 'arg ?arg\...?'+
2101 This command treats its arguments as the specification
2102 of one or more UNIX commands to execute as subprocesses.
2103 The commands take the form of a standard shell pipeline;
2104 +|+ arguments separate commands in the
2105 pipeline and cause standard output of the preceding command
2106 to be piped into standard input of the next command (or +|&+ for
2107 both standard output and standard error).
2109 Under normal conditions the result of the `exec` command
2110 consists of the standard output produced by the last command
2111 in the pipeline followed by the standard error output.
2113 If any of the commands writes to its standard error file,
2114 then this will be included in the result after the standard output
2115 of the last command.
2117 Note that unlike Tcl, data written to standard error does not cause
2118 `exec` to return an error.
2120 If any of the commands in the pipeline exit abnormally or
2121 are killed or suspended, then `exec` will return an error.
2122 If no standard error output was produced, or is redirected,
2123 the error message will include the normal result, as above,
2124 followed by error messages describing the abnormal terminations.
2126 If any standard error output was produced, these abnormal termination
2127 messages are suppressed.
2129 If the last character of the result or error message
2130 is a newline then that character is deleted from the result
2131 or error message for consistency with normal
2132 Tcl return values.
2134 An +'arg'+ may have one of the following special forms:
2136 +>filename+::
2137     The standard output of the last command in the pipeline
2138     is redirected to the file.  In this situation `exec`
2139     will normally return an empty string.
2141 +>>filename+::
2142     As above, but append to the file.
2144 +>@fileId+::
2145     The standard output of the last command in the pipeline is
2146     redirected to the given (writable) file descriptor (e.g. stdout,
2147     stderr, or the result of `open`). In this situation `exec`
2148     will normally return an empty string.
2150 +2>filename+::
2151     The standard error of the last command in the pipeline
2152     is redirected to the file.
2154 +2>>filename+::
2155     As above, but append to the file.
2157 +2>@fileId+::
2158     The standard error of the last command in the pipeline is
2159     redirected to the given (writable) file descriptor.
2161 +2>@1+::
2162     The standard error of the last command in the pipeline is
2163     redirected to the same file descriptor as the standard output.
2165 +>&filename+::
2166     Both the standard output and standard error of the last command
2167     in the pipeline is redirected to the file.
2169 +>>&filename+::
2170     As above, but append to the file.
2172 +<filename+::
2173     The standard input of the first command in the pipeline
2174     is taken from the file.
2176 +<<string+::
2177     The standard input of the first command is taken as the
2178     given immediate value.
2180 +<@fileId+::
2181     The standard input of the first command in the pipeline
2182     is taken from the given (readable) file descriptor.
2184 If there is no redirection of standard input, standard error
2185 or standard output, these are connected to the corresponding
2186 input or output of the application.
2188 If the last +'arg'+ is +&+ then the command will be
2189 executed in background.
2190 In this case the standard output from the last command
2191 in the pipeline will
2192 go to the application's standard output unless
2193 redirected in the command, and error output from all
2194 the commands in the pipeline will go to the application's
2195 standard error file. The return value of exec in this case
2196 is a list of process ids (pids) in the pipeline.
2198 Each +'arg'+ becomes one word for a command, except for
2199 +|+, +<+, +<<+, +>+, and +&+ arguments, and the
2200 arguments that follow +<+, +<<+, and +>+.
2202 The first word in each command is taken as the command name;
2203 the directories in the PATH environment variable are searched for
2204 an executable by the given name.
2206 No `glob` expansion or other shell-like substitutions
2207 are performed on the arguments to commands.
2209 If the command fails, the global $::errorCode (and the -errorcode
2210 option in `catch`) will be set to a list, as follows:
2212 +*CHILDKILLED* 'pid sigName msg'+::
2213         This format is used when a child process has been killed
2214         because of a signal. The pid element will be the process's
2215         identifier (in decimal). The sigName element will be the
2216         symbolic name of the signal that caused the process to
2217         terminate; it will be one of the names from the include
2218         file signal.h, such as SIGPIPE. The msg element will be a
2219         short human-readable message describing the signal, such
2220         as "write on pipe with no readers" for SIGPIPE.
2222 +*CHILDSUSP* 'pid sigName msg'+::
2223         This format is used when a child process has been suspended
2224         because of a signal. The pid element will be the process's
2225         identifier, in decimal. The sigName element will be the
2226         symbolic name of the signal that caused the process to
2227         suspend; this will be one of the names from the include
2228         file signal.h, such as SIGTTIN. The msg element will be a
2229         short human-readable message describing the signal, such
2230         as "background tty read" for SIGTTIN.
2232 +*CHILDSTATUS* 'pid code'+::
2233         This format is used when a child process has exited with a
2234         non-zero exit status. The pid element will be the process's
2235         identifier (in decimal) and the code element will be the
2236         exit code returned by the process (also in decimal).
2238 The environment for the executed command is set from $::env (unless
2239 this variable is unset, in which case the original environment is used).
2241 exists
2242 ~~~~~~
2243 +*exists ?-var|-proc|-command|-alias?* 'name'+
2245 Checks the existence of the given variable, procedure, command
2246 or alias respectively and returns 1 if it exists or 0 if not.  This command
2247 provides a more simplified/convenient version of `info exists`,
2248 `info procs` and `info commands`.
2250 If the type is omitted, a type of '-var' is used. The type may be abbreviated.
2252 exit
2253 ~~~~
2254 +*exit* '?returnCode?'+
2256 Terminate the process, returning +'returnCode'+ to the
2257 parent as the exit status.
2259 If +'returnCode'+ isn't specified then it defaults
2260 to 0.
2262 Note that exit can be caught with `catch`.
2264 expr
2265 ~~~~
2266 +*expr* 'arg'+
2268 Calls the expression processor to evaluate +'arg'+, and returns
2269 the result as a string.  See the section EXPRESSIONS above.
2271 Note that Jim supports a shorthand syntax for `expr` as +$(\...)+
2272 The following two are identical.
2274   set x [expr {3 * 2 + 1}]
2275   set x $(3 * 2 + 1)
2277 file
2278 ~~~~
2279 +*file* 'option name ?arg\...?'+
2281 Operate on a file or a file name.  +'name'+ is the name of a file.
2283 +'option'+ indicates what to do with the file name.  Any unique
2284 abbreviation for +'option'+ is acceptable.  The valid options are:
2286 +*file atime* 'name'+::
2287     Return a decimal string giving the time at which file +'name'+
2288     was last accessed.  The time is measured in the standard UNIX
2289     fashion as seconds from a fixed starting time (often January 1, 1970).
2290     If the file doesn't exist or its access time cannot be queried then an
2291     error is generated.
2293 +*file copy ?-force?* 'source target'+::
2294     Copies file +'source'+ to file +'target'+. The source file must exist.
2295     The target file must not exist, unless +-force+ is specified.
2297 +*file delete ?-force? ?--?* 'name\...'+::
2298     Deletes file or directory +'name'+. If the file or directory doesn't exist, nothing happens.
2299     If it can't be deleted, an error is generated. Non-empty directories will not be deleted
2300     unless the +-force+ options is given. In this case no errors will be generated, even
2301     if the file/directory can't be deleted. Use +'--'+ if there is any possibility of
2302     the first name being +'-force'+.
2304 +*file dirname* 'name'+::
2305     Return all of the characters in +'name'+ up to but not including
2306     the last slash character.  If there are no slashes in +'name'+
2307     then return +.+ (a single dot).  If the last slash in +'name'+ is its first
2308     character, then return +/+.
2310 +*file executable* 'name'+::
2311     Return '1' if file +'name'+ is executable by
2312     the current user, '0' otherwise.
2314 +*file exists* 'name'+::
2315     Return '1' if file +'name'+ exists and the current user has
2316     search privileges for the directories leading to it, '0' otherwise.
2318 +*file extension* 'name'+::
2319     Return all of the characters in +'name'+ after and including the
2320     last dot in +'name'+.  If there is no dot in +'name'+ then return
2321     the empty string.
2323 +*file isdirectory* 'name'+::
2324     Return '1' if file +'name'+ is a directory,
2325     '0' otherwise.
2327 +*file isfile* 'name'+::
2328     Return '1' if file +'name'+ is a regular file,
2329     '0' otherwise.
2331 +*file join* 'arg\...'+::
2332     Joins multiple path components. Note that if any components is
2333     an absolute path, the preceding components are ignored.
2334     Thus +"`file` join /tmp /root"+ returns +"/root"+.
2336 +*file link* ?*-hard|-symbolic*? 'newname target'+::
2337     Creates a hard link (default) or symbolic link from +'newname'+ to +'target'+.
2338     Note that the sense of this command is the opposite of `file rename` and `file copy`
2339     and also of `ln`, but this is compatible with Tcl.
2340     An error is returned if +'target'+ doesn't exist or +'newname'+ already exists.
2342 +*file lstat* 'name varName'+::
2343     Same as 'stat' option (see below) except uses the +'lstat'+
2344     kernel call instead of +'stat'+.  This means that if +'name'+
2345     refers to a symbolic link the information returned in +'varName'+
2346     is for the link rather than the file it refers to.  On systems that
2347     don't support symbolic links this option behaves exactly the same
2348     as the 'stat' option.
2350 +*file mkdir* 'dir1 ?dir2\...?'+::
2351     Creates each directory specified. For each pathname +'dir'+ specified,
2352     this command will create all non-existing parent directories
2353     as well as +'dir'+ itself. If an existing directory is specified,
2354     then no action is taken and no error is returned. Trying to
2355     overwrite an existing file with a directory will result in an
2356     error.  Arguments are processed in the order specified, halting
2357     at the first error, if any.
2359 +*file mtime* 'name ?time?'+::
2360     Return a decimal string giving the time at which file +'name'+
2361     was last modified.  The time is measured in the standard UNIX
2362     fashion as seconds from a fixed starting time (often January 1, 1970).
2363     If the file doesn't exist or its modified time cannot be queried then an
2364     error is generated. If +'time'+ is given, sets the modification time
2365     of the file to the given value.
2367 +*file normalize* 'name'+::
2368     Return the normalized path of +'name'+. See 'realpath(3)'.
2370 +*file owned* 'name'+::
2371     Return '1' if file +'name'+ is owned by the current user,
2372     '0' otherwise.
2374 +*file readable* 'name'+::
2375     Return '1' if file +'name'+ is readable by
2376     the current user, '0' otherwise.
2378 +*file readlink* 'name'+::
2379     Returns the value of the symbolic link given by +'name'+ (i.e. the
2380     name of the file it points to).  If
2381     +'name'+ isn't a symbolic link or its value cannot be read, then
2382     an error is returned.  On systems that don't support symbolic links
2383     this option is undefined.
2385 +*file rename* ?*-force*? 'oldname' 'newname'+::
2386     Renames the file from the old name to the new name.
2387     If +'newname'+ already exists, an error is returned unless +'-force'+ is
2388     specified.
2390 +*file rootname* 'name'+::
2391     Return all of the characters in +'name'+ up to but not including
2392     the last '.' character in the name.  If +'name'+ doesn't contain
2393     a dot, then return +'name'+.
2395 +*file size* 'name'+::
2396     Return a decimal string giving the size of file +'name'+ in bytes.
2397     If the file doesn't exist or its size cannot be queried then an
2398     error is generated.
2400 +*file stat* 'name ?varName?'+::
2401     Invoke the 'stat' kernel call on +'name'+, and return the result
2402     as a dictionary with the following keys: 'atime',
2403     'ctime', 'dev', 'gid', 'ino', 'mode', 'mtime',
2404     'nlink', 'size', 'type', 'uid'.
2405     Each element except 'type' is a decimal string with the value of
2406     the corresponding field from the 'stat' return structure; see the
2407     manual entry for 'stat' for details on the meanings of the values.
2408     The 'type' element gives the type of the file in the same form
2409     returned by the command `file type`.
2410     If +'varName'+ is specified, it is taken to be the name of an array
2411     variable and the values are also stored into the array.
2413 +*file tail* 'name'+::
2414     Return all of the characters in +'name'+ after the last slash.
2415     If +'name'+ contains no slashes then return +'name'+.
2417 +*file tempfile* '?template?'+::
2418     Creates and returns the name of a unique temporary file. If +'template'+ is omitted, a
2419     default template will be used to place the file in /tmp. See 'mkstemp(3)' for
2420     the format of the template and security concerns.
2422 +*file type* 'name'+::
2423     Returns a string giving the type of file +'name'+, which will be
2424     one of +file+, +directory+, +characterSpecial+,
2425     +blockSpecial+, +fifo+, +link+, or +socket+.
2427 +*file writable* 'name'+::
2428     Return '1' if file +'name'+ is writable by
2429     the current user, '0' otherwise.
2431 The `file` commands that return 0/1 results are often used in
2432 conditional or looping commands, for example:
2434     if {![file exists foo]} {
2435         error {bad file name}
2436     } else {
2437         ...
2438     }
2440 finalize
2441 ~~~~~~~~
2442 +*finalize* 'reference ?command?'+
2444 If +'command'+ is omitted, returns the finalizer command for the given reference.
2446 Otherwise, sets a new finalizer command for the given reference. +'command'+ may be
2447 the empty string to remove the current finalizer.
2449 The reference must be a valid reference create with the `ref`
2450 command.
2452 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2454 flush
2455 ~~~~~
2456 +*flush* 'fileId'+
2458 +'fileId' *flush*+
2460 Flushes any output that has been buffered for +'fileId'+.  +'fileId'+ must
2461 have been the return value from a previous call to `open`, or it may be
2462 +stdout+ or +stderr+ to access one of the standard I/O streams; it must
2463 refer to a file that was opened for writing.  This command returns an
2464 empty string.
2468 +*for* 'start test next body'+
2470 `for` is a looping command, similar in structure to the C `for` statement.
2471 The +'start'+, +'next'+, and +'body'+ arguments must be Tcl command strings,
2472 and +'test'+ is an expression string.
2474 The `for` command first invokes the Tcl interpreter to execute +'start'+.
2475 Then it repeatedly evaluates +'test'+ as an expression; if the result is
2476 non-zero it invokes the Tcl interpreter on +'body'+, then invokes the Tcl
2477 interpreter on +'next'+, then repeats the loop.  The command terminates
2478 when +'test'+ evaluates to 0.
2480 If a `continue` command is invoked within +'body'+ then any remaining
2481 commands in the current execution of +'body'+ are skipped; processing
2482 continues by invoking the Tcl interpreter on +'next'+, then evaluating
2483 +'test'+, and so on.
2485 If a `break` command is invoked within +'body'+ or +'next'+, then the `for`
2486 command will return immediately.
2488 The operation of `break` and `continue` are similar to the corresponding
2489 statements in C.
2491 `for` returns an empty string.
2493 foreach
2494 ~~~~~~~
2495 +*foreach* 'varName list body'+
2497 +*foreach* 'varList list ?varList2 list2 \...? body'+
2499 In this command, +'varName'+ is the name of a variable, +'list'+
2500 is a list of values to assign to +'varName'+, and +'body'+ is a
2501 collection of Tcl commands.
2503 For each field in +'list'+ (in order from left to right), `foreach` assigns
2504 the contents of the field to +'varName'+ (as if the `lindex` command
2505 had been used to extract the field), then calls the Tcl interpreter to
2506 execute +'body'+.
2508 If instead of being a simple name, +'varList'+ is used, multiple assignments
2509 are made each time through the loop, one for each element of +'varList'+.
2511 For example, if there are two elements in +'varList'+ and six elements in
2512 the list, the loop will be executed three times.
2514 If the length of the list doesn't evenly divide by the number of elements
2515 in +'varList'+, the value of the remaining variables in the last iteration
2516 of the loop are undefined.
2518 The `break` and `continue` statements may be invoked inside +'body'+,
2519 with the same effect as in the `for` command.
2521 `foreach` returns an empty string.
2523 format
2524 ~~~~~~
2525 +*format* 'formatString ?arg \...?'+
2527 This command generates a formatted string in the same way as the
2528 C 'sprintf' procedure (it uses 'sprintf' in its
2529 implementation).  +'formatString'+ indicates how to format
2530 the result, using +%+ fields as in 'sprintf', and the additional
2531 arguments, if any, provide values to be substituted into the result.
2533 All of the 'sprintf' options are valid; see the 'sprintf'
2534 man page for details.  Each +'arg'+ must match the expected type
2535 from the +%+ field in +'formatString'+; the `format` command
2536 converts each argument to the correct type (floating, integer, etc.)
2537 before passing it to 'sprintf' for formatting.
2539 The only unusual conversion is for +%c+; in this case the argument
2540 must be a decimal string, which will then be converted to the corresponding
2541 ASCII (or UTF-8) character value.
2543 In addition, Jim Tcl provides basic support for conversion to binary with +%b+.
2545 `format` does backslash substitution on its +'formatString'+
2546 argument, so backslash sequences in +'formatString'+ will be handled
2547 correctly even if the argument is in braces.
2549 The return value from `format` is the formatted string.
2551 getref
2552 ~~~~~~
2553 +*getref* 'reference'+
2555 Returns the string associated with +'reference'+. The reference must
2556 be a valid reference create with the `ref` command.
2558 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2560 gets
2561 ~~~~
2562 +*gets* 'fileId ?varName?'+
2564 +'fileId' *gets* '?varName?'+
2566 Reads the next line from the file given by +'fileId'+ and discards
2567 the terminating newline character.
2569 If +'varName'+ is specified, then the line is placed in the variable
2570 by that name and the return value is a count of the number of characters
2571 read (not including the newline).
2573 If the end of the file is reached before reading
2574 any characters then -1 is returned and +'varName'+ is set to an
2575 empty string.
2577 If +'varName'+ is not specified then the return value will be
2578 the line (minus the newline character) or an empty string if
2579 the end of the file is reached before reading any characters.
2581 An empty string will also be returned if a line contains no characters
2582 except the newline, so `eof` may have to be used to determine
2583 what really happened.
2585 If the last character in the file is not a newline character, then
2586 `gets` behaves as if there were an additional newline character
2587 at the end of the file.
2589 +'fileId'+ must be +stdin+ or the return value from a previous
2590 call to `open`; it must refer to a file that was opened
2591 for reading.
2593 glob
2594 ~~~~
2595 +*glob* ?*-nocomplain*? ?*-directory* 'dir'? ?*-tails*? ?*--*? 'pattern ?pattern \...?'+
2597 This command performs filename globbing, using csh rules.  The returned
2598 value from `glob` is the list of expanded filenames.
2600 If +-nocomplain+ is specified as the first argument then an empty
2601 list may be returned;  otherwise an error is returned if the expanded
2602 list is empty.  The +-nocomplain+ argument must be provided
2603 exactly: an abbreviation will not be accepted.
2605 If +-directory+ is given, the +'dir'+ is understood to contain a
2606 directory name to search in. This allows globbing inside directories
2607 whose names may contain glob-sensitive characters. The returned names
2608 include the directory name unless +'-tails'+ is specified.
2610 If +'-tails'+ is specified, along with +-directory+, the returned names
2611 are relative to the given directory.
2613 global
2614 ~~~~~~
2616 +*global* 'varName ?varName \...?'+
2618 This command is ignored unless a Tcl procedure is being interpreted.
2619 If so, then it declares each given +'varName'+ to be a global variable
2620 rather than a local one.  For the duration of the current procedure
2621 (and only while executing in the current procedure), any reference to
2622 +'varName'+ will be bound to a global variable instead
2623 of a local one.
2625 An alternative to using `global` is to use the +::+ prefix
2626 to explicitly name a variable in the global scope.
2630 +*if* 'expr1' ?*then*? 'body1' *elseif* 'expr2' ?*then*? 'body2' *elseif* \... ?*else*? ?'bodyN'?+
2632 The `if` command evaluates +'expr1'+ as an expression (in the same way
2633 that `expr` evaluates its argument).  The value of the expression must
2634 be numeric; if it is non-zero then +'body1'+ is executed by passing it to
2635 the Tcl interpreter.
2637 Otherwise +'expr2'+ is evaluated as an expression and if it is non-zero
2638 then +'body2'+ is executed, and so on.
2640 If none of the expressions evaluates to non-zero then +'bodyN'+ is executed.
2642 The +then+ and +else+ arguments are optional "noise words" to make the
2643 command easier to read.
2645 There may be any number of +elseif+ clauses, including zero.  +'bodyN'+
2646 may also be omitted as long as +else+ is omitted too.
2648 The return value from the command is the result of the body script that
2649 was executed, or an empty string if none of the expressions was non-zero
2650 and there was no +'bodyN'+.
2652 incr
2653 ~~~~
2654 +*incr* 'varName ?increment?'+
2656 Increment the value stored in the variable whose name is +'varName'+.
2657 The value of the variable must be integral.
2659 If +'increment'+ is supplied then its value (which must be an
2660 integer) is added to the value of variable +'varName'+;  otherwise
2661 1 is added to +'varName'+.
2663 The new value is stored as a decimal string in variable +'varName'+
2664 and also returned as result.
2666 If the variable does not exist, the variable is implicitly created
2667 and set to +0+ first.
2669 info
2670 ~~~~
2672 +*info* 'option ?arg\...?'+::
2674 Provide information about various internals to the Tcl interpreter.
2675 The legal +'option'+'s (which may be abbreviated) are:
2677 +*info args* 'procname'+::
2678     Returns a list containing the names of the arguments to procedure
2679     +'procname'+, in order.  +'procname'+ must be the name of a
2680     Tcl command procedure.
2682 +*info alias* 'command'+::
2683     +'command'+ must be an alias created with `alias`. In which case the target
2684     command and arguments, as passed to `alias` are returned. See `exists -alias`
2686 +*info body* 'procname'+::
2687     Returns the body of procedure +'procname'+.  +'procname'+ must be
2688     the name of a Tcl command procedure.
2690 +*info channels*+::
2691     Returns a list of all open file handles from `open` or `socket`
2693 +*info commands* ?'pattern'?+::
2694     If +'pattern'+ isn't specified, returns a list of names of all the
2695     Tcl commands, including both the built-in commands written in C and
2696     the command procedures defined using the `proc` command.
2697     If +'pattern'+ is specified, only those names matching +'pattern'+
2698     are returned.  Matching is determined using the same rules as for
2699     `string match`.
2701 +*info complete* 'command' ?'missing'?+::
2702     Returns 1 if +'command'+ is a complete Tcl command in the sense of
2703     having no unclosed quotes, braces, brackets or array element names,
2704     If the command doesn't appear to be complete then 0 is returned.
2705     This command is typically used in line-oriented input environments
2706     to allow users to type in commands that span multiple lines;  if the
2707     command isn't complete, the script can delay evaluating it until additional
2708     lines have been typed to complete the command. If +'varName'+ is specified, the
2709     missing character is stored in the variable with that name.
2711 +*info exists* 'varName'+::
2712     Returns '1' if the variable named +'varName'+ exists in the
2713     current context (either as a global or local variable), returns '0'
2714     otherwise.
2716 +*info frame* ?'number'?+::
2717     If +'number'+ is not specified, this command returns a number
2718     which is the same result as `info level` - the current stack frame level.
2719     If +'number'+ is specified, then the result is a list consisting of the procedure,
2720     filename and line number for the procedure call at level +'number'+ on the stack.
2721     If +'number'+ is positive then it selects a particular stack level (1 refers
2722     to the top-most active procedure, 2 to the procedure it called, and
2723     so on); otherwise it gives a level relative to the current level
2724     (0 refers to the current procedure, -1 to its caller, and so on).
2725     The level has an identical meaning to `info level`.
2727 +*info globals* ?'pattern'?+::
2728     If +'pattern'+ isn't specified, returns a list of all the names
2729     of currently-defined global variables.
2730     If +'pattern'+ is specified, only those names matching +'pattern'+
2731     are returned.  Matching is determined using the same rules as for
2732     `string match`.
2734 +*info hostname*+::
2735     An alias for `os.gethostname` for compatibility with Tcl 6.x
2737 +*info level* ?'number'?+::
2738     If +'number'+ is not specified, this command returns a number
2739     giving the stack level of the invoking procedure, or 0 if the
2740     command is invoked at top-level.  If +'number'+ is specified,
2741     then the result is a list consisting of the name and arguments for the
2742     procedure call at level +'number'+ on the stack.  If +'number'+
2743     is positive then it selects a particular stack level (1 refers
2744     to the top-most active procedure, 2 to the procedure it called, and
2745     so on); otherwise it gives a level relative to the current level
2746     (0 refers to the current procedure, -1 to its caller, and so on).
2747     See the `uplevel` command for more information on what stack
2748     levels mean.
2750 +*info locals* ?'pattern'?+::
2751     If +'pattern'+ isn't specified, returns a list of all the names
2752     of currently-defined local variables, including arguments to the
2753     current procedure, if any.  Variables defined with the `global`
2754     and `upvar` commands will not be returned.  If +'pattern'+ is
2755     specified, only those names matching +'pattern'+ are returned.
2756     Matching is determined using the same rules as for `string match`.
2758 +*info nameofexecutable*+::
2759     Returns the name of the binary file from which the application
2760     was invoked. A full path will be returned, unless the path
2761     can't be determined, in which case the empty string will be returned.
2763 +*info procs* ?'pattern'?+::
2764     If +'pattern'+ isn't specified, returns a list of all the
2765     names of Tcl command procedures.
2766     If +'pattern'+ is specified, only those names matching +'pattern'+
2767     are returned.  Matching is determined using the same rules as for
2768     `string match`.
2770 +*info references*+::
2771     Returns a list of all references which have not yet been garbage
2772     collected.
2774 +*info returncodes* ?'code'?+::
2775     Returns a list representing the mapping of standard return codes
2776     to names. e.g. +{0 ok 1 error 2 return \...}+. If a code is given,
2777     instead returns the name for the given code.
2779 +*info script*+::
2780     If a Tcl script file is currently being evaluated (i.e. there is a
2781     call to 'Jim_EvalFile' active or there is an active invocation
2782     of the `source` command), then this command returns the name
2783     of the innermost file being processed.  Otherwise the command returns an
2784     empty string.
2786 +*info source* 'script ?filename line?'+::
2787     With a single argument, returns the original source location of the given script as a list of
2788     +{filename linenumber}+. If the source location can't be determined, the
2789     list +{{} 0}+ is returned. If +'filename'+ and +'line'+ are given, returns a copy
2790     of +'script'+ with the associate source information. This can be useful to produce
2791     useful messages from `eval`, etc. if the original source information may be lost.
2793 +*info stacktrace*+::
2794     After an error is caught with `catch`, returns the stack trace as a list
2795     of +{procedure filename line \...}+.
2797 +*info statics* 'procname'+::
2798     Returns a dictionary of the static variables of procedure
2799     +'procname'+.  +'procname'+ must be the name of a Tcl command
2800     procedure. An empty dictionary is returned if the procedure has
2801     no static variables.
2803 +*info version*+::
2804     Returns the version number for this version of Jim in the form +*x.yy*+.
2806 +*info vars* ?'pattern'?+::
2807     If +'pattern'+ isn't specified,
2808     returns a list of all the names of currently-visible variables, including
2809     both locals and currently-visible globals.
2810     If +'pattern'+ is specified, only those names matching +'pattern'+
2811     are returned.  Matching is determined using the same rules as for
2812     `string match`.
2814 join
2815 ~~~~
2816 +*join* 'list ?joinString?'+
2818 The +'list'+ argument must be a valid Tcl list.  This command returns the
2819 string formed by joining all of the elements of +'list'+ together with
2820 +'joinString'+ separating each adjacent pair of elements.
2822 The +'joinString'+ argument defaults to a space character.
2824 kill
2825 ~~~~
2826 +*kill* ?'SIG'|*-0*? 'pid'+
2828 Sends the given signal to the process identified by +'pid'+.
2830 The signal may be specified by name or number in one of the following forms:
2832 * +TERM+
2833 * +SIGTERM+
2834 * +-TERM+
2835 * +15+
2836 * +-15+
2838 The signal name may be in either upper or lower case.
2840 The special signal name +-0+ simply checks that a signal +'could'+ be sent.
2842 If no signal is specified, SIGTERM is used.
2844 An error is raised if the signal could not be delivered.
2846 lambda
2847 ~~~~~~
2848 +*lambda* 'args ?statics? body'+
2850 The `lambda` command is identical to `proc`, except rather than
2851 creating a named procedure, it creates an anonymous procedure and returns
2852 the name of the procedure.
2854 See `proc` and GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
2856 lappend
2857 ~~~~~~~
2858 +*lappend* 'varName value ?value value \...?'+
2860 Treat the variable given by +'varName'+ as a list and append each of
2861 the +'value'+ arguments to that list as a separate element, with spaces
2862 between elements.
2864 If +'varName'+ doesn't exist, it is created as a list with elements given
2865 by the +'value'+ arguments. `lappend` is similar to `append` except that
2866 each +'value'+ is appended as a list element rather than raw text.
2868 This command provides a relatively efficient way to build up large lists.
2869 For example,
2871     lappend a $b
2873 is much more efficient than
2875     set a [concat $a [list $b]]
2877 when +$a+ is long.
2879 lassign
2880 ~~~~~~~
2881 +*lassign* 'list varName ?varName \...?'+
2883 This command treats the value +'list'+ as a list and assigns successive elements from that list to
2884 the variables given by the +'varName'+ arguments in order. If there are more variable names than
2885 list elements, the remaining variables are set to the empty string. If there are more list elements
2886 than variables, a list of unassigned elements is returned.
2888     jim> lassign {1 2 3} a b; puts a=$a,b=$b
2889     3
2890     a=1,b=2
2892 local
2893 ~~~~~
2894 +*local* 'cmd ?arg\...?'+
2896 First, `local` evaluates +'cmd'+ with the given arguments. The return value must
2897 be the name of an existing command, which is marked as having local scope.
2898 This means that when the current procedure exits, the specified
2899 command is deleted. This can be useful with `lambda`, local procedures or
2900 to automatically close a filehandle.
2902 In addition, if a command already exists with the same name,
2903 the existing command will be kept rather than deleted, and may be called
2904 via `upcall`. The previous command will be restored when the current
2905 procedure exits. See `upcall` for more details.
2907 In this example, a local procedure is created. Note that the procedure
2908 continues to have global scope while it is active.
2910     proc outer {} {
2911       # proc ... returns "inner" which is marked local
2912       local proc inner {} {
2913         # will be deleted when 'outer' exits
2914       }
2916       inner
2917       ...
2918     }
2920 In this example, the lambda is deleted at the end of the procedure rather
2921 than waiting until garbage collection.
2923     proc outer {} {
2924       set x [lambda inner {args} {
2925         # will be deleted when 'outer' exits
2926       }]
2927       # Use 'function' here which simply returns $x
2928       local function $x
2930       $x ...
2931       ...
2932     }
2934 loop
2935 ~~~~
2936 +*loop* 'var first limit ?incr? body'+
2938 Similar to `for` except simpler and possibly more efficient.
2939 With a positive increment, equivalent to:
2941   for {set var $first} {$var < $limit} {incr var $incr} $body
2943 If +'incr'+ is not specified, 1 is used.
2944 Note that setting the loop variable inside the loop does not
2945 affect the loop count.
2947 lindex
2948 ~~~~~~
2949 +*lindex* 'list ?index ...?'+
2951 Treats +'list'+ as a Tcl list and returns element +'index'+ from it
2952 (0 refers to the first element of the list).
2953 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2955 In extracting the element, +'lindex'+ observes the same rules concerning
2956 braces and quotes and backslashes as the Tcl command interpreter; however,
2957 variable substitution and command substitution do not occur.
2959 If no index values are given, simply returns +'list'+
2961 If +'index'+ is negative or greater than or equal to the number of elements
2962 in +'list'+, then an empty string is returned.
2964 If additional index arguments are supplied, then each argument is
2965 used in turn to select an element from the previous indexing
2966 operation, allowing the script to select elements from sublists.
2968 linsert
2969 ~~~~~~~
2970 +*linsert* 'list index element ?element element \...?'+
2972 This command produces a new list from +'list'+ by inserting all
2973 of the +'element'+ arguments just before the element +'index'+
2974 of +'list'+. Each +'element'+ argument will become
2975 a separate element of the new list. If +'index'+ is less than
2976 or equal to zero, then the new elements are inserted at the
2977 beginning of the list. If +'index'+ is greater than or equal
2978 to the number of elements in the list, then the new elements are
2979 appended to the list.
2981 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
2983 list
2984 ~~~~
2986 +*list* 'arg ?arg \...?'+
2988 This command returns a list comprised of all the arguments, +'arg'+. Braces
2989 and backslashes get added as necessary, so that the `lindex` command
2990 may be used on the result to re-extract the original arguments, and also
2991 so that `eval` may be used to execute the resulting list, with
2992 +'arg1'+ comprising the command's name and the other args comprising
2993 its arguments. `list` produces slightly different results than
2994 `concat`:  `concat` removes one level of grouping before forming
2995 the list, while `list` works directly from the original arguments.
2996 For example, the command
2998     list a b {c d e} {f {g h}}
3000 will return
3002     a b {c d e} {f {g h}}
3004 while `concat` with the same arguments will return
3006     a b c d e f {g h}
3008 llength
3009 ~~~~~~~
3010 +*llength* 'list'+
3012 Treats +'list'+ as a list and returns a decimal string giving
3013 the number of elements in it.
3015 lset
3016 ~~~~
3017 +*lset* 'varName ?index ..? newValue'+
3019 Sets an element in a list.
3021 The `lset` command accepts a parameter, +'varName'+, which it interprets
3022 as the name of a variable containing a Tcl list. It also accepts
3023 zero or more indices into the list. Finally, it accepts a new value
3024 for an element of varName. If no indices are presented, the command
3025 takes the form:
3027     lset varName newValue
3029 In this case, newValue replaces the old value of the variable
3030 varName.
3032 When presented with a single index, the `lset` command
3033 treats the content of the varName variable as a Tcl list. It addresses
3034 the index'th element in it (0 refers to the first element of the
3035 list). When interpreting the list, `lset` observes the same rules
3036 concerning braces and quotes and backslashes as the Tcl command
3037 interpreter; however, variable substitution and command substitution
3038 do not occur. The command constructs a new list in which the
3039 designated element is replaced with newValue. This new list is
3040 stored in the variable varName, and is also the return value from
3041 the `lset` command.
3043 If index is negative or greater than or equal to the number of
3044 elements in $varName, then an error occurs.
3046 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'index'+.
3048 If additional index arguments are supplied, then each argument is
3049 used in turn to address an element within a sublist designated by
3050 the previous indexing operation, allowing the script to alter
3051 elements in sublists. The command,
3053     lset a 1 2 newValue
3055 replaces element 2 of sublist 1 with +'newValue'+.
3057 The integer appearing in each index argument must be greater than
3058 or equal to zero. The integer appearing in each index argument must
3059 be strictly less than the length of the corresponding list. In other
3060 words, the `lset` command cannot change the size of a list. If an
3061 index is outside the permitted range, an error is reported.
3063 lmap
3064 ~~~~
3066 +*lmap* 'varName list body'+
3068 +*lmap* 'varList list ?varList2 list2 \...? body'+
3070 `lmap` is a "collecting" `foreach` which returns a list of its results.
3072 For example:
3074     jim> lmap i {1 2 3 4 5} {expr $i*$i}
3075     1 4 9 16 25
3076     jim> lmap a {1 2 3} b {A B C} {list $a $b}
3077     {1 A} {2 B} {3 C}
3079 If the body invokes `continue`, no value is added for this iteration.
3080 If the body invokes `break`, the loop ends and no more values are added.
3082 load
3083 ~~~~
3084 +*load* 'filename'+
3086 Loads the dynamic extension, +'filename'+. Generally the filename should have
3087 the extension +.so+. The initialisation function for the module must be based
3088 on the name of the file. For example loading +hwaccess.so+ will invoke
3089 the initialisation function, +Jim_hwaccessInit+. Normally the `load` command
3090 should not be used directly. Instead it is invoked automatically by `package require`.
3092 lrange
3093 ~~~~~~
3094 +*lrange* 'list first last'+
3096 +'list'+ must be a valid Tcl list. This command will return a new
3097 list consisting of elements +'first'+ through +'last'+, inclusive.
3099 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
3101 If +'last'+ is greater than or equal to the number of elements
3102 in the list, then it is treated as if it were +end+.
3104 If +'first'+ is greater than +'last'+ then an empty string
3105 is returned.
3107 Note: +"`lrange` 'list first first'"+ does not always produce the
3108 same result as +"`lindex` 'list first'"+ (although it often does
3109 for simple fields that aren't enclosed in braces); it does, however,
3110 produce exactly the same results as +"`list` [`lindex` 'list first']"+
3112 lreplace
3113 ~~~~~~~~
3115 +*lreplace* 'list first last ?element element \...?'+
3117 Returns a new list formed by replacing one or more elements of
3118 +'list'+ with the +'element'+ arguments.
3120 +'first'+ gives the index in +'list'+ of the first element
3121 to be replaced.
3123 If +'first'+ is less than zero then it refers to the first
3124 element of +'list'+;  the element indicated by +'first'+
3125 must exist in the list.
3127 +'last'+ gives the index in +'list'+ of the last element
3128 to be replaced;  it must be greater than or equal to +'first'+.
3130 See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
3132 The +'element'+ arguments specify zero or more new arguments to
3133 be added to the list in place of those that were deleted.
3135 Each +'element'+ argument will become a separate element of
3136 the list.
3138 If no +'element'+ arguments are specified, then the elements
3139 between +'first'+ and +'last'+ are simply deleted.
3141 lrepeat
3142 ~~~~~~~~
3143 +*lrepeat* 'number element1 ?element2 \...?'+
3145 Build a list by repeating elements +'number'+ times (which must be
3146 a positive integer).
3148     jim> lrepeat 3 a b
3149     a b a b a b
3151 lreverse
3152 ~~~~~~~~
3153 +*lreverse* 'list'+
3155 Returns the list in reverse order.
3157     jim> lreverse {1 2 3}
3158     3 2 1
3160 lsearch
3161 ~~~~~~~
3162 +*lsearch* '?options? list pattern'+
3164 This command searches the elements +'list'+ to see if one of them matches +'pattern'+. If so, the
3165 command returns the index of the first matching element (unless the options +-all+, +-inline+ or +-bool+ are
3166 specified.) If not, the command returns -1. The option arguments indicates how the elements of
3167 the list are to be matched against pattern and must have one of the values below:
3169 *Note* that this command is different from Tcl in that default match type is +-exact+ rather than +-glob+.
3171 +*-exact*+::
3172     +'pattern'+ is a literal string that is compared for exact equality against each list element.
3173     This is the default.
3175 +*-glob*+::
3176     +'pattern'+ is a glob-style pattern which is matched against each list element using the same
3177     rules as the string match command.
3179 +*-regexp*+::
3180     +'pattern'+ is treated as a regular expression and matched against each list element using
3181     the rules described by `regexp`.
3183 +*-command* 'cmdname'+::
3184     +'cmdname'+ is a command which is used to match the pattern against each element of the
3185     list. It is invoked as +'cmdname' ?*-nocase*? 'pattern listvalue'+ and should return 1
3186     for a match, or 0 for no match.
3188 +*-all*+::
3189     Changes the result to be the list of all matching indices (or all matching values if
3190     +-inline+ is specified as well). If indices are returned, the indices will be in numeric
3191     order. If values are returned, the order of the values will be the order of those values
3192     within the input list.
3194 +*-inline*+::
3195     The matching value is returned instead of its index (or an empty string if no value
3196     matches). If +-all+ is also specified, then the result of the command is the list of all
3197     values that matched. The +-inline+ and +-bool+ options are mutually exclusive.
3199 +*-bool*+::
3200     Changes the result to '1' if a match was found, or '0' otherwise. If +-all+ is also specified,
3201     the result will be a list of '0' and '1' for each element of the list depending upon whether
3202     the corresponding element matches. The +-inline+ and +-bool+ options are mutually exclusive.
3204 +*-not*+::
3205     This negates the sense of the match, returning the index (or value
3206     if +-inline+ is specified) of the first non-matching value in the
3207     list. If +-bool+ is also specified, the '0' will be returned if a
3208     match is found, or '1' otherwise. If +-all+ is also specified,
3209     non-matches will be returned rather than matches.
3211 +*-nocase*+::
3212     Causes comparisons to be handled in a case-insensitive manner.
3214 lsort
3215 ~~~~~
3216 +*lsort* ?*-index* 'listindex'? ?*-nocase|-integer|-real|-command* 'cmdname'? ?*-unique*? ?*-decreasing*|*-increasing*? 'list'+
3218 Sort the elements of +'list'+, returning a new list in sorted order.
3219 By default, ASCII (or UTF-8) sorting is used, with the result in increasing order.
3221 If +-nocase+ is specified, comparisons are case-insensitive.
3223 If +-integer+ is specified, numeric sorting is used.
3225 If +-real+ is specified, floating point number sorting is used.
3227 If +-command 'cmdname'+ is specified, +'cmdname'+ is treated as a command
3228 name. For each comparison, +'cmdname $value1 $value2+' is called which
3229 should compare the values and return an integer less than, equal
3230 to, or greater than zero if the +'$value1'+ is to be considered less
3231 than, equal to, or greater than +'$value2'+, respectively.
3233 If +-decreasing+ is specified, the resulting list is in the opposite
3234 order to what it would be otherwise. +-increasing+ is the default.
3236 If +-unique+ is specified, then only the last set of duplicate elements found in the list will be retained.
3237 Note that duplicates are determined relative to the comparison used in the sort. Thus if +-index 0+ is used,
3238 +{1 a}+ and +{1 b}+ would be considered duplicates and only the second element, +{1 b}+, would be retained.
3240 If +-index 'listindex'+ is specified, each element of the list is treated as a list and
3241 the given index is extracted from the list for comparison. The list index may
3242 be any valid list index, such as +1+, +end+ or +end-2+.
3244 open
3245 ~~~~
3246 +*open* 'fileName ?access?'+
3248 +*open* '|command-pipeline ?access?'+
3250 Opens a file and returns an identifier
3251 that may be used in future invocations
3252 of commands like `read`, `puts`, and `close`.
3253 +'fileName'+ gives the name of the file to open.
3255 The +'access'+ argument indicates the way in which the file is to be accessed.
3256 It may have any of the following values:
3258 +r+::
3259     Open the file for reading only; the file must already exist.
3261 +r++::
3262     Open the file for both reading and writing; the file must
3263     already exist.
3265 +w+::
3266     Open the file for writing only. Truncate it if it exists. If it doesn't
3267     exist, create a new file.
3269 +w++::
3270     Open the file for reading and writing. Truncate it if it exists.
3271     If it doesn't exist, create a new file.
3273 +a+::
3274     Open the file for writing only. The file must already exist, and the file
3275     is positioned so that new data is appended to the file.
3277 +a++::
3278     Open the file for reading and writing. If the file doesn't
3279     exist, create a new empty file. Set the initial access position
3280     to the end of the file.
3282 +'access'+ defaults to 'r'.
3284 If a file is opened for both reading and writing, then `seek`
3285 must be invoked between a read and a write, or vice versa.
3287 If the first character of +'fileName'+ is "|" then the remaining
3288 characters of +'fileName'+ are treated as a list of arguments that
3289 describe a command pipeline to invoke, in the same style as the
3290 arguments for exec. In this case, the channel identifier returned
3291 by open may be used to write to the command's input pipe or read
3292 from its output pipe, depending on the value of +'access'+. If write-only
3293 access is used (e.g. +'access'+ is 'w'), then standard output for the
3294 pipeline is directed to the current standard output unless overridden
3295 by the command. If read-only access is used (e.g. +'access'+ is r),
3296 standard input for the pipeline is taken from the current standard
3297 input unless overridden by the command.
3299 The `pid` command may be used to return the process ids of the commands
3300 forming the command pipeline.
3302 See also `socket`, `pid`, `exec`
3304 package
3305 ~~~~~~~
3306 +*package provide* 'name ?version?'+
3308 Indicates that the current script provides the package named +'name'+.
3309 If no version is specified, '1.0' is used.
3311 Any script which provides a package may include this statement
3312 as the first statement, although it is not required.
3314 +*package require* 'name ?version?'*+
3316 Searches for the package with the given +'name'+ by examining each path
3317 in '$::auto_path' and trying to load '$path/$name.so' as a dynamic extension,
3318 or '$path/$name.tcl' as a script package.
3320 The first such file which is found is considered to provide the package.
3321 (The version number is ignored).
3323 If '$name.so' exists, it is loaded with the `load` command,
3324 otherwise if '$name.tcl' exists it is loaded with the `source` command.
3326 If `load` or `source` fails, `package require` will fail immediately.
3327 No further attempt will be made to locate the file.
3331 +*pid*+
3333 +*pid* 'fileId'+
3335 The first form returns the process identifier of the current process.
3337 The second form accepts a handle returned by `open` and returns a list
3338 of the process ids forming the pipeline in the same form as `exec ... &`.
3339 If 'fileId' represents a regular file handle rather than a command pipeline,
3340 the empty string is returned instead.
3342 See also `open`, `exec`
3344 proc
3345 ~~~~
3346 +*proc* 'name args ?statics? body'+
3348 The `proc` command creates a new Tcl command procedure, +'name'+.
3349 When the new command is invoked, the contents of +'body'+ will be executed.
3350 Tcl interpreter. +'args'+ specifies the formal arguments to the procedure.
3351 If specified, +'statics'+, declares static variables which are bound to the
3352 procedure.
3354 See PROCEDURES for detailed information about Tcl procedures.
3356 The `proc` command returns +'name'+ (which is useful with `local`).
3358 When a procedure is invoked, the procedure's return value is the
3359 value specified in a `return` command.  If the procedure doesn't
3360 execute an explicit `return`, then its return value is the value
3361 of the last command executed in the procedure's body.
3363 If an error occurs while executing the procedure body, then the
3364 procedure-as-a-whole will return that same error.
3366 puts
3367 ~~~~
3368 +*puts* ?*-nonewline*? '?fileId? string'+
3370 +'fileId' *puts* ?*-nonewline*? 'string'+
3372 Writes the characters given by +'string'+ to the file given
3373 by +'fileId'+. +'fileId'+ must have been the return
3374 value from a previous call to `open`, or it may be
3375 +stdout+ or +stderr+ to refer to one of the standard I/O
3376 channels; it must refer to a file that was opened for
3377 writing.
3379 In the first form, if no +'fileId'+ is specified then it defaults to +stdout+.
3380 `puts` normally outputs a newline character after +'string'+,
3381 but this feature may be suppressed by specifying the +-nonewline+
3382 switch.
3384 Output to files is buffered internally by Tcl; the `flush`
3385 command may be used to force buffered characters to be output.
3389 +*pwd*+
3391 Returns the path name of the current working directory.
3393 rand
3394 ~~~~
3395 +*rand* '?min? ?max?'+
3397 Returns a random integer between +'min'+ (defaults to 0) and +'max'+
3398 (defaults to the maximum integer).
3400 If only one argument is given, it is interpreted as +'max'+.
3402 range
3403 ~~~~
3404 +*range* '?start? end ?step?'+
3406 Returns a list of integers starting at +'start'+ (defaults to 0)
3407 and ranging up to but not including +'end'+ in steps of +'step'+ defaults to 1).
3409     jim> range 5
3410     0 1 2 3 4
3411     jim> range 2 5
3412     2 3 4
3413     jim> range 2 10 4
3414     2 6
3415     jim> range 7 4 -2
3416     7 5
3418 read
3419 ~~~~
3420 +*read* ?*-nonewline*? 'fileId'+
3422 +'fileId' *read* ?*-nonewline*?+
3424 +*read* 'fileId numBytes'+
3426 +'fileId' *read* 'numBytes'+
3429 In the first form, all of the remaining bytes are read from the file
3430 given by +'fileId'+; they are returned as the result of the command.
3431 If the +-nonewline+ switch is specified then the last
3432 character of the file is discarded if it is a newline.
3434 In the second form, the extra argument specifies how many bytes to read;
3435 exactly this many bytes will be read and returned, unless there are fewer than
3436 +'numBytes'+ bytes left in the file; in this case, all the remaining
3437 bytes are returned.
3439 +'fileId'+ must be +stdin+ or the return value from a previous call
3440 to `open`; it must refer to a file that was opened for reading.
3442 regexp
3443 ~~~~~~
3444 +*regexp ?-nocase? ?-line? ?-indices? ?-start* 'offset'? *?-all? ?-inline? ?--?* 'exp string ?matchVar? ?subMatchVar subMatchVar \...?'+
3446 Determines whether the regular expression +'exp'+ matches part or
3447 all of +'string'+ and returns 1 if it does, 0 if it doesn't.
3449 See REGULAR EXPRESSIONS above for complete information on the
3450 syntax of +'exp'+ and how it is matched against +'string'+.
3452 If additional arguments are specified after +'string'+ then they
3453 are treated as the names of variables to use to return
3454 information about which part(s) of +'string'+ matched +'exp'+.
3455 +'matchVar'+ will be set to the range of +'string'+ that
3456 matched all of +'exp'+. The first +'subMatchVar'+ will contain
3457 the characters in +'string'+ that matched the leftmost parenthesized
3458 subexpression within +'exp'+, the next +'subMatchVar'+ will
3459 contain the characters that matched the next parenthesized
3460 subexpression to the right in +'exp'+, and so on.
3462 Normally, +'matchVar'+ and the each +'subMatchVar'+ are set to hold the
3463 matching characters from `string`, however see +-indices+ and
3464 +-inline+ below.
3466 If there are more values for +'subMatchVar'+ than parenthesized subexpressions
3467 within +'exp'+, or if a particular subexpression in +'exp'+ doesn't
3468 match the string (e.g. because it was in a portion of the expression
3469 that wasn't matched), then the corresponding +'subMatchVar'+ will be
3470 set to +"-1 -1"+ if +-indices+ has been specified or to an empty
3471 string otherwise.
3473 The following switches modify the behaviour of +'regexp'+
3475 +*-nocase*+::
3476     Causes upper-case and lower-case characters to be treated as
3477     identical during the matching process.
3479 +*-line*+::
3480     Use newline-sensitive matching. By default, newline
3481     is a completely ordinary character with no special meaning in
3482     either REs or strings. With this flag, +[^+ bracket expressions
3483     and +.+ never match newline, an +^+ anchor matches the null
3484     string after any newline in the string in addition to its normal
3485     function, and the +$+ anchor matches the null string before any
3486     newline in the string in addition to its normal function.
3488 +*-indices*+::
3489     Changes what is stored in the subMatchVars. Instead of
3490     storing the matching characters from string, each variable
3491     will contain a list of two decimal strings giving the indices
3492     in string of the first and last characters in the matching
3493     range of characters.
3495 +*-start* 'offset'+::
3496     Specifies a character index offset into the string at which to start
3497     matching the regular expression. If +-indices+ is
3498     specified, the indices will be indexed starting from the
3499     absolute beginning of the input string. +'offset'+ will be
3500     constrained to the bounds of the input string.
3502 +*-all*+::
3503     Causes the regular expression to be matched as many times as possible
3504     in the string, returning the total number of matches found. If this
3505     is specified with match variables, they will contain information
3506     for the last match only.
3508 +*-inline*+::
3509     Causes the command to return, as a list, the data that would otherwise
3510     be placed in match variables. When using +-inline+, match variables
3511     may not be specified. If used with +-all+, the list will be concatenated
3512     at each iteration, such that a flat list is always returned. For
3513     each match iteration, the command will append the overall match
3514     data, plus one element for each subexpression in the regular
3515     expression.
3517 +*--*+::
3518     Marks the end of switches. The argument following this one will be
3519     treated as +'exp'+ even if it starts with a +-+.
3521 regsub
3522 ~~~~~~
3523 +*regsub ?-nocase? ?-all? ?-line? ?-start* 'offset'? ?*--*? 'exp string subSpec ?varName?'+
3525 This command matches the regular expression +'exp'+ against
3526 +'string'+ using the rules described in REGULAR EXPRESSIONS
3527 above.
3529 If +'varName'+ is specified, the commands stores +'string'+ to +'varName'+
3530 with the substitutions detailed below, and returns the number of
3531 substitutions made (normally 1 unless +-all+ is specified).
3532 This is 0 if there were no matches.
3534 If +'varName'+ is not specified, the substituted string will be returned
3535 instead.
3537 When copying +'string'+, the portion of +'string'+ that
3538 matched +'exp'+ is replaced with +'subSpec'+.
3539 If +'subSpec'+ contains a +&+ or +{backslash}0+, then it is replaced
3540 in the substitution with the portion of +'string'+ that
3541 matched +'exp'+.
3543 If +'subSpec'+ contains a +{backslash}n+, where +'n'+ is a digit
3544 between 1 and 9, then it is replaced in the substitution with
3545 the portion of +'string'+ that matched the +'n'+\'-th
3546 parenthesized subexpression of +'exp'+.
3547 Additional backslashes may be used in +'subSpec'+ to prevent special
3548 interpretation of +&+ or +{backslash}0+ or +{backslash}n+ or
3549 backslash.
3551 The use of backslashes in +'subSpec'+ tends to interact badly
3552 with the Tcl parser's use of backslashes, so it's generally
3553 safest to enclose +'subSpec'+ in braces if it includes
3554 backslashes.
3556 The following switches modify the behaviour of +'regsub'+
3558 +*-nocase*+::
3559     Upper-case characters in +'string'+ are converted to lower-case
3560     before matching against +'exp'+;  however, substitutions
3561     specified by +'subSpec'+ use the original unconverted form
3562     of +'string'+.
3564 +*-all*+::
3565     All ranges in +'string'+ that match +'exp'+ are found and substitution
3566     is performed for each of these ranges, rather than only the
3567     first. The +&+ and +{backslash}n+ sequences are handled for
3568     each substitution using the information from the corresponding
3569     match.
3571 +*-line*+::
3572     Use newline-sensitive matching. By default, newline
3573     is a completely ordinary character with no special meaning in
3574     either REs or strings.  With this flag, +[^+ bracket expressions
3575     and +.+ never match newline, an +^+ anchor matches the null
3576     string after any newline in the string in addition to its normal
3577     function, and the +$+ anchor matches the null string before any
3578     newline in the string in addition to its normal function.
3580 +*-start* 'offset'+::
3581     Specifies a character index offset into the string at which to
3582     start matching the regular expression. +'offset'+ will be
3583     constrained to the bounds of the input string.
3585 +*--*+::
3586     Marks the end of switches. The argument following this one will be
3587     treated as +'exp'+ even if it starts with a +-+.
3591 +*ref* 'string tag ?finalizer?'+
3593 Create a new reference containing +'string'+ of type +'tag'+.
3594 If +'finalizer'+ is specified, it is a command which will be invoked
3595 when the a garbage collection cycle runs and this reference is
3596 no longer accessible.
3598 The finalizer is invoked as:
3600   finalizer reference string
3602 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
3604 rename
3605 ~~~~~~
3606 +*rename* 'oldName newName'+
3608 Rename the command that used to be called +'oldName'+ so that it
3609 is now called +'newName'+.  If +'newName'+ is an empty string
3610 (e.g. {}) then +'oldName'+ is deleted.  The `rename` command
3611 returns an empty string as result.
3613 return
3614 ~~~~~~
3615 +*return* ?*-code* 'code'? ?*-errorinfo* 'stacktrace'? ?*-errorcode* 'errorcode'? ?*-level* 'n'? ?'value'?+
3617 Return immediately from the current procedure (or top-level command
3618 or `source` command), with +'value'+ as the return value.  If +'value'+
3619 is not specified, an empty string will be returned as result.
3621 If +-code+ is specified (as either a number or ok, error, break,
3622 continue, signal, return or exit), this code will be used instead
3623 of +JIM_OK+. This is generally useful when implementing flow of control
3624 commands.
3626 If +-level+ is specified and greater than 1, it has the effect of delaying
3627 the new return code from +-code+. This is useful when rethrowing an error
3628 from `catch`. See the implementation of try/catch in tclcompat.tcl for
3629 an example of how this is done.
3631 Note: The following options are only used when +-code+ is JIM_ERR.
3633 If +-errorinfo+ is specified (as returned from `info stacktrace`)
3634 it is used to initialize the stacktrace.
3636 If +-errorcode+ is specified, it is used to set the global variable $::errorCode.
3638 scan
3639 ~~~~
3640 +*scan* 'string format varName1 ?varName2 \...?'+
3642 This command parses fields from an input string in the same fashion
3643 as the C 'sscanf' procedure.  +'string'+ gives the input to be parsed
3644 and +'format'+ indicates how to parse it, using '%' fields as in
3645 'sscanf'.  All of the 'sscanf' options are valid; see the 'sscanf'
3646 man page for details.  Each +'varName'+ gives the name of a variable;
3647 when a field is scanned from +'string'+, the result is converted back
3648 into a string and assigned to the corresponding +'varName'+.  The
3649 only unusual conversion is for '%c'.  For '%c' conversions a single
3650 character value is converted to a decimal string, which is then
3651 assigned to the corresponding +'varName'+; no field width may be
3652 specified for this conversion.
3654 seek
3655 ~~~~
3656 +*seek* 'fileId offset ?origin?'+
3658 +'fileId' *seek* 'offset ?origin?'+
3660 Change the current access position for +'fileId'+.
3661 The +'offset'+ and +'origin'+ arguments specify the position at
3662 which the next read or write will occur for +'fileId'+.
3663 +'offset'+ must be a number (which may be negative) and +'origin'+
3664 must be one of the following:
3666 +*start*+::
3667     The new access position will be +'offset'+ bytes from the start
3668     of the file.
3670 +*current*+::
3671     The new access position will be +'offset'+ bytes from the current
3672     access position; a negative +'offset'+ moves the access position
3673     backwards in the file.
3675 +*end*+::
3676     The new access position will be +'offset'+ bytes from the end of
3677     the file.  A negative +'offset'+ places the access position before
3678     the end-of-file, and a positive +'offset'+ places the access position
3679     after the end-of-file.
3681 The +'origin'+ argument defaults to +start+.
3683 +'fileId'+ must have been the return value from a previous call to
3684 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
3685 of the standard I/O channels.
3687 This command returns an empty string.
3691 +*set* 'varName ?value?'+
3693 Returns the value of variable +'varName'+.
3695 If +'value'+ is specified, then set the value of +'varName'+ to +'value'+,
3696 creating a new variable if one doesn't already exist, and return
3697 its value.
3699 If +'varName'+ contains an open parenthesis and ends with a
3700 close parenthesis, then it refers to an array element:  the characters
3701 before the open parenthesis are the name of the array, and the characters
3702 between the parentheses are the index within the array.
3703 Otherwise +'varName'+ refers to a scalar variable.
3705 If no procedure is active, then +'varName'+ refers to a global
3706 variable.
3708 If a procedure is active, then +'varName'+ refers to a parameter
3709 or local variable of the procedure, unless the +'global'+ command
3710 has been invoked to declare +'varName'+ to be global.
3712 The +::+ prefix may also be used to explicitly reference a variable
3713 in the global scope.
3715 setref
3716 ~~~~~~
3717 +*setref* 'reference string'+
3719 Store a new string in +'reference'+, replacing the existing string.
3720 The reference must be a valid reference create with the `ref`
3721 command.
3723 See GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION for more detail.
3725 signal
3726 ~~~~~~
3727 Command for signal handling.
3729 See `kill` for the different forms which may be used to specify signals.
3731 Commands which return a list of signal names do so using the canonical form:
3732 "+SIGINT SIGTERM+".
3734 +*signal handle* ?'signals \...'?+::
3735     If no signals are given, returns a list of all signals which are currently
3736     being handled.
3737     If signals are specified, these are added to the list of signals currently
3738     being handled.
3740 +*signal ignore* ?'signals \...'?+::
3741     If no signals are given, returns a lists all signals which are currently
3742     being ignored.
3743     If signals are specified, these are added to the list of signals
3744     currently being ignored. These signals are still delivered, but
3745     are not considered by `catch -signal` or `try -signal`. Use
3746     `signal check` to determine which signals have occurred but
3747     been ignored.
3749 +*signal default* ?'signals \...'?+::
3750     If no signals are given, returns a lists all signals which are currently have
3751     the default behaviour.
3752     If signals are specified, these are added to the list of signals which have
3753     the default behaviour.
3755 +*signal check ?-clear?* ?'signals \...'?+::
3756     Returns a list of signals which have been delivered to the process
3757     but are 'ignored'. If signals are specified, only that set of signals will
3758     be checked, otherwise all signals will be checked.
3759     If +-clear+ is specified, any signals returned are removed and will not be
3760     returned by subsequent calls to `signal check` unless delivered again.
3762 +*signal throw* ?'signal'?+::
3763     Raises the given signal, which defaults to +SIGINT+ if not specified.
3764     The behaviour is identical to:
3766         kill signal [pid]
3768 Note that `signal handle` and `signal ignore` represent two forms of signal
3769 handling. `signal handle` is used in conjunction with `catch -signal` or `try -signal`
3770 to immediately abort execution when the signal is delivered. Alternatively, `signal ignore`
3771 is used in conjunction with `signal check` to handle signal synchronously. Consider the
3772 two examples below.
3774 Prevent a processing from taking too long
3776     signal handle SIGALRM
3777     alarm 20
3778     try -signal {
3779         .. possibly long running process ..
3780         alarm 0
3781     } on signal {sig} {
3782         puts stderr "Process took too long"
3783     }
3785 Handle SIGHUP to reconfigure:
3787     signal ignore SIGHUP
3788     while {1} {
3789         ... handle configuration/reconfiguration ...
3790         while {[signal check -clear SIGHUP] eq ""} {
3791             ... do processing ..
3792         }
3793         # Received SIGHUP, so reconfigure
3794     }
3796 Note: signal handling is currently not supported in child interpreters.
3797 In these interpreters, the signal command does not exist.
3799 sleep
3800 ~~~~~
3801 +*sleep* 'seconds'+
3803 Pauses for the given number of seconds, which may be a floating
3804 point value less than one to sleep for less than a second, or an
3805 integer to sleep for one or more seconds.
3807 source
3808 ~~~~~~
3809 +*source* 'fileName'+
3811 Read file +'fileName'+ and pass the contents to the Tcl interpreter
3812 as a sequence of commands to execute in the normal fashion.  The return
3813 value of `source` is the return value of the last command executed
3814 from the file.  If an error occurs in executing the contents of the
3815 file, then the `source` command will return that error.
3817 If a `return` command is invoked from within the file, the remainder of
3818 the file will be skipped and the `source` command will return
3819 normally with the result from the `return` command.
3821 split
3822 ~~~~~
3823 +*split* 'string ?splitChars?'+
3825 Returns a list created by splitting +'string'+ at each character
3826 that is in the +'splitChars'+ argument.
3828 Each element of the result list will consist of the
3829 characters from +'string'+ between instances of the
3830 characters in +'splitChars'+.
3832 Empty list elements will be generated if +'string'+ contains
3833 adjacent characters in +'splitChars'+, or if the first or last
3834 character of +'string'+ is in +'splitChars'+.
3836 If +'splitChars'+ is an empty string then each character of
3837 +'string'+ becomes a separate element of the result list.
3839 +'splitChars'+ defaults to the standard white-space characters.
3840 For example,
3842     split "comp.unix.misc" .
3844 returns +'"comp unix misc"'+ and
3846     split "Hello world" {}
3848 returns +'"H e l l o { } w o r l d"'+.
3850 stackdump
3851 ~~~~~~~~~
3853 +*stackdump* 'stacktrace'+
3855 Creates a human readable representation of a stack trace.
3857 stacktrace
3858 ~~~~~~~~~~
3860 +*stacktrace*+
3862 Returns a live stack trace as a list of +proc file line proc file line \...+.
3863 Iteratively uses `info frame` to create the stack trace. This stack trace is in the
3864 same form as produced by `catch` and `info stacktrace`
3866 See also `stackdump`.
3868 string
3869 ~~~~~~
3871 +*string* 'option arg ?arg \...?'+
3873 Perform one of several string operations, depending on +'option'+.
3874 The legal options (which may be abbreviated) are:
3876 +*string bytelength* 'string'+::
3877     Returns the length of the string in bytes. This will return
3878     the same value as `string length` if UTF-8 support is not enabled,
3879     or if the string is composed entirely of ASCII characters.
3880     See UTF-8 AND UNICODE.
3882 +*string byterange* 'string first last'+::
3883     Like `string range` except works on bytes rather than characters.
3884     These commands are identical if UTF-8 support is not enabled.
3886 +*string cat* '?string1 string2 \...?'+::
3887     Concatenates the given strings into a single string.
3889 +*string compare ?-nocase?* ?*-length* 'len? string1 string2'+::
3890     Perform a character-by-character comparison of strings +'string1'+ and
3891     +'string2'+ in the same way as the C 'strcmp' procedure.  Return
3892     -1, 0, or 1, depending on whether +'string1'+ is lexicographically
3893     less than, equal to, or greater than +'string2'+. If +-length+
3894     is specified, then only the first +'len'+ characters are used
3895     in the comparison.  If +'len'+ is negative, it is ignored.
3896     Performs a case-insensitive comparison if +-nocase+ is specified.
3898 +*string equal ?-nocase?* '?*-length* len?' 'string1 string2'+::
3899     Returns 1 if the strings are equal, or 0 otherwise. If +-length+
3900     is specified, then only the first +'len'+ characters are used
3901     in the comparison.  If +'len'+ is negative, it is ignored.
3902     Performs a case-insensitive comparison if +-nocase+ is specified.
3904 +*string first* 'string1 string2 ?firstIndex?'+::
3905     Search +'string2'+ for a sequence of characters that exactly match
3906     the characters in +'string1'+.  If found, return the index of the
3907     first character in the first such match within +'string2'+.  If not
3908     found, return -1. If +'firstIndex'+ is specified, matching will start
3909     from +'firstIndex'+ of +'string1'+.
3910  ::
3911     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'firstIndex'+.
3913 +*string index* 'string charIndex'+::
3914     Returns the +'charIndex'+'th character of the +'string'+
3915     argument.  A +'charIndex'+ of 0 corresponds to the first
3916     character of the string.
3917     If +'charIndex'+ is less than 0 or greater than
3918     or equal to the length of the string then an empty string is
3919     returned.
3920  ::
3921     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'charIndex'+.
3923 +*string is* 'class' ?*-strict*? 'string'+::
3924     Returns 1 if +'string'+ is a valid member of the specified character
3925     class, otherwise returns 0. If +-strict+ is specified, then an
3926     empty string returns 0, otherwise an empty string will return 1
3927     on any class. The following character classes are recognized
3928     (the class name can be abbreviated):
3929   ::
3930   +alnum+;;  Any alphabet or digit character.
3931   +alpha+;;  Any alphabet character.
3932   +ascii+;;  Any character with a value less than 128 (those that are in the 7-bit ascii range).
3933   +boolean+;;  Any of the valid string formats for a boolean value in Tcl (0, false, no, off, 1, true, yes, on)
3934   +control+;; Any control character.
3935   +digit+;;  Any digit character.
3936   +double+;; Any of the valid forms for a double in Tcl, with optional surrounding whitespace.
3937              In case of under/overflow in the value, 0 is returned.
3938   +graph+;;  Any printing character, except space.
3939   +integer+;; Any of the valid string formats for an integer value in Tcl, with optional surrounding whitespace.
3940   +lower+;;  Any lower case alphabet character.
3941   +print+;;  Any printing character, including space.
3942   +punct+;;  Any punctuation character.
3943   +space+;;  Any space character.
3944   +upper+;;  Any upper case alphabet character.
3945   +xdigit+;; Any hexadecimal digit character ([0-9A-Fa-f]).
3946  ::
3947     Note that string classification does +'not'+ respect UTF-8. See UTF-8 AND UNICODE
3948  ::
3949     Note that only +'lowercase'+ boolean values are recognized (Tcl accepts any case).
3951 +*string last* 'string1 string2 ?lastIndex?'+::
3952     Search +'string2'+ for a sequence of characters that exactly match
3953     the characters in +'string1'+.  If found, return the index of the
3954     first character in the last such match within +'string2'+.  If there
3955     is no match, then return -1. If +'lastIndex'+ is specified, only characters
3956     up to +'lastIndex'+ of +'string2'+ will be considered in the match.
3957  ::
3958     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'lastIndex'+.
3960 +*string length* 'string'+::
3961     Returns a decimal string giving the number of characters in +'string'+.
3962     If UTF-8 support is enabled, this may be different than the number of bytes.
3963     See UTF-8 AND UNICODE
3965 +*string map ?-nocase?* 'mapping string'+::
3966     Replaces substrings in +'string'+ based on the key-value pairs in
3967     +'mapping'+, which is a list of +key value key value \...+ as in the form
3968     returned by `array get`. Each instance of a key in the string will be
3969     replaced with its corresponding value.  If +-nocase+ is specified, then
3970     matching is done without regard to case differences. Both key and value may
3971     be multiple characters.  Replacement is done in an ordered manner, so the
3972     key appearing first in the list will be checked first, and so on. +'string'+ is
3973     only iterated over once, so earlier key replacements will have no affect for
3974     later key matches. For example,
3976       string map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc
3978  ::
3979     will return the string +01321221+.
3980  ::
3981     Note that if an earlier key is a prefix of a later one, it will completely mask the later
3982     one.  So if the previous example is reordered like this,
3984       string map {1 0 ab 2 a 3 abc 1} 1abcaababcabababc
3986  ::
3987     it will return the string +02c322c222c+.
3989 +*string match ?-nocase?* 'pattern string'+::
3990     See if +'pattern'+ matches +'string'+; return 1 if it does, 0
3991     if it doesn't.  Matching is done in a fashion similar to that
3992     used by the C-shell.  For the two strings to match, their contents
3993     must be identical except that the following special sequences
3994     may appear in +'pattern'+:
3996     +*+;;
3997         Matches any sequence of characters in +'string'+,
3998         including a null string.
4000     +?+;;
4001         Matches any single character in +'string'+.
4003     +['chars']+;;
4004         Matches any character in the set given by +'chars'+.
4005         If a sequence of the form +'x-y'+ appears in +'chars'+,
4006         then any character between +'x'+ and +'y'+, inclusive,
4007         will match.
4009     +{backslash}x+;;
4010         Matches the single character +'x'+.  This provides a way of
4011         avoiding the special interpretation of the characters +{backslash}*?[]+
4012         in +'pattern'+.
4013  ::
4014     Performs a case-insensitive comparison if +-nocase+ is specified.
4016 +*string range* 'string first last'+::
4017     Returns a range of consecutive characters from +'string'+, starting
4018     with the character whose index is +'first'+ and ending with the
4019     character whose index is +'last'+.  An index of 0 refers to the
4020     first character of the string.
4021  ::
4022     See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for +'first'+ and +'last'+.
4023  ::
4024     If +'first'+ is less than zero then it is treated as if it were zero, and
4025     if +'last'+ is greater than or equal to the length of the string then
4026     it is treated as if it were +end+.  If +'first'+ is greater than
4027     +'last'+ then an empty string is returned.
4029 +*string repeat* 'string count'+::
4030     Returns a new string consisting of +'string'+ repeated +'count'+ times.
4032 +*string replace* 'string first last ?newstring?'+::
4033     Removes a range of consecutive characters from +'string'+, starting
4034     with the character whose index is +'first'+ and ending with the
4035     character whose index is +'last'+.  If +'newstring'+ is specified,
4036     then it is placed in the removed character range. If +'first'+ is
4037     less than zero then it is treated as if it were zero, and if +'last'+
4038     is greater than or equal to the length of the string then it is
4039     treated as if it were +end+. If +'first'+ is greater than +'last'+
4040     or the length of the initial string, or +'last'+ is less than 0,
4041     then the initial string is returned untouched.
4043 +*string reverse* 'string'+::
4044     Returns a string that is the same length as +'string'+ but
4045     with its characters in the reverse order.
4047 +*string tolower* 'string'+::
4048     Returns a value equal to +'string'+ except that all upper case
4049     letters have been converted to lower case.
4051 +*string totitle* 'string'+::
4052     Returns a value equal to +'string'+ except that the first character
4053     is converted to title case (or upper case if there is no UTF-8 titlecase variant)
4054     and all remaining characters have been converted to lower case.
4056 +*string toupper* 'string'+::
4057     Returns a value equal to +'string'+ except that all lower case
4058     letters have been converted to upper case.
4060 +*string trim* 'string ?chars?'+::
4061     Returns a value equal to +'string'+ except that any leading
4062     or trailing characters from the set given by +'chars'+ are
4063     removed.
4064     If +'chars'+ is not specified then white space is removed
4065     (spaces, tabs, newlines, and carriage returns).
4067 +*string trimleft* 'string ?chars?'+::
4068     Returns a value equal to +'string'+ except that any
4069     leading characters from the set given by +'chars'+ are
4070     removed.
4071     If +'chars'+ is not specified then white space is removed
4072     (spaces, tabs, newlines, and carriage returns).
4074 +*string trimright* 'string ?chars?'+::
4075     Returns a value equal to +'string'+ except that any
4076     trailing characters from the set given by +'chars'+ are
4077     removed.
4078     If +'chars'+ is not specified then white space is removed
4079     (spaces, tabs, newlines, and carriage returns).
4080     Null characters are always removed.
4082 subst
4083 ~~~~~
4084 +*subst ?-nobackslashes? ?-nocommands? ?-novariables?* 'string'+
4086 This command performs variable substitutions, command substitutions,
4087 and backslash substitutions on its string argument and returns the
4088 fully-substituted result. The substitutions are performed in exactly
4089 the same way as for Tcl commands. As a result, the string argument
4090 is actually substituted twice, once by the Tcl parser in the usual
4091 fashion for Tcl commands, and again by the subst command.
4093 If any of the +-nobackslashes+, +-nocommands+, or +-novariables+ are
4094 specified, then the corresponding substitutions are not performed.
4095 For example, if +-nocommands+ is specified, no command substitution
4096 is performed: open and close brackets are treated as ordinary
4097 characters with no special interpretation.
4099 *Note*: when it performs its substitutions, subst does not give any
4100 special treatment to double quotes or curly braces. For example,
4101 the following script returns +xyz \{44\}+, not +xyz \{$a\}+.
4103     set a 44
4104     subst {xyz {$a}}
4107 switch
4108 ~~~~~~
4109 +*switch* '?options? string pattern body ?pattern body \...?'+
4111 +*switch* '?options? string {pattern body ?pattern body \...?}'+
4113 The `switch` command matches its string argument against each of
4114 the pattern arguments in order. As soon as it finds a pattern that
4115 matches string it evaluates the following body and returns the
4116 result of that evaluation. If the last pattern argument is default
4117 then it matches anything. If no pattern argument matches string and
4118 no default is given, then the `switch` command returns an empty string.
4119 If the initial arguments to switch start with - then they are treated
4120 as options. The following options are currently supported:
4122     +-exact+::
4123         Use exact matching when comparing string to a
4124         pattern. This is the default.
4126     +-glob+::
4127         When matching string to the patterns, use glob-style
4128         matching (i.e. the same as implemented by the string
4129         match command).
4131     +-regexp+::
4132         When matching string to the patterns, use regular
4133         expression matching (i.e. the same as implemented
4134         by the regexp command).
4136     +-command 'commandname'+::
4137         When matching string to the patterns, use the given command, which
4138         must be a single word. The command is invoked as
4139         'commandname pattern string', or 'commandname -nocase pattern string'
4140         and must return 1 if matched, or 0 if not.
4142     +--+::
4143         Marks the end of options. The argument following
4144         this one will be treated as string even if it starts
4145         with a +-+.
4147 Two syntaxes are provided for the pattern and body arguments. The
4148 first uses a separate argument for each of the patterns and commands;
4149 this form is convenient if substitutions are desired on some of the
4150 patterns or commands. The second form places all of the patterns
4151 and commands together into a single argument; the argument must
4152 have proper list structure, with the elements of the list being the
4153 patterns and commands. The second form makes it easy to construct
4154 multi-line `switch` commands, since the braces around the whole list
4155 make it unnecessary to include a backslash at the end of each line.
4156 Since the pattern arguments are in braces in the second form, no
4157 command or variable substitutions are performed on them; this makes
4158 the behaviour of the second form different than the first form in
4159 some cases.
4161 If a body is specified as +-+ it means that the body for the next
4162 pattern should also be used as the body for this pattern (if the
4163 next pattern also has a body of +-+ then the body after that is
4164 used, and so on). This feature makes it possible to share a single
4165 body among several patterns.
4167 Below are some examples of `switch` commands:
4169     switch abc a - b {format 1} abc {format 2} default {format 3}
4171 will return 2,
4173     switch -regexp aaab {
4174            ^a.*b$ -
4175            b {format 1}
4176            a* {format 2}
4177            default {format 3}
4178     }
4180 will return 1, and
4182     switch xyz {
4183            a -
4184            b {format 1}
4185            a* {format 2}
4186            default {format 3}
4187     }
4189 will return 3.
4191 tailcall
4192 ~~~~~~~~
4193 +*tailcall* 'cmd ?arg\...?'+
4195 The `tailcall` command provides an optimised way of invoking a command whilst replacing
4196 the current call frame. This is similar to 'exec' in Bourne Shell.
4198 The following are identical except the first immediately replaces the current call frame.
4200   tailcall a b c
4202   return [uplevel 1 [list a b c]]
4204 `tailcall` is useful as a dispatch mechanism:
4206   proc a {cmd args} {
4207     tailcall sub_$cmd {*}$args
4208   }
4209   proc sub_cmd1 ...
4210   proc sub_cmd2 ...
4212 tell
4213 ~~~~
4214 +*tell* 'fileId'+
4216 +'fileId' *tell*+
4218 Returns a decimal string giving the current access position in
4219 +'fileId'+.
4221 +'fileId'+ must have been the return value from a previous call to
4222 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
4223 of the standard I/O channels.
4225 throw
4226 ~~~~~
4227 +*throw* 'code ?msg?'+
4229 This command throws an exception (return) code along with an optional message.
4230 This command is mostly for convenient usage with `try`.
4232 The command +throw break+ is equivalent to +break+.
4233 The command +throw 20 message+ can be caught with an +on 20 \...+ clause to `try`.
4235 time
4236 ~~~~
4237 +*time* 'command ?count?'+
4239 This command will call the Tcl interpreter +'count'+
4240 times to execute +'command'+ (or once if +'count'+ isn't
4241 specified).  It will then return a string of the form
4243     503 microseconds per iteration
4245 which indicates the average amount of time required per iteration,
4246 in microseconds.
4248 Time is measured in elapsed time, not CPU time.
4252 +*try* '?catchopts? tryscript' ?*on* 'returncodes {?resultvar? ?optsvar?} handlerscript \...'? ?*finally* 'finalscript'?+
4254 The `try` command is provided as a convenience for exception handling.
4256 This interpeter first evaluates +'tryscript'+ under the effect of the catch
4257 options +'catchopts'+ (e.g. +-signal -noexit --+, see `catch`).
4259 It then evaluates the script for the first matching 'on' handler
4260 (there many be zero or more) based on the return code from the `try`
4261 section. For example a normal +JIM_ERR+ error will be matched by
4262 an 'on error' handler.
4264 Finally, any +'finalscript'+ is evaluated.
4266 The result of this command is the result of +'tryscript'+, except in the
4267 case where an exception occurs in a matching 'on' handler script or the 'finally' script,
4268 in which case the result is this new exception.
4270 The specified +'returncodes'+ is a list of return codes either as names ('ok', 'error', 'break', etc.)
4271 or as integers.
4273 If +'resultvar'+ and +'optsvar'+ are specified, they are set as for `catch` before evaluating
4274 the matching handler.
4276 For example:
4278     set f [open input]
4279     try -signal {
4280         process $f
4281     } on {continue break} {} {
4282         error "Unexpected break/continue"
4283     } on error {msg opts} {
4284         puts "Dealing with error"
4285         return {*}$opts $msg
4286     } on signal sig {
4287         puts "Got signal: $sig"
4288     } finally {
4289         $f close
4290     }
4292 If break, continue or error are raised, they are dealt with by the matching
4293 handler.
4295 In any case, the file will be closed via the 'finally' clause.
4297 See also `throw`, `catch`, `return`, `error`.
4299 unknown
4300 ~~~~~~~
4301 +*unknown* 'cmdName ?arg arg ...?'+
4303 This command doesn't actually exist as part of Tcl, but Tcl will
4304 invoke it if it does exist.
4306 If the Tcl interpreter encounters a command name for which there
4307 is not a defined command, then Tcl checks for the existence of
4308 a command named `unknown`.
4310 If there is no such command, then the interpreter returns an
4311 error.
4313 If the `unknown` command exists, then it is invoked with
4314 arguments consisting of the fully-substituted name and arguments
4315 for the original non-existent command.
4317 The `unknown` command typically does things like searching
4318 through library directories for a command procedure with the name
4319 +'cmdName'+, or expanding abbreviated command names to full-length,
4320 or automatically executing unknown commands as UNIX sub-processes.
4322 In some cases (such as expanding abbreviations) `unknown` will
4323 change the original command slightly and then (re-)execute it.
4324 The result of the `unknown` command is used as the result for
4325 the original non-existent command.
4327 unset
4328 ~~~~~
4329 +*unset ?-nocomplain? ?--?* '?name name ...?'+
4331 Remove variables.
4332 Each +'name'+ is a variable name, specified in any of the
4333 ways acceptable to the `set` command.
4335 If a +'name'+ refers to an element of an array, then that
4336 element is removed without affecting the rest of the array.
4338 If a +'name'+ consists of an array name with no parenthesized
4339 index, then the entire array is deleted.
4341 The `unset` command returns an empty string as result.
4343 An error occurs if any of the variables doesn't exist, unless '-nocomplain'
4344 is specified. The '--' argument may be specified to stop option processing
4345 in case the variable name may be '-nocomplain'.
4347 upcall
4348 ~~~~~~~
4349 +*upcall* 'command ?args ...?'+
4351 May be used from within a proc defined as `local` `proc` in order to call
4352 the previous, hidden version of the same command.
4354 If there is no previous definition of the command, an error is returned.
4356 uplevel
4357 ~~~~~~~
4358 +*uplevel* '?level? command ?command ...?'+
4360 All of the +'command'+ arguments are concatenated as if they had
4361 been passed to `concat`; the result is then evaluated in the
4362 variable context indicated by +'level'+.  `uplevel` returns
4363 the result of that evaluation.  If +'level'+ is an integer, then
4364 it gives a distance (up the procedure calling stack) to move before
4365 executing the command.  If +'level'+ consists of +\#+ followed by
4366 a number then the number gives an absolute level number.  If +'level'+
4367 is omitted then it defaults to +1+.  +'level'+ cannot be
4368 defaulted if the first +'command'+ argument starts with a digit or +#+.
4370 For example, suppose that procedure 'a' was invoked
4371 from top-level, and that it called 'b', and that 'b' called 'c'.
4372 Suppose that 'c' invokes the `uplevel` command.  If +'level'+
4373 is +1+ or +#2+  or omitted, then the command will be executed
4374 in the variable context of 'b'.  If +'level'+ is +2+ or +#1+
4375 then the command will be executed in the variable context of 'a'.
4377 If +'level'+ is '3' or +#0+ then the command will be executed
4378 at top-level (only global variables will be visible).
4379 The `uplevel` command causes the invoking procedure to disappear
4380 from the procedure calling stack while the command is being executed.
4381 In the above example, suppose 'c' invokes the command
4383     uplevel 1 {set x 43; d}
4385 where 'd' is another Tcl procedure.  The `set` command will
4386 modify the variable 'x' in 'b's context, and 'd' will execute
4387 at level 3, as if called from 'b'.  If it in turn executes
4388 the command
4390     uplevel {set x 42}
4392 then the `set` command will modify the same variable 'x' in 'b's
4393 context:  the procedure 'c' does not appear to be on the call stack
4394 when 'd' is executing.  The command `info level` may
4395 be used to obtain the level of the current procedure.
4397 `uplevel` makes it possible to implement new control
4398 constructs as Tcl procedures (for example, `uplevel` could
4399 be used to implement the `while` construct as a Tcl procedure).
4401 upvar
4402 ~~~~~
4403 +*upvar* '?level? otherVar myVar ?otherVar myVar ...?'+
4405 This command arranges for one or more local variables in the current
4406 procedure to refer to variables in an enclosing procedure call or
4407 to global variables.
4409 +'level'+ may have any of the forms permitted for the `uplevel`
4410 command, and may be omitted if the first letter of the first +'otherVar'+
4411 isn't +#+ or a digit (it defaults to '1').
4413 For each +'otherVar'+ argument, `upvar` makes the variable
4414 by that name in the procedure frame given by +'level'+ (or at
4415 global level, if +'level'+ is +#0+) accessible
4416 in the current procedure by the name given in the corresponding
4417 +'myVar'+ argument.
4419 The variable named by +'otherVar'+ need not exist at the time of the
4420 call;  it will be created the first time +'myVar'+ is referenced, just like
4421 an ordinary variable.
4423 `upvar` may only be invoked from within procedures.
4425 `upvar` returns an empty string.
4427 The `upvar` command simplifies the implementation of call-by-name
4428 procedure calling and also makes it easier to build new control constructs
4429 as Tcl procedures.
4430 For example, consider the following procedure:
4432     proc add2 name {
4433         upvar $name x
4434         set x [expr $x+2]
4435     }
4437 'add2' is invoked with an argument giving the name of a variable,
4438 and it adds two to the value of that variable.
4439 Although 'add2' could have been implemented using `uplevel`
4440 instead of `upvar`, `upvar` makes it simpler for 'add2'
4441 to access the variable in the caller's procedure frame.
4443 while
4444 ~~~~~
4445 +*while* 'test body'+
4447 The +'while'+ command evaluates +'test'+ as an expression
4448 (in the same way that `expr` evaluates its argument).
4449 The value of the expression must be numeric; if it is non-zero
4450 then +'body'+ is executed by passing it to the Tcl interpreter.
4452 Once +'body'+ has been executed then +'test'+ is evaluated
4453 again, and the process repeats until eventually +'test'+
4454 evaluates to a zero numeric value.  `continue`
4455 commands may be executed inside +'body'+ to terminate the current
4456 iteration of the loop, and `break`
4457 commands may be executed inside +'body'+ to cause immediate
4458 termination of the `while` command.
4460 The `while` command always returns an empty string.
4462 OPTIONAL-EXTENSIONS
4463 -------------------
4465 The following extensions may or may not be available depending upon
4466 what options were selected when Jim Tcl was built.
4468 [[cmd_1]]
4469 posix: os.fork, os.wait, os.gethostname, os.getids, os.uptime
4470 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4471 +*os.fork*+::
4472     Invokes 'fork(2)' and returns the result.
4474 +*os.wait -nohang* 'pid'+::
4475     Invokes waitpid(2), with WNOHANG if +-nohang+ is specified.
4476     Returns a list of 3 elements.
4478    {0 none 0} if -nohang is specified, and the process is still alive.
4480    {-1 error <error-description>} if the process does not exist or has already been waited for.
4482    {<pid> exit <exit-status>} if the process exited normally.
4484    {<pid> signal <signal-number>} if the process terminated on a signal.
4486    {<pid> other 0} otherwise (core dump, stopped, continued, etc.)
4488 +*os.gethostname*+::
4489     Invokes 'gethostname(3)' and returns the result.
4491 +*os.getids*+::
4492     Returns the various user/group ids for the current process.
4494     jim> os.getids
4495     uid 1000 euid 1000 gid 100 egid 100
4497 +*os.uptime*+::
4498     Returns the number of seconds since system boot. See description of 'uptime' in 'sysinfo(2)'.
4500 ANSI I/O (aio) and EVENTLOOP API
4501 --------------------------------
4502 Jim provides an alternative object-based API for I/O.
4504 See `open` and `socket` for commands which return an I/O handle.
4508 +$handle *accept* ?addrvar?+::
4509     Server socket only: Accept a connection and return stream.
4510     If +'addrvar'+ is specified, the address of the connected client is stored
4511     in the named variable in the form 'addr:port'. See `socket` for details.
4513 +$handle *buffering none|line|full*+::
4514     Sets the buffering mode of the stream.
4516 +$handle *close* ?r(ead)|w(rite)?+::
4517     Closes the stream.
4518     The  two-argument form is a "half-close" on a socket. See the +shutdown(2)+ man page.
4520 +$handle *copyto* 'tofd ?size?'+::
4521     Copy bytes to the file descriptor +'tofd'+. If +'size'+ is specified, at most
4522     that many bytes will be copied. Otherwise copying continues until the end
4523     of the input file. Returns the number of bytes actually copied.
4525 +$handle *eof*+::
4526     Returns 1 if stream is at eof
4528 +$handle *filename*+::
4529     Returns the original filename associated with the handle.
4530     Handles returned by `socket` give the socket type instead of a filename.
4532 +$handle *flush*+::
4533     Flush the stream
4535 +$handle *gets* '?var?'+::
4536     Read one line and return it or store it in the var
4538 +$handle *isatty*+::
4539     Returns 1 if the stream is a tty device.
4541 +$handle *lock*+::
4542     Apply a POSIX lock to the open file associated with the handle using
4543     fcntl(2).
4544     The handle must be open for write access.
4545     Returns 1 if the lock was successfully obtained, 0 otherwise.
4546     An error occurs if the handle is not suitable for locking (e.g.
4547     if it is not open for write)
4549 +$handle *ndelay ?0|1?*+::
4550     Set O_NDELAY (if arg). Returns current/new setting.
4551     Note that in general ANSI I/O interacts badly with non-blocking I/O.
4552     Use with care.
4554 +$handle *tcp_nodelay* boolean+::
4555     Enable or disable TCP_NODELAY (Nagle's) algorithm.
4557 +$handle *puts ?-nonewline?* 'str'+::
4558     Write the string, with newline unless -nonewline
4560 +$handle *read ?-nonewline?* '?len?'+::
4561     Read and return bytes from the stream. To eof if no len.
4563 +$handle *recvfrom* 'maxlen ?addrvar?'+::
4564     Receives a message from the handle via recvfrom(2) and returns it.
4565     At most +'maxlen'+ bytes are read.
4566     If +'addrvar'+ is specified, the sending address of the message is stored in
4567     the named variable in the form 'addr:port'. See `socket` for details.
4569 +$handle *seek* 'offset' *?start|current|end?*+::
4570     Seeks in the stream (default 'current')
4572 +$handle *sendto* 'str ?addr:?port'+::
4573     Sends the string, +'str'+, to the given address via the socket using sendto(2).
4574     This is intended for udp/dgram sockets and may give an error or behave in unintended
4575     ways for other handle types.
4576     Returns the number of bytes written.
4578 +$handle *sync*+::
4579     Flush the stream, then fsync(2) to commit any changes to storage.
4580     Only available on platforms that support fsync(2).
4582 +$handle *tell*+::
4583     Returns the current seek position
4585 +$handle *tty* ?settings?+::
4586         If no arguments are given, returns a dictionary containing the tty settings for the stream.
4587         If arguments are given, they must either be a dictionary, or +setting value \...+
4588         Abbrevations are supported for both settings and values, so the following is acceptable:
4589         +$f tty parity e input c out raw+.
4590     Only available on platforms that support termios(3). Supported settings are:
4592     +*baud* 'rate'+;;
4593         Baud rate. e.g. 115200
4595     +*data 5|6|7|8*+;;
4596         Number of data bits
4598     +*stop 1|2*+;;
4599         Number of stop bits
4601     +*parity even|odd|none*+;;
4602         Parity setting
4604     +*handshake xonxoff|rtscts|none*+;;
4605                 Handshaking type
4607     +*input raw|cooked*+;;
4608                 Input character processing. In raw mode, the usual key sequences such as ^C do
4609                 not generate signals.
4611     +*output raw|cooked*+;;
4612                 Output character processing. Typically CR -> CRNL is disabled in raw mode.
4614     +*vmin* 'numchars'+;;
4615                 Minimum number of characters to read.
4617     +*vtime* 'time'+;;
4618                 Timeout for noncanonical read (units of 0.1 seconds)
4620 +$handle *ssl* *?-server cert priv?*+::
4621     Initiates a SSL/TLS session and returns a new stream
4623 +$handle *unlock*+::
4624     Release a POSIX lock previously acquired by `aio lock`.
4626 +$handle *verify*+::
4627     Verifies the certificate of a SSL/TLS stream peer
4629 +*load_ssl_certs* 'dir'+::
4630     Loads SSL/TLS CA certificates for use during verification
4632 fconfigure
4633 ~~~~~~~~~~
4634 +*fconfigure* 'handle' *?-blocking 0|1? ?-buffering noneline|full? ?-translation* 'mode'?+::
4635     For compatibility with Tcl, a limited form of the `fconfigure`
4636     command is supported.
4637     * `fconfigure ... -blocking` maps to `aio ndelay`
4638     * `fconfigure ... -buffering` maps to `aio buffering`
4639     * `fconfigure ... -translation` is accepted but ignored
4641 [[cmd_2]]
4642 eventloop: after, vwait, update
4643 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4645 The following commands allow a script to be invoked when the given condition occurs.
4646 If no script is given, returns the current script. If the given script is the empty, the
4647 handler is removed.
4649 +$handle *readable* '?readable-script?'+::
4650     Sets or returns the script for when the socket is readable.
4652 +$handle *writable* '?writable-script?'+::
4653     Sets or returns the script for when the socket is writable.
4655 +$handle *onexception* '?exception-script?'+::
4656     Sets or returns the script for when oob data received.
4658 For compatibility with 'Tcl', these may be prefixed with `fileevent`.  e.g.
4660  ::
4661     +fileevent $handle *readable* '\...'+
4663 Time-based execution is also available via the eventloop API.
4665 +*after* 'ms'+::
4666     Sleeps for the given number of milliseconds. No events are
4667     processed during this time.
4669 +*after* 'ms'|*idle* 'script ?script \...?'+::
4670     The scripts are concatenated and executed after the given
4671     number of milliseconds have elapsed.  If 'idle' is specified,
4672     the script will run the next time the event loop is processed
4673     with `vwait` or `update`. The script is only run once and
4674     then removed.  Returns an event id.
4676 +*after cancel* 'id|command'+::
4677     Cancels an `after` event with the given event id or matching
4678     command (script).  Returns the number of milliseconds
4679     remaining until the event would have fired.  Returns the
4680     empty string if no matching event is found.
4682 +*after info* '?id?'+::
4683     If +'id'+ is not given, returns a list of current `after`
4684     events.  If +'id'+ is given, returns a list containing the
4685     associated script and either 'timer' or 'idle' to indicated
4686     the type of the event. An error occurs if +'id'+ does not
4687     match an event.
4689 +*vwait* 'variable'+::
4690     A call to `vwait` enters the eventloop. `vwait` processes
4691     events until the named (global) variable changes or all
4692     event handlers are removed. The variable need not exist
4693     beforehand.  If there are no event handlers defined, `vwait`
4694     returns immediately.
4696 +*update ?idletasks?*+::
4697     A call to `update` enters the eventloop to process expired events, but
4698     no new events. If 'idletasks' is specified, only expired time events are handled,
4699     not file events.
4700     Returns once handlers have been run for all expired events.
4702 Scripts are executed at the global scope. If an error occurs during a handler script,
4703 an attempt is made to call (the user-defined command) `bgerror` with the details of the error.
4704 If the `bgerror` command does not exist, the error message details are printed to stderr instead.
4706 If a file event handler script generates an error, the handler is automatically removed
4707 to prevent infinite errors. (A time event handler is always removed after execution).
4709 +*bgerror* 'msg'+::
4710     Called when an event handler script generates an error. Note that the normal command resolution
4711     rules are used for bgerror. First the name is resolved in the current namespace, then in the
4712     global scope.
4714 socket
4715 ~~~~~~
4716 Various socket types may be created.
4718 +*socket unix* 'path'+::
4719     A unix domain socket client.
4721 +*socket unix.server* 'path'+::
4722     A unix domain socket server.
4724 +*socket ?-ipv6? stream* 'addr:port'+::
4725     A TCP socket client. (See the forms for +'addr'+ below)
4727 +*socket ?-ipv6? stream.server* '?addr:?port'+::
4728     A TCP socket server (+'addr'+ defaults to +0.0.0.0+ for IPv4 or +[::]+ for IPv6).
4730 +*socket ?-ipv6? dgram* ?'addr:port'?+::
4731     A UDP socket client. If the address is not specified,
4732     the client socket will be unbound and 'sendto' must be used
4733     to indicated the destination.
4735 +*socket ?-ipv6? dgram.server* 'addr:port'+::
4736     A UDP socket server.
4738 +*socket pipe*+::
4739     A pipe. Note that unlike all other socket types, this command returns
4740     a list of two channels: {read write}
4742 +*socket pair*+::
4743     A socketpair (see socketpair(2)). Like `socket pipe`, this command returns
4744     a list of two channels: {s1 s2}. These channels are both readable and writable.
4746 This command creates a socket connected (client) or bound (server) to the given
4747 address.
4749 The returned value is channel and may generally be used with the various file I/O
4750 commands (gets, puts, read, etc.), either as object-based syntax or Tcl-compatible syntax.
4752     . set f [socket stream www.google.com:80]
4753     aio.sockstream1
4754     . $f puts -nonewline "GET / HTTP/1.0\r\n\r\n"
4755     . $f gets
4756     HTTP/1.0 302 Found
4757     . $f close
4759 Server sockets, however support only 'accept', which is most useful in conjunction with
4760 the EVENTLOOP API.
4762     set f [socket stream.server 80]
4763     $f readable {
4764         set client [$f accept]
4765         $client gets $buf
4766         ...
4767         $client puts -nonewline "HTTP/1.1 404 Not found\r\n"
4768         $client close
4769     }
4770     vwait done
4772 The address, +'addr'+, can be given in one of the following forms:
4774 1. For IPv4 socket types, an IPv4 address such as 192.168.1.1
4775 2. For IPv6 socket types, an IPv6 address such as [fe80::1234] or [::]
4776 3. A hostname
4778 Note that on many systems, listening on an IPv6 address such as [::] will
4779 also accept requests via IPv4.
4781 Where a hostname is specified, the +'first'+ returned address is used
4782 which matches the socket type is used.
4784 The special type 'pipe' isn't really a socket.
4786     lassign [socket pipe] r w
4788     # Must close $w after exec
4789     exec ps >@$w &
4790     $w close
4792     $r readable ...
4794 syslog
4795 ~~~~~~
4796 +*syslog* '?options? ?priority? message'+
4798 This  command sends message to system syslog facility with given
4799 priority. Valid priorities are:
4801     emerg, alert, crit, err, error, warning, notice, info, debug
4803 If a message is specified, but no priority is specified, then a
4804 priority of info is used.
4806 By default, facility user is used and the value of global tcl variable
4807 argv0 is used as ident string. However, any of the following options
4808 may be specified before priority to control these parameters:
4810 +*-facility* 'value'+::
4811     Use specified facility instead of user. The following
4812     values for facility are recognized:
4814     authpriv, cron, daemon, kernel, lpr, mail, news, syslog, user,
4815     uucp, local0-local7
4817 +*-ident* 'string'+::
4818     Use given string instead of argv0 variable for ident string.
4820 +*-options* 'integer'+::
4821     Set syslog options such as +LOG_CONS+, +LOG_NDELAY+. You should
4822     use numeric values of those from your system syslog.h file,
4823     because I haven't got time to implement yet another hash
4824     table.
4826 pack: pack, unpack
4827 ~~~~~~~~~~~~~~~~~~
4828 The optional 'pack' extension provides commands to encode and decode binary strings.
4830 +*pack* 'varName value' *-intle|-intbe|-floatle|-floatbe|-str* 'bitwidth ?bitoffset?'+::
4831     Packs the binary representation of +'value'+ into the variable
4832     +'varName'+. The value is packed according to the given type
4833     (integer/floating point/string, big-endian/little-endian), width and bit offset.
4834     The variable is created if necessary (like `append`).
4835     The variable is expanded if necessary.
4837 +*unpack* 'binvalue' *-intbe|-intle|-uintbe|-uintle|-floatbe|-floatle|-str* 'bitpos bitwidth'+::
4838     Unpacks bits from +'binvalue'+ at bit position +'bitpos'+ and with +'bitwidth'+.
4839     Interprets the value according to the type (integer/floating point/string, big-endian/little-endian
4840     and signed/unsigned) and returns it. For integer types, +'bitwidth'+
4841     may be up to the size of a Jim Tcl integer (typically 64 bits). For floating point types,
4842     +'bitwidth'+ may be 32 bits (for single precision numbers) or 64 bits (for double precision).
4843     For the string type, both the width and the offset must be on a byte boundary (multiple of 8). Attempting to
4844     access outside the length of the value will return 0 for integer types, 0.0 for floating point types
4845     or the empty string for the string type.
4847 zlib
4848 ~~~~
4849 The optional 'zlib' extension provides a Tcl-compatible subset of the `zlib` command.
4851 +*crc32* 'data' '?startValue?'+::
4852     Returns the CRC32 checksum of a buffer. Optionally, an initial value may be specified; this is most useful
4853     for calculating the checksum of chunked data read from a stream (for instance, a pipe).
4855 +*deflate* 'string' '?level?'+::
4856     Compresses a buffer and outputs a raw, Deflate-compressed stream. Optionally, a compression level (1-9) may
4857     be specified to choose the desired speed vs. compression rate ratio.
4859 +*inflate* 'data' '?bufferSize?'+::
4860     Decompresses a raw, Deflate-compressed stream. When the uncompressed data size is known and specified, memory
4861     allocation is more efficient. Otherwise, decomperssion is chunked and therefore slower.
4863 +*gzip* 'string' '?-level level?'+::
4864     Compresses a buffer and adds a gzip header.
4866 +*gunzip* 'data' '?-buffersize size?'+::
4867     Decompresses a gzip-compressed buffer. Decompression is chunked, with a default, small buffer size of 64K
4868     which guarantees lower memory footprint at the cost of speed. It is recommended to use a bigger size, on
4869     systems without a severe memory constraint.
4871 binary
4872 ~~~~~~
4873 The optional, pure-Tcl 'binary' extension provides the Tcl-compatible `binary scan` and `binary format`
4874 commands based on the low-level `pack` and `unpack` commands.
4876 See the Tcl documentation at: http://www.tcl.tk/man/tcl8.5/TclCmd/binary.htm
4878 Note that 'binary format' with f/r/R specifiers (single-precision float) uses the value of Infinity
4879  in case of overflow.
4881 oo: class, super
4882 ~~~~~~~~~~~~~~~~
4883 The optional, pure-Tcl 'oo' extension provides object-oriented (OO) support for Jim Tcl.
4885 See the online documentation (http://jim.tcl.tk/index.html/doc/www/www/documentation/oo/) for more details.
4887 +*class* 'classname ?baseclasses? classvars'+::
4888     Create a new class, +'classname'+, with the given dictionary
4889     (+'classvars'+) as class variables. These are the initial variables
4890     which all newly created objects of this class are initialised with.
4891     If a list of baseclasses is given, methods and instance variables
4892     are inherited.
4894 +*super* 'method ?args \...?'+::
4895     From within a method, invokes the given method on the base class.
4896     Note that this will only call the last baseclass given.
4898 tree
4899 ~~~~
4900 The optional, pure-Tcl 'tree' extension implements an OO, general purpose tree structure
4901 similar to that provided by tcllib ::struct::tree (http://core.tcl.tk/tcllib/doc/trunk/embedded/www/tcllib/files/modules/struct/struct_tree.html)
4903 A tree is a collection of nodes, where each node (except the root node) has a single parent
4904 and zero or more child nodes (ordered), as well as zero or more attribute/value pairs.
4906 +*tree*+::
4907     Creates and returns a new tree object with a single node named "root".
4908     All operations on the tree are invoked through this object.
4910 +$tree *destroy*+::
4911     Destroy the tree and all it's nodes. (Note that the tree will also
4912     be automatically garbage collected once it goes out of scope).
4914 +$tree *set* 'nodename key value'+::
4915     Set the value for the given attribute key.
4917 +$tree *lappend* 'nodename key value \...'+::
4918     Append to the (list) value(s) for the given attribute key, or set if not yet set.
4920 +$tree *keyexists* 'nodename key'+::
4921     Returns 1 if the given attribute key exists.
4923 +$tree *get* 'nodename key'+::
4924     Returns the value associated with the given attribute key.
4926 +$tree *getall* 'nodename'+::
4927     Returns the entire attribute dictionary associated with the given key.
4929 +$tree *depth* 'nodename'+::
4930     Returns the depth of the given node. The depth of "root" is 0.
4932 +$tree *parent* 'nodename'+::
4933     Returns the node name of the parent node, or "" for the root node.
4935 +$tree *numchildren* 'nodename'+::
4936     Returns the number of child nodes.
4938 +$tree *children* 'nodename'+::
4939     Returns a list of the child nodes.
4941 +$tree *next* 'nodename'+::
4942     Returns the next sibling node, or "" if none.
4944 +$tree *insert* 'nodename ?index?'+::
4945     Add a new child node to the given node. The index is a list index
4946     such as +3+ or +end-2+. The default index is +end+.
4947     Returns the name of the newly added node.
4949 +$tree *walk* 'nodename' *dfs|bfs* {'actionvar nodevar'} 'script'+::
4950     Walks the tree starting from the given node, either breadth first (+bfs+)
4951     depth first (+dfs+).
4952     The value +"enter"+ or +"exit"+ is stored in variable +'actionvar'+.
4953     The name of each node is stored in +'nodevar'+.
4954     The script is evaluated twice for each node, on entry and exit.
4956 +$tree *dump*+::
4957     Dumps the tree contents to stdout
4959 tcl::prefix
4960 ~~~~~~~~~~~
4961 The optional tclprefix extension provides the Tcl8.6-compatible `tcl::prefix` command
4962 (http://www.tcl.tk/man/tcl8.6/TclCmd/prefix.htm) for matching strings against a table
4963 of possible values (typically commands or options).
4965 +*tcl::prefix all* 'table string'+::
4966     Returns a list of all elements in +'table'+ that begin with the prefix +'string'+.
4968 +*tcl::prefix longest* 'table string'+::
4969     Returns the longest common prefix of all elements in +'table'+ that begin with the prefix +'string'+.
4971 +*tcl::prefix match* '?options? table string'+::
4972     If +'string'+ equals one element in +'table'+ or is a prefix to
4973     exactly one element, the matched element is returned. If not, the
4974     result depends on the +-error+ option.
4976     * +*-exact*+ Accept only exact matches.
4977     * +*-message* 'string'+ Use +'string'+ in the error message at a mismatch. Default is "option".
4978     * +*-error* 'options'+ The options are used when no match is found. If +'options'+ is
4979       empty, no error is generated and an empty string is returned.
4980       Otherwise the options are used as return options when
4981       generating the error message. The default corresponds to
4982       setting +-level 0+.
4984 tcl::autocomplete
4985 ~~~~~~~~~~~~~~~~~
4986 Scriptable command line completion is supported in the interactive shell, 'jimsh', through
4987 the `tcl::autocomplete` callback. A simple implementation is provided, however this may
4988 be replaced with a custom command instead if desired.
4990 In the interactive shell, press <TAB> to activate command line completion.
4992 +*tcl::autocomplete* 'commandline'+::
4993         This command is called with the current command line when the user presses <TAB>.
4994         The command should return a list of all possible command lines that match the current command line.
4995         For example if +*pr*+ is the current command line, the list +*{prefix proc}*+ may be returned.
4997 history
4998 ~~~~~~~
4999 The optional history extension provides script access to the command line editing
5000 and history support available in 'jimsh'. See 'examples/jtclsh.tcl' for an example.
5001 Note: if line editing support is not available, `history getline` acts like `gets` and
5002 the remaining subcommands do nothing.
5004 +*history load* 'filename'+::
5005     Load history from a (text) file. If the file does not exist or is not readable,
5006     it is ignored.
5008 +*history getline* 'prompt ?varname?'+::
5009     Displays the given prompt and allows a line to be entered. Similarly to `gets`,
5010     if +'varname'+ is given, it receives the line and the length of the line is returned,
5011     or -1 on EOF. If +'varname'+ is not given, the line is returned directly.
5013 +*history add* 'line'+::
5014     Adds the given line to the history buffer.
5016 +*history save* 'filename'+::
5017     Saves the current history buffer to the given file.
5019 +*history show*+::
5020     Displays the current history buffer to standard output.
5022 namespace
5023 ~~~~~~~~~
5024 Provides namespace-related functions. See also: http://www.tcl.tk/man/tcl8.6/TclCmd/namespace.htm
5026 +*namespace code* 'script'+::
5027     Captures the current namespace context for later execution of
5028     the script +'script'+. It returns a new script in which script has
5029     been wrapped in a +*namespace inscope*+ command.
5031 +*namespace current*+::
5032     Returns the fully-qualified name for the current namespace.
5034 +*namespace delete* '?namespace ...?'+::
5035     Deletes all commands and variables with the given namespace prefixes.
5037 +*namespace eval* 'namespace arg ?arg...?'+::
5038     Activates a namespace called +'namespace'+ and evaluates some code in that context.
5040 +*namespace origin* 'command'+::
5041     Returns the fully-qualified name of the original command to which the imported command +'command'+ refers.
5043 +*namespace parent* ?namespace?+::
5044     Returns the fully-qualified name of the parent namespace for namespace +'namespace'+, if given, otherwise
5045     for the current namespace.
5047 +*namespace qualifiers* 'string'+::
5048     Returns any leading namespace qualifiers for +'string'+
5050 +*namespace tail* 'string'+::
5051     Returns the simple name at the end of a qualified string.
5053 +*namespace upvar* 'namespace ?arg...?'+::
5054     This command arranges for zero or more local variables in the current procedure to refer to variables in +'namespace'+
5056 +*namespace which* '?-command|-variable? name'+::
5057     Looks up +'name'+ as either a command (the default) or variable and returns its fully-qualified name.
5059 interp
5060 ~~~~~~
5061 The optional 'interp' command allows sub-interpreters to be created where commands may be run
5062 independently (but synchronously) of the main interpreter.
5064 +*interp*+::
5065     Creates and returns a new interpreter object (command).
5066         The created interpeter contains any built-in commands along with static extensions,
5067         but does not include any dynamically loaded commands (package require, load).
5068         These must be reloaded in the child interpreter if required.
5070 +*$interp delete*+::
5071     Deletes the interpeter object.
5073 +*$interp eval* 'script' ...+::
5074         Evaluates a script in the context for the child interpreter, in the same way as 'eval'.
5076 +*$interp alias* 'alias childcmd parentcmd ?arg ...?'+::
5077         Similar to 'alias', but creates a command, +'childcmd'+, in the child interpreter that is an
5078         alias for +'parentcmd'+ in the parent interpreter, with the given, fixed arguments.
5079         The alias may be deleted in the child with 'rename'.
5081 [[BuiltinVariables]]
5082 BUILT-IN VARIABLES
5083 ------------------
5085 The following global variables are created automatically
5086 by the Tcl library.
5088 +*env*+::
5089     This variable is set by Jim as an array
5090     whose elements are the environment variables for the process.
5091     Reading an element will return the value of the corresponding
5092     environment variable.
5093     This array is initialised at startup from the `env` command.
5094     It may be modified and will affect the environment passed to
5095     commands invoked with `exec`.
5097 +*platform_tcl*+::
5098     This variable is set by Jim as an array containing information
5099     about the platform on which Jim was built. Currently this includes
5100     'os' and 'platform'.
5102 +*auto_path*+::
5103     This variable contains a list of paths to search for packages.
5104     It defaults to a location based on where jim is installed
5105     (e.g. +/usr/local/lib/jim+), but may be changed by +jimsh+
5106     or the embedding application. Note that +jimsh+ will consider
5107     the environment variable +$JIMLIB+ to be a list of colon-separated
5108     list of paths to add to +*auto_path*+.
5110 +*errorCode*+::
5111     This variable holds the value of the -errorcode return
5112     option set by the most recent error that occurred in this
5113     interpreter. This list value represents additional information
5114     about the error in a form that is easy to process with
5115     programs. The first element of the list identifies a general
5116     class of errors, and determines the format of the rest of
5117     the list. The following formats for -errorcode return options
5118     are used by the Tcl core; individual applications may define
5119     additional formats. Currently only `exec` sets this variable.
5120     Otherwise it will be +NONE+.
5122 The following global variables are set by jimsh.
5124 +*tcl_interactive*+::
5125     This variable is set to 1 if jimsh is started in interactive mode
5126     or 0 otherwise.
5128 +*tcl_platform*+::
5129     This variable is set by Jim as an array containing information
5130     about the platform upon which Jim was built. The following is an
5131     example of the contents of this array.
5133     tcl_platform(byteOrder)     = littleEndian
5134     tcl_platform(engine)        = Jim
5135     tcl_platform(os)            = Darwin
5136     tcl_platform(platform)      = unix
5137     tcl_platform(pointerSize)   = 8
5138     tcl_platform(threaded)      = 0
5139     tcl_platform(wordSize)      = 8
5140     tcl_platform(pathSeparator) = :
5142 +*argv0*+::
5143     If jimsh is invoked to run a script, this variable contains the name
5144     of the script.
5146 +*argv*+::
5147     If jimsh is invoked to run a script, this variable contains a list
5148     of any arguments supplied to the script.
5150 +*argc*+::
5151     If jimsh is invoked to run a script, this variable contains the number
5152     of arguments supplied to the script.
5154 +*jim::argv0*+::
5155     The value of argv[0] when jimsh was invoked.
5157 CHANGES IN PREVIOUS RELEASES
5158 ----------------------------
5160 === In v0.70 ===
5162 1. +platform_tcl()+ settings are now automatically determined
5163 2. Add aio `$handle filename`
5164 3. Add `info channels`
5165 4. The 'bio' extension is gone. Now `aio` supports 'copyto'.
5166 5. Add `exists` command
5167 6. Add the pure-Tcl 'oo' extension
5168 7. The `exec` command now only uses vfork(), not fork()
5169 8. Unit test framework is less verbose and more Tcl-compatible
5170 9. Optional UTF-8 support
5171 10. Optional built-in regexp engine for better Tcl compatibility and UTF-8 support
5172 11. Command line editing in interactive mode, e.g. 'jimsh'
5174 === In v0.63 ===
5176 1. `source` now checks that a script is complete (.i.e. not missing a brace)
5177 2. 'info complete' now uses the real parser and so is 100% accurate
5178 3. Better access to live stack frames with 'info frame', `stacktrace` and `stackdump`
5179 4. `tailcall` no longer loses stack trace information
5180 5. Add `alias` and `curry`
5181 6. `lambda`, `alias` and `curry` are implemented via `tailcall` for efficiency
5182 7. `local` allows procedures to be deleted automatically at the end of the current procedure
5183 8. udp sockets are now supported for both clients and servers.
5184 9. vfork-based exec is now working correctly
5185 10. Add 'file tempfile'
5186 11. Add 'socket pipe'
5187 12. Enhance 'try ... on ... finally' to be more Tcl 8.6 compatible
5188 13. It is now possible to `return` from within `try`
5189 14. IPv6 support is now included
5190 15. Add 'string is'
5191 16. Event handlers works better if an error occurs. eof handler has been removed.
5192 17. `exec` now sets $::errorCode, and catch sets opts(-errorcode) for exit status
5193 18. Command pipelines via open "|..." are now supported
5194 19. `pid` can now return pids of a command pipeline
5195 20. Add 'info references'
5196 21. Add support for 'after +'ms'+', 'after idle', 'after info', `update`
5197 22. `exec` now sets environment based on $::env
5198 23. Add 'dict keys'
5199 24. Add support for 'lsort -index'
5201 === In v0.62 ===
5203 1. Add support to `exec` for '>&', '>>&', '|&', '2>@1'
5204 2. Fix `exec` error messages when special token (e.g. '>') is the last token
5205 3. Fix `subst` handling of backslash escapes.
5206 4. Allow abbreviated options for `subst`
5207 5. Add support for `return`, `break`, `continue` in subst
5208 6. Many `expr` bug fixes
5209 7. Add support for functions in `expr` (e.g. int(), abs()), and also 'in', 'ni' list operations
5210 8. The variable name argument to `regsub` is now optional
5211 9. Add support for 'unset -nocomplain'
5212 10. Add support for list commands: `lassign`, `lrepeat`
5213 11. Fully-functional `lsearch` is now implemented
5214 12. Add 'info nameofexecutable' and 'info returncodes'
5215 13. Allow `catch` to determine what return codes are caught
5216 14. Allow `incr` to increment an unset variable by first setting to 0
5217 15. Allow 'args' and optional arguments to the left or required arguments in `proc`
5218 16. Add 'file copy'
5219 17. Add 'try ... finally' command
5222 LICENCE
5223 -------
5225  Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
5226  Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
5227  Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
5228  Copyright 2008 oharboe - Oyvind Harboe - oyvind.harboe@zylin.com
5229  Copyright 2008 Andrew Lunn <andrew@lunn.ch>
5230  Copyright 2008 Duane Ellis <openocd@duaneellis.com>
5231  Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
5232  Copyright 2009 Steve Bennett <steveb@workware.net.au>
5234 [literal]
5235  Redistribution and use in source and binary forms, with or without
5236  modification, are permitted provided that the following conditions
5237  are met:
5238  1. Redistributions of source code must retain the above copyright
5239     notice, this list of conditions and the following disclaimer.
5240  2. Redistributions in binary form must reproduce the above
5241     copyright notice, this list of conditions and the following
5242     disclaimer in the documentation and/or other materials
5243     provided with the distribution.
5245  THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
5246  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
5247  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
5248  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
5249  JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
5250  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
5251  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
5252  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
5253  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
5254  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
5255  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
5256  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5258  The views and conclusions contained in the software and documentation
5259  are those of the authors and should not be interpreted as representing
5260  official policies, either expressed or implied, of the Jim Tcl Project.