scan: Fix a utf-8 bug for string length
[jimtcl.git] / jim_tcl.txt
blob0ba2e5b892af35f178f80dbee2e710d7b8e4db6a
1 Jim Tcl(n)
2 ==========
4 NAME
5 ----
6 Jim Tcl v0.79 - 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.uptime`, `wait`, `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.78 and 0.79
56 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
57 1. Add `file mtimeus` for high resolution file timestamps
58 2. `aio` now supports datagram Unix-Domain sockets
59 3. Add support for `aio lock -wait`
60 4. Add `signal block` to prevent delivery of signals
61 5. Add support for `file split`
62 6. Add support for `json::encode` and `json::decode`
63 7. `aio tty` now allows setting +echo+ without full +raw+ mode
64 8. `regsub` now fully supports +{backslash}A+
66 Changes between 0.77 and 0.78
67 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68 1. Add serial/tty support with `aio tty`
69 2. Add support for 'jimsh -'
70 3. Add hidden '-commands' option to many commands
71 4. Add scriptable autocompletion support in interactive mode with `tcl::autocomplete`
72 5. Add `aio sockopt`
73 6. Add scriptable autocompletion support with `history completion`
74 7. Add support for `tree delete`
75 8. Add support for `defer` and '$jim::defer'
76 9. Renamed `os.wait` to `wait`, now more Tcl-compatible and compatible with `exec ... &`
77 10. `pipe` is now a synonym for `socket pipe`
78 11. Closing a pipe open with `open |...` now returns Tcl-like status
79 12. It is now possible to used `exec` redirection with a pipe opened with `open |...`
80 13. Interactive line editing now supports multiline mode if $::history::multiline is set
82 Changes between 0.76 and 0.77
83 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
84 1. Add support for `aio sync`
85 2. Add SSL and TLS support in aio
86 3. Added `zlib`
87 4. Added support for boolean constants in `expr`
88 5. `string is` now supports 'boolean' class
89 6. Add support for `aio lock` and `aio unlock`
90 7. Add new `interp` command
92 Changes between 0.75 and 0.76
93 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
94 1. `glob` now supports the +-tails+ option
95 2. Add support for `string cat`
96 3. Allow `info source` to add source info
98 Changes between 0.74 and 0.75
99 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
100 1. `binary`, `pack` and `unpack` now support floating point
101 2. `file copy` +-force+ handles source and target as the same file
102 3. `format` now supports +%b+ for binary conversion
103 4. `lsort` now supports +-unique+ and +-real+
104 5. Add support for half-close with `aio close` +?r|w?+
105 6. Add `socket pair` for a bidirectional pipe
106 7. Add '--random-hash' to randomise hash tables for greater security
107 8. `dict` now supports 'for', 'values', 'incr', 'append', 'lappend', 'update', 'info' and 'replace'
108 9. `file stat` no longer requires the variable name
109 10. Add support for `file link`
111 TCL INTRODUCTION
112 -----------------
113 Tcl stands for 'tool command language' and is pronounced
114 'http://www.oxforddictionaries.com/definition/american_english/tickle[tickle]'.
115 It is actually two things: a language and a library.
117 First, Tcl is a simple textual language, intended primarily for
118 issuing commands to interactive programs such as text editors,
119 debuggers, illustrators, and shells.  It has a simple syntax and is also
120 programmable, so Tcl users can write command procedures to provide more
121 powerful commands than those in the built-in set.
123 Second, Tcl is a library package that can be embedded in application
124 programs.  The Tcl library consists of a parser for the Tcl language,
125 routines to implement the Tcl built-in commands, and procedures that
126 allow each application to extend Tcl with additional commands specific
127 to that application.  The application program generates Tcl commands and
128 passes them to the Tcl parser for execution.  Commands may be generated
129 by reading characters from an input source, or by associating command
130 strings with elements of the application's user interface, such as menu
131 entries, buttons, or keystrokes.
133 When the Tcl library receives commands it parses them into component
134 fields and executes built-in commands directly.  For commands implemented
135 by the application, Tcl calls back to the application to execute the
136 commands.  In many cases commands will invoke recursive invocations of the
137 Tcl interpreter by passing in additional strings to execute (procedures,
138 looping commands, and conditional commands all work in this way).
140 An application program gains three advantages by using Tcl for its command
141 language.  First, Tcl provides a standard syntax:  once users know Tcl,
142 they will be able to issue commands easily to any Tcl-based application.
143 Second, Tcl provides programmability.  All a Tcl application needs
144 to do is to implement a few application-specific low-level commands.
145 Tcl provides many utility commands plus a general programming interface
146 for building up complex command procedures.  By using Tcl, applications
147 need not re-implement these features.
149 Third, Tcl can be used as a common language for communicating between
150 applications.  Inter-application communication is not built into the
151 Tcl core described here, but various add-on libraries, such as the Tk
152 toolkit, allow applications to issue commands to each other.  This makes
153 it possible for applications to work together in much more powerful ways
154 than was previously possible.
156 Fourth, Jim Tcl includes a command processor, +jimsh+, which can be
157 used to run standalone Tcl scripts, or to run Tcl commands interactively.
159 This manual page focuses primarily on the Tcl language.  It describes
160 the language syntax and the built-in commands that will be available
161 in any application based on Tcl.  The individual library procedures are
162 described in more detail in separate manual pages, one per procedure.
164 JIMSH COMMAND INTERPRETER
165 -------------------------
166 A simple, but powerful command processor, +jimsh+, is part of Jim Tcl.
167 It may be invoked in interactive mode as:
169   jimsh
171 or to process the Tcl script in a file with:
173   jimsh filename
175 or to process the Tcl script from standard input:
177   jimsh -
179 It may also be invoked to execute an immediate script with:
181   jimsh -e "script"
183 Interactive Mode
184 ~~~~~~~~~~~~~~~~
185 Interactive mode reads Tcl commands from standard input, evaluates
186 those commands and prints the results.
188   $ jimsh
189   Welcome to Jim version 0.73, Copyright (c) 2005-8 Salvatore Sanfilippo
190   . info version
191   0.73
192   . lsort [info commands p*]
193   package parray pid popen proc puts pwd
194   . foreach i {a b c} {
195   {> puts $i
196   {> }
197   a
198   b
199   c
200   . bad
201   invalid command name "bad"
202   [error] . exit
203   $
205 If +jimsh+ is configured with line editing (it is by default) and a VT-100-compatible
206 terminal is detected, Emacs-style line editing commands are available, including:
207 arrow keys, +\^W+ to erase a word, +\^U+ to erase the line, +^R+ for reverse incremental search
208 in history. Additionally, the +h+ command may be used to display the command history.
210 Command line history is automatically saved and loaded from +~/.jim_history+
212 In interactive mode, +jimsh+ automatically runs the script +~/.jimrc+ at startup
213 if it exists.
215 INTERPRETERS
216 ------------
217 The central data structure in Tcl is an interpreter (C type 'Jim_Interp').
218 An interpreter consists of a set of command bindings, a set of variable
219 values, and a few other miscellaneous pieces of state.  Each Tcl command
220 is interpreted in the context of a particular interpreter.
222 Some Tcl-based applications will maintain multiple interpreters
223 simultaneously, each associated with a different widget or portion of
224 the application.  Interpreters are relatively lightweight structures.
225 They can be created and deleted quickly, so application programmers should
226 feel free to use multiple interpreters if that simplifies the application.
228 DATA TYPES
229 ----------
230 Tcl supports only one type of data:  strings.  All commands, all arguments
231 to commands, all command results, and all variable values are strings.
233 Where commands require numeric arguments or return numeric results,
234 the arguments and results are passed as strings.  Many commands expect
235 their string arguments to have certain formats, but this interpretation
236 is up to the individual commands.  For example, arguments often contain
237 Tcl command strings, which may get executed as part of the commands.
238 The easiest way to understand the Tcl interpreter is to remember that
239 everything is just an operation on a string.  In many cases Tcl constructs
240 will look similar to more structured constructs from other languages.
241 However, the Tcl constructs are not structured at all; they are just
242 strings of characters, and this gives them a different behaviour than
243 the structures they may look like.
245 Although the exact interpretation of a Tcl string depends on who is doing
246 the interpretation, there are three common forms that strings take:
247 commands, expressions, and lists.  The major sections below discuss
248 these three forms in more detail.
250 BASIC COMMAND SYNTAX
251 --------------------
252 The Tcl language has syntactic similarities to both the Unix shells
253 and Lisp.  However, the interpretation of commands is different
254 in Tcl than in either of those other two systems.
255 A Tcl command string consists of one or more commands separated
256 by newline characters or semi-colons.
257 Each command consists of a collection of fields separated by
258 white space (spaces or tabs).
259 The first field must be the name of a command, and the
260 additional fields, if any, are arguments that will be passed to
261 that command.  For example, the command:
263 ----
264     set a 22
265 ----
267 has three fields:  the first, `set`, is the name of a Tcl command, and
268 the last two, 'a' and '22', will be passed as arguments to
269 the `set` command.  The command name may refer either to a built-in
270 Tcl command, an application-specific command bound in with the library
271 procedure 'Jim_CreateCommand', or a command procedure defined with the
272 `proc` built-in command.
274 Arguments are passed literally as text strings.  Individual commands may
275 interpret those strings in any fashion they wish.  The `set` command,
276 for example, will treat its first argument as the name of a variable
277 and its second argument as a string value to assign to that variable.
278 For other commands arguments may be interpreted as integers, lists,
279 file names, or Tcl commands.
281 Command names should normally be typed completely (e.g. no abbreviations).
282 However, if the Tcl interpreter cannot locate a command it invokes a
283 special command named `unknown` which attempts to find or create the
284 command.
286 For example, at many sites `unknown` will search through library
287 directories for the desired command and create it as a Tcl procedure if
288 it is found.  The `unknown` command often provides automatic completion
289 of abbreviated commands, but usually only for commands that were typed
290 interactively.
292 It's probably a bad idea to use abbreviations in command scripts and
293 other forms that will be re-used over time:  changes to the command set
294 may cause abbreviations to become ambiguous, resulting in scripts that
295 no longer work.
297 COMMENTS
298 --------
299 If the first non-blank character in a command is +\#+, then everything
300 from the +#+ up through the next newline character is treated as
301 a comment and ignored.  When comments are embedded inside nested
302 commands (e.g. fields enclosed in braces) they must have properly-matched
303 braces (this is necessary because when Tcl parses the top-level command
304 it doesn't yet know that the nested field will be used as a command so
305 it cannot process the nested comment character as a comment).
307 GROUPING ARGUMENTS WITH DOUBLE-QUOTES
308 -------------------------------------
309 Normally each argument field ends at the next white space, but
310 double-quotes may be used to create arguments with embedded space.
312 If an argument field begins with a double-quote, then the argument isn't
313 terminated by white space (including newlines) or a semi-colon (see below
314 for information on semi-colons); instead it ends at the next double-quote
315 character.  The double-quotes are not included in the resulting argument.
316 For example, the command
318 ----
319     set a "This is a single argument"
320 ----
322 will pass two arguments to `set`:  'a' and 'This is a single argument'.
324 Within double-quotes, command substitutions, variable substitutions,
325 and backslash substitutions still occur, as described below.  If the
326 first character of a command field is not a quote, then quotes receive
327 no special interpretation in the parsing of that field.
329 GROUPING ARGUMENTS WITH BRACES
330 ------------------------------
331 Curly braces may also be used for grouping arguments.  They are similar
332 to quotes except for two differences.  First, they nest; this makes them
333 easier to use for complicated arguments like nested Tcl command strings.
334 Second, the substitutions described below for commands, variables, and
335 backslashes do *not* occur in arguments enclosed in braces, so braces
336 can be used to prevent substitutions where they are undesirable.
338 If an argument field begins with a left brace, then the argument ends
339 at the matching right brace.  Tcl will strip off the outermost layer
340 of braces and pass the information between the braces to the command
341 without any further modification.  For example, in the command
343 ----
344     set a {xyz a {b c d}}
345 ----
347 the `set` command will receive two arguments: 'a'
348 and 'xyz a {b c d}'.
350 When braces or quotes are in effect, the matching brace or quote need
351 not be on the same line as the starting quote or brace; in this case
352 the newline will be included in the argument field along with any other
353 characters up to the matching brace or quote.  For example, the `eval`
354 command takes one argument, which is a command string; `eval` invokes
355 the Tcl interpreter to execute the command string.  The command
357 ----
358     eval {
359       set a 22
360       set b 33
361     }
362 ----
364 will assign the value '22' to 'a' and '33' to 'b'.
366 If the first character of a command field is not a left
367 brace, then neither left nor right
368 braces in the field will be treated specially (except as part of
369 variable substitution; see below).
371 COMMAND SUBSTITUTION WITH BRACKETS
372 ----------------------------------
373 If an open bracket occurs in a field of a command, then command
374 substitution occurs (except for fields enclosed in braces).  All of the
375 text up to the matching close bracket is treated as a Tcl command and
376 executed immediately.  Then the result of that command is substituted
377 for the bracketed text.  For example, consider the command
379 ----
380     set a [set b]
381 ----
383 When the `set` command has only a single argument, it is the name of a
384 variable and `set` returns the contents of that variable.  In this case,
385 if variable 'b' has the value 'foo', then the command above is equivalent
386 to the command
388 ----
389     set a foo
390 ----
392 Brackets can be used in more complex ways.  For example, if the variable
393 'b' has the value 'foo' and the variable 'c' has the value 'gorp',
394 then the command
396 ----
397     set a xyz[set b].[set c]
398 ----
400 is equivalent to the command
402 ----
403     set a xyzfoo.gorp
404 ----
406 A bracketed command may contain multiple commands separated by newlines
407 or semi-colons in the usual fashion.  In this case the value of the last
408 command is used for substitution.  For example, the command
410 ----
411     set a x[set b 22
412     expr $b+2]x
413 ----
415 is equivalent to the command
417 ----
418     set a x24x
419 ----
421 If a field is enclosed in braces then the brackets and the characters
422 between them are not interpreted specially; they are passed through to
423 the argument verbatim.
425 VARIABLE SUBSTITUTION WITH $
426 ----------------------------
427 The dollar sign (+$+) may be used as a special shorthand form for
428 substituting variable values.  If +$+ appears in an argument that isn't
429 enclosed in braces then variable substitution will occur.  The characters
430 after the +$+, up to the first character that isn't a number, letter,
431 or underscore, are taken as a variable name and the string value of that
432 variable is substituted for the name.
434 For example, if variable 'foo' has the value 'test', then the command
436 ----
437     set a $foo.c
438 ----
440 is equivalent to the command
442 ----
443     set a test.c
444 ----
446 There are two special forms for variable substitution.  If the next
447 character after the name of the variable is an open parenthesis, then
448 the variable is assumed to be an array name, and all of the characters
449 between the open parenthesis and the next close parenthesis are taken as
450 an index into the array.  Command substitutions and variable substitutions
451 are performed on the information between the parentheses before it is
452 used as an index.
454 For example, if the variable 'x' is an array with one element named
455 'first' and value '87' and another element named '14' and value 'more',
456 then the command
458 ----
459     set a xyz$x(first)zyx
460 ----
462 is equivalent to the command
464 ----
465     set a xyz87zyx
466 ----
468 If the variable 'index' has the value '14', then the command
470 ----
471     set a xyz$x($index)zyx
472 ----
474 is equivalent to the command
476 ----
477     set a xyzmorezyx
478 ----
480 For more information on arrays, see <<_variables_scalars_and_arrays,VARIABLES - SCALARS AND ARRAYS>> below.
482 The second special form for variables occurs when the dollar sign is
483 followed by an open curly brace.  In this case the variable name consists
484 of all the characters up to the next curly brace.
486 Array references are not possible in this form:  the name between braces
487 is assumed to refer to a scalar variable.  For example, if variable
488 'foo' has the value 'test', then the command
490 ----
491     set a abc${foo}bar
492 ----
494 is equivalent to the command
496 ----
497     set a abctestbar
498 ----
501 Variable substitution does not occur in arguments that are enclosed in
502 braces:  the dollar sign and variable name are passed through to the
503 argument verbatim.
505 The dollar sign abbreviation is simply a shorthand form.  +$a+ is
506 completely equivalent to +[set a]+; it is provided as a convenience
507 to reduce typing.
509 SEPARATING COMMANDS WITH SEMI-COLONS
510 ------------------------------------
511 Normally, each command occupies one line (the command is terminated by a
512 newline character).  However, semi-colon (+;+) is treated as a command
513 separator character; multiple commands may be placed on one line by
514 separating them with a semi-colon.  Semi-colons are not treated as
515 command separators if they appear within curly braces or double-quotes.
517 BACKSLASH SUBSTITUTION
518 ----------------------
519 Backslashes may be used to insert non-printing characters into command
520 fields and also to insert special characters like braces and brackets
521 into fields without them being interpreted specially as described above.
523 The backslash sequences understood by the Tcl interpreter are
524 listed below.  In each case, the backslash
525 sequence is replaced by the given character:
526 [[BackslashSequences]]
527 +{backslash}b+::
528     Backspace (0x8)
530 +{backslash}f+::
531     Form feed (0xc)
533 +{backslash}n+::
534     Newline (0xa)
536 +{backslash}r+::
537     Carriage-return (0xd).
539 +{backslash}t+::
540     Tab (0x9).
542 +{backslash}v+::
543     Vertical tab (0xb).
545 +{backslash}{+::
546     Left brace ({).
548 +{backslash}}+::
549     Right brace (}).
551 +{backslash}[+::
552     Open bracket ([).
554 +{backslash}]+::
555     Close bracket (]).
557 +{backslash}$+::
558     Dollar sign ($).
560 +{backslash}<space>+::
561     Space ( ): doesn't terminate argument.
563 +{backslash};+::
564     Semi-colon: doesn't terminate command.
566 +{backslash}"+::
567     Double-quote.
569 +{backslash}<newline>+::
570     Nothing:  this joins two lines together
571     into a single line.  This backslash feature is unique in that
572     it will be applied even when the sequence occurs within braces.
574 +{backslash}{backslash}+::
575     Backslash ('{backslash}').
577 +{backslash}ddd+::
578     The digits +'ddd'+ (one, two, or three of them) give the octal value of
579     the character.  Note that Jim supports null characters in strings.
581 +{backslash}unnnn+::
582 +{backslash}u\{nnn\}+::
583 +{backslash}Unnnnnnnn+::
584     The UTF-8 encoding of the unicode codepoint represented by the hex digits, +'nnnn'+, is inserted.
585     The 'u' form allows for one to four hex digits.
586     The 'U' form allows for one to eight hex digits.
587     The 'u\{nnn\}' form allows for one to eight hex digits, but makes it easier to insert
588     characters UTF-8 characters which are followed by a hex digit.
590 For example, in the command
592 ----
593     set a \{x\[\ yz\141
594 ----
596 the second argument to `set` will be +{x[ yza+.
598 If a backslash is followed by something other than one of the options
599 described above, then the backslash is transmitted to the argument
600 field without any special processing, and the Tcl scanner continues
601 normal processing with the next character.  For example, in the
602 command
604 ----
605     set \*a \\\{foo
606 ----
608 The first argument to `set` will be +{backslash}*a+ and the second
609 argument will be +{backslash}{foo+.
611 If an argument is enclosed in braces, then backslash sequences inside
612 the argument are parsed but no substitution occurs (except for
613 backslash-newline):  the backslash
614 sequence is passed through to the argument as is, without making
615 any special interpretation of the characters in the backslash sequence.
616 In particular, backslashed braces are not counted in locating the
617 matching right brace that terminates the argument.
618 For example, in the
619 command
621 ----
622     set a {\{abc}
623 ----
625 the second argument to `set` will be +{backslash}{abc+.
627 This backslash mechanism is not sufficient to generate absolutely
628 any argument structure; it only covers the
629 most common cases.  To produce particularly complicated arguments
630 it is probably easiest to use the `format` command along with
631 command substitution.
633 STRING AND LIST INDEX SPECIFICATIONS
634 ------------------------------------
636 Many string and list commands take one or more 'index' parameters which
637 specify a position in the string relative to the start or end of the string/list.
639 The index may be one of the following forms:
641 +integer+::
642     A simple integer, where '0' refers to the first element of the string
643     or list.
645 +integer+integer+ or::
646 +integer-integer+::
647     The sum or difference of the two integers. e.g. +2+3+ refers to the 5th element.
648     This is useful when used with (e.g.) +$i+1+ rather than the more verbose
649     +[expr {$i+1\}]+
651 +end+::
652     The last element of the string or list.
654 +end-integer+::
655     The 'nth-from-last' element of the string or list.
657 COMMAND SUMMARY
658 ---------------
659 1. A command is just a string.
660 2. Within a string commands are separated by newlines or semi-colons
661    (unless the newline or semi-colon is within braces or brackets
662    or is backslashed).
663 3. A command consists of fields.  The first field is the name of the command.
664    The other fields are strings that are passed to that command as arguments.
665 4. Fields are normally separated by white space.
666 5. Double-quotes allow white space and semi-colons to appear within
667    a single argument.
668    Command substitution, variable substitution, and backslash substitution
669    still occur inside quotes.
670 6. Braces defer interpretation of special characters.
671    If a field begins with a left brace, then it consists of everything
672    between the left brace and the matching right brace. The
673    braces themselves are not included in the argument.
674    No further processing is done on the information between the braces
675    except that backslash-newline sequences are eliminated.
676 7. If a field doesn't begin with a brace then backslash,
677    variable, and command substitution are done on the field.  Only a
678    single level of processing is done:  the results of one substitution
679    are not scanned again for further substitutions or any other
680    special treatment.  Substitution can
681    occur on any field of a command, including the command name
682    as well as the arguments.
683 8. If the first non-blank character of a command is a +\#+, everything
684    from the +#+ up through the next newline is treated as a comment
685    and ignored.
687 EXPRESSIONS
688 -----------
689 The second major interpretation applied to strings in Tcl is
690 as expressions.  Several commands, such as `expr`, `for`,
691 and `if`, treat one or more of their arguments as expressions
692 and call the Tcl expression processors ('Jim_ExprLong',
693 'Jim_ExprBoolean', etc.) to evaluate them.
695 The operators permitted in Tcl expressions are a subset of
696 the operators permitted in C expressions, and they have the
697 same meaning and precedence as the corresponding C operators.
698 Expressions almost always yield numeric results
699 (integer or floating-point values).
700 For example, the expression
702 ----
703     8.2 + 6
704 ----
706 evaluates to 14.2.
708 Tcl expressions differ from C expressions in the way that
709 operands are specified, and in that Tcl expressions support
710 non-numeric operands and string comparisons.
712 A Tcl expression consists of a combination of operands, operators,
713 and parentheses.
715 White space may be used between the operands and operators and
716 parentheses; it is ignored by the expression processor.
717 Where possible, operands are interpreted as integer values.
719 Integer values may be specified in decimal (the normal case) or in
720 hexadecimal (if the first two characters of the operand are '0x').
721 Note that Jim Tcl does *not* treat numbers with leading zeros as octal.
723 If an operand does not have one of the integer formats given
724 above, then it is treated as a floating-point number if that is
725 possible.  Floating-point numbers may be specified in any of the
726 ways accepted by an ANSI-compliant C compiler (except that the
727 'f', 'F', 'l', and 'L' suffixes will not be permitted in
728 most installations).  For example, all of the
729 following are valid floating-point numbers:  2.1, 3., 6e4, 7.91e+16.
731 If no numeric interpretation is possible, then an operand is left
732 as a string (and only a limited set of operators may be applied to
733 it).
735 String constants representing boolean constants
736 (+'0'+, +'1'+, +'false'+, +'off'+, +'no'+, +'true'+, +'on'+, +'yes'+)
737 are also recognized and can be used in logical operations.
739 1. Operands may be specified in any of the following ways:
741 2. As a numeric value, either integer or floating-point.
743 3. As one of valid boolean constants
745 4. As a Tcl variable, using standard '$' notation.
746 The variable's value will be used as the operand.
748 5. As a string enclosed in double-quotes.
749 The expression parser will perform backslash, variable, and
750 command substitutions on the information between the quotes,
751 and use the resulting value as the operand
753 6. As a string enclosed in braces.
754 The characters between the open brace and matching close brace
755 will be used as the operand without any substitutions.
757 7. As a Tcl command enclosed in brackets.
758 The command will be executed and its result will be used as
759 the operand.
761 Where substitutions occur above (e.g. inside quoted strings), they
762 are performed by the expression processor.
763 However, an additional layer of substitution may already have
764 been performed by the command parser before the expression
765 processor was called.
767 As discussed below, it is usually best to enclose expressions
768 in braces to prevent the command parser from performing substitutions
769 on the contents.
771 For some examples of simple expressions, suppose the variable 'a' has
772 the value 3 and the variable 'b' has the value 6.  Then the expression
773 on the left side of each of the lines below will evaluate to the value
774 on the right side of the line:
776 ----
777     $a + 3.1                6.1
778     2 + "$a.$b"             5.6
779     4*[llength "6 2"]       8
780     {word one} < "word $a"  0
781 ----
783 The valid operators are listed below, grouped in decreasing order
784 of precedence:
785 [[OperatorPrecedence]]
786 +int() double() round() abs(), rand(), srand()+::
787     Unary functions (except rand() which takes no arguments)
788     * +'int()'+ converts the numeric argument to an integer by truncating down.
789     * +'double()'+ converts the numeric argument to floating point.
790     * +'round()'+ converts the numeric argument to the closest integer value.
791     * +'abs()'+ takes the absolute value of the numeric argument.
792     * +'rand()'+ returns a pseudo-random floating-point value in the range (0,1).
793     * +'srand()'+ takes an integer argument to (re)seed the random number generator. Returns the first random number from that seed.
795 +sin() cos() tan() asin() acos() atan() sinh() cosh() tanh() ceil() floor() exp() log() log10() sqrt()+::
796     Unary math functions.
797     If Jim is compiled with math support, these functions are available.
799 +- + ~ !+::
800     Unary minus, unary plus, bit-wise NOT, logical NOT.  None of these operands
801     may be applied to string operands, and bit-wise NOT may be
802     applied only to integers.
804 +** pow(x,y)+::
805     Power. e.g. 'x^y^'. If Jim is compiled with math support, supports doubles and
806     integers. Otherwise supports integers only. (Note that the math-function form
807     has the same highest precedence)
809 +* / %+::
810     Multiply, divide, remainder.  None of these operands may be
811     applied to string operands, and remainder may be applied only
812     to integers.
814 ++ -+::
815     Add and subtract.  Valid for any numeric operands.
817 +<<  >> <<< >>>+::
818     Left and right shift, left and right rotate.  Valid for integer operands only.
820 +<  >  \<=  >=+::
821     Boolean less, greater, less than or equal, and greater than or equal.
822     Each operator produces 1 if the condition is true, 0 otherwise.
823     These operators may be applied to strings as well as numeric operands,
824     in which case string comparison is used.
826 +==  !=+::
827     Boolean equal and not equal.  Each operator produces a zero/one result.
828     Valid for all operand types. *Note* that values will be converted to integers
829     if possible, then floating point types, and finally strings will be compared.
830     It is recommended that 'eq' and 'ne' should be used for string comparison.
832 +eq ne+::
833     String equal and not equal.  Uses the string value directly without
834     attempting to convert to a number first.
836 +in ni+::
837     String in list and not in list. For 'in', result is 1 if the left operand (as a string)
838     is contained in the right operand (as a list), or 0 otherwise. The result for
839     +{$a ni $list}+ is equivalent to +{!($a in $list)}+.
841 +&+::
842     Bit-wise AND.  Valid for integer operands only.
844 +|+::
845     Bit-wise OR.  Valid for integer operands only.
847 +^+::
848     Bit-wise exclusive OR.  Valid for integer operands only.
850 +&&+::
851     Logical AND.  Produces a 1 result if both operands are non-zero, 0 otherwise.
852     Valid for numeric operands only (integers or floating-point).
854 +||+::
855     Logical OR.  Produces a 0 result if both operands are zero, 1 otherwise.
856     Valid for numeric operands only (integers or floating-point).
858 +x ? y : z+::
859     If-then-else, as in C.  If +'x'+
860     evaluates to non-zero, then the result is the value of +'y'+.
861     Otherwise the result is the value of +'z'+.
862     The +'x'+ operand must have a numeric value, while +'y'+ and +'z'+ can
863     be of any type.
865 See the C manual for more details on the results
866 produced by each operator.
867 All of the binary operators group left-to-right within the same
868 precedence level.  For example, the expression
870 ----
871     4*2 < 7
872 ----
874 evaluates to 0.
876 The +&&+, +||+, and +?:+ operators have 'lazy evaluation', just as
877 in C, which means that operands are not evaluated if they are not
878 needed to determine the outcome.  For example, in
880 ----
881     $v ? [a] : [b]
882 ----
884 only one of +[a]+ or +[b]+ will actually be evaluated,
885 depending on the value of +$v+.
887 All internal computations involving integers are done with the C
888 type 'long long' if available, or 'long' otherwise, and all internal
889 computations involving floating-point are done with the C type
890 'double'.
892 When converting a string to floating-point, exponent overflow is
893 detected and results in a Tcl error.
894 For conversion to integer from string, detection of overflow depends
895 on the behaviour of some routines in the local C library, so it should
896 be regarded as unreliable.
897 In any case, overflow and underflow are generally not detected
898 reliably for intermediate results.
900 Conversion among internal representations for integer, floating-point,
901 string operands is done automatically as needed.
902 For arithmetic computations, integers are used until some
903 floating-point number is introduced, after which floating-point is used.
904 For example,
906 ----
907     5 / 4
908 ----
910 yields the result 1, while
912 ----
913     5 / 4.0
914     5 / ( [string length "abcd"] + 0.0 )
915 ----
917 both yield the result 1.25.
919 String values may be used as operands of the comparison operators,
920 although the expression evaluator tries to do comparisons as integer
921 or floating-point when it can.
922 If one of the operands of a comparison is a string and the other
923 has a numeric value, the numeric operand is converted back to
924 a string using the C 'sprintf' format specifier
925 '%d' for integers and '%g' for floating-point values.
926 For example, the expressions
928 ----
929     "0x03" > "2"
930     "0y" < "0x12"
931 ----
933 both evaluate to 1.  The first comparison is done using integer
934 comparison, and the second is done using string comparison after
935 the second operand is converted to the string '18'.
937 In general it is safest to enclose an expression in braces when
938 entering it in a command:  otherwise, if the expression contains
939 any white space then the Tcl interpreter will split it
940 among several arguments.  For example, the command
942 ----
943     expr $a + $b
944 ----
946 results in three arguments being passed to `expr`:  +$a+,
947 \+, and +$b+.  In addition, if the expression isn't in braces
948 then the Tcl interpreter will perform variable and command substitution
949 immediately (it will happen in the command parser rather than in
950 the expression parser).  In many cases the expression is being
951 passed to a command that will evaluate the expression later (or
952 even many times if, for example, the expression is to be used to
953 decide when to exit a loop).  Usually the desired goal is to re-do
954 the variable or command substitutions each time the expression is
955 evaluated, rather than once and for all at the beginning.  For example,
956 the command
958 ----
959     for {set i 1} $i<=10 {incr i} {...}        ** WRONG **
960 ----
962 is probably intended to iterate over all values of +i+ from 1 to 10.
963 After each iteration of the body of the loop, `for` will pass
964 its second argument to the expression evaluator to see whether or not
965 to continue processing.  Unfortunately, in this case the value of +i+
966 in the second argument will be substituted once and for all when the
967 `for` command is parsed.  If +i+ was 0 before the `for`
968 command was invoked then the second argument of `for` will be +0\<=10+
969 which will always evaluate to 1, even though +i+ eventually
970 becomes greater than 10.  In the above case the loop will never
971 terminate.  Instead, the expression should be placed in braces:
973 ----
974     for {set i 1} {$i<=10} {incr i} {...}      ** RIGHT **
975 ----
977 This causes the substitution of 'i'
978 to be delayed; it will be re-done each time the expression is
979 evaluated, which is the desired result.
981 LISTS
982 -----
983 The third major way that strings are interpreted in Tcl is as lists.
984 A list is just a string with a list-like structure
985 consisting of fields separated by white space.  For example, the
986 string
988 ----
989     Al Sue Anne John
990 ----
992 is a list with four elements or fields.
993 Lists have the same basic structure as command strings, except
994 that a newline character in a list is treated as a field separator
995 just like space or tab.  Conventions for braces and quotes
996 and backslashes are the same for lists as for commands.  For example,
997 the string
999 ----
1000     a b\ c {d e {f g h}}
1001 ----
1003 is a list with three elements:  +a+, +b c+, and +d e {f g h}+.
1005 Whenever an element is extracted from a list, the same rules about
1006 braces and quotes and backslashes are applied as for commands.  Thus in
1007 the example above when the third element is extracted from the list,
1008 the result is
1010 ----
1011     d e {f g h}
1012 ----
1014 (when the field was extracted, all that happened was to strip off
1015 the outermost layer of braces).  Command substitution and
1016 variable substitution are never
1017 made on a list (at least, not by the list-processing commands; the
1018 list can always be passed to the Tcl interpreter for evaluation).
1020 The Tcl commands `concat`, `foreach`, `lappend`, `lindex`, `linsert`,
1021 `list`, `llength`, `lrange`, `lreplace`, `lsearch`, and `lsort` allow
1022 you to build lists, extract elements from them, search them, and perform
1023 other list-related functions.
1025 Advanced list commands include `lrepeat`, `lreverse`, `lmap`, `lassign`, `lset`.
1027 LIST EXPANSION
1028 --------------
1030 A new addition to Tcl 8.5 is the ability to expand a list into separate
1031 arguments. Support for this feature is also available in Jim.
1033 Consider the following attempt to exec a list:
1035 ----
1036     set cmd {ls -l}
1037     exec $cmd
1038 ----
1040 This will attempt to exec a command named "ls -l", which will clearly not
1041 work. Typically eval and concat are required to solve this problem, however
1042 it can be solved much more easily with +\{*\}+.
1044 ----
1045     exec {*}$cmd
1046 ----
1048 This will expand the following argument into individual elements and then evaluate
1049 the resulting command.
1051 Note that the official Tcl syntax is +\{*\}+, however +\{expand\}+ is retained
1052 for backward compatibility with experimental versions of this feature.
1054 REGULAR EXPRESSIONS
1055 -------------------
1056 Jim Tcl provides two commands that support string matching using regular
1057 expressions, `regexp` and `regsub`, as well as `switch -regexp` and
1058 `lsearch -regexp`.
1060 Regular expressions may be implemented one of two ways. Either using the system's C library
1061 POSIX regular expression support, or using the built-in regular expression engine.
1062 The differences between these are described below.
1064 *NOTE* Tcl 7.x and 8.x use perl-style Advanced Regular Expressions (+ARE+).
1066 POSIX Regular Expressions
1067 ~~~~~~~~~~~~~~~~~~~~~~~~~
1068 If the system supports POSIX regular expressions, and UTF-8 support is not enabled,
1069 this support will be used by default. The type of regular expressions supported are
1070 Extended Regular Expressions (+ERE+) rather than Basic Regular Expressions (+BRE+).
1071 See REG_EXTENDED in the documentation.
1073 Using the system-supported POSIX regular expressions will typically
1074 make for the smallest code size, but some features such as UTF-8
1075 and +{backslash}w+, +{backslash}d+, +{backslash}s+ are not supported, and null characters
1076 in strings are not supported.
1078 See regex(3) and regex(7) for full details.
1080 Jim built-in Regular Expressions
1081 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1082 The Jim built-in regular expression engine may be selected with +./configure --with-jim-regexp+
1083 or it will be selected automatically if UTF-8 support is enabled.
1085 This engine supports UTF-8 as well as some +ARE+ features. The differences with both Tcl 7.x/8.x
1086 and POSIX are highlighted below.
1088 1. UTF-8 strings and patterns are both supported
1089 2. All Tcl character classes are supported (e.g. +[:alnum:]+, +[:digit:]+, +[:space:]+), but...
1090 3. Character classes apply to ASCII characters only
1091 4. Supported shorthand character classes: +{backslash}w+ = +[:alnum:]+, +{backslash}W+ = +^[:alnum:]+, +{backslash}d+ = +[:digit:],+ +{backslash}D+ = +^[:digit:],+ +{backslash}s+ = +[:space:]+, + +{backslash}S+ = +^[:space:]+
1092 5. Supported constraint escapes: +{backslash}m+ = +{backslash}<+ = start of word, +{backslash}M+ = +{backslash}>+ = end of word, +{backslash}A+ = start of string, +{backslash}Z+ = end of string
1093 6. Backslash escapes may be used within regular expressions, such as +{backslash}n+ = newline, +{backslash}uNNNN+ = unicode
1094 7. Support for the +?+ non-greedy quantifier. e.g. +*?+
1095 8. Support for non-capturing parentheses +(?:...)+
1096 9. Jim Tcl considers that both patterns and strings end at a null character (+\x00+)
1098 STRING MATCHING
1099 ---------------
1100 A number of commands in Jim support C-shell style "glob matching", including
1101 `string match`, `switch -glob`, `array names` and others. This form of string matching
1102 works as follows:
1104 A test occurs where a +'string'+ is matched against a +'pattern'+. The match is considered
1105 successful if the contents of +'string'+ and +'pattern'+ are identical except that the
1106 following special sequences may appear in +'pattern'+:
1108 +*+;;
1109     Matches any sequence of characters in +'string'+, including a null string.
1111 +?+;;
1112     Matches any single character in +'string'+.
1114 +['chars']+;;
1115     Matches any character in the set given by +'chars'+.
1116     If a sequence of the form +'x-y'+ appears in +'chars'+,
1117     then any character between +'x'+ and +'y'+, inclusive,
1118     will match.
1120 +{backslash}x+;;
1121     Matches the single character +'x'+.  This provides a way of
1122     avoiding the special interpretation of the characters +{backslash}*?[]+
1123     in +'pattern'+.
1125 *NOTE* Jim considers that both patterns and strings end at a null character (\x00).
1127 COMMAND RESULTS
1128 ---------------
1129 Each command produces two results:  a code and a string.  The
1130 code indicates whether the command completed successfully or not,
1131 and the string gives additional information.  The valid codes are
1132 defined in jim.h, and are:
1134 +JIM_OK(0)+::
1135     This is the normal return code, and indicates that the command completed
1136     successfully.  The string gives the command's return value.
1138 +JIM_ERR(1)+::
1139     Indicates that an error occurred; the string gives a message describing
1140     the error.
1142 +JIM_RETURN(2)+::
1143     Indicates that the `return` command has been invoked, and that the
1144     current procedure (or top-level command or `source` command)
1145     should return immediately.  The
1146     string gives the return value for the procedure or command.
1148 +JIM_BREAK(3)+::
1149     Indicates that the `break` command has been invoked, so the
1150     innermost loop should abort immediately.  The string should always
1151     be empty.
1153 +JIM_CONTINUE(4)+::
1154     Indicates that the `continue` command has been invoked, so the
1155     innermost loop should go on to the next iteration.  The string
1156     should always be empty.
1158 +JIM_SIGNAL(5)+::
1159     Indicates that a signal was caught while executing a commands.
1160     The string contains the name of the signal caught.
1161     See the `signal` and `catch` commands.
1163 +JIM_EXIT(6)+::
1164     Indicates that the command called the `exit` command.
1165     The string contains the exit code.
1167 Tcl programmers do not normally need to think about return codes,
1168 since +JIM_OK+ is almost always returned.  If anything else is returned
1169 by a command, then the Tcl interpreter immediately stops processing
1170 commands and returns to its caller.  If there are several nested
1171 invocations of the Tcl interpreter in progress, then each nested
1172 command will usually return the error to its caller, until eventually
1173 the error is reported to the top-level application code.  The
1174 application will then display the error message for the user.
1176 In a few cases, some commands will handle certain `error` conditions
1177 themselves and not return them upwards.  For example, the `for`
1178 command checks for the +JIM_BREAK+ code; if it occurs, then `for`
1179 stops executing the body of the loop and returns +JIM_OK+ to its
1180 caller.  The `for` command also handles +JIM_CONTINUE+ codes and the
1181 procedure interpreter handles +JIM_RETURN+ codes.  The `catch`
1182 command allows Tcl programs to catch errors and handle them without
1183 aborting command interpretation any further.
1185 The `info returncodes` command may be used to programmatically map between
1186 return codes and names.
1188 PROCEDURES
1189 ----------
1190 Tcl allows you to extend the command interface by defining
1191 procedures.  A Tcl procedure can be invoked just like any other Tcl
1192 command (it has a name and it receives one or more arguments).
1193 The only difference is that its body isn't a piece of C code linked
1194 into the program; it is a string containing one or more other
1195 Tcl commands.
1197 The `proc` command is used to create a new Tcl command procedure:
1199 +*proc* 'name arglist ?statics? body'+
1201 The new command is named +'name'+, and it replaces any existing command
1202 there may have been by that name. Whenever the new command is
1203 invoked, the contents of +'body'+ will be executed by the Tcl
1204 interpreter.
1206 +'arglist'+ specifies the formal arguments to the procedure.
1207 It consists of a list, possibly empty, of the following
1208 argument specifiers:
1210 +name+::
1211     Required Argument - A simple argument name.
1213 +{name default}+::
1214     Optional Argument - A two-element list consisting of the
1215     argument name, followed by the default value, which will
1216     be used if the corresponding argument is not supplied.
1218 +&name+::
1219     Reference Argument - The caller is expected to pass the name of
1220     an existing variable. An implicit +`upvar` 1 origname name+ is done
1221     to make the variable available in the proc scope.
1223 +*args*+::
1224     Variable Argument - The special name +'args'+, which is
1225     assigned all remaining arguments (including none) as a list. The
1226     variable argument may only be specified once. Note that
1227     the syntax +{args newname}+ may be used to retain the special
1228     behaviour of +'args'+ with a different local name. In this case,
1229     the variable is named +'newname'+ rather than +'args'+.
1231 When the command is invoked, a local variable will be created for each of
1232 the formal arguments to the procedure; its value will be the value
1233 of corresponding argument in the invoking command or the argument's
1234 default value.
1236 Arguments with default values need not be specified in a procedure
1237 invocation.  However, there must be enough actual arguments for all
1238 required arguments, and there must not be any extra actual arguments
1239 (unless the Variable Argument is specified).
1241 Actual arguments are assigned to formal arguments as in left-to-right
1242 order with the following precedence.
1244 1. Required Arguments (including Reference Arguments)
1245 2. Optional Arguments
1246 3. Variable Argument
1248 The following example illustrates precedence. Assume a procedure declaration:
1250 ----
1251     proc p {{a A} args b {c C} d} {...}
1252 ----
1254 This procedure requires at least two arguments, but can accept an unlimited number.
1255 The following table shows how various numbers of arguments are assigned.
1256 Values marked as +-+ are assigned the default value.
1258 [width="40%",frame="topbot",options="header"]
1259 |==============
1260 |Number of arguments|a|args|b|c|d
1261 |2|-|-|1|-|2
1262 |3|1|-|2|-|3
1263 |4|1|-|2|3|4
1264 |5|1|2|3|4|5
1265 |6|1|2,3|4|5|6
1266 |==============
1268 When +'body'+ is being executed, variable names normally refer to local
1269 variables, which are created automatically when referenced and deleted
1270 when the procedure returns.  One local variable is automatically created
1271 for each of the procedure's arguments.  Global variables can be
1272 accessed by invoking the `global` command or via the +::+ prefix.
1274 New in Jim
1275 ~~~~~~~~~~
1276 In addition to procedure arguments, Jim procedures may declare static variables.
1277 These variables scoped to the procedure and initialised at procedure definition.
1278 Either from the static variable definition, or from the enclosing scope.
1280 Consider the following example:
1282 ----
1283     . set a 1
1284     . proc a {} {a {b 2}} {
1285         set c 1
1286         puts "$a $b $c"
1287         incr a
1288         incr b
1289         incr c
1290     }
1291     . a
1292     1 2 1
1293     . a
1294     2 3 1
1295 ----
1297 The static variable +'a'+ has no initialiser, so it is initialised from
1298 the enclosing scope with the value 1. (Note that it is an error if there
1299 is no variable with the same name in the enclosing scope). However +'b'+
1300 has an initialiser, so it is initialised to 2.
1302 Unlike a local variable, the value of a static variable is retained across
1303 invocations of the procedure.
1305 See the `proc` command for information on how to define procedures
1306 and what happens when they are invoked. See also <<_namespaces,NAMESPACES>>.
1308 VARIABLES - SCALARS AND ARRAYS
1309 ------------------------------
1310 Tcl allows the definition of variables and the use of their values
1311 either through '$'-style variable substitution, the `set`
1312 command, or a few other mechanisms.
1314 Variables need not be declared:  a new variable will automatically
1315 be created each time a new variable name is used.
1317 Tcl supports two types of variables:  scalars and arrays.
1318 A scalar variable has a single value, whereas an array variable
1319 can have any number of elements, each with a name (called
1320 its 'index') and a value.
1322 Array indexes may be arbitrary strings; they need not be numeric.
1323 Parentheses are used refer to array elements in Tcl commands.
1324 For example, the command
1326 ----
1327     set x(first) 44
1328 ----
1330 will modify the element of 'x' whose index is 'first'
1331 so that its new value is '44'.
1333 Two-dimensional arrays can be simulated in Tcl by using indexes
1334 that contain multiple concatenated values.
1335 For example, the commands
1337 ----
1338     set a(2,3) 1
1339     set a(3,6) 2
1340 ----
1342 set the elements of 'a' whose indexes are '2,3' and '3,6'.
1344 In general, array elements may be used anywhere in Tcl that scalar
1345 variables may be used.
1347 If an array is defined with a particular name, then there may
1348 not be a scalar variable with the same name.
1350 Similarly, if there is a scalar variable with a particular
1351 name then it is not possible to make array references to the
1352 variable.
1354 To convert a scalar variable to an array or vice versa, remove
1355 the existing variable with the `unset` command.
1357 The `array` command provides several features for dealing
1358 with arrays, such as querying the names of all the elements of
1359 the array and converting between an array and a list.
1361 Variables may be either global or local.  If a variable
1362 name is used when a procedure isn't being executed, then it
1363 automatically refers to a global variable.  Variable names used
1364 within a procedure normally refer to local variables associated with that
1365 invocation of the procedure.  Local variables are deleted whenever
1366 a procedure exits.  Either `global` command may be used to request
1367 that a name refer to a global variable for the duration of the current
1368 procedure (this is somewhat analogous to 'extern' in C), or the variable
1369 may be explicitly scoped with the +::+ prefix. For example
1371 ----
1372     . set a 1
1373     . set b 2
1374     . proc p {} {
1375         set c 3
1376         global a
1378         puts "$a $::b $c"
1379     }
1380     . p
1381 ----
1383 will output:
1385     1 2 3
1387 ARRAYS AS LISTS IN JIM
1388 ----------------------
1389 Unlike Tcl, Jim can automatically convert between a list (with an even
1390 number of elements) and an array value. This is similar to the way Tcl
1391 can convert between a string and a list.
1393 For example:
1395 ----
1396   set a {1 one 2 two}
1397   puts $a(2)
1398 ----
1400 will output:
1402 ----
1403   two
1404 ----
1406 Thus `array set` is equivalent to `set` when the variable does not
1407 exist or is empty.
1409 The reverse is also true where an array will be converted into
1410 a list.
1412 ----
1413   set a(1) one; set a(2) two
1414   puts $a
1415 ----
1417 will output:
1419 ----
1420   1 one 2 two
1421 ----
1423 DICTIONARY VALUES
1424 -----------------
1425 Tcl 8.5 introduced the dict command, and Jim Tcl has added a version
1426 of this command. Dictionaries provide efficient access to key-value
1427 pairs, just like arrays, but dictionaries are pure values. This
1428 means that you can pass them to a procedure just as a list or a
1429 string. Tcl dictionaries are therefore much more like Tcl lists,
1430 except that they represent a mapping from keys to values, rather
1431 than an ordered sequence.
1433 You can nest dictionaries, so that the value for a particular key
1434 consists of another dictionary. That way you can elegantly build
1435 complicated data structures, such as hierarchical databases. You
1436 can also combine dictionaries with other Tcl data structures. For
1437 instance, you can build a list of dictionaries that themselves
1438 contain lists.
1440 Dictionaries are values that contain an efficient, order-preserving
1441 mapping from arbitrary keys to arbitrary values. Each key in the
1442 dictionary maps to a single value. They have a textual format that
1443 is exactly that of any list with an even number of elements, with
1444 each mapping in the dictionary being represented as two items in
1445 the list. When a command takes a dictionary and produces a new
1446 dictionary based on it (either returning it or writing it back into
1447 the variable that the starting dictionary was read from) the new
1448 dictionary will have the same order of keys, modulo any deleted
1449 keys and with new keys added on to the end. When a string is
1450 interpreted as a dictionary and it would otherwise have duplicate
1451 keys, only the last value for a particular key is used; the others
1452 are ignored, meaning that, "apple banana" and "apple carrot apple
1453 banana" are equivalent dictionaries (with different string
1454 representations).
1456 Note that in Jim, arrays are implemented as dictionaries.
1457 Thus automatic conversion between lists and dictionaries applies
1458 as it does for arrays.
1460 ----
1461   . dict set a 1 one
1462   1 one
1463   . dict set a 2 two
1464   1 one 2 two
1465   . puts $a
1466   1 one 2 two
1467   . puts $a(2)
1468   two
1469   . dict set a 3 T three
1470   1 one 2 two 3 {T three}
1471 ----
1473 See the `dict` command for more details.
1475 NAMESPACES
1476 ----------
1477 Tcl added namespaces as a mechanism avoiding name clashes, especially in applications
1478 including a number of 3rd party components. While there is less need for namespaces
1479 in Jim Tcl (which does not strive to support large applications), it is convenient to
1480 provide a subset of the support for namespaces to easy porting code from Tcl.
1482 Jim Tcl currently supports "light-weight" namespaces which should be adequate for most
1483 purposes. This feature is currently experimental. See README.namespaces for more information
1484 and the documentation of the `namespace` command.
1486 GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION
1487 -----------------------------------------------
1488 Unlike Tcl, Jim has some sophisticated support for functional programming.
1489 These are described briefly below.
1491 More information may be found at http://wiki.tcl.tk/13847
1493 References
1494 ~~~~~~~~~~
1495 A reference can be thought of as holding a value with one level of indirection,
1496 where the value may be garbage collected when unreferenced.
1497 Consider the following example:
1499 ----
1500     . set r [ref "One String" test]
1501     <reference.<test___>.00000000000000000000>
1502     . getref $r
1503     One String
1504 ----
1506 The operation `ref` creates a references to the value specified by the
1507 first argument. (The second argument is a "type" used for documentation purposes).
1509 The operation `getref` is the dereferencing operation which retrieves the value
1510 stored in the reference.
1512 ----
1513     . setref $r "New String"
1514     New String
1515     . getref $r
1516     New String
1517 ----
1519 The operation `setref` replaces the value stored by the reference. If the old value
1520 is no longer accessible by any reference, it will eventually be automatically be garbage
1521 collected.
1523 Garbage Collection
1524 ~~~~~~~~~~~~~~~~~~
1525 Normally, all values in Tcl are passed by value. As such values are copied and released
1526 automatically as necessary.
1528 With the introduction of references, it is possible to create values whose lifetime
1529 transcend their scope. To support this, case, the Jim system will periodically identify
1530 and discard objects which are no longer accessible by any reference.
1532 The `collect` command may be used to force garbage collection.  Consider a reference created
1533 with a finalizer:
1535 ----
1536     . proc f {ref value} { puts "Finaliser called for $ref,$value" }
1537     . set r [ref "One String" test f]
1538     <reference.<test___>.00000000000
1539     . collect
1540     0
1541     . set r ""
1542     . collect
1543     Finaliser called for <reference.<test___>.00000000000,One String
1544     1
1545 ----
1547 Note that once the reference, 'r', was modified so that it no longer
1548 contained a reference to the value, the garbage collector discarded
1549 the value (after calling the finalizer).
1551 The finalizer for a reference may be examined or changed with the `finalize` command
1553 ----
1554     . finalize $r
1555     f
1556     . finalize $r newf
1557     newf
1558 ----
1560 Lambda Function
1561 ~~~~~~~~~~~~~~~
1562 Jim provides a garbage collected `lambda` function. This is a procedure
1563 which is able to create an anonymous procedure.  Consider:
1565 ----
1566     . set f [lambda {a} {{x 0}} { incr x $a }]
1567     . $f 1
1568     1
1569     . $f 2
1570     3
1571     . set f ""
1572 ----
1574 This create an anonymous procedure (with the name stored in 'f'), with a static variable
1575 which is incremented by the supplied value and the result returned.
1577 Once the procedure name is no longer accessible, it will automatically be deleted
1578 when the garbage collector runs.
1580 The procedure may also be delete immediately by renaming it "". e.g.
1582 ----
1583     . rename $f ""
1584 ----
1586 UTF-8 AND UNICODE
1587 -----------------
1588 If Jim is built with UTF-8 support enabled (configure --enable-utf),
1589 then most string-related commands become UTF-8 aware.  These include,
1590 but are not limited to, `string match`, `split`, `glob`, `scan` and
1591 `format`.
1593 UTF-8 encoding has many advantages, but one of the complications is that
1594 characters can take a variable number of bytes. Thus the addition of
1595 `string bytelength` which returns the number of bytes in a string,
1596 while `string length` returns the number of characters.
1598 If UTF-8 support is not enabled, all commands treat bytes as characters
1599 and `string bytelength` returns the same value as `string length`.
1601 Note that even if UTF-8 support is not enabled, the +{backslash}uNNNN+ and related syntax
1602 is still available to embed UTF-8 sequences.
1604 Jim Tcl supports all currently defined unicode codepoints. That is 21 bits, up to +'U+1FFFFF'.
1606 String Matching
1607 ~~~~~~~~~~~~~~~
1608 Commands such as `string match`, `lsearch -glob`, `array names` and others use
1609 <<_string_matching,STRING MATCHING>> rules. These commands support UTF-8. For example:
1611 ----
1612   string match a\[\ua0-\ubf\]b "a\u00a3b"
1613 ----
1615 format and scan
1616 ~~~~~~~~~~~~~~~
1617 +format %c+ allows a unicode codepoint to be be encoded. For example, the following will return
1618 a string with two bytes and one character. The same as +{backslash}ub5+
1620 ----
1621   format %c 0xb5
1622 ----
1624 `format` respects widths as character widths, not byte widths. For example, the following will
1625 return a string with three characters, not three bytes.
1627 ----
1628   format %.3s \ub5\ub6\ub7\ub8
1629 ----
1631 Similarly, +scan ... %c+ allows a UTF-8 to be decoded to a unicode codepoint. The following will set
1632 +'a'+ to 181 (0xb5) and +'b'+ to 65 (0x41).
1634 ----
1635   scan \u00b5A %c%c a b
1636 ----
1638 `scan %s` will also accept a character class, including unicode ranges.
1640 String Classes
1641 ~~~~~~~~~~~~~~
1642 `string is` has *not* been extended to classify UTF-8 characters. Therefore, the following
1643 will return 0, even though the string may be considered to be alphabetic.
1645 ----
1646   string is alpha \ub5Test
1647 ----
1649 This does not affect the string classes 'ascii', 'control', 'digit', 'double', 'integer' or 'xdigit'.
1651 Case Mapping and Conversion
1652 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1653 Jim provides a simplified unicode case mapping. This means that case conversion
1654 and comparison will not increase or decrease the number of characters in a string.
1655 (Although it may change the number of bytes).
1657 `string toupper` will convert any lowercase letters to their uppercase equivalent.
1658 Any character which is not a letter or has no uppercase equivalent is left unchanged.
1659 Similarly for `string tolower` and `string totitle`.
1661 Commands which perform case insensitive matches, such as `string compare -nocase`
1662 and `lsearch -nocase` fold both strings to uppercase before comparison.
1664 Invalid UTF-8 Sequences
1665 ~~~~~~~~~~~~~~~~~~~~~~~
1666 Some UTF-8 character sequences are invalid, such as those beginning with '0xff',
1667 those which represent character sequences longer than 3 bytes (greater than U+FFFF),
1668 and those which end prematurely, such as a lone '0xc2'.
1670 In these situations, the offending bytes are treated as single characters. For example,
1671 the following returns 2.
1673 ----
1674   string bytelength \xff\xff
1675 ----
1677 Regular Expressions
1678 ~~~~~~~~~~~~~~~~~~~
1679 If UTF-8 support is enabled, the built-in regular expression engine will be
1680 selected which supports UTF-8 strings and patterns.
1682 See <<_regular_expressions,REGULAR EXPRESSIONS>>
1684 BUILT-IN COMMANDS
1685 -----------------
1686 The Tcl library provides the following built-in commands, which will
1687 be available in any application using Tcl.  In addition to these
1688 built-in commands, there may be additional commands defined by each
1689 application, plus commands defined as Tcl procedures.
1691 In the command syntax descriptions below, words in +*boldface*+ are
1692 literals that you type verbatim to Tcl.
1694 Words in +'italics'+ are meta-symbols; they serve as names for any of
1695 a range of values that you can type.
1697 Optional arguments or groups of arguments are indicated by enclosing them
1698 in +?question-marks?+.
1700 Ellipses (+\...+) indicate that any number of additional
1701 arguments or groups of arguments may appear, in the same format
1702 as the preceding argument(s).
1704 [[CommandIndex]]
1705 Command Index
1706 ~~~~~~~~~~~~~
1707 @INSERTINDEX@
1709 alarm
1710 ~~~~~
1711 +*alarm* 'seconds'+
1713 Delivers the +SIGALRM+ signal to the process after the given
1714 number of seconds. If the platform supports 'ualarm(3)' then
1715 the argument may be a floating point value. Otherwise it must
1716 be an integer.
1718 Note that unless a signal handler for +SIGALRM+ has been installed
1719 (see `signal`), the process will exit on this signal.
1721 alias
1722 ~~~~~
1723 +*alias* 'name args\...'+
1725 Creates a single word alias (command) for one or more words. For example,
1726 the following creates an alias for the command `info exists`.
1728 ----
1729     alias e info exists
1730     if {[e var]} {
1731       ...
1732     }
1733 ----
1735 `alias` returns +'name'+, allowing it to be used with `local`.
1737 See also `proc`, `curry`, `lambda`, `local`, `info alias`, `exists -alias`
1739 append
1740 ~~~~~~
1741 +*append* 'varName value ?value value ...?'+
1743 Append all of the +'value'+ arguments to the current value
1744 of variable +'varName'+.  If +'varName'+ doesn't exist,
1745 it is given a value equal to the concatenation of all the
1746 +'value'+ arguments.
1748 This command provides an efficient way to build up long
1749 variables incrementally.
1750 For example, "`append a $b`" is much more efficient than
1751 "`set a $a$b`" if +$a+ is long.
1753 apply
1754 ~~~~~~
1755 +*apply* 'lambdaExpr ?arg1 arg2 \...?'+
1757 The command `apply` provides for anonymous procedure calls,
1758 similar to `lambda`, but without a command name being created, even temporarily.
1760 The function  +'lambdaExpr'+ is a two element list, +{args body}+
1761 or a three element list, +{args body namespace}+. The first element
1762 +'args'+ specifies the formal arguments in the same form as the `proc` and `lambda` commands.
1764 array
1765 ~~~~~
1766 +*array* 'option arrayName ?arg\...?'+
1768 This command performs one of several operations on the
1769 variable given by +'arrayName'+.
1771 Note that in general, if the named array does not exist, the +'array'+ command behaves
1772 as though the array exists but is empty.
1774 The +'option'+ argument determines what action is carried out by the
1775 command.  The legal +'options'+ (which may be abbreviated) are:
1777 +*array exists* 'arrayName'+::
1778     Returns 1 if +'arrayName'+ is an array variable, 0 if there is
1779     no variable by that name.
1781 +*array get* 'arrayName ?pattern?'+::
1782     Returns a list containing pairs of elements. The first
1783     element in each pair is the name of an element in +'arrayName'+
1784     and the second element of each pair is the value of the
1785     array element. The order of the pairs is undefined. If
1786     +'pattern'+ is not specified, then all of the elements of the
1787     array are included in the result. If +'pattern'+ is specified,
1788     then only those elements whose names match +'pattern'+ (using
1789     <<_string_matching,STRING MATCHING>> rules) are included. If +'arrayName'+
1790     isn't the name of an array variable, or if the array contains
1791     no elements, then an empty list is returned.
1793 +*array names* 'arrayName ?pattern?'+::
1794     Returns a list containing the names of all of the elements
1795     in the array that match +'pattern'+. If +'pattern'+ is omitted then
1796     the command returns all of the element names in the array.
1797     If +'pattern'+ is specified, then only those elements whose
1798     names match +'pattern'+ (using <<_string_matching,STRING MATCHING>> rules)
1799     are included. If there are no (matching) elements
1800     in the array, or if +'arrayName'+ isn't the name of an array
1801     variable, then an empty string is returned.
1803 +*array set* 'arrayName list'+::
1804     Sets the values of one or more elements in +'arrayName'+. +'list'+
1805     must have a form like that returned by array get, consisting
1806     of an even number of elements. Each odd-numbered element
1807     in list is treated as an element name within arrayName, and
1808     the following element in list is used as a new value for
1809     that array element. If the variable +'arrayName'+ does not
1810     already exist and list is empty, +'arrayName'+ is created with
1811     an empty array value.
1813 +*array size* 'arrayName'+::
1814     Returns the number of elements in the array. If +'arrayName'+
1815     isn't the name of an array then 0 is returned.
1817 +*array unset* 'arrayName ?pattern?'+::
1818     Unsets all of the elements in the array that match +'pattern'+
1819     (using <<_string_matching,STRING MATCHING>> rules). If +'arrayName'+
1820     isn't the name of an array variable or there are no matching
1821     elements in the array, no error will be raised. If +'pattern'+
1822     is omitted and +'arrayName'+ is an array variable, then the
1823     command unsets the entire array. The command always returns
1824     an empty string.
1826 break
1827 ~~~~~
1828 +*break*+
1830 This command may be invoked only inside the body of a loop command
1831 such as `for` or `foreach` or `while`.  It returns a +JIM_BREAK+ code
1832 to signal the innermost containing loop command to return immediately.
1834 case
1835 ~~~~
1836 The obsolete '+*case*+' command has been removed from Jim Tcl since v0.75.
1837 Use `switch` instead.
1839 catch
1840 ~~~~~
1841 +*catch* ?-?no?'code \...'? ?--? 'command ?resultVarName? ?optionsVarName?'+
1843 The `catch` command may be used to prevent errors from aborting
1844 command interpretation.  `catch` evaluates +'command'+, and returns a
1845 +JIM_OK+ code, regardless of any errors that might occur while
1846 executing +'command'+ (with the possible exception of +JIM_SIGNAL+ -
1847 see below).
1849 The return value from `catch` is a decimal string giving the code
1850 returned by the Tcl interpreter after executing +'command'+.  This
1851 will be '0' (+JIM_OK+) if there were no errors in +'command'+; otherwise
1852 it will have a non-zero value corresponding to one of the exceptional
1853 return codes (see jim.h for the definitions of code values, or the
1854 `info returncodes` command).
1856 If the +'resultVarName'+ argument is given, then it gives the name
1857 of a variable; `catch` will set the value of the variable to the
1858 string returned from +'command'+ (either a result or an error message).
1860 If the +'optionsVarName'+ argument is given, then it gives the name
1861 of a variable; `catch` will set the value of the variable to a
1862 dictionary. For any return code other than +JIM_RETURN+, the value
1863 for the key +-code+ will be set to the return code. For +JIM_RETURN+
1864 it will be set to the code given in `return -code`. Additionally,
1865 for the return code +JIM_ERR+, the value of the key +-errorinfo+
1866 will contain the current stack trace (the same result as `info stacktrace`),
1867 the value of the key +-errorcode+ will contain the
1868 same value as the global variable $::errorCode, and the value of
1869 the key +-level+ will be the current return level (see `return -level`).
1870 This can be useful to rethrow an error:
1872 ----
1873     if {[catch {...} msg opts]} {
1874         ...maybe do something with the error...
1875         incr opts(-level)
1876         return {*}$opts $msg
1877     }
1878 ----
1880 Normally `catch` will +'not'+ catch any of the codes +JIM_EXIT+, +JIM_EVAL+ or +JIM_SIGNAL+.
1881 The set of codes which will be caught may be modified by specifying the one more codes before
1882 +'command'+.
1884 e.g. To catch +JIM_EXIT+ but not +JIM_BREAK+ or +JIM_CONTINUE+
1886 ----
1887     catch -exit -nobreak -nocontinue -- { ... }
1888 ----
1890 The use of +--+ is optional. It signifies that no more return code options follow.
1892 Note that if a signal marked as `signal handle` is caught with `catch -signal`, the return value
1893 (stored in +'resultVarName'+) is name of the signal caught.
1897 +*cd* 'dirName'+
1899 Change the current working directory to +'dirName'+.
1901 Returns an empty string.
1903 This command can potentially be disruptive to an application, so it may
1904 be removed in some applications.
1906 clock
1907 ~~~~~
1908 +*clock seconds*+::
1909     Returns the current time as seconds since the epoch.
1911 +*clock clicks*+::
1912     Returns the current time in "clicks", a system-dependent, high-resolution time.
1914 +*clock microseconds*+::
1915     Returns the current time in microseconds.
1917 +*clock milliseconds*+::
1918     Returns the current time in milliseconds.
1920 +*clock format* 'seconds' ?*-format* 'format?' ?*-gmt* 'boolean?'+::
1921     Format the given time (seconds since the epoch) according to the given
1922     format. See strftime(3) for supported formats.
1923     If no format is supplied, "%c" is used.
1924   ::
1925     If +'boolean'+ is true, processing is performed in UTC.
1926     If +'boolean'+ is false (the default), processing  is performed in the local time zone.
1928 +*clock scan* 'str' *-format* 'format' ?*-gmt* 'boolean?'+::
1929     Scan the given time string using the given format string.
1930     See strptime(3) for supported formats.
1931     See `clock format` for the handling of '-gmt'.
1933 *NOTE* Some systems such as 32-bit Linux have only a 32-bit time_t, and are therefore not year 2038
1934 compliant.
1936 close
1937 ~~~~~
1938 +*close* 'fileId'+
1940 +'fileId' *close*+
1942 Closes the file given by +'fileId'+.
1943 +'fileId'+ must be the return value from a previous invocation
1944 of the `open` command; after this command, it should not be
1945 used anymore.
1947 collect
1948 ~~~~~~~
1949 +*collect*+
1951 Normally reference garbage collection is automatically performed periodically.
1952 However it may be run immediately with the `collect` command.
1954 See <<_garbage_collection_references_lambda_function,GARBAGE COLLECTION>> for more detail.
1956 concat
1957 ~~~~~~
1958 +*concat* 'arg ?arg \...?'+
1960 This command treats each argument as a list and concatenates them
1961 into a single list.  It permits any number of arguments.  For example,
1962 the command
1964 ----
1965     concat a b {c d e} {f {g h}}
1966 ----
1968 will return
1970 ----
1971     a b c d e f {g h}
1972 ----
1974 as its result.
1976 continue
1977 ~~~~~~~~
1978 +*continue*+
1980 This command may be invoked only inside the body of a loop command such
1981 as `for` or `foreach` or `while`.  It returns a  +JIM_CONTINUE+ code to
1982 signal the innermost containing loop command to skip the remainder of
1983 the loop's body but continue with the next iteration of the loop.
1985 curry
1986 ~~~~~
1987 +*alias* 'args\...'+
1989 Similar to `alias` except it creates an anonymous procedure (lambda) instead of
1990 a named procedure.
1992 the following creates a local, unnamed alias for the command `info exists`.
1994 ----
1995     set e [local curry info exists]
1996     if {[$e var]} {
1997       ...
1998     }
1999 ----
2001 `curry` returns the name of the procedure.
2003 See also `proc`, `alias`, `lambda`, `local`.
2005 dict
2006 ~~~~
2007 +*dict* 'option ?arg\...?'+
2009 Performs one of several operations on dictionary values.
2011 The +'option'+ argument determines what action is carried out by the
2012 command.  The legal +'options'+ are:
2014 +*dict create* '?key value \...?'+::
2015     Create and return a new dictionary value that contains each of
2016     the key/value mappings listed as  arguments (keys and values
2017     alternating, with each key being followed by its associated
2018     value.)
2020 +*dict exists* 'dictionary key ?key \...?'+::
2021     Returns a boolean value indicating whether the given key (or path
2022     of keys through a set of nested dictionaries) exists in the given
2023     dictionary value.  This returns a true value exactly when `dict get`
2024     on that path will succeed.
2026 +*dict get* 'dictionary ?key \...?'+::
2027     Given a dictionary value (first argument) and a key (second argument),
2028     this will retrieve the value for that key. Where several keys are
2029     supplied, the behaviour of the command shall be as if the result
2030     of "`dict get $dictVal $key`" was passed as the first argument to
2031     dict get with the remaining arguments as second (and possibly
2032     subsequent) arguments. This facilitates lookups in nested dictionaries.
2033     If no keys are provided, dict would return a list containing pairs
2034     of elements in a manner similar to array get. That is, the first
2035     element of each pair would be the key and the second element would
2036     be the value for that key.  It is an error to attempt to retrieve
2037     a value for a key that is not present in the dictionary.
2039 +*dict keys* 'dictionary ?pattern?'+::
2040     Returns a list of the keys in the dictionary.
2041     If +'pattern'+ is specified, then only those keys whose
2042     names match +'pattern'+ (using <<_string_matching,STRING MATCHING>> rules)
2043     are included.
2045 +*dict merge* ?'dictionary \...'?+::
2046     Return a dictionary that contains the contents of each of the
2047     +'dictionary'+ arguments. Where two (or more) dictionaries
2048     contain a mapping for the same key, the resulting dictionary
2049     maps that key to the value according to the last dictionary on
2050     the command line containing a mapping for that key.
2052 +*dict set* 'dictionaryName key ?key \...? value'+::
2053     This operation takes the +'name'+ of a variable containing a dictionary
2054     value and places an updated dictionary value in that variable
2055     containing a mapping from the given key to the given value. When
2056     multiple keys are present, this operation creates or updates a chain
2057     of nested dictionaries.
2059 +*dict size* 'dictionary'+::
2060     Return the number of key/value mappings in the given dictionary value.
2062 +*dict unset* 'dictionaryName key ?key \...? value'+::
2063     This operation (the companion to `dict set`) takes the name of a
2064     variable containing a dictionary value and places an updated
2065     dictionary value in that variable that does not contain a mapping
2066     for the given key. Where multiple keys are present, this describes
2067     a path through nested dictionaries to the mapping to remove. At
2068     least one key must be specified, but the last key on the key-path
2069     need not exist. All other components on the path must exist.
2071 +*dict with* 'dictionaryName key ?key \...? script'+::
2072     Execute the Tcl script in +'script'+ with the value for each
2073     key in +'dictionaryName'+ mapped to a variable with the same
2074     name. Where one or more keys are given, these indicate a chain
2075     of nested dictionaries, with the innermost dictionary being the
2076     one opened out for the execution of body. Making +'dictionaryName'+
2077     unreadable will make the updates to the dictionary be discarded,
2078     and this also happens if the contents of +'dictionaryName'+ are
2079     adjusted so that the chain of dictionaries no longer exists.
2080     The result of `dict with` is (unless some kind of error occurs)
2081     the result of the evaluation of body.
2082  ::
2083     The variables are mapped in the scope enclosing the `dict with`;
2084     it is recommended that this command only be used in a local
2085     scope (procedure). Because of this, the variables set by
2086     `dict with` will continue to exist after the command finishes (unless
2087     explicitly unset). Note that changes to the contents of +'dictionaryName'+
2088     only happen when +'script'+ terminates.
2090 +*dict for, values, incr, append, lappend, update, info, replace*+ to be documented...
2094 +*env* '?name? ?default?'+
2096 If +'name'+ is supplied, returns the value of +'name'+ from the initial
2097 environment (see getenv(3)). An error is returned if +'name'+ does not
2098 exist in the environment, unless +'default'+ is supplied - in which case
2099 that value is returned instead.
2101 If no arguments are supplied, returns a list of all environment variables
2102 and their values as +{name value \...}+
2104 See also the global variable +::env+
2108 +*eof* 'fileId'+
2110 +'fileId' *eof*+
2112 Returns 1 if an end-of-file condition has occurred on +'fileId'+,
2113 0 otherwise.
2115 +'fileId'+ must have been the return value from a previous call to `open`,
2116 or it may be +stdin+, +stdout+, or +stderr+ to refer to one of the
2117 standard I/O channels.
2119 error
2120 ~~~~~
2121 +*error* 'message ?stacktrace?'+
2123 Returns a +JIM_ERR+ code, which causes command interpretation to be
2124 unwound.  +'message'+ is a string that is returned to the application
2125 to indicate what went wrong.
2127 If the +'stacktrace'+ argument is provided and is non-empty,
2128 it is used to initialize the stacktrace.
2130 This feature is most useful in conjunction with the `catch` command:
2131 if a caught error cannot be handled successfully, +'stacktrace'+ can be used
2132 to return a stack trace reflecting the original point of occurrence
2133 of the error:
2135 ----
2136     catch {...} errMsg
2137     ...
2138     error $errMsg [info stacktrace]
2139 ----
2141 See also `errorInfo`, `info stacktrace`, `catch` and `return`
2143 errorInfo
2144 ~~~~~~~~~
2145 +*errorInfo* 'error ?stacktrace?'+
2147 Returns a human-readable representation of the given error message and stack trace.
2148 Typical usage is:
2150 ----
2151     if {[catch {...} error]} {
2152         puts stderr [errorInfo $error [info stacktrace]]
2153         exit 1
2154     }
2155 ----
2157 See also `error`.
2159 eval
2160 ~~~~
2161 +*eval* 'arg ?arg\...?'+
2163 `eval` takes one or more arguments, which together comprise a Tcl
2164 command (or collection of Tcl commands separated by newlines in the
2165 usual way).  `eval` concatenates all its arguments in the same
2166 fashion as the `concat` command, passes the concatenated string to the
2167 Tcl interpreter recursively, and returns the result of that
2168 evaluation (or any error generated by it).
2170 exec
2171 ~~~~
2172 +*exec* 'arg ?arg\...?'+
2174 This command treats its arguments as the specification
2175 of one or more UNIX commands to execute as subprocesses.
2176 The commands take the form of a standard shell pipeline;
2177 +|+ arguments separate commands in the
2178 pipeline and cause standard output of the preceding command
2179 to be piped into standard input of the next command (or +|&+ for
2180 both standard output and standard error).
2182 Under normal conditions the result of the `exec` command
2183 consists of the standard output produced by the last command
2184 in the pipeline followed by the standard error output.
2186 If any of the commands writes to its standard error file,
2187 then this will be included in the result after the standard output
2188 of the last command.
2190 Note that unlike Tcl, data written to standard error does not cause
2191 `exec` to return an error.
2193 If any of the commands in the pipeline exit abnormally or
2194 are killed or suspended, then `exec` will return an error.
2195 If no standard error output was produced, or is redirected,
2196 the error message will include the normal result, as above,
2197 followed by error messages describing the abnormal terminations.
2199 If any standard error output was produced, these abnormal termination
2200 messages are suppressed.
2202 If the last character of the result or error message
2203 is a newline then that character is deleted from the result
2204 or error message for consistency with normal
2205 Tcl return values.
2207 An +'arg'+ may have one of the following special forms:
2209 +>filename+::
2210     The standard output of the last command in the pipeline
2211     is redirected to the file.  In this situation `exec`
2212     will normally return an empty string.
2214 +>>filename+::
2215     As above, but append to the file.
2217 +>@fileId+::
2218     The standard output of the last command in the pipeline is
2219     redirected to the given (writable) file descriptor (e.g. stdout,
2220     stderr, or the result of `open`). In this situation `exec`
2221     will normally return an empty string.
2223 +2>filename+::
2224     The standard error of the last command in the pipeline
2225     is redirected to the file.
2227 +2>>filename+::
2228     As above, but append to the file.
2230 +2>@fileId+::
2231     The standard error of the last command in the pipeline is
2232     redirected to the given (writable) file descriptor.
2234 +2>@1+::
2235     The standard error of the last command in the pipeline is
2236     redirected to the same file descriptor as the standard output.
2238 +>&filename+::
2239     Both the standard output and standard error of the last command
2240     in the pipeline is redirected to the file.
2242 +>>&filename+::
2243     As above, but append to the file.
2245 +<filename+::
2246     The standard input of the first command in the pipeline
2247     is taken from the file.
2249 +<<string+::
2250     The standard input of the first command is taken as the
2251     given immediate value.
2253 +<@fileId+::
2254     The standard input of the first command in the pipeline
2255     is taken from the given (readable) file descriptor.
2257 If there is no redirection of standard input, standard error
2258 or standard output, these are connected to the corresponding
2259 input or output of the application.
2261 If the last +'arg'+ is +&+ then the command will be
2262 executed in background.
2263 In this case the standard output from the last command
2264 in the pipeline will
2265 go to the application's standard output unless
2266 redirected in the command, and error output from all
2267 the commands in the pipeline will go to the application's
2268 standard error file. The return value of exec in this case
2269 is a list of process ids (pids) in the pipeline.
2271 Each +'arg'+ becomes one word for a command, except for
2272 +|+, +<+, +<<+, +>+, and +&+ arguments, and the
2273 arguments that follow +<+, +<<+, and +>+.
2275 The first word in each command is taken as the command name;
2276 the directories in the PATH environment variable are searched for
2277 an executable by the given name.
2279 No `glob` expansion or other shell-like substitutions
2280 are performed on the arguments to commands.
2282 If the command fails, the global $::errorCode (and the -errorcode
2283 option in `catch`) will be set to a list, as follows:
2285 +*CHILDKILLED* 'pid sigName msg'+::
2286         This format is used when a child process has been killed
2287         because of a signal. The pid element will be the process's
2288         identifier (in decimal). The sigName element will be the
2289         symbolic name of the signal that caused the process to
2290         terminate; it will be one of the names from the include
2291         file signal.h, such as SIGPIPE. The msg element will be a
2292         short human-readable message describing the signal, such
2293         as "write on pipe with no readers" for SIGPIPE.
2295 +*CHILDSUSP* 'pid sigName msg'+::
2296         This format is used when a child process has been suspended
2297         because of a signal. The pid element will be the process's
2298         identifier, in decimal. The sigName element will be the
2299         symbolic name of the signal that caused the process to
2300         suspend; this will be one of the names from the include
2301         file signal.h, such as SIGTTIN. The msg element will be a
2302         short human-readable message describing the signal, such
2303         as "background tty read" for SIGTTIN.
2305 +*CHILDSTATUS* 'pid code'+::
2306         This format is used when a child process has exited with a
2307         non-zero exit status. The pid element will be the process's
2308         identifier (in decimal) and the code element will be the
2309         exit code returned by the process (also in decimal).
2311 The environment for the executed command is set from $::env (unless
2312 this variable is unset, in which case the original environment is used).
2314 exists
2315 ~~~~~~
2316 +*exists ?-var|-proc|-command|-alias?* 'name'+
2318 Checks the existence of the given variable, procedure, command
2319 or alias respectively and returns 1 if it exists or 0 if not.  This command
2320 provides a more simplified/convenient version of `info exists`,
2321 `info procs` and `info commands`.
2323 If the type is omitted, a type of '-var' is used. The type may be abbreviated.
2325 exit
2326 ~~~~
2327 +*exit* '?returnCode?'+
2329 Terminate the process, returning +'returnCode'+ to the
2330 parent as the exit status.
2332 If +'returnCode'+ isn't specified then it defaults
2333 to 0.
2335 Note that exit can be caught with `catch`.
2337 expr
2338 ~~~~
2339 +*expr* 'arg'+
2341 Calls the expression processor to evaluate +'arg'+, and returns
2342 the result as a string.  See the section <<_expressions,EXPRESSIONS>> above.
2344 Note that Jim supports a shorthand syntax for `expr` as +$(\...)+
2345 The following two are identical.
2347 ----
2348   set x [expr {3 * 2 + 1}]
2349   set x $(3 * 2 + 1)
2350 ----
2352 file
2353 ~~~~
2354 +*file* 'option name ?arg\...?'+
2356 Operate on a file or a file name.  +'name'+ is the name of a file.
2358 +'option'+ indicates what to do with the file name.  Any unique
2359 abbreviation for +'option'+ is acceptable.  The valid options are:
2361 +*file atime* 'name'+::
2362     Return a decimal string giving the time at which file +'name'+
2363     was last accessed.  The time is measured in the standard UNIX
2364     fashion as seconds from a fixed starting time (often January 1, 1970).
2365     If the file doesn't exist or its access time cannot be queried then an
2366     error is generated.
2368 +*file copy ?-force?* 'source target'+::
2369     Copies file +'source'+ to file +'target'+. The source file must exist.
2370     The target file must not exist, unless +-force+ is specified.
2372 +*file delete ?-force? ?--?* 'name\...'+::
2373     Deletes file or directory +'name'+. If the file or directory doesn't exist, nothing happens.
2374     If it can't be deleted, an error is generated. Non-empty directories will not be deleted
2375     unless the +-force+ options is given. In this case no errors will be generated, even
2376     if the file/directory can't be deleted. Use +'--'+ if there is any possibility of
2377     the first name being +'-force'+.
2379 +*file dirname* 'name'+::
2380     Return all of the characters in +'name'+ up to but not including
2381     the last slash character.  If there are no slashes in +'name'+
2382     then return +.+ (a single dot).  If the last slash in +'name'+ is its first
2383     character, then return +/+.
2385 +*file executable* 'name'+::
2386     Return '1' if file +'name'+ is executable by
2387     the current user, '0' otherwise.
2389 +*file exists* 'name'+::
2390     Return '1' if file +'name'+ exists and the current user has
2391     search privileges for the directories leading to it, '0' otherwise.
2393 +*file extension* 'name'+::
2394     Return all of the characters in +'name'+ after and including the
2395     last dot in +'name'+.  If there is no dot in +'name'+ then return
2396     the empty string.
2398 +*file isdirectory* 'name'+::
2399     Return '1' if file +'name'+ is a directory,
2400     '0' otherwise.
2402 +*file isfile* 'name'+::
2403     Return '1' if file +'name'+ is a regular file,
2404     '0' otherwise.
2406 +*file join* 'arg\...'+::
2407     Joins multiple path components. Note that if any components is
2408     an absolute path, the preceding components are ignored.
2409     Thus +"`file` join /tmp /root"+ returns +"/root"+.
2411 +*file link* ?*-hard|-symbolic*? 'newname target'+::
2412     Creates a hard link (default) or symbolic link from +'newname'+ to +'target'+.
2413     Note that the sense of this command is the opposite of `file rename` and `file copy`
2414     and also of `ln`, but this is compatible with Tcl.
2415     An error is returned if +'target'+ doesn't exist or +'newname'+ already exists.
2417 +*file lstat* 'name varName'+::
2418     Same as 'stat' option (see below) except uses the +'lstat'+
2419     kernel call instead of +'stat'+.  This means that if +'name'+
2420     refers to a symbolic link the information returned in +'varName'+
2421     is for the link rather than the file it refers to.  On systems that
2422     don't support symbolic links this option behaves exactly the same
2423     as the 'stat' option.
2425 +*file mkdir* 'dir1 ?dir2\...?'+::
2426     Creates each directory specified. For each pathname +'dir'+ specified,
2427     this command will create all non-existing parent directories
2428     as well as +'dir'+ itself. If an existing directory is specified,
2429     then no action is taken and no error is returned. Trying to
2430     overwrite an existing file with a directory will result in an
2431     error.  Arguments are processed in the order specified, halting
2432     at the first error, if any.
2434 +*file mtime* 'name ?time?'+::
2435     Return a decimal string giving the time at which file +'name'+
2436     was last modified.  The time is measured in the standard UNIX
2437     fashion as seconds from a fixed starting time (often January 1, 1970).
2438     If the file doesn't exist or its modified time cannot be queried then an
2439     error is generated. If +'time'+ is given, sets the modification time
2440     of the file to the given value.
2442 +*file mtimeus* 'name ?time_us?'+::
2443     As for `file mtime` except the time value is in microseconds
2444     since the epoch (see also `clock microseconds`).
2445     Note that some platforms and some filesystems don't support high
2446     resolution timestamps for files.
2448 +*file normalize* 'name'+::
2449     Return the normalized path of +'name'+. See 'realpath(3)'.
2451 +*file owned* 'name'+::
2452     Return '1' if file +'name'+ is owned by the current user,
2453     '0' otherwise.
2455 +*file readable* 'name'+::
2456     Return '1' if file +'name'+ is readable by
2457     the current user, '0' otherwise.
2459 +*file readlink* 'name'+::
2460     Returns the value of the symbolic link given by +'name'+ (i.e. the
2461     name of the file it points to).  If
2462     +'name'+ isn't a symbolic link or its value cannot be read, then
2463     an error is returned.  On systems that don't support symbolic links
2464     this option is undefined.
2466 +*file rename* ?*-force*? 'oldname' 'newname'+::
2467     Renames the file from the old name to the new name.
2468     If +'newname'+ already exists, an error is returned unless +'-force'+ is
2469     specified.
2471 +*file rootname* 'name'+::
2472     Return all of the characters in +'name'+ up to but not including
2473     the last '.' character in the name.  If +'name'+ doesn't contain
2474     a dot, then return +'name'+.
2476 +*file split* 'name'+::
2477     Returns a list whose elements are the path components in +'name'+.
2478     The first element of the list will have the same path type as
2479     +'name'+. All other elements will be relative. Path separators
2480     will be discarded.
2482 +*file stat* 'name ?varName?'+::
2483     Invoke the 'stat' kernel call on +'name'+, and return the result
2484     as a dictionary with the following keys: 'atime',
2485     'ctime', 'dev', 'gid', 'ino', 'mode', 'mtime',
2486     'nlink', 'size', 'type', 'uid', 'mtimeus' (if supported - see `file mtimeus`)
2487     Each element except 'type' is a decimal string with the value of
2488     the corresponding field from the 'stat' return structure; see the
2489     manual entry for 'stat' for details on the meanings of the values.
2490     The 'type' element gives the type of the file in the same form
2491     returned by the command `file type`.
2492     If +'varName'+ is specified, it is taken to be the name of an array
2493     variable and the values are also stored into the array.
2495 +*file tail* 'name'+::
2496     Return all of the characters in +'name'+ after the last slash.
2497     If +'name'+ contains no slashes then return +'name'+.
2499 +*file tempfile* '?template?'+::
2500     Creates and returns the name of a unique temporary file. If +'template'+ is omitted, a
2501     default template will be used to place the file in /tmp. See 'mkstemp(3)' for
2502     the format of the template and security concerns.
2504 +*file type* 'name'+::
2505     Returns a string giving the type of file +'name'+, which will be
2506     one of +file+, +directory+, +characterSpecial+,
2507     +blockSpecial+, +fifo+, +link+, or +socket+.
2509 +*file writable* 'name'+::
2510     Return '1' if file +'name'+ is writable by
2511     the current user, '0' otherwise.
2513 The `file` commands that return 0/1 results are often used in
2514 conditional or looping commands, for example:
2516 ----
2517     if {![file exists foo]} {
2518         error {bad file name}
2519     } else {
2520         ...
2521     }
2522 ----
2524 finalize
2525 ~~~~~~~~
2526 +*finalize* 'reference ?command?'+
2528 If +'command'+ is omitted, returns the finalizer command for the given reference.
2530 Otherwise, sets a new finalizer command for the given reference. +'command'+ may be
2531 the empty string to remove the current finalizer.
2533 The reference must be a valid reference create with the `ref`
2534 command.
2536 See <<_garbage_collection_references_lambda_function,GARBAGE COLLECTION>> for more detail.
2538 flush
2539 ~~~~~
2540 +*flush* 'fileId'+
2542 +'fileId' *flush*+
2544 Flushes any output that has been buffered for +'fileId'+.  +'fileId'+ must
2545 have been the return value from a previous call to `open`, or it may be
2546 +stdout+ or +stderr+ to access one of the standard I/O streams; it must
2547 refer to a file that was opened for writing.  This command returns an
2548 empty string.
2552 +*for* 'start test next body'+
2554 `for` is a looping command, similar in structure to the C `for` statement.
2555 The +'start'+, +'next'+, and +'body'+ arguments must be Tcl command strings,
2556 and +'test'+ is an expression string.
2558 The `for` command first invokes the Tcl interpreter to execute +'start'+.
2559 Then it repeatedly evaluates +'test'+ as an expression; if the result is
2560 non-zero it invokes the Tcl interpreter on +'body'+, then invokes the Tcl
2561 interpreter on +'next'+, then repeats the loop.  The command terminates
2562 when +'test'+ evaluates to 0.
2564 If a `continue` command is invoked within +'body'+ then any remaining
2565 commands in the current execution of +'body'+ are skipped; processing
2566 continues by invoking the Tcl interpreter on +'next'+, then evaluating
2567 +'test'+, and so on.
2569 If a `break` command is invoked within +'body'+ or +'next'+, then the `for`
2570 command will return immediately.
2572 The operation of `break` and `continue` are similar to the corresponding
2573 statements in C.
2575 `for` returns an empty string.
2577 foreach
2578 ~~~~~~~
2579 +*foreach* 'varName list body'+
2581 +*foreach* 'varList list ?varList2 list2 \...? body'+
2583 In this command, +'varName'+ is the name of a variable, +'list'+
2584 is a list of values to assign to +'varName'+, and +'body'+ is a
2585 collection of Tcl commands.
2587 For each field in +'list'+ (in order from left to right), `foreach` assigns
2588 the contents of the field to +'varName'+ (as if the `lindex` command
2589 had been used to extract the field), then calls the Tcl interpreter to
2590 execute +'body'+.
2592 If instead of being a simple name, +'varList'+ is used, multiple assignments
2593 are made each time through the loop, one for each element of +'varList'+.
2595 For example, if there are two elements in +'varList'+ and six elements in
2596 the list, the loop will be executed three times.
2598 If the length of the list doesn't evenly divide by the number of elements
2599 in +'varList'+, the value of the remaining variables in the last iteration
2600 of the loop are undefined.
2602 The `break` and `continue` statements may be invoked inside +'body'+,
2603 with the same effect as in the `for` command.
2605 `foreach` returns an empty string.
2607 format
2608 ~~~~~~
2609 +*format* 'formatString ?arg \...?'+
2611 This command generates a formatted string in the same way as the
2612 C 'sprintf' procedure (it uses 'sprintf' in its
2613 implementation).  +'formatString'+ indicates how to format
2614 the result, using +%+ fields as in 'sprintf', and the additional
2615 arguments, if any, provide values to be substituted into the result.
2617 All of the 'sprintf' options are valid; see the 'sprintf'
2618 man page for details.  Each +'arg'+ must match the expected type
2619 from the +%+ field in +'formatString'+; the `format` command
2620 converts each argument to the correct type (floating, integer, etc.)
2621 before passing it to 'sprintf' for formatting.
2623 The only unusual conversion is for +%c+; in this case the argument
2624 must be a decimal string, which will then be converted to the corresponding
2625 ASCII (or UTF-8) character value.
2627 In addition, Jim Tcl provides basic support for conversion to binary with +%b+.
2629 `format` does backslash substitution on its +'formatString'+
2630 argument, so backslash sequences in +'formatString'+ will be handled
2631 correctly even if the argument is in braces.
2633 The return value from `format` is the formatted string.
2635 getref
2636 ~~~~~~
2637 +*getref* 'reference'+
2639 Returns the string associated with +'reference'+. The reference must
2640 be a valid reference create with the `ref` command.
2642 See <<_garbage_collection_references_lambda_function,GARBAGE COLLECTION>> for more detail.
2644 gets
2645 ~~~~
2646 +*gets* 'fileId ?varName?'+
2648 +'fileId' *gets* '?varName?'+
2650 Reads the next line from the file given by +'fileId'+ and discards
2651 the terminating newline character.
2653 If +'varName'+ is specified, then the line is placed in the variable
2654 by that name and the return value is a count of the number of characters
2655 read (not including the newline).
2657 If the end of the file is reached before reading
2658 any characters then -1 is returned and +'varName'+ is set to an
2659 empty string.
2661 If +'varName'+ is not specified then the return value will be
2662 the line (minus the newline character) or an empty string if
2663 the end of the file is reached before reading any characters.
2665 An empty string will also be returned if a line contains no characters
2666 except the newline, so `eof` may have to be used to determine
2667 what really happened.
2669 If the last character in the file is not a newline character, then
2670 `gets` behaves as if there were an additional newline character
2671 at the end of the file.
2673 +'fileId'+ must be +stdin+ or the return value from a previous
2674 call to `open`; it must refer to a file that was opened
2675 for reading.
2677 glob
2678 ~~~~
2679 +*glob* ?*-nocomplain*? ?*-directory* 'dir'? ?*-tails*? ?*--*? 'pattern ?pattern \...?'+
2681 This command performs filename globbing, using csh rules.  The returned
2682 value from `glob` is the list of expanded filenames.
2684 If +-nocomplain+ is specified as the first argument then an empty
2685 list may be returned;  otherwise an error is returned if the expanded
2686 list is empty.  The +-nocomplain+ argument must be provided
2687 exactly: an abbreviation will not be accepted.
2689 If +-directory+ is given, the +'dir'+ is understood to contain a
2690 directory name to search in. This allows globbing inside directories
2691 whose names may contain glob-sensitive characters. The returned names
2692 include the directory name unless +'-tails'+ is specified.
2694 If +'-tails'+ is specified, along with +-directory+, the returned names
2695 are relative to the given directory.
2697 global
2698 ~~~~~~
2700 +*global* 'varName ?varName \...?'+
2702 This command is ignored unless a Tcl procedure is being interpreted.
2703 If so, then it declares each given +'varName'+ to be a global variable
2704 rather than a local one.  For the duration of the current procedure
2705 (and only while executing in the current procedure), any reference to
2706 +'varName'+ will be bound to a global variable instead
2707 of a local one.
2709 An alternative to using `global` is to use the +::+ prefix
2710 to explicitly name a variable in the global scope.
2714 +*if* 'expr1' ?*then*? 'body1' *elseif* 'expr2' ?*then*? 'body2' *elseif* \... ?*else*? ?'bodyN'?+
2716 The `if` command evaluates +'expr1'+ as an expression (in the same way
2717 that `expr` evaluates its argument).  The value of the expression must
2718 be numeric; if it is non-zero then +'body1'+ is executed by passing it to
2719 the Tcl interpreter.
2721 Otherwise +'expr2'+ is evaluated as an expression and if it is non-zero
2722 then +'body2'+ is executed, and so on.
2724 If none of the expressions evaluates to non-zero then +'bodyN'+ is executed.
2726 The +then+ and +else+ arguments are optional "noise words" to make the
2727 command easier to read.
2729 There may be any number of +elseif+ clauses, including zero.  +'bodyN'+
2730 may also be omitted as long as +else+ is omitted too.
2732 The return value from the command is the result of the body script that
2733 was executed, or an empty string if none of the expressions was non-zero
2734 and there was no +'bodyN'+.
2736 incr
2737 ~~~~
2738 +*incr* 'varName ?increment?'+
2740 Increment the value stored in the variable whose name is +'varName'+.
2741 The value of the variable must be integral.
2743 If +'increment'+ is supplied then its value (which must be an
2744 integer) is added to the value of variable +'varName'+;  otherwise
2745 1 is added to +'varName'+.
2747 The new value is stored as a decimal string in variable +'varName'+
2748 and also returned as result.
2750 If the variable does not exist, the variable is implicitly created
2751 and set to +0+ first.
2753 info
2754 ~~~~
2756 +*info* 'option ?arg\...?'+::
2758 Provide information about various internals to the Tcl interpreter.
2759 The legal +'option'+'s (which may be abbreviated) are:
2761 +*info args* 'procname'+::
2762     Returns a list containing the names of the arguments to procedure
2763     +'procname'+, in order.  +'procname'+ must be the name of a
2764     Tcl command procedure.
2766 +*info alias* 'command'+::
2767     +'command'+ must be an alias created with `alias`. In which case the target
2768     command and arguments, as passed to `alias` are returned. See `exists -alias`
2770 +*info body* 'procname'+::
2771     Returns the body of procedure +'procname'+.  +'procname'+ must be
2772     the name of a Tcl command procedure.
2774 +*info channels*+::
2775     Returns a list of all open file handles from `open` or `socket`
2777 +*info commands* ?'pattern'?+::
2778     If +'pattern'+ isn't specified, returns a list of names of all the
2779     Tcl commands, including both the built-in commands written in C and
2780     the command procedures defined using the `proc` command.
2781     If +'pattern'+ is specified, only those names matching +'pattern'+
2782     (using <<_string_matching,STRING MATCHING>> rules) are returned.
2784 +*info complete* 'command' ?'missing'?+::
2785     Returns 1 if +'command'+ is a complete Tcl command in the sense of
2786     having no unclosed quotes, braces, brackets or array element names,
2787     If the command doesn't appear to be complete then 0 is returned.
2788     This command is typically used in line-oriented input environments
2789     to allow users to type in commands that span multiple lines;  if the
2790     command isn't complete, the script can delay evaluating it until additional
2791     lines have been typed to complete the command. If +'varName'+ is specified, the
2792     missing character is stored in the variable with that name.
2794 +*info exists* 'varName'+::
2795     Returns '1' if the variable named +'varName'+ exists in the
2796     current context (either as a global or local variable), returns '0'
2797     otherwise.
2799 +*info frame* ?'number'?+::
2800     If +'number'+ is not specified, this command returns a number
2801     which is the same result as `info level` - the current stack frame level.
2802     If +'number'+ is specified, then the result is a list consisting of the procedure,
2803     filename and line number for the procedure call at level +'number'+ on the stack.
2804     If +'number'+ is positive then it selects a particular stack level (1 refers
2805     to the top-most active procedure, 2 to the procedure it called, and
2806     so on); otherwise it gives a level relative to the current level
2807     (0 refers to the current procedure, -1 to its caller, and so on).
2808     The level has an identical meaning to `info level`.
2810 +*info globals* ?'pattern'?+::
2811     If +'pattern'+ isn't specified, returns a list of all the names
2812     of currently-defined global variables.
2813     If +'pattern'+ is specified, only those names matching +'pattern'+
2814     (using <<_string_matching,STRING MATCHING>> rules) are returned.
2816 +*info hostname*+::
2817     An alias for `os.gethostname` for compatibility with Tcl 6.x
2819 +*info level* ?'number'?+::
2820     If +'number'+ is not specified, this command returns a number
2821     giving the stack level of the invoking procedure, or 0 if the
2822     command is invoked at top-level.  If +'number'+ is specified,
2823     then the result is a list consisting of the name and arguments for the
2824     procedure call at level +'number'+ on the stack.  If +'number'+
2825     is positive then it selects a particular stack level (1 refers
2826     to the top-most active procedure, 2 to the procedure it called, and
2827     so on); otherwise it gives a level relative to the current level
2828     (0 refers to the current procedure, -1 to its caller, and so on).
2829     See the `uplevel` command for more information on what stack
2830     levels mean.
2832 +*info locals* ?'pattern'?+::
2833     If +'pattern'+ isn't specified, returns a list of all the names
2834     of currently-defined local variables, including arguments to the
2835     current procedure, if any.  Variables defined with the `global`
2836     and `upvar` commands will not be returned.  If +'pattern'+ is
2837     specified, only those names matching +'pattern'+
2838     (using <<_string_matching,STRING MATCHING>> rules) are returned.
2840 +*info nameofexecutable*+::
2841     Returns the name of the binary file from which the application
2842     was invoked. A full path will be returned, unless the path
2843     can't be determined, in which case the empty string will be returned.
2845 +*info procs* ?'pattern'?+::
2846     If +'pattern'+ isn't specified, returns a list of all the
2847     names of Tcl command procedures.
2848     If +'pattern'+ is specified, only those names matching +'pattern'+
2849     (using <<_string_matching,STRING MATCHING>> rules) are returned.
2851 +*info references*+::
2852     Returns a list of all references which have not yet been garbage
2853     collected.
2855 +*info returncodes* ?'code'?+::
2856     Returns a list representing the mapping of standard return codes
2857     to names. e.g. +{0 ok 1 error 2 return \...}+. If a code is given,
2858     instead returns the name for the given code.
2860 +*info script*+::
2861     If a Tcl script file is currently being evaluated (i.e. there is a
2862     call to 'Jim_EvalFile' active or there is an active invocation
2863     of the `source` command), then this command returns the name
2864     of the innermost file being processed.  Otherwise the command returns an
2865     empty string.
2867 +*info source* 'script ?filename line?'+::
2868     With a single argument, returns the original source location of the given script as a list of
2869     +{filename linenumber}+. If the source location can't be determined, the
2870     list +{{} 0}+ is returned. If +'filename'+ and +'line'+ are given, returns a copy
2871     of +'script'+ with the associate source information. This can be useful to produce
2872     useful messages from `eval`, etc. if the original source information may be lost.
2874 +*info stacktrace*+::
2875     After an error is caught with `catch`, returns the stack trace as a list
2876     of +{procedure filename line \...}+.
2878 +*info statics* 'procname'+::
2879     Returns a dictionary of the static variables of procedure
2880     +'procname'+.  +'procname'+ must be the name of a Tcl command
2881     procedure. An empty dictionary is returned if the procedure has
2882     no static variables.
2884 +*info version*+::
2885     Returns the version number for this version of Jim in the form +*x.yy*+.
2887 +*info vars* ?'pattern'?+::
2888     If +'pattern'+ isn't specified,
2889     returns a list of all the names of currently-visible variables, including
2890     both locals and currently-visible globals.
2891     If +'pattern'+ is specified, only those names matching +'pattern'+
2892     (using <<_string_matching,STRING MATCHING>> rules) are returned.
2894 join
2895 ~~~~
2896 +*join* 'list ?joinString?'+
2898 The +'list'+ argument must be a valid Tcl list.  This command returns the
2899 string formed by joining all of the elements of +'list'+ together with
2900 +'joinString'+ separating each adjacent pair of elements.
2902 The +'joinString'+ argument defaults to a space character.
2904 kill
2905 ~~~~
2906 +*kill* ?'SIG'|*-0*? 'pid'+
2908 Sends the given signal to the process identified by +'pid'+.
2910 The signal may be specified by name or number in one of the following forms:
2912 * +TERM+
2913 * +SIGTERM+
2914 * +-TERM+
2915 * +15+
2916 * +-15+
2918 The signal name may be in either upper or lower case.
2920 The special signal name +-0+ simply checks that a signal +'could'+ be sent.
2922 If no signal is specified, SIGTERM is used.
2924 An error is raised if the signal could not be delivered.
2926 lambda
2927 ~~~~~~
2928 +*lambda* 'args ?statics? body'+
2930 The `lambda` command is identical to `proc`, except rather than
2931 creating a named procedure, it creates an anonymous procedure and returns
2932 the name of the procedure.
2934 See `proc` and <<_garbage_collection_references_lambda_function,GARBAGE COLLECTION>> for more detail.
2936 lappend
2937 ~~~~~~~
2938 +*lappend* 'varName value ?value value \...?'+
2940 Treat the variable given by +'varName'+ as a list and append each of
2941 the +'value'+ arguments to that list as a separate element, with spaces
2942 between elements.
2944 If +'varName'+ doesn't exist, it is created as a list with elements given
2945 by the +'value'+ arguments. `lappend` is similar to `append` except that
2946 each +'value'+ is appended as a list element rather than raw text.
2948 This command provides a relatively efficient way to build up large lists.
2949 For example,
2951 ----
2952     lappend a $b
2953 ----
2955 is much more efficient than
2957 ----
2958     set a [concat $a [list $b]]
2959 ----
2961 when +$a+ is long.
2963 lassign
2964 ~~~~~~~
2965 +*lassign* 'list varName ?varName \...?'+
2967 This command treats the value +'list'+ as a list and assigns successive elements from that list to
2968 the variables given by the +'varName'+ arguments in order. If there are more variable names than
2969 list elements, the remaining variables are set to the empty string. If there are more list elements
2970 than variables, a list of unassigned elements is returned.
2972 ----
2973     . lassign {1 2 3} a b; puts a=$a,b=$b
2974     3
2975     a=1,b=2
2976 ----
2978 local
2979 ~~~~~
2980 +*local* 'cmd ?arg\...?'+
2982 First, `local` evaluates +'cmd'+ with the given arguments. The return value must
2983 be the name of an existing command, which is then marked as having local scope.
2984 This means that when the current procedure exits, the specified
2985 command is deleted. This can be useful with `lambda`, local procedures or
2986 to automatically close a filehandle.
2988 In addition, if a the command already exists with the same name,
2989 the existing command will be kept rather than being deleted, and may be called
2990 via `upcall`. The previous command will be restored when the current
2991 procedure exits. See `upcall` for more details.
2993 In this example, a local procedure is created. Note that the procedure
2994 continues to have global scope while it is active.
2996 ----
2997     proc outer {} {
2998       # proc ... returns "inner" which is marked local
2999       local proc inner {} {
3000         # will be deleted when 'outer' exits
3001       }
3003       inner
3004       ...
3005     }
3006 ----
3008 In this example, the lambda is deleted at the end of the procedure rather
3009 than waiting until garbage collection.
3011 ----
3012     proc outer {} {
3013       set x [lambda inner {args} {
3014         # will be deleted when 'outer' exits
3015       }]
3016       # Use 'function' here which simply returns $x
3017       local function $x
3019       $x ...
3020       ...
3021     }
3022 ----
3024 Also see `defer` as another mechanism for cleaning up at the end of a procedure.
3026 loop
3027 ~~~~
3028 +*loop* 'var first limit ?incr? body'+
3030 Similar to `for` except simpler and possibly more efficient.
3031 If +'incr'+ is positive, the effect is, equivalent to:
3033 ----
3034     for {set var $first} {$var < $limit} {incr var $incr} $body
3035 ----
3037 While if +'incr'+ is negative, the count is downwards.
3039 If +'incr'+ is not specified, 1 is used.
3040 Note that setting the loop variable inside the loop does not
3041 affect the loop count.
3043 lindex
3044 ~~~~~~
3045 +*lindex* 'list ?index ...?'+
3047 Treats +'list'+ as a Tcl list and returns element +'index'+ from it
3048 (0 refers to the first element of the list).
3049 See <<_string_and_list_index_specifications,STRING AND LIST INDEX SPECIFICATIONS>> for all allowed forms for +'index'+.
3051 In extracting the element, +'lindex'+ observes the same rules concerning
3052 braces and quotes and backslashes as the Tcl command interpreter; however,
3053 variable substitution and command substitution do not occur.
3055 If no index values are given, simply returns +'list'+
3057 If +'index'+ is negative or greater than or equal to the number of elements
3058 in +'list'+, then an empty string is returned.
3060 If additional index arguments are supplied, then each argument is
3061 used in turn to select an element from the previous indexing
3062 operation, allowing the script to select elements from sublists.
3064 linsert
3065 ~~~~~~~
3066 +*linsert* 'list index element ?element element \...?'+
3068 This command produces a new list from +'list'+ by inserting all
3069 of the +'element'+ arguments just before the element +'index'+
3070 of +'list'+. Each +'element'+ argument will become
3071 a separate element of the new list. If +'index'+ is less than
3072 or equal to zero, then the new elements are inserted at the
3073 beginning of the list. If +'index'+ is greater than or equal
3074 to the number of elements in the list, then the new elements are
3075 appended to the list.
3077 See <<_string_and_list_index_specifications,STRING AND LIST INDEX SPECIFICATIONS>> for all allowed forms for +'index'+.
3079 list
3080 ~~~~
3082 +*list* 'arg ?arg \...?'+
3084 This command returns a list comprised of all the arguments, +'arg'+. Braces
3085 and backslashes get added as necessary, so that the `lindex` command
3086 may be used on the result to re-extract the original arguments, and also
3087 so that `eval` may be used to execute the resulting list, with
3088 +'arg1'+ comprising the command's name and the other args comprising
3089 its arguments. `list` produces slightly different results than
3090 `concat`:  `concat` removes one level of grouping before forming
3091 the list, while `list` works directly from the original arguments.
3092 For example, the command
3094 ----
3095     list a b {c d e} {f {g h}}
3096 ----
3098 will return
3100 ----
3101     a b {c d e} {f {g h}}
3102 ----
3104 while `concat` with the same arguments will return
3106 ----
3107     a b c d e f {g h}
3108 ----
3110 llength
3111 ~~~~~~~
3112 +*llength* 'list'+
3114 Treats +'list'+ as a list and returns the number of elements in that list.
3116 lset
3117 ~~~~
3118 +*lset* 'varName ?index ..? newValue'+
3120 Sets an element in a list.
3122 The `lset` command accepts a parameter, +'varName'+, which it interprets
3123 as the name of a variable containing a Tcl list. It also accepts
3124 zero or more indices into the list. Finally, it accepts a new value
3125 for an element of +'varName'+. If no indices are presented, the command
3126 takes the form:
3128 ----
3129     lset varName newValue
3130 ----
3132 In this case, newValue replaces the old value of the variable
3133 +'varName'+.
3135 When presented with a single index, the `lset` command
3136 treats the content of the +'varName'+ variable as a Tcl list. It addresses
3137 the index'th element in it (0 refers to the first element of the
3138 list). When interpreting the list, `lset` observes the same rules
3139 concerning braces and quotes and backslashes as the Tcl command
3140 interpreter; however, variable substitution and command substitution
3141 do not occur. The command constructs a new list in which the
3142 designated element is replaced with newValue. This new list is
3143 stored in the variable +'varName'+, and is also the return value from
3144 the `lset` command.
3146 If index is negative or greater than or equal to the number of
3147 elements in +$varName+, then an error occurs.
3149 See <<_string_and_list_index_specifications,STRING AND LIST INDEX SPECIFICATIONS>> for all allowed forms for +'index'+.
3151 If additional index arguments are supplied, then each argument is
3152 used in turn to address an element within a sublist designated by
3153 the previous indexing operation, allowing the script to alter
3154 elements in sublists. The command,
3156 ----
3157     lset a 1 2 newValue
3158 ----
3160 replaces element 2 of sublist 1 with +'newValue'+.
3162 The integer appearing in each index argument must be greater than
3163 or equal to zero. The integer appearing in each index argument must
3164 be strictly less than the length of the corresponding list. In other
3165 words, the `lset` command cannot change the size of a list. If an
3166 index is outside the permitted range, an error is reported.
3168 lmap
3169 ~~~~
3171 +*lmap* 'varName list body'+
3173 +*lmap* 'varList list ?varList2 list2 \...? body'+
3175 `lmap` is a "collecting" `foreach` which returns a list of its results.
3177 For example:
3179 ----
3180     . lmap i {1 2 3 4 5} {expr $i*$i}
3181     1 4 9 16 25
3182     . lmap a {1 2 3} b {A B C} {list $a $b}
3183     {1 A} {2 B} {3 C}
3184 ----
3186 If the body invokes `continue`, no value is added for this iteration.
3187 If the body invokes `break`, the loop ends and no more values are added.
3189 load
3190 ~~~~
3191 +*load* 'filename'+
3193 Loads the dynamic extension, +'filename'+. Generally the filename should have
3194 the extension +.so+. The initialisation function for the module must be based
3195 on the name of the file. For example loading +hwaccess.so+ will invoke
3196 the initialisation function, +Jim_hwaccessInit+. Normally the `load` command
3197 should not be used directly. Instead it is invoked automatically by `package require`.
3199 lrange
3200 ~~~~~~
3201 +*lrange* 'list first last'+
3203 +'list'+ must be a valid Tcl list. This command will return a new
3204 list consisting of elements +'first'+ through +'last'+, inclusive.
3206 See <<_string_and_list_index_specifications,STRING AND LIST INDEX SPECIFICATIONS>> for all allowed forms for +'first'+ and +'last'+.
3208 If +'last'+ is greater than or equal to the number of elements
3209 in the list, then it is treated as if it were +end+.
3211 If +'first'+ is greater than +'last'+ then an empty string
3212 is returned.
3214 Note: +"`lrange` 'list first first'"+ does not always produce the
3215 same result as +"`lindex` 'list first'"+ (although it often does
3216 for simple fields that aren't enclosed in braces); it does, however,
3217 produce exactly the same results as +"`list` [`lindex` 'list first']"+
3219 lreplace
3220 ~~~~~~~~
3222 +*lreplace* 'list first last ?element element \...?'+
3224 Returns a new list formed by replacing one or more elements of
3225 +'list'+ with the +'element'+ arguments.
3227 +'first'+ gives the index in +'list'+ of the first element
3228 to be replaced.
3230 If +'first'+ is less than zero then it refers to the first
3231 element of +'list'+;  the element indicated by +'first'+
3232 must exist in the list.
3234 +'last'+ gives the index in +'list'+ of the last element
3235 to be replaced;  it must be greater than or equal to +'first'+.
3237 See <<_string_and_list_index_specifications,STRING AND LIST INDEX SPECIFICATIONS>> for all allowed forms for +'first'+ and +'last'+.
3239 The +'element'+ arguments specify zero or more new arguments to
3240 be added to the list in place of those that were deleted.
3242 Each +'element'+ argument will become a separate element of
3243 the list.
3245 If no +'element'+ arguments are specified, then the elements
3246 between +'first'+ and +'last'+ are simply deleted.
3248 lrepeat
3249 ~~~~~~~~
3250 +*lrepeat* 'number element1 ?element2 \...?'+
3252 Build a list by repeating elements +'number'+ times (which must be
3253 a positive integer).
3255 ----
3256     . lrepeat 3 a b
3257     a b a b a b
3258 ----
3260 lreverse
3261 ~~~~~~~~
3262 +*lreverse* 'list'+
3264 Returns the list in reverse order.
3266 ----
3267     . lreverse {1 2 3}
3268     3 2 1
3269 ----
3271 lsearch
3272 ~~~~~~~
3273 +*lsearch* '?options? list pattern'+
3275 This command searches the elements +'list'+ to see if one of them matches +'pattern'+. If so, the
3276 command returns the index of the first matching element (unless the options +-all+, +-inline+ or +-bool+ are
3277 specified.) If not, the command returns -1. The option arguments indicates how the elements of
3278 the list are to be matched against pattern and must have one of the values below:
3280 *Note* that this command is different from Tcl in that default match type is +-exact+ rather than +-glob+.
3282 +*-exact*+::
3283     +'pattern'+ is a literal string that is compared for exact equality against each list element.
3284     This is the default.
3286 +*-glob*+::
3287     +'pattern'+ is a glob-style pattern which is matched against each list element using
3288     <<_string_matching,STRING MATCHING>> rules.
3290 +*-regexp*+::
3291     +'pattern'+ is treated as a regular expression and matched against each list element using
3292     <<_regular_expressions,REGULAR EXPRESSIONS>> rules.
3294 +*-command* 'cmdname'+::
3295     +'cmdname'+ is a command which is used to match the pattern against each element of the
3296     list. It is invoked as +'cmdname' ?*-nocase*? 'pattern listvalue'+ and should return 1
3297     for a match, or 0 for no match.
3299 +*-all*+::
3300     Changes the result to be the list of all matching indices (or all matching values if
3301     +-inline+ is specified as well). If indices are returned, the indices will be in numeric
3302     order. If values are returned, the order of the values will be the order of those values
3303     within the input list.
3305 +*-inline*+::
3306     The matching value is returned instead of its index (or an empty string if no value
3307     matches). If +-all+ is also specified, then the result of the command is the list of all
3308     values that matched. The +-inline+ and +-bool+ options are mutually exclusive.
3310 +*-bool*+::
3311     Changes the result to '1' if a match was found, or '0' otherwise. If +-all+ is also specified,
3312     the result will be a list of '0' and '1' for each element of the list depending upon whether
3313     the corresponding element matches. The +-inline+ and +-bool+ options are mutually exclusive.
3315 +*-not*+::
3316     This negates the sense of the match, returning the index (or value
3317     if +-inline+ is specified) of the first non-matching value in the
3318     list. If +-bool+ is also specified, the '0' will be returned if a
3319     match is found, or '1' otherwise. If +-all+ is also specified,
3320     non-matches will be returned rather than matches.
3322 +*-nocase*+::
3323     Causes comparisons to be handled in a case-insensitive manner.
3325 lsort
3326 ~~~~~
3327 +*lsort* ?*-index* 'listindex'? ?*-nocase|-integer|-real|-command* 'cmdname'? ?*-unique*? ?*-decreasing*|*-increasing*? 'list'+
3329 Sort the elements of +'list'+, returning a new list in sorted order.
3330 By default, ASCII (or UTF-8) sorting is used, with the result in increasing order.
3332 If +-nocase+ is specified, comparisons are case-insensitive.
3334 If +-integer+ is specified, numeric sorting is used.
3336 If +-real+ is specified, floating point number sorting is used.
3338 If +-command 'cmdname'+ is specified, +'cmdname'+ is treated as a command
3339 name. For each comparison, +'cmdname $value1 $value2+' is called which
3340 should compare the values and return an integer less than, equal
3341 to, or greater than zero if the +'$value1'+ is to be considered less
3342 than, equal to, or greater than +'$value2'+, respectively.
3344 If +-decreasing+ is specified, the resulting list is in the opposite
3345 order to what it would be otherwise. +-increasing+ is the default.
3347 If +-unique+ is specified, then only the last set of duplicate elements found in the list will be retained.
3348 Note that duplicates are determined relative to the comparison used in the sort. Thus if +-index 0+ is used,
3349 +{1 a}+ and +{1 b}+ would be considered duplicates and only the second element, +{1 b}+, would be retained.
3351 If +-index 'listindex'+ is specified, each element of the list is treated as a list and
3352 the given index is extracted from the list for comparison. The list index may
3353 be any valid list index, such as +1+, +end+ or +end-2+.
3355 defer
3356 ~~~~~
3357 +*defer* 'script'+
3359 This command is a simple helper command to add a script to the '+$jim::defer+' variable
3360 that will run when the current proc or interpreter exits. For example:
3362 ----
3363     . proc a {} { defer {puts "Leaving a"}; puts "Exit" }
3364     . a
3365     Exit
3366     Leaving a
3367 ----
3369 If the '+$jim::defer+' variable exists, it is treated as a list of scripts to run
3370 when the proc or interpreter exits.
3372 open
3373 ~~~~
3374 +*open* 'fileName ?access?'+
3376 +*open* '|command-pipeline ?access?'+
3378 Opens a file and returns an identifier
3379 that may be used in future invocations
3380 of commands like `read`, `puts`, and `close`.
3381 +'fileName'+ gives the name of the file to open.
3383 The +'access'+ argument indicates the way in which the file is to be accessed.
3384 It may have any of the following values:
3386 +r+::
3387     Open the file for reading only; the file must already exist.
3389 +r++::
3390     Open the file for both reading and writing; the file must
3391     already exist.
3393 +w+::
3394     Open the file for writing only. Truncate it if it exists. If it doesn't
3395     exist, create a new file.
3397 +w++::
3398     Open the file for reading and writing. Truncate it if it exists.
3399     If it doesn't exist, create a new file.
3401 +a+::
3402     Open the file for writing only. The file must already exist, and the file
3403     is positioned so that new data is appended to the file.
3405 +a++::
3406     Open the file for reading and writing. If the file doesn't
3407     exist, create a new empty file. Set the initial access position
3408     to the end of the file.
3410 +'access'+ defaults to 'r'.
3412 If a file is opened for both reading and writing, then `seek`
3413 must be invoked between a read and a write, or vice versa.
3415 If the first character of +'fileName'+ is "|" then the remaining
3416 characters of +'fileName'+ are treated as a list of arguments that
3417 describe a command pipeline to invoke, in the same style as the
3418 arguments for exec. In this case, the channel identifier returned
3419 by open may be used to write to the command's input pipe or read
3420 from its output pipe, depending on the value of +'access'+. If write-only
3421 access is used (e.g. +'access'+ is 'w'), then standard output for the
3422 pipeline is directed to the current standard output unless overridden
3423 by the command. If read-only access is used (e.g. +'access'+ is r),
3424 standard input for the pipeline is taken from the current standard
3425 input unless overridden by the command.
3427 The `pid` command may be used to return the process ids of the commands
3428 forming the command pipeline.
3430 See also `socket`, `pid`, `exec`
3432 package
3433 ~~~~~~~
3434 +*package provide* 'name ?version?'+
3436 Indicates that the current script provides the package named +'name'+.
3437 *Note*: The supplied version is ignored. All packages are registered as version 1.0
3438 (it is simply accepted for compatibility purposes).
3440 Any script that provides a package may include this statement
3441 as the first statement, although it is not required.
3443 +*package require* 'name ?version?'+
3445 Searches for the package with the given +'name'+ by examining each path
3446 in '$::auto_path' and trying to load '$path/$name.so' as a dynamic extension,
3447 or '$path/$name.tcl' as a script package.
3449 The first such file which is found is considered to provide the package.
3450 (The version number is ignored).
3452 If '$name.so' exists, it is loaded with the `load` command,
3453 otherwise if '$name.tcl' exists it is loaded with the `source` command.
3455 If `load` or `source` fails, `package require` will fail immediately.
3456 No further attempt will be made to locate the file.
3458 +*package names*+
3460 Returns a list of all known/loaded packages, including internal packages.
3464 +*pid*+
3466 +*pid* 'fileId'+
3468 The first form returns the process identifier of the current process.
3470 The second form accepts a handle returned by `open` and returns a list
3471 of the process ids forming the pipeline in the same form as `exec ... &`.
3472 If 'fileId' represents a regular file handle rather than a command pipeline,
3473 the empty string is returned instead.
3475 See also `open`, `exec`
3477 proc
3478 ~~~~
3479 +*proc* 'name args ?statics? body'+
3481 The `proc` command creates a new Tcl command procedure, +'name'+.
3482 When the new command is invoked, the contents of +'body'+ will be executed.
3483 Tcl interpreter. +'args'+ specifies the formal arguments to the procedure.
3484 If specified, +'statics'+, declares static variables which are bound to the
3485 procedure.
3487 See <<_procedures,PROCEDURES> for detailed information about Tcl procedures.
3489 The `proc` command returns +'name'+ (which is useful with `local`).
3491 When a procedure is invoked, the procedure's return value is the
3492 value specified in a `return` command.  If the procedure doesn't
3493 execute an explicit `return`, then its return value is the value
3494 of the last command executed in the procedure's body.
3496 If an error occurs while executing the procedure body, then the
3497 procedure-as-a-whole will return that same error.
3499 puts
3500 ~~~~
3501 +*puts* ?*-nonewline*? '?fileId? string'+
3503 +'fileId' *puts* ?*-nonewline*? 'string'+
3505 Writes the characters given by +'string'+ to the file given
3506 by +'fileId'+. +'fileId'+ must have been the return
3507 value from a previous call to `open`, or it may be
3508 +stdout+ or +stderr+ to refer to one of the standard I/O
3509 channels; it must refer to a file that was opened for
3510 writing.
3512 In the first form, if no +'fileId'+ is specified then it defaults to +stdout+.
3513 `puts` normally outputs a newline character after +'string'+,
3514 but this feature may be suppressed by specifying the +-nonewline+
3515 switch.
3517 Output to files is buffered internally by Tcl; the `flush`
3518 command may be used to force buffered characters to be output.
3520 pipe
3521 ~~~~
3522 Creates a pair of `aio` channels and returns the handles as a list: +{read write}+
3524 ----
3525     lassign [pipe] r w
3527     # Must close $w after exec
3528     exec ps >@$w &
3529     $w close
3531     $r readable ...
3532 ----
3536 +*pwd*+
3538 Returns the path name of the current working directory.
3540 rand
3541 ~~~~
3542 +*rand* '?min? ?max?'+
3544 Returns a random integer between +'min'+ (defaults to 0) and +'max'+
3545 (defaults to the maximum integer).
3547 If only one argument is given, it is interpreted as +'max'+.
3549 range
3550 ~~~~
3551 +*range* '?start? end ?step?'+
3553 Returns a list of integers starting at +'start'+ (defaults to 0)
3554 and ranging up to but not including +'end'+ in steps of +'step'+ defaults to 1).
3556 ----
3557     . range 5
3558     0 1 2 3 4
3559     . range 2 5
3560     2 3 4
3561     . range 2 10 4
3562     2 6
3563     . range 7 4 -2
3564     7 5
3565 ----
3567 read
3568 ~~~~
3569 +*read* ?*-nonewline*? 'fileId'+
3571 +'fileId' *read* ?*-nonewline*?+
3573 +*read* 'fileId numBytes'+
3575 +'fileId' *read* 'numBytes'+
3577 In the first form, all of the remaining bytes are read from the file
3578 given by +'fileId'+; they are returned as the result of the command.
3579 If the +-nonewline+ switch is specified then the last
3580 character of the file is discarded if it is a newline.
3582 In the second form, the extra argument specifies how many bytes to read;
3583 exactly this many bytes will be read and returned, unless there are fewer than
3584 +'numBytes'+ bytes left in the file; in this case, all the remaining
3585 bytes are returned.
3587 +'fileId'+ must be +stdin+ or the return value from a previous call
3588 to `open`; it must refer to a file that was opened for reading.
3590 regexp
3591 ~~~~~~
3592 +*regexp ?-nocase? ?-line? ?-indices? ?-start* 'offset'? *?-all? ?-inline? ?--?* 'exp string ?matchVar? ?subMatchVar subMatchVar \...?'+
3594 Determines whether the regular expression +'exp'+ matches part or
3595 all of +'string'+ and returns 1 if it does, 0 if it doesn't.
3597 See <<_regular_expressions,REGULAR EXPRESSIONS>> above for complete information on the
3598 syntax of +'exp'+ and how it is matched against +'string'+.
3600 If additional arguments are specified after +'string'+ then they
3601 are treated as the names of variables to use to return
3602 information about which part(s) of +'string'+ matched +'exp'+.
3603 +'matchVar'+ will be set to the range of +'string'+ that
3604 matched all of +'exp'+. The first +'subMatchVar'+ will contain
3605 the characters in +'string'+ that matched the leftmost parenthesized
3606 subexpression within +'exp'+, the next +'subMatchVar'+ will
3607 contain the characters that matched the next parenthesized
3608 subexpression to the right in +'exp'+, and so on.
3610 Normally, +'matchVar'+ and the each +'subMatchVar'+ are set to hold the
3611 matching characters from `string`, however see +-indices+ and
3612 +-inline+ below.
3614 If there are more values for +'subMatchVar'+ than parenthesized subexpressions
3615 within +'exp'+, or if a particular subexpression in +'exp'+ doesn't
3616 match the string (e.g. because it was in a portion of the expression
3617 that wasn't matched), then the corresponding +'subMatchVar'+ will be
3618 set to +"-1 -1"+ if +-indices+ has been specified or to an empty
3619 string otherwise.
3621 The following switches modify the behaviour of +'regexp'+
3623 +*-nocase*+::
3624     Causes upper-case and lower-case characters to be treated as
3625     identical during the matching process.
3627 +*-line*+::
3628     Use newline-sensitive matching. By default, newline
3629     is a completely ordinary character with no special meaning in
3630     either REs or strings. With this flag, +[^+ bracket expressions
3631     and +.+ never match newline, an +^+ anchor matches the null
3632     string after any newline in the string in addition to its normal
3633     function, and the +$+ anchor matches the null string before any
3634     newline in the string in addition to its normal function.
3636 +*-indices*+::
3637     Changes what is stored in the subMatchVars. Instead of
3638     storing the matching characters from string, each variable
3639     will contain a list of two decimal strings giving the indices
3640     in string of the first and last characters in the matching
3641     range of characters.
3643 +*-start* 'offset'+::
3644     Specifies a character index offset into the string at which to start
3645     matching the regular expression. If +-indices+ is
3646     specified, the indices will be indexed starting from the
3647     absolute beginning of the input string. +'offset'+ will be
3648     constrained to the bounds of the input string.
3650 +*-all*+::
3651     Causes the regular expression to be matched as many times as possible
3652     in the string, returning the total number of matches found. If this
3653     is specified with match variables, they will contain information
3654     for the last match only.
3656 +*-inline*+::
3657     Causes the command to return, as a list, the data that would otherwise
3658     be placed in match variables. When using +-inline+, match variables
3659     may not be specified. If used with +-all+, the list will be concatenated
3660     at each iteration, such that a flat list is always returned. For
3661     each match iteration, the command will append the overall match
3662     data, plus one element for each subexpression in the regular
3663     expression.
3665 +*--*+::
3666     Marks the end of switches. The argument following this one will be
3667     treated as +'exp'+ even if it starts with a +-+.
3669 regsub
3670 ~~~~~~
3671 +*regsub ?-nocase? ?-all? ?-line? ?-start* 'offset'? ?*--*? 'exp string subSpec ?varName?'+
3673 This command matches the regular expression +'exp'+ against
3674 +'string'+ using the rules described in REGULAR EXPRESSIONS
3675 above.
3677 If +'varName'+ is specified, the commands stores +'string'+ to +'varName'+
3678 with the substitutions detailed below, and returns the number of
3679 substitutions made (normally 1 unless +-all+ is specified).
3680 This is 0 if there were no matches.
3682 If +'varName'+ is not specified, the substituted string will be returned
3683 instead.
3685 When copying +'string'+, the portion of +'string'+ that
3686 matched +'exp'+ is replaced with +'subSpec'+.
3687 If +'subSpec'+ contains a +&+ or +{backslash}0+, then it is replaced
3688 in the substitution with the portion of +'string'+ that
3689 matched +'exp'+.
3691 If +'subSpec'+ contains a +{backslash}n+, where +'n'+ is a digit
3692 between 1 and 9, then it is replaced in the substitution with
3693 the portion of +'string'+ that matched the +'n'+\'-th
3694 parenthesized subexpression of +'exp'+.
3695 Additional backslashes may be used in +'subSpec'+ to prevent special
3696 interpretation of +&+ or +{backslash}0+ or +{backslash}n+ or
3697 backslash.
3699 The use of backslashes in +'subSpec'+ tends to interact badly
3700 with the Tcl parser's use of backslashes, so it's generally
3701 safest to enclose +'subSpec'+ in braces if it includes
3702 backslashes.
3704 The following switches modify the behaviour of +'regsub'+
3706 +*-nocase*+::
3707     Upper-case characters in +'string'+ are converted to lower-case
3708     before matching against +'exp'+;  however, substitutions
3709     specified by +'subSpec'+ use the original unconverted form
3710     of +'string'+.
3712 +*-all*+::
3713     All ranges in +'string'+ that match +'exp'+ are found and substitution
3714     is performed for each of these ranges, rather than only the
3715     first. The +&+ and +{backslash}n+ sequences are handled for
3716     each substitution using the information from the corresponding
3717     match.
3719 +*-line*+::
3720     Use newline-sensitive matching. By default, newline
3721     is a completely ordinary character with no special meaning in
3722     either REs or strings.  With this flag, +[^+ bracket expressions
3723     and +.+ never match newline, an +^+ anchor matches the null
3724     string after any newline in the string in addition to its normal
3725     function, and the +$+ anchor matches the null string before any
3726     newline in the string in addition to its normal function.
3728 +*-start* 'offset'+::
3729     Specifies a character index offset into the string at which to
3730     start matching the regular expression. +'offset'+ will be
3731     constrained to the bounds of the input string.
3733 +*--*+::
3734     Marks the end of switches. The argument following this one will be
3735     treated as +'exp'+ even if it starts with a +-+.
3739 +*ref* 'string tag ?finalizer?'+
3741 Create a new reference containing +'string'+ of type +'tag'+.
3742 If +'finalizer'+ is specified, it is a command which will be invoked
3743 when the a garbage collection cycle runs and this reference is
3744 no longer accessible.
3746 The finalizer is invoked as:
3748 ----
3749     finalizer reference string
3750 ----
3752 See <<_garbage_collection_references_lambda_function,GARBAGE COLLECTION>> for more detail.
3754 rename
3755 ~~~~~~
3756 +*rename* 'oldName newName'+
3758 Rename the command that used to be called +'oldName'+ so that it
3759 is now called +'newName'+.  If +'newName'+ is an empty string
3760 (e.g. {}) then +'oldName'+ is deleted.  The `rename` command
3761 returns an empty string as result.
3763 return
3764 ~~~~~~
3765 +*return* ?*-code* 'code'? ?*-errorinfo* 'stacktrace'? ?*-errorcode* 'errorcode'? ?*-level* 'n'? ?'value'?+
3767 Return immediately from the current procedure (or top-level command
3768 or `source` command), with +'value'+ as the return value.  If +'value'+
3769 is not specified, an empty string will be returned as result.
3771 If +-code+ is specified (as either a number or ok, error, break,
3772 continue, signal, return or exit), this code will be used instead
3773 of +JIM_OK+. This is generally useful when implementing flow of control
3774 commands.
3776 If +-level+ is specified and greater than 1, it has the effect of delaying
3777 the new return code from +-code+. This is useful when rethrowing an error
3778 from `catch`. See the implementation of try/catch in tclcompat.tcl for
3779 an example of how this is done.
3781 Note: The following options are only used when +-code+ is JIM_ERR.
3783 If +-errorinfo+ is specified (as returned from `info stacktrace`)
3784 it is used to initialize the stacktrace.
3786 If +-errorcode+ is specified, it is used to set the global variable $::errorCode.
3788 scan
3789 ~~~~
3790 +*scan* 'string format varName1 ?varName2 \...?'+
3792 This command parses fields from an input string in the same fashion
3793 as the C 'sscanf' procedure.  +'string'+ gives the input to be parsed
3794 and +'format'+ indicates how to parse it, using '%' fields as in
3795 'sscanf'.  All of the 'sscanf' options are valid; see the 'sscanf'
3796 man page for details.  Each +'varName'+ gives the name of a variable;
3797 when a field is scanned from +'string'+, the result is converted back
3798 into a string and assigned to the corresponding +'varName'+.  The
3799 only unusual conversion is for '%c'.  For '%c' conversions a single
3800 character value is converted to a decimal string, which is then
3801 assigned to the corresponding +'varName'+; no field width may be
3802 specified for this conversion.
3804 seek
3805 ~~~~
3806 +*seek* 'fileId offset ?origin?'+
3808 +'fileId' *seek* 'offset ?origin?'+
3810 Change the current access position for +'fileId'+.
3811 The +'offset'+ and +'origin'+ arguments specify the position at
3812 which the next read or write will occur for +'fileId'+.
3813 +'offset'+ must be a number (which may be negative) and +'origin'+
3814 must be one of the following:
3816 +*start*+::
3817     The new access position will be +'offset'+ bytes from the start
3818     of the file.
3820 +*current*+::
3821     The new access position will be +'offset'+ bytes from the current
3822     access position; a negative +'offset'+ moves the access position
3823     backwards in the file.
3825 +*end*+::
3826     The new access position will be +'offset'+ bytes from the end of
3827     the file.  A negative +'offset'+ places the access position before
3828     the end-of-file, and a positive +'offset'+ places the access position
3829     after the end-of-file.
3831 The +'origin'+ argument defaults to +start+.
3833 +'fileId'+ must have been the return value from a previous call to
3834 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
3835 of the standard I/O channels.
3837 This command returns an empty string.
3841 +*set* 'varName ?value?'+
3843 Returns the value of variable +'varName'+.
3845 If +'value'+ is specified, then set the value of +'varName'+ to +'value'+,
3846 creating a new variable if one doesn't already exist, and return
3847 its value.
3849 If +'varName'+ contains an open parenthesis and ends with a
3850 close parenthesis, then it refers to an array element:  the characters
3851 before the open parenthesis are the name of the array, and the characters
3852 between the parentheses are the index within the array.
3853 Otherwise +'varName'+ refers to a scalar variable.
3855 If no procedure is active, then +'varName'+ refers to a global
3856 variable.
3858 If a procedure is active, then +'varName'+ refers to a parameter
3859 or local variable of the procedure, unless the +'global'+ command
3860 has been invoked to declare +'varName'+ to be global.
3862 The +::+ prefix may also be used to explicitly reference a variable
3863 in the global scope.
3865 setref
3866 ~~~~~~
3867 +*setref* 'reference string'+
3869 Store a new string in +'reference'+, replacing the existing string.
3870 The reference must be a valid reference create with the `ref`
3871 command.
3873 See <<_garbage_collection_references_lambda_function,GARBAGE COLLECTION>> for more detail.
3875 signal
3876 ~~~~~~
3877 Command for signal handling.
3879 See `kill` for the different forms which may be used to specify signals.
3881 Commands which return a list of signal names do so using the canonical form:
3882 "+SIGINT SIGTERM+".
3884 +*signal handle* ?'signals \...'?+::
3885     If no signals are given, returns a list of all signals which are currently
3886     being handled.
3887     If signals are specified, these are added to the list of signals currently
3888     being handled.
3890 +*signal ignore* ?'signals \...'?+::
3891     If no signals are given, returns a lists all signals which are currently
3892     being ignored.
3893     If signals are specified, these are added to the list of signals
3894     currently being ignored. These signals are still delivered, but
3895     are not considered by `catch -signal` or `try -signal`. Use
3896     `signal check` to determine which signals have occurred but
3897     been ignored.
3899 +*signal block* ?'signals \...'?+::
3900     If no signals are given, returns a lists all signals which are currently
3901     being blocked.
3902     If signals are specified, these are added to the list of signals
3903     currently being blocked. These signals are not delivered to the process.
3904     This can be useful for signals such as +SIGPIPE+, especially in conjunction
3905     with `exec` as child processes inherit the parent's signal disposition.
3907 +*signal default* ?'signals \...'?+::
3908     If no signals are given, returns a lists all signals which currently have
3909     the default behaviour.
3910     If signals are specified, these are added to the list of signals which have
3911     the default behaviour.
3913 +*signal check ?-clear?* ?'signals \...'?+::
3914     Returns a list of signals which have been delivered to the process
3915     but are 'ignored'. If signals are specified, only that set of signals will
3916     be checked, otherwise all signals will be checked.
3917     If +-clear+ is specified, any signals returned are removed and will not be
3918     returned by subsequent calls to `signal check` unless delivered again.
3920 +*signal throw* ?'signal'?+::
3921     Raises the given signal, which defaults to +SIGINT+ if not specified.
3922     The behaviour is identical to:
3924 ----
3925     kill signal [pid]
3926 ----
3928 Note that `signal handle` and `signal ignore` represent two forms of signal
3929 handling. `signal handle` is used in conjunction with `catch -signal` or `try -signal`
3930 to immediately abort execution when the signal is delivered. Alternatively, `signal ignore`
3931 is used in conjunction with `signal check` to handle signal synchronously. Consider the
3932 two examples below.
3934 Prevent a processing from taking too long
3936 ----
3937     signal handle SIGALRM
3938     alarm 20
3939     try -signal {
3940         .. possibly long running process ..
3941         alarm 0
3942     } on signal {sig} {
3943         puts stderr "Process took too long"
3944     }
3945 ----
3947 Handle SIGHUP to reconfigure:
3949 ----
3950     signal ignore SIGHUP
3951     while {1} {
3952         ... handle configuration/reconfiguration ...
3953         while {[signal check -clear SIGHUP] eq ""} {
3954             ... do processing ..
3955         }
3956         # Received SIGHUP, so reconfigure
3957     }
3958 ----
3960 Note: signal handling is currently not supported in child interpreters.
3961 In these interpreters, the signal command does not exist.
3963 sleep
3964 ~~~~~
3965 +*sleep* 'seconds'+
3967 Pauses for the given number of seconds, which may be a floating
3968 point value less than one to sleep for less than a second, or an
3969 integer to sleep for one or more seconds.
3971 source
3972 ~~~~~~
3973 +*source* 'fileName'+
3975 Read file +'fileName'+ and pass the contents to the Tcl interpreter
3976 as a sequence of commands to execute in the normal fashion.  The return
3977 value of `source` is the return value of the last command executed
3978 from the file.  If an error occurs in executing the contents of the
3979 file, then the `source` command will return that error.
3981 If a `return` command is invoked from within the file, the remainder of
3982 the file will be skipped and the `source` command will return
3983 normally with the result from the `return` command.
3985 split
3986 ~~~~~
3987 +*split* 'string ?splitChars?'+
3989 Returns a list created by splitting +'string'+ at each character
3990 that is in the +'splitChars'+ argument.
3992 Each element of the result list will consist of the
3993 characters from +'string'+ between instances of the
3994 characters in +'splitChars'+.
3996 Empty list elements will be generated if +'string'+ contains
3997 adjacent characters in +'splitChars'+, or if the first or last
3998 character of +'string'+ is in +'splitChars'+.
4000 If +'splitChars'+ is an empty string then each character of
4001 +'string'+ becomes a separate element of the result list.
4003 +'splitChars'+ defaults to the standard white-space characters.
4004 For example,
4006 ----
4007     split "comp.unix.misc" .
4008 ----
4010 returns +'"comp unix misc"'+ and
4012 ----
4013     split "Hello world" {}
4014 ----
4016 returns +'"H e l l o { } w o r l d"'+.
4018 stackdump
4019 ~~~~~~~~~
4021 +*stackdump* 'stacktrace'+
4023 Creates a human readable representation of a stack trace.
4025 stacktrace
4026 ~~~~~~~~~~
4028 +*stacktrace*+
4030 Returns a live stack trace as a list of +proc file line proc file line \...+.
4031 Iteratively uses `info frame` to create the stack trace. This stack trace is in the
4032 same form as produced by `catch` and `info stacktrace`
4034 See also `stackdump`.
4036 string
4037 ~~~~~~
4039 +*string* 'option arg ?arg \...?'+
4041 Perform one of several string operations, depending on +'option'+.
4042 The legal options (which may be abbreviated) are:
4044 +*string bytelength* 'string'+::
4045     Returns the length of the string in bytes. This will return
4046     the same value as `string length` if UTF-8 support is not enabled,
4047     or if the string is composed entirely of ASCII characters.
4048     See <<_utf_8_and_unicode,UTF-8 AND UNICODE>>.
4050 +*string byterange* 'string first last'+::
4051     Like `string range` except works on bytes rather than characters.
4052     These commands are identical if UTF-8 support is not enabled.
4054 +*string cat* '?string1 string2 \...?'+::
4055     Concatenates the given strings into a single string.
4057 +*string compare ?-nocase?* ?*-length* 'len? string1 string2'+::
4058     Perform a character-by-character comparison of strings +'string1'+ and
4059     +'string2'+ in the same way as the C 'strcmp' procedure.  Return
4060     -1, 0, or 1, depending on whether +'string1'+ is lexicographically
4061     less than, equal to, or greater than +'string2'+. If +-length+
4062     is specified, then only the first +'len'+ characters are used
4063     in the comparison.  If +'len'+ is negative, it is ignored.
4064     Performs a case-insensitive comparison if +-nocase+ is specified.
4066 +*string equal ?-nocase?* '?*-length* len?' 'string1 string2'+::
4067     Returns 1 if the strings are equal, or 0 otherwise. If +-length+
4068     is specified, then only the first +'len'+ characters are used
4069     in the comparison.  If +'len'+ is negative, it is ignored.
4070     Performs a case-insensitive comparison if +-nocase+ is specified.
4072 +*string first* 'string1 string2 ?firstIndex?'+::
4073     Search +'string2'+ for a sequence of characters that exactly match
4074     the characters in +'string1'+.  If found, return the index of the
4075     first character in the first such match within +'string2'+.  If not
4076     found, return -1. If +'firstIndex'+ is specified, matching will start
4077     from +'firstIndex'+ of +'string1'+.
4078  ::
4079     See <<_string_and_list_index_specifications,STRING AND LIST INDEX SPECIFICATIONS>> for all allowed forms for +'firstIndex'+.
4081 +*string index* 'string charIndex'+::
4082     Returns the +'charIndex'+'th character of the +'string'+
4083     argument.  A +'charIndex'+ of 0 corresponds to the first
4084     character of the string.
4085     If +'charIndex'+ is less than 0 or greater than
4086     or equal to the length of the string then an empty string is
4087     returned.
4088  ::
4089     See <<_string_and_list_index_specifications,STRING AND LIST INDEX SPECIFICATIONS>> for all allowed forms for +'charIndex'+.
4091 +*string is* 'class' ?*-strict*? 'string'+::
4092     Returns 1 if +'string'+ is a valid member of the specified character
4093     class, otherwise returns 0. If +-strict+ is specified, then an
4094     empty string returns 0, otherwise an empty string will return 1
4095     on any class. The following character classes are recognized
4096     (the class name can be abbreviated):
4097   ::
4098   +alnum+;;  Any alphabet or digit character.
4099   +alpha+;;  Any alphabet character.
4100   +ascii+;;  Any character with a value less than 128 (those that are in the 7-bit ascii range).
4101   +boolean+;;  Any of the valid string formats for a boolean value in Tcl (0, false, no, off, 1, true, yes, on)
4102   +control+;; Any control character.
4103   +digit+;;  Any digit character.
4104   +double+;; Any of the valid forms for a double in Tcl, with optional surrounding whitespace.
4105              In case of under/overflow in the value, 0 is returned.
4106   +graph+;;  Any printing character, except space.
4107   +integer+;; Any of the valid string formats for an integer value in Tcl, with optional surrounding whitespace.
4108   +lower+;;  Any lower case alphabet character.
4109   +print+;;  Any printing character, including space.
4110   +punct+;;  Any punctuation character.
4111   +space+;;  Any space character.
4112   +upper+;;  Any upper case alphabet character.
4113   +xdigit+;; Any hexadecimal digit character ([0-9A-Fa-f]).
4114  ::
4115     Note that string classification does +'not'+ respect UTF-8. See <<_utf_8_and_unicode,UTF-8 AND UNICODE>>.
4116  ::
4117     Note that only +'lowercase'+ boolean values are recognized (Tcl accepts any case).
4119 +*string last* 'string1 string2 ?lastIndex?'+::
4120     Search +'string2'+ for a sequence of characters that exactly match
4121     the characters in +'string1'+.  If found, return the index of the
4122     first character in the last such match within +'string2'+.  If there
4123     is no match, then return -1. If +'lastIndex'+ is specified, only characters
4124     up to +'lastIndex'+ of +'string2'+ will be considered in the match.
4125  ::
4126     See <<_string_and_list_index_specifications,STRING AND LIST INDEX SPECIFICATIONS>> for all allowed forms for +'lastIndex'+.
4128 +*string length* 'string'+::
4129     Returns a decimal string giving the number of characters in +'string'+.
4130     If UTF-8 support is enabled, this may be different than the number of bytes.
4131     See <<_utf_8_and_unicode,UTF-8 AND UNICODE>>.
4133 +*string map ?-nocase?* 'mapping string'+::
4134     Replaces substrings in +'string'+ based on the key-value pairs in
4135     +'mapping'+, which is a list of +key value key value \...+ as in the form
4136     returned by `array get`. Each instance of a key in the string will be
4137     replaced with its corresponding value.  If +-nocase+ is specified, then
4138     matching is done without regard to case differences. Both key and value may
4139     be multiple characters.  Replacement is done in an ordered manner, so the
4140     key appearing first in the list will be checked first, and so on. +'string'+ is
4141     only iterated over once, so earlier key replacements will have no affect for
4142     later key matches. For example,
4144 ----
4145       string map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc
4146 ----
4148  ::
4149     will return the string +01321221+.
4150  ::
4151     Note that if an earlier key is a prefix of a later one, it will completely mask the later
4152     one.  So if the previous example is reordered like this,
4154 ----
4155       string map {1 0 ab 2 a 3 abc 1} 1abcaababcabababc
4156 ----
4158  ::
4159     it will return the string +02c322c222c+.
4161 +*string match ?-nocase?* 'pattern string'+::
4162     See if +'pattern'+ matches +'string'+ according to
4163     <<_string_matching,STRING MATCHING>> rules
4164     ; return 1 if it does, 0
4165     if it doesn't. The match is performed in a case-insensitive manner if +-nocase+ is specified.
4167 +*string range* 'string first last'+::
4168     Returns a range of consecutive characters from +'string'+, starting
4169     with the character whose index is +'first'+ and ending with the
4170     character whose index is +'last'+.  An index of 0 refers to the
4171     first character of the string.
4172  ::
4173     See <<_string_and_list_index_specifications,STRING AND LIST INDEX SPECIFICATIONS>> for all allowed forms for +'first'+ and +'last'+.
4174  ::
4175     If +'first'+ is less than zero then it is treated as if it were zero, and
4176     if +'last'+ is greater than or equal to the length of the string then
4177     it is treated as if it were +end+.  If +'first'+ is greater than
4178     +'last'+ then an empty string is returned.
4180 +*string repeat* 'string count'+::
4181     Returns a new string consisting of +'string'+ repeated +'count'+ times.
4183 +*string replace* 'string first last ?newstring?'+::
4184     Removes a range of consecutive characters from +'string'+, starting
4185     with the character whose index is +'first'+ and ending with the
4186     character whose index is +'last'+.  If +'newstring'+ is specified,
4187     then it is placed in the removed character range. If +'first'+ is
4188     less than zero then it is treated as if it were zero, and if +'last'+
4189     is greater than or equal to the length of the string then it is
4190     treated as if it were +end+. If +'first'+ is greater than +'last'+
4191     or the length of the initial string, or +'last'+ is less than 0,
4192     then the initial string is returned untouched.
4194 +*string reverse* 'string'+::
4195     Returns a string that is the same length as +'string'+ but
4196     with its characters in the reverse order.
4198 +*string tolower* 'string'+::
4199     Returns a value equal to +'string'+ except that all upper case
4200     letters have been converted to lower case.
4202 +*string totitle* 'string'+::
4203     Returns a value equal to +'string'+ except that the first character
4204     is converted to title case (or upper case if there is no UTF-8 titlecase variant)
4205     and all remaining characters have been converted to lower case.
4207 +*string toupper* 'string'+::
4208     Returns a value equal to +'string'+ except that all lower case
4209     letters have been converted to upper case.
4211 +*string trim* 'string ?chars?'+::
4212     Returns a value equal to +'string'+ except that any leading
4213     or trailing characters from the set given by +'chars'+ are
4214     removed.
4215     If +'chars'+ is not specified then white space is removed
4216     (spaces, tabs, newlines, and carriage returns).
4218 +*string trimleft* 'string ?chars?'+::
4219     Returns a value equal to +'string'+ except that any
4220     leading characters from the set given by +'chars'+ are
4221     removed.
4222     If +'chars'+ is not specified then white space is removed
4223     (spaces, tabs, newlines, and carriage returns).
4225 +*string trimright* 'string ?chars?'+::
4226     Returns a value equal to +'string'+ except that any
4227     trailing characters from the set given by +'chars'+ are
4228     removed.
4229     If +'chars'+ is not specified then white space is removed
4230     (spaces, tabs, newlines, and carriage returns).
4231     Null characters are always removed.
4233 subst
4234 ~~~~~
4235 +*subst ?-nobackslashes? ?-nocommands? ?-novariables?* 'string'+
4237 This command performs variable substitutions, command substitutions,
4238 and backslash substitutions on its string argument and returns the
4239 fully-substituted result. The substitutions are performed in exactly
4240 the same way as for Tcl commands. As a result, the string argument
4241 is actually substituted twice, once by the Tcl parser in the usual
4242 fashion for Tcl commands, and again by the subst command.
4244 If any of the +-nobackslashes+, +-nocommands+, or +-novariables+ are
4245 specified, then the corresponding substitutions are not performed.
4246 For example, if +-nocommands+ is specified, no command substitution
4247 is performed: open and close brackets are treated as ordinary
4248 characters with no special interpretation.
4250 *Note*: when it performs its substitutions, subst does not give any
4251 special treatment to double quotes or curly braces. For example,
4252 the following script returns +xyz \{44\}+, not +xyz \{$a\}+.
4254 ----
4255     set a 44
4256     subst {xyz {$a}}
4257 ----
4260 switch
4261 ~~~~~~
4262 +*switch* '?options? string pattern body ?pattern body \...?'+
4264 +*switch* '?options? string {pattern body ?pattern body \...?}'+
4266 The `switch` command matches its string argument against each of
4267 the pattern arguments in order. As soon as it finds a pattern that
4268 matches string it evaluates the following body and returns the
4269 result of that evaluation. If the last pattern argument is default
4270 then it matches anything. If no pattern argument matches string and
4271 no default is given, then the `switch` command returns an empty string.
4272 If the initial arguments to switch start with - then they are treated
4273 as options. The following options are currently supported:
4275     +-exact+::
4276         Use exact matching when comparing string to a
4277         pattern. This is the default.
4279     +-glob+::
4280         When matching string to the patterns, use glob-style
4281         <<_string_matching,STRING MATCHING>> rules.
4283     +-regexp+::
4284         When matching string to the patterns, use
4285         <<_regular_expressions,REGULAR EXPRESSIONS>> rules.
4287     +-command 'commandname'+::
4288         When matching string to the patterns, use the given command, which
4289         must be a single word. The command is invoked as
4290         'commandname pattern string', or 'commandname -nocase pattern string'
4291         and must return 1 if matched, or 0 if not.
4293     +--+::
4294         Marks the end of options. The argument following
4295         this one will be treated as string even if it starts
4296         with a +-+.
4298 Two syntaxes are provided for the pattern and body arguments. The
4299 first uses a separate argument for each of the patterns and commands;
4300 this form is convenient if substitutions are desired on some of the
4301 patterns or commands. The second form places all of the patterns
4302 and commands together into a single argument; the argument must
4303 have proper list structure, with the elements of the list being the
4304 patterns and commands. The second form makes it easy to construct
4305 multi-line `switch` commands, since the braces around the whole list
4306 make it unnecessary to include a backslash at the end of each line.
4307 Since the pattern arguments are in braces in the second form, no
4308 command or variable substitutions are performed on them; this makes
4309 the behaviour of the second form different than the first form in
4310 some cases.
4312 If a body is specified as +-+ it means that the body for the next
4313 pattern should also be used as the body for this pattern (if the
4314 next pattern also has a body of +-+ then the body after that is
4315 used, and so on). This feature makes it possible to share a single
4316 body among several patterns.
4318 Below are some examples of `switch` commands:
4320 ----
4321     switch abc a - b {format 1} abc {format 2} default {format 3}
4322 ----
4324 will return 2,
4326 ----
4327     switch -regexp aaab {
4328            ^a.*b$ -
4329            b {format 1}
4330            a* {format 2}
4331            default {format 3}
4332     }
4333 ----
4335 will return 1, and
4337 ----
4338     switch xyz {
4339            a -
4340            b {format 1}
4341            a* {format 2}
4342            default {format 3}
4343     }
4344 ----
4346 will return 3.
4348 tailcall
4349 ~~~~~~~~
4350 +*tailcall* 'cmd ?arg\...?'+
4352 The `tailcall` command provides an optimised way of invoking a command whilst replacing
4353 the current call frame. This is similar to 'exec' in Bourne Shell.
4355 The following are identical except the first immediately replaces the current call frame.
4357 ----
4358   tailcall a b c
4359 ----
4361 ----
4362   return [uplevel 1 [list a b c]]
4363 ----
4365 `tailcall` is useful as a dispatch mechanism:
4367 ----
4368   proc a {cmd args} {
4369     tailcall sub_$cmd {*}$args
4370   }
4371   proc sub_cmd1 ...
4372   proc sub_cmd2 ...
4373 ----
4375 tell
4376 ~~~~
4377 +*tell* 'fileId'+
4379 +'fileId' *tell*+
4381 Returns a decimal string giving the current access position in
4382 +'fileId'+.
4384 +'fileId'+ must have been the return value from a previous call to
4385 `open`, or it may be +stdin+, +stdout+, or +stderr+ to refer to one
4386 of the standard I/O channels.
4388 throw
4389 ~~~~~
4390 +*throw* 'code ?msg?'+
4392 This command throws an exception (return) code along with an optional message.
4393 This command is mostly for convenient usage with `try`.
4395 The command +throw break+ is equivalent to +break+.
4396 The command +throw 20 message+ can be caught with an +on 20 \...+ clause to `try`.
4398 time
4399 ~~~~
4400 +*time* 'command ?count?'+
4402 This command will call the Tcl interpreter +'count'+
4403 times to execute +'command'+ (or once if +'count'+ isn't
4404 specified).  It will then return a string of the form
4406 ----
4407     503 microseconds per iteration
4408 ----
4410 which indicates the average amount of time required per iteration,
4411 in microseconds.
4413 Time is measured in elapsed time, not CPU time.
4417 +*try* '?catchopts? tryscript' ?*on* 'returncodes {?resultvar? ?optsvar?} handlerscript \...'? ?*finally* 'finalscript'?+
4419 The `try` command is provided as a convenience for exception handling.
4421 This interpeter first evaluates +'tryscript'+ under the effect of the catch
4422 options +'catchopts'+ (e.g. +-signal -noexit --+, see `catch`).
4424 It then evaluates the script for the first matching 'on' handler
4425 (there many be zero or more) based on the return code from the `try`
4426 section. For example a normal +JIM_ERR+ error will be matched by
4427 an 'on error' handler.
4429 Finally, any +'finalscript'+ is evaluated.
4431 The result of this command is the result of +'tryscript'+, except in the
4432 case where an exception occurs in a matching 'on' handler script or the 'finally' script,
4433 in which case the result is this new exception.
4435 The specified +'returncodes'+ is a list of return codes either as names ('ok', 'error', 'break', etc.)
4436 or as integers.
4438 If +'resultvar'+ and +'optsvar'+ are specified, they are set as for `catch` before evaluating
4439 the matching handler.
4441 For example:
4443 ----
4444     set f [open input]
4445     try -signal {
4446         process $f
4447     } on {continue break} {} {
4448         error "Unexpected break/continue"
4449     } on error {msg opts} {
4450         puts "Dealing with error"
4451         return {*}$opts $msg
4452     } on signal sig {
4453         puts "Got signal: $sig"
4454     } finally {
4455         $f close
4456     }
4457 ----
4459 If break, continue or error are raised, they are dealt with by the matching
4460 handler.
4462 In any case, the file will be closed via the 'finally' clause.
4464 See also `throw`, `catch`, `return`, `error`.
4466 unknown
4467 ~~~~~~~
4468 +*unknown* 'cmdName ?arg arg ...?'+
4470 This command doesn't actually exist as part of Tcl, but Tcl will
4471 invoke it if it does exist.
4473 If the Tcl interpreter encounters a command name for which there
4474 is not a defined command, then Tcl checks for the existence of
4475 a command named `unknown`.
4477 If there is no such command, then the interpreter returns an
4478 error.
4480 If the `unknown` command exists, then it is invoked with
4481 arguments consisting of the fully-substituted name and arguments
4482 for the original non-existent command.
4484 The `unknown` command typically does things like searching
4485 through library directories for a command procedure with the name
4486 +'cmdName'+, or expanding abbreviated command names to full-length,
4487 or automatically executing unknown commands as UNIX sub-processes.
4489 In some cases (such as expanding abbreviations) `unknown` will
4490 change the original command slightly and then (re-)execute it.
4491 The result of the `unknown` command is used as the result for
4492 the original non-existent command.
4494 unset
4495 ~~~~~
4496 +*unset ?-nocomplain? ?--?* '?name name ...?'+
4498 Remove variables.
4499 Each +'name'+ is a variable name, specified in any of the
4500 ways acceptable to the `set` command.
4502 If a +'name'+ refers to an element of an array, then that
4503 element is removed without affecting the rest of the array.
4505 If a +'name'+ consists of an array name with no parenthesized
4506 index, then the entire array is deleted.
4508 The `unset` command returns an empty string as result.
4510 An error occurs if any of the variables doesn't exist, unless '-nocomplain'
4511 is specified. The '--' argument may be specified to stop option processing
4512 in case the variable name may be '-nocomplain'.
4514 upcall
4515 ~~~~~~~
4516 +*upcall* 'command ?args ...?'+
4518 May be used from within a proc defined as `local` `proc` in order to call
4519 the previous, hidden version of the same command.
4521 If there is no previous definition of the command, an error is returned.
4523 uplevel
4524 ~~~~~~~
4525 +*uplevel* '?level? command ?command ...?'+
4527 All of the +'command'+ arguments are concatenated as if they had
4528 been passed to `concat`; the result is then evaluated in the
4529 variable context indicated by +'level'+.  `uplevel` returns
4530 the result of that evaluation.  If +'level'+ is an integer, then
4531 it gives a distance (up the procedure calling stack) to move before
4532 executing the command.  If +'level'+ consists of +\#+ followed by
4533 a number then the number gives an absolute level number.  If +'level'+
4534 is omitted then it defaults to +1+.  +'level'+ cannot be
4535 defaulted if the first +'command'+ argument starts with a digit or +#+.
4537 For example, suppose that procedure 'a' was invoked
4538 from top-level, and that it called 'b', and that 'b' called 'c'.
4539 Suppose that 'c' invokes the `uplevel` command.  If +'level'+
4540 is +1+ or +#2+  or omitted, then the command will be executed
4541 in the variable context of 'b'.  If +'level'+ is +2+ or +#1+
4542 then the command will be executed in the variable context of 'a'.
4544 If +'level'+ is '3' or +#0+ then the command will be executed
4545 at top-level (only global variables will be visible).
4546 The `uplevel` command causes the invoking procedure to disappear
4547 from the procedure calling stack while the command is being executed.
4548 In the above example, suppose 'c' invokes the command
4550 ----
4551     uplevel 1 {set x 43; d}
4552 ----
4554 where 'd' is another Tcl procedure.  The `set` command will
4555 modify the variable 'x' in 'b's context, and 'd' will execute
4556 at level 3, as if called from 'b'.  If it in turn executes
4557 the command
4559 ----
4560     uplevel {set x 42}
4561 ----
4563 then the `set` command will modify the same variable 'x' in 'b's
4564 context:  the procedure 'c' does not appear to be on the call stack
4565 when 'd' is executing.  The command `info level` may
4566 be used to obtain the level of the current procedure.
4568 `uplevel` makes it possible to implement new control
4569 constructs as Tcl procedures (for example, `uplevel` could
4570 be used to implement the `while` construct as a Tcl procedure).
4572 upvar
4573 ~~~~~
4574 +*upvar* '?level? otherVar myVar ?otherVar myVar ...?'+
4576 This command arranges for one or more local variables in the current
4577 procedure to refer to variables in an enclosing procedure call or
4578 to global variables.
4580 +'level'+ may have any of the forms permitted for the `uplevel`
4581 command, and may be omitted if the first letter of the first +'otherVar'+
4582 isn't +#+ or a digit (it defaults to '1').
4584 For each +'otherVar'+ argument, `upvar` makes the variable
4585 by that name in the procedure frame given by +'level'+ (or at
4586 global level, if +'level'+ is +#0+) accessible
4587 in the current procedure by the name given in the corresponding
4588 +'myVar'+ argument.
4590 The variable named by +'otherVar'+ need not exist at the time of the
4591 call;  it will be created the first time +'myVar'+ is referenced, just like
4592 an ordinary variable.
4594 `upvar` may only be invoked from within procedures.
4596 `upvar` returns an empty string.
4598 The `upvar` command simplifies the implementation of call-by-name
4599 procedure calling and also makes it easier to build new control constructs
4600 as Tcl procedures.
4601 For example, consider the following procedure:
4603 ----
4604     proc add2 name {
4605         upvar $name x
4606         set x [expr $x+2]
4607     }
4608 ----
4610 'add2' is invoked with an argument giving the name of a variable,
4611 and it adds two to the value of that variable.
4612 Although 'add2' could have been implemented using `uplevel`
4613 instead of `upvar`, `upvar` makes it simpler for 'add2'
4614 to access the variable in the caller's procedure frame.
4616 wait
4617 ~~~~
4618 +*wait*+
4620 +*wait -nohang* 'pid'+
4622 With no arguments, cleans up any processes started by `exec ... &` that have completed
4623 (reaps zombie processes).
4625 With one or two arguments, waits for a process by id, either returned by `exec ... &`
4626 or by `os.fork` (if supported).
4628 Waits for the process to complete, unless +-nohang+ is specified, in which case returns
4629 immediately if the process is still running.
4631 Returns a list of 3 elements.
4633 +{NONE x x}+ if the process does not exist or has already been waited for, or
4634 if -nohang is specified, and the process is still alive.
4636 +{CHILDSTATUS <pid> <exit-status>}+ if the process exited normally.
4638 +{CHILDKILLED <pid> <signal>}+ if the process terminated on a signal.
4640 +{CHILDSUSP <pid> none}+ if the process terminated for some other reason.
4642 Note that on platforms supporting waitpid(2), +pid+ can also be given special values such
4643 as 0 or -1. See waitpid(2) for more detail.
4645 while
4646 ~~~~~
4647 +*while* 'test body'+
4649 The +'while'+ command evaluates +'test'+ as an expression
4650 (in the same way that `expr` evaluates its argument).
4651 The value of the expression must be numeric; if it is non-zero
4652 then +'body'+ is executed by passing it to the Tcl interpreter.
4654 Once +'body'+ has been executed then +'test'+ is evaluated
4655 again, and the process repeats until eventually +'test'+
4656 evaluates to a zero numeric value.  `continue`
4657 commands may be executed inside +'body'+ to terminate the current
4658 iteration of the loop, and `break`
4659 commands may be executed inside +'body'+ to cause immediate
4660 termination of the `while` command.
4662 The `while` command always returns an empty string.
4664 OPTIONAL-EXTENSIONS
4665 -------------------
4667 The following extensions may or may not be available depending upon
4668 what options were selected when Jim Tcl was built.
4671 [[cmd_1]]
4672 posix: os.fork, os.gethostname, os.getids, os.uptime
4673 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4674 +*os.fork*+::
4675     Invokes 'fork(2)' and returns the result.
4677 +*os.gethostname*+::
4678     Invokes 'gethostname(3)' and returns the result.
4680 +*os.getids*+::
4681     Returns the various user/group ids for the current process.
4683 ----
4684     . os.getids
4685     uid 1000 euid 1000 gid 100 egid 100
4686 ----
4688 +*os.uptime*+::
4689     Returns the number of seconds since system boot. See description of 'uptime' in 'sysinfo(2)'.
4691 ANSI I/O (aio) and EVENTLOOP API
4692 --------------------------------
4693 Jim provides an alternative object-based API for I/O.
4695 See `open` and `socket` for commands which return an I/O handle.
4699 +$handle *accept* ?addrvar?+::
4700     Server socket only: Accept a connection and return stream.
4701     If +'addrvar'+ is specified, the address of the connected client is stored
4702     in the named variable in the form 'addr:port' for IP sockets or 'path' for Unix domain sockets.
4703     See `socket` for details.
4705 +$handle *buffering none|line|full*+::
4706     Sets the buffering mode of the stream.
4708 +$handle *close ?r(ead)|w(rite)|-nodelete?*+::
4709     Closes the stream.
4710     The +'read'+ and +'write'+ arguments perform a "half-close" on a socket. See the 'shutdown(2)' man page.
4711     The +'-nodelete'+ option is applicable only for Unix domain sockets. It closes the socket
4712     but does not delete the bound path (e.g. after `os.fork`).
4715 +$handle *copyto* 'tofd ?size?'+::
4716     Copy bytes to the file descriptor +'tofd'+. If +'size'+ is specified, at most
4717     that many bytes will be copied. Otherwise copying continues until the end
4718     of the input file. Returns the number of bytes actually copied.
4720 +$handle *eof*+::
4721     Returns 1 if stream is at eof
4723 +$handle *filename*+::
4724     Returns the original filename associated with the handle.
4725     Handles returned by `socket` give the socket type instead of a filename.
4727 +$handle *flush*+::
4728     Flush the stream
4730 +$handle *gets* '?var?'+::
4731     Read one line and return it or store it in the var
4733 +$handle *isatty*+::
4734     Returns 1 if the stream is a tty device.
4736 +$handle *lock ?-wait?*+::
4737     Apply a POSIX lock to the open file associated with the handle using
4738     'fcntl(F_SETLK)', or 'fcntl(F_SETLKW)' to wait for the lock to be available if +'-wait'+
4739     is specified.
4740     The handle must be open for write access.
4741     Returns 1 if the lock was successfully obtained, 0 otherwise.
4742     An error occurs if the handle is not suitable for locking (e.g.
4743     if it is not open for write)
4745 +$handle *ndelay ?0|1?*+::
4746     Set O_NDELAY (if arg). Returns current/new setting.
4747     Note that in general ANSI I/O interacts badly with non-blocking I/O.
4748     Use with care.
4750 +$handle *peername*+::
4751     Returns the remote address or path of the connected socket. See 'getpeername(2)'.
4753 +$handle *puts ?-nonewline?* 'str'+::
4754     Write the string, with newline unless -nonewline
4756 +$handle *read ?-nonewline?* '?len?'+::
4757     Read and return bytes from the stream. To eof if no len.
4759 +$handle *recvfrom* 'maxlen ?addrvar?'+::
4760     Receives a message from the handle via recvfrom(2) and returns it.
4761     At most +'maxlen'+ bytes are read. If +'addrvar'+ is specified, the sending address
4762     of the message is stored in the named variable in the form 'addr:port' for IP sockets
4763     or 'path' for Unix domain sockets. See `socket` for details.
4765 +$handle *seek* 'offset' *?start|current|end?*+::
4766     Seeks in the stream (default 'current')
4768 +$handle *sendto* 'str ?address'+::
4769     Sends the string, +'str'+, to the given address (host:port or path) via the socket using 'sendto(2)'.
4770     This is intended for udp/dgram sockets and may give an error or behave in unintended
4771     ways for other handle types.
4772     Returns the number of bytes written.
4774 +$handle *sockname*+::
4775     Returns the bound address or path of the socket. See 'getsockname(2)'.
4777 +$handle *sockopt* '?name value?'+::
4778     With no arguments, returns a dictionary of socket options currently set for the handle
4779     (will be empty for a non-socket). With +'name'+ and +'value'+, sets the socket option
4780     to the given value. Currently supports the following boolean socket options:
4781     +broadcast, debug, keepalive, nosigpipe, oobinline, tcp_nodelay+, and the following
4782     integer socket options: +sndbuf, rcvbuf+
4784 +$handle *sync*+::
4785     Flush the stream, then 'fsync(2)' to commit any changes to storage.
4786     Only available on platforms that support 'fsync(2)'.
4788 +$handle *tell*+::
4789     Returns the current seek position
4791 +$handle *tty* ?settings?+::
4792     If no arguments are given, returns a dictionary containing the tty settings for the stream.
4793     If arguments are given, they must either be a dictionary, or +setting value \...+
4794     Abbreviations are supported for both settings and values, so the following is acceptable:
4795     +$f tty parity e input c out raw+.
4796     Only available on platforms that support 'termios(3)'. Supported settings are:
4798     +*baud* 'rate'+;;
4799         Baud rate. e.g. 115200
4801     +*data 5|6|7|8*+;;
4802         Number of data bits
4804     +*stop 1|2*+;;
4805         Number of stop bits
4807     +*parity even|odd|none*+;;
4808         Parity setting
4810     +*handshake xonxoff|rtscts|none*+;;
4811         Handshaking type
4813     +*input raw|cooked*+;;
4814         Input character processing. In raw mode, the usual key sequences such as ^C do
4815         not generate signals.
4817     +*output raw|cooked*+;;
4818         Output character processing. Typically CR -> CRNL is disabled in raw mode.
4820     +*echo 0|1*+;;
4821         Disable or enable echo on input. Note that this is a set-only value.
4822         Setting +input+ to +raw+ or +cooked+ will overwrite this setting.
4824     +*vmin* 'numchars'+;;
4825         Minimum number of characters to read.
4827     +*vtime* 'time'+;;
4828         Timeout for noncanonical read (units of 0.1 seconds)
4830 +$handle *ssl* ?*-server* 'cert priv'?+::
4831     Upgrades the stream to a SSL/TLS session and returns the handle.
4833 +$handle *unlock*+::
4834     Release a POSIX lock previously acquired by `aio lock`.
4836 +$handle *verify*+::
4837     Verifies the certificate of a SSL/TLS stream peer
4839 +*load_ssl_certs* 'dir'+::
4840     Loads SSL/TLS CA certificates for use during verification
4842 fconfigure
4843 ~~~~~~~~~~
4844 +*fconfigure* 'handle' *?-blocking 0|1? ?-buffering noneline|full? ?-translation* 'mode'?+::
4845     For compatibility with Tcl, a limited form of the `fconfigure`
4846     command is supported.
4847     * `fconfigure ... -blocking` maps to `aio ndelay`
4848     * `fconfigure ... -buffering` maps to `aio buffering`
4849     * `fconfigure ... -translation` is accepted but ignored
4851 [[cmd_2]]
4852 eventloop: after, vwait, update
4853 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4855 The following commands allow a script to be invoked when the given condition occurs.
4856 If no script is given, returns the current script. If the given script is the empty, the
4857 handler is removed.
4859 +$handle *readable* '?readable-script?'+::
4860     Sets or returns the script for when the socket is readable.
4862 +$handle *writable* '?writable-script?'+::
4863     Sets or returns the script for when the socket is writable.
4865 +$handle *onexception* '?exception-script?'+::
4866     Sets or returns the script for when oob data received.
4868 For compatibility with 'Tcl', these may be prefixed with `fileevent`.  e.g.
4870  ::
4871     +fileevent $handle *readable* '\...'+
4873 Time-based execution is also available via the eventloop API.
4875 +*after* 'ms'+::
4876     Sleeps for the given number of milliseconds. No events are
4877     processed during this time.
4879 +*after* 'ms'|*idle* 'script ?script \...?'+::
4880     The scripts are concatenated and executed after the given
4881     number of milliseconds have elapsed.  If 'idle' is specified,
4882     the script will run the next time the event loop is processed
4883     with `vwait` or `update`. The script is only run once and
4884     then removed.  Returns an event id.
4886 +*after cancel* 'id|command'+::
4887     Cancels an `after` event with the given event id or matching
4888     command (script).  Returns the number of milliseconds
4889     remaining until the event would have fired.  Returns the
4890     empty string if no matching event is found.
4892 +*after info* '?id?'+::
4893     If +'id'+ is not given, returns a list of current `after`
4894     events.  If +'id'+ is given, returns a list containing the
4895     associated script and either 'timer' or 'idle' to indicated
4896     the type of the event. An error occurs if +'id'+ does not
4897     match an event.
4899 +*vwait* 'variable'+::
4900     A call to `vwait` enters the eventloop. `vwait` processes
4901     events until the named (global) variable changes or all
4902     event handlers are removed. The variable need not exist
4903     beforehand.  If there are no event handlers defined, `vwait`
4904     returns immediately.
4906 +*update ?idletasks?*+::
4907     A call to `update` enters the eventloop to process expired events, but
4908     no new events. If 'idletasks' is specified, only expired time events are handled,
4909     not file events.
4910     Returns once handlers have been run for all expired events.
4912 Scripts are executed at the global scope. If an error occurs during a handler script,
4913 an attempt is made to call (the user-defined command) `bgerror` with the details of the error.
4914 If the `bgerror` command does not exist, the error message details are printed to stderr instead.
4916 If a file event handler script generates an error, the handler is automatically removed
4917 to prevent infinite errors. (A time event handler is always removed after execution).
4919 +*bgerror* 'msg'+::
4920     Called when an event handler script generates an error. Note that the normal command resolution
4921     rules are used for bgerror. First the name is resolved in the current namespace, then in the
4922     global scope.
4924 socket
4925 ~~~~~~
4926 Various socket types may be created.
4928 +*socket unix* 'path'+::
4929     A unix domain socket client connected to 'path'
4931 +*socket unix.server* 'path'+::
4932     A unix domain socket server listening on 'path'
4934 +*socket unix.dgram* '?path?'+::
4935     A unix domain socket datagram client, optionally connected to 'path'
4937 +*socket unix.dgram.server* 'path'+::
4938     A unix domain socket datagram server server listening on 'path'
4940 +*socket ?-ipv6? stream* 'addr:port'+::
4941     A TCP socket client. (See the forms for +'addr'+ below)
4943 +*socket ?-ipv6? stream.server* '?addr:?port'+::
4944     A TCP socket server (+'addr'+ defaults to +0.0.0.0+ for IPv4 or +[::]+ for IPv6).
4946 +*socket ?-ipv6? dgram* ?'addr:port'?+::
4947     A UDP socket client. If the address is not specified,
4948     the client socket will be unbound and 'sendto' must be used
4949     to indicated the destination.
4951 +*socket ?-ipv6? dgram.server* 'addr:port'+::
4952     A UDP socket server.
4954 +*socket pipe*+::
4955     A synonym for `pipe`
4957 +*socket pair*+::
4958     A socketpair (see socketpair(2)). Like `pipe`, this command returns
4959     a list of two channels: {s1 s2}. These channels are both readable and writable.
4961 This command creates a socket connected (client) or bound (server) to the given
4962 address.
4964 The returned value is channel and may generally be used with the various file I/O
4965 commands (gets, puts, read, etc.), either as object-based syntax or Tcl-compatible syntax.
4967 ----
4968     . set f [socket stream www.google.com:80]
4969     aio.sockstream1
4970     . $f puts -nonewline "GET / HTTP/1.0\r\n\r\n"
4971     . $f gets
4972     HTTP/1.0 302 Found
4973     . $f close
4974 ----
4976 Server sockets, however support only 'accept', which is most useful in conjunction with
4977 the EVENTLOOP API.
4979 ----
4980     set f [socket stream.server 80]
4981     $f readable {
4982         set client [$f accept]
4983         $client gets $buf
4984         ...
4985         $client puts -nonewline "HTTP/1.1 404 Not found\r\n"
4986         $client close
4987     }
4988     vwait done
4989 ----
4991 The address, +'addr'+, can be given in one of the following forms:
4993 1. For IPv4 socket types, an IPv4 address such as 192.168.1.1
4994 2. For IPv6 socket types, an IPv6 address such as [fe80::1234] or [::]
4995 3. A hostname
4997 Note that on many systems, listening on an IPv6 address such as [::] will
4998 also accept requests via IPv4.
5000 Where a hostname is specified, the +'first'+ returned address is used
5001 which matches the socket type is used.
5003 An unconnected dgram socket (either 'dgram' or 'unix.dgram') must use
5004 `sendto` to specify the destination address.
5006 The path for Unix domain sockets is automatically removed when the socket
5007 is closed. Use `close -nodelete` in the rare case where this behaviour
5008 should be avoided (e.g. after `os.fork`).
5010 syslog
5011 ~~~~~~
5012 +*syslog* '?options? ?priority? message'+
5014 This  command sends message to system syslog facility with given
5015 priority. Valid priorities are:
5017     emerg, alert, crit, err, error, warning, notice, info, debug
5019 If a message is specified, but no priority is specified, then a
5020 priority of info is used.
5022 By default, facility user is used and the value of global tcl variable
5023 argv0 is used as ident string. However, any of the following options
5024 may be specified before priority to control these parameters:
5026 +*-facility* 'value'+::
5027     Use specified facility instead of user. The following
5028     values for facility are recognized:
5030     authpriv, cron, daemon, kernel, lpr, mail, news, syslog, user,
5031     uucp, local0-local7
5033 +*-ident* 'string'+::
5034     Use given string instead of argv0 variable for ident string.
5036 +*-options* 'integer'+::
5037     Set syslog options such as +LOG_CONS+, +LOG_NDELAY+. You should
5038     use numeric values of those from your system syslog.h file,
5039     because I haven't got time to implement yet another hash
5040     table.
5042 pack: pack, unpack
5043 ~~~~~~~~~~~~~~~~~~
5044 The optional 'pack' extension provides commands to encode and decode binary strings.
5046 +*pack* 'varName value' *-intle|-intbe|-floatle|-floatbe|-str* 'bitwidth ?bitoffset?'+::
5047     Packs the binary representation of +'value'+ into the variable
5048     +'varName'+. The value is packed according to the given type
5049     (integer/floating point/string, big-endian/little-endian), width and bit offset.
5050     The variable is created if necessary (like `append`).
5051     The variable is expanded if necessary.
5053 +*unpack* 'binvalue' *-intbe|-intle|-uintbe|-uintle|-floatbe|-floatle|-str* 'bitpos bitwidth'+::
5054     Unpacks bits from +'binvalue'+ at bit position +'bitpos'+ and with +'bitwidth'+.
5055     Interprets the value according to the type (integer/floating point/string, big-endian/little-endian
5056     and signed/unsigned) and returns it. For integer types, +'bitwidth'+
5057     may be up to the size of a Jim Tcl integer (typically 64 bits). For floating point types,
5058     +'bitwidth'+ may be 32 bits (for single precision numbers) or 64 bits (for double precision).
5059     For the string type, both the width and the offset must be on a byte boundary (multiple of 8). Attempting to
5060     access outside the length of the value will return 0 for integer types, 0.0 for floating point types
5061     or the empty string for the string type.
5063 zlib
5064 ~~~~
5065 The optional 'zlib' extension provides a Tcl-compatible subset of the `zlib` command.
5067 +*crc32* 'data' '?startValue?'+::
5068     Returns the CRC32 checksum of a buffer. Optionally, an initial value may be specified; this is most useful
5069     for calculating the checksum of chunked data read from a stream (for instance, a pipe).
5071 +*deflate* 'string' '?level?'+::
5072     Compresses a buffer and outputs a raw, Deflate-compressed stream. Optionally, a compression level (1-9) may
5073     be specified to choose the desired speed vs. compression rate ratio.
5075 +*inflate* 'data' '?bufferSize?'+::
5076     Decompresses a raw, Deflate-compressed stream. When the uncompressed data size is known and specified, memory
5077     allocation is more efficient. Otherwise, decompression is chunked and therefore slower.
5079 +*gzip* 'string' '?-level level?'+::
5080     Compresses a buffer and adds a gzip header.
5082 +*gunzip* 'data' '?-buffersize size?'+::
5083     Decompresses a gzip-compressed buffer. Decompression is chunked, with a default, small buffer size of 64K
5084     which guarantees lower memory footprint at the cost of speed. It is recommended to use a bigger size, on
5085     systems without a severe memory constraint.
5087 binary
5088 ~~~~~~
5089 The optional, pure-Tcl 'binary' extension provides the Tcl-compatible `binary scan` and `binary format`
5090 commands based on the low-level `pack` and `unpack` commands.
5092 See the Tcl documentation at: http://www.tcl.tk/man/tcl8.5/TclCmd/binary.htm
5094 Note that 'binary format' with f/r/R specifiers (single-precision float) uses the value of Infinity
5095 in case of overflow.
5097 oo: class, super
5098 ~~~~~~~~~~~~~~~~
5099 The optional, pure-Tcl 'oo' extension provides object-oriented (OO) support for Jim Tcl.
5101 See the online documentation (http://jim.tcl.tk/index.html/doc/www/www/documentation/oo/) for more details.
5103 +*class* 'classname ?baseclasses? classvars'+::
5104     Create a new class, +'classname'+, with the given dictionary
5105     (+'classvars'+) as class variables. These are the initial variables
5106     which all newly created objects of this class are initialised with.
5107     If a list of baseclasses is given, methods and instance variables
5108     are inherited.
5110 +*super* 'method ?args \...?'+::
5111     From within a method, invokes the given method on the base class.
5112     Note that this will only call the last baseclass given.
5114 tree
5115 ~~~~
5116 The optional, pure-Tcl 'tree' extension implements an OO, general purpose tree structure
5117 similar to that provided by tcllib ::struct::tree (http://core.tcl.tk/tcllib/doc/trunk/embedded/www/tcllib/files/modules/struct/struct_tree.html)
5119 A tree is a collection of nodes, where each node (except the root node) has a single parent
5120 and zero or more child nodes (ordered), as well as zero or more attribute/value pairs.
5122 +*tree*+::
5123     Creates and returns a new tree object with a single node named "root".
5124     All operations on the tree are invoked through this object.
5126 +$tree *destroy*+::
5127     Destroy the tree and all it's nodes. (Note that the tree will also
5128     be automatically garbage collected once it goes out of scope).
5130 +$tree *set* 'nodename key value'+::
5131     Set the value for the given attribute key.
5133 +$tree *lappend* 'nodename key value \...'+::
5134     Append to the (list) value(s) for the given attribute key, or set if not yet set.
5136 +$tree *keyexists* 'nodename key'+::
5137     Returns 1 if the given attribute key exists.
5139 +$tree *get* 'nodename key'+::
5140     Returns the value associated with the given attribute key.
5142 +$tree *getall* 'nodename'+::
5143     Returns the entire attribute dictionary associated with the given key.
5145 +$tree *depth* 'nodename'+::
5146     Returns the depth of the given node. The depth of "root" is 0.
5148 +$tree *parent* 'nodename'+::
5149     Returns the node name of the parent node, or "" for the root node.
5151 +$tree *numchildren* 'nodename'+::
5152     Returns the number of child nodes.
5154 +$tree *children* 'nodename'+::
5155     Returns a list of the child nodes.
5157 +$tree *next* 'nodename'+::
5158     Returns the next sibling node, or "" if none.
5160 +$tree *insert* 'nodename ?index?'+::
5161     Add a new child node to the given node. The index is a list index
5162     such as +3+ or +end-2+. The default index is +end+.
5163     Returns the name of the newly added node.
5165 +$tree *walk* 'nodename' *dfs|bfs* {'actionvar nodevar'} 'script'+::
5166     Walks the tree starting from the given node, either breadth first (+bfs+)
5167     depth first (+dfs+).
5168     The value +"enter"+ or +"exit"+ is stored in variable +'actionvar'+.
5169     The name of each node is stored in +'nodevar'+.
5170     The script is evaluated twice for each node, on entry and exit.
5172 +$tree *dump*+::
5173     Dumps the tree contents to stdout
5175 tcl::prefix
5176 ~~~~~~~~~~~
5177 The optional tclprefix extension provides the Tcl8.6-compatible `tcl::prefix` command
5178 (http://www.tcl.tk/man/tcl8.6/TclCmd/prefix.htm) for matching strings against a table
5179 of possible values (typically commands or options).
5181 +*tcl::prefix all* 'table string'+::
5182     Returns a list of all elements in +'table'+ that begin with the prefix +'string'+.
5184 +*tcl::prefix longest* 'table string'+::
5185     Returns the longest common prefix of all elements in +'table'+ that begin with the prefix +'string'+.
5187 +*tcl::prefix match* '?options? table string'+::
5188     If +'string'+ equals one element in +'table'+ or is a prefix to
5189     exactly one element, the matched element is returned. If not, the
5190     result depends on the +-error+ option.
5192     * +*-exact*+ Accept only exact matches.
5193     * +*-message* 'string'+ Use +'string'+ in the error message at a mismatch. Default is "option".
5194     * +*-error* 'options'+ The options are used when no match is found. If +'options'+ is
5195       empty, no error is generated and an empty string is returned.
5196       Otherwise the options are used as return options when
5197       generating the error message. The default corresponds to
5198       setting +-level 0+.
5200 tcl::autocomplete
5201 ~~~~~~~~~~~~~~~~~
5202 Scriptable command line completion is supported in the interactive shell, 'jimsh', through
5203 the `tcl::autocomplete` callback. A simple implementation is provided, however this may
5204 be replaced with a custom command instead if desired.
5206 In the interactive shell, press <TAB> to activate command line completion.
5208 +*tcl::autocomplete* 'commandline'+::
5209     This command is called with the current command line when the user presses <TAB>.
5210     The command should return a list of all possible command lines that match the current command line.
5211     For example if +*pr*+ is the current command line, the list +*{prefix proc}*+ may be returned.
5213 history
5214 ~~~~~~~
5215 The optional history extension provides script access to the command line editing
5216 and history support available in 'jimsh'. See 'examples/jtclsh.tcl' for an example.
5217 Note: if line editing support is not available, `history getline` acts like `gets` and
5218 the remaining subcommands do nothing.
5220 +*history load* 'filename'+::
5221     Load history from a (text) file. If the file does not exist or is not readable,
5222     it is ignored.
5224 +*history getline* 'prompt ?varname?'+::
5225     Displays the given prompt and allows a line to be entered. Similarly to `gets`,
5226     if +'varname'+ is given, it receives the line and the length of the line is returned,
5227     or -1 on EOF. If +'varname'+ is not given, the line is returned directly.
5229 +*history completion* 'command'+::
5230     Sets an autocompletion command (see `tcl::autocomplete`) that is active during `history getline`.
5231     If the command is empty, autocompletion is disabled.
5233 +*history add* 'line'+::
5234     Adds the given line to the history buffer.
5236 +*history save* 'filename'+::
5237     Saves the current history buffer to the given file.
5239 +*history show*+::
5240     Displays the current history buffer to standard output.
5242 namespace
5243 ~~~~~~~~~
5244 Provides namespace-related functions. See also: http://www.tcl.tk/man/tcl8.6/TclCmd/namespace.htm
5246 +*namespace code* 'script'+::
5247     Captures the current namespace context for later execution of
5248     the script +'script'+. It returns a new script in which script has
5249     been wrapped in a +*namespace inscope*+ command.
5251 +*namespace current*+::
5252     Returns the fully-qualified name for the current namespace.
5254 +*namespace delete* '?namespace ...?'+::
5255     Deletes all commands and variables with the given namespace prefixes.
5257 +*namespace eval* 'namespace arg ?arg...?'+::
5258     Activates a namespace called +'namespace'+ and evaluates some code in that context.
5260 +*namespace origin* 'command'+::
5261     Returns the fully-qualified name of the original command to which the imported command +'command'+ refers.
5263 +*namespace parent* ?namespace?+::
5264     Returns the fully-qualified name of the parent namespace for namespace +'namespace'+, if given, otherwise
5265     for the current namespace.
5267 +*namespace qualifiers* 'string'+::
5268     Returns any leading namespace qualifiers for +'string'+
5270 +*namespace tail* 'string'+::
5271     Returns the simple name at the end of a qualified string.
5273 +*namespace upvar* 'namespace ?arg...?'+::
5274     This command arranges for zero or more local variables in the current procedure to refer to variables in +'namespace'+
5276 +*namespace which* '?-command|-variable? name'+::
5277     Looks up +'name'+ as either a command (the default) or variable and returns its fully-qualified name.
5279 interp
5280 ~~~~~~
5281 The optional 'interp' command allows sub-interpreters to be created where commands may be run
5282 independently (but synchronously) of the main interpreter.
5284 +*interp*+::
5285     Creates and returns a new interpreter object (command).
5286     The created interpreter contains any built-in commands along with static extensions,
5287     but does not include any dynamically loaded commands (package require, load).
5288     These must be reloaded in the child interpreter if required.
5290 +*$interp delete*+::
5291     Deletes the interpreter object.
5293 +*$interp eval* 'script' ...+::
5294     Evaluates a script in the context for the child interpreter, in the same way as 'eval'.
5296 +*$interp alias* 'alias childcmd parentcmd ?arg ...?'+::
5297     Similar to 'alias', but creates a command, +'childcmd'+, in the child interpreter that is an
5298     alias for +'parentcmd'+ in the parent interpreter, with the given, fixed arguments.
5299     The alias may be deleted in the child with 'rename'.
5301 json::encode
5302 ~~~~~~~~~~~~
5304 The Tcl -> JSON encoder is part of the optional 'json' package.
5306 +*json::encode* 'value ?schema?'+::
5308 Encode a Tcl value as JSON according to the schema (defaults to +'str'+). The following schema types are supported:
5309 * 'str' - Tcl string -> JSON string
5310 * 'num' - Tcl value -> bare numeric value or null
5311 * 'bool' - Tcl boolean value -> true, false
5312 * 'obj ?name subschema ...?' - Tcl dict -> JSON object. For each dict key matching 'name', the corresponding 'subschema'
5313 is applied. The special name +'*'+ matches any keys not otherwise matched, otherwise the default +'str'+ is used.
5314 * 'list ?subschema?' - Tcl list -> JSON array. The 'subschema' (default +'str'+) is applied for each element of the list/array.
5315 * 'mixed ?subschema ...?' = Tcl list -> JSON array. Each 'subschema' is applied for the corresponding element of the list/array.
5316   ::
5317 The following are examples:
5318 ----
5319     . json::encode {1 2 true false null 5.0} list
5320     [ "1", "2", "true", "false", "null", "5.0" ]
5321     . json::encode {1 2 true false null 5.0} {list num}
5322     [ 1, 2, true, false, null, 5.0 ]
5323     . json::encode {0 1 2 true false 5.0 off} {list bool}
5324     [ false, true, true, true, false, true, false ]
5325     . json::encode {a 1 b hello c {3 4}} obj
5326     { "a":"1", "b":"hello", "c":"3 4" }
5327     . json::encode {a 1 b hello c {3 4}} {obj a num c {list num}}
5328     { "a":1, "b":"hello", "c":[ 3, 4 ] }
5329     . json::encode {true true {abc def}} {mixed str num obj}
5330     [ "true", true, { "abc":"def" } ]
5331     . json::encode {a 1 b 3.0 c hello d null} {obj c str * num}
5332     { "a":1, "b":3.0, "c":"hello", "d":null }
5333 ----
5335 json::decode
5336 ~~~~~~~~~~~~
5338 The JSON -> Tcl decoder is part of the optional 'json' package.
5340 +*json::decode* ?*-index*? ?*-null* 'string'? ?*-schema*? 'json-string'+::
5342 Decodes the given JSON string (must be array or object) into a Tcl data structure. If '+-index+' is specified,
5343 decodes JSON arrays as dictionaries with numeric keys. This makes it possible to retrieve data from nested
5344 arrays and dictionaries with just '+dict get+'. With the option '+-schema+' returns a list of +'{data schema}'+
5345 where the schema is compatible with `json::encode`. Otherwise just returns the data.
5346 Decoding is as follows (with schema types listed in parentheses):
5347 * object -> dict ('obj')
5348 * array -> list ('mixed' or 'list')
5349 * number -> as-is ('num')
5350 * boolean -> as-is ('bool')
5351 * string -> string ('str')
5352 * null -> supplied null string or the default +'"null"'+ ('num')
5353  ::
5354  Note that an object decoded into a dict will return the keys in the same order as the original string.
5355 ----
5356     . json::decode {[1, 2]}
5357     {1 2}
5358     . json::decode -schema {[1, 2]}
5359     {1 2} {list num}
5360     . json::decode -schema {{"a":1, "b":2}}
5361     {a 1 b 2} {obj a num b num}
5362     . json::decode -schema {[1, 2, {a:"b", c:false}, "hello"]}
5363     {1 2 {a b c false} hello} {mixed num num {obj a str c bool} str}
5364     . json::decode -index {["foo", "bar"]}
5365     {0 foo 1 bar}
5366 ----
5368 [[BuiltinVariables]]
5369 BUILT-IN VARIABLES
5370 ------------------
5372 The following global variables are created automatically
5373 by the Tcl library.
5375 +*env*+::
5376     This variable is set by Jim as an array
5377     whose elements are the environment variables for the process.
5378     Reading an element will return the value of the corresponding
5379     environment variable.
5380     This array is initialised at startup from the `env` command.
5381     It may be modified and will affect the environment passed to
5382     commands invoked with `exec`.
5384 +*platform_tcl*+::
5385     This variable is set by Jim as an array containing information
5386     about the platform on which Jim was built. Currently this includes
5387     'os' and 'platform'.
5389 +*auto_path*+::
5390     This variable contains a list of paths to search for packages.
5391     It defaults to a location based on where jim is installed
5392     (e.g. +/usr/local/lib/jim+), but may be changed by +jimsh+
5393     or the embedding application. Note that +jimsh+ will consider
5394     the environment variable +$JIMLIB+ to be a list of colon-separated
5395     list of paths to add to +*auto_path*+.
5397 +*errorCode*+::
5398     This variable holds the value of the -errorcode return
5399     option set by the most recent error that occurred in this
5400     interpreter. This list value represents additional information
5401     about the error in a form that is easy to process with
5402     programs. The first element of the list identifies a general
5403     class of errors, and determines the format of the rest of
5404     the list. The following formats for -errorcode return options
5405     are used by the Tcl core; individual applications may define
5406     additional formats. Currently only `exec` sets this variable.
5407     Otherwise it will be +NONE+.
5409 The following global variables are set by jimsh.
5411 +*tcl_interactive*+::
5412     This variable is set to 1 if jimsh is started in interactive mode
5413     or 0 otherwise.
5415 +*tcl_platform*+::
5416     This variable is set by Jim as an array containing information
5417     about the platform upon which Jim was built. The following is an
5418     example of the contents of this array.
5420 ----
5421     tcl_platform(byteOrder)     = littleEndian
5422     tcl_platform(engine)        = Jim
5423     tcl_platform(os)            = Darwin
5424     tcl_platform(platform)      = unix
5425     tcl_platform(pointerSize)   = 8
5426     tcl_platform(threaded)      = 0
5427     tcl_platform(wordSize)      = 8
5428     tcl_platform(pathSeparator) = :
5429 ----
5431 +*argv0*+::
5432     If jimsh is invoked to run a script, this variable contains the name
5433     of the script.
5435 +*argv*+::
5436     If jimsh is invoked to run a script, this variable contains a list
5437     of any arguments supplied to the script.
5439 +*argc*+::
5440     If jimsh is invoked to run a script, this variable contains the number
5441     of arguments supplied to the script.
5443 +*jim::argv0*+::
5444     The value of argv[0] when jimsh was invoked.
5446 The following variables have special meaning to Jim Tcl:
5448 +*jim::defer*+::
5449     If this variable is set, it is considered to be a list of scripts to evaluate
5450     when the current proc exits (local variables), or the interpreter exits (global variable).
5451     See `defer`.
5453 +*history::multiline*+::
5454     If this variable is set to "1", interactive line editing operates in multiline mode.
5455     That is, long lines will wrap across multiple lines rather than scrolling within a
5456     single line.
5458 CHANGES IN PREVIOUS RELEASES
5459 ----------------------------
5461 === In v0.74 ===
5463 1. Numbers with leading zeros are treated as decimal, not octal
5464 2. Add `aio isatty`
5465 3. Add LFS (64 bit) support for `aio seek`, `aio tell`, `aio copyto`, `file copy`
5466 4. `string compare` and `string equal` now support '-length'
5467 5. `glob` now supports '-directory'
5469 === In v0.73 ===
5471 1. Built-in regexp now support non-capturing parentheses: (?:...)
5472 2. Add `string replace`
5473 3. Add `string totitle`
5474 4. Add `info statics`
5475 5. Add +build-jim-ext+ for easy separate building of loadable modules (extensions)
5476 6. `local` now works with any command, not just procs
5477 7. Add `info alias` to access the target of an alias
5478 8. UTF-8 encoding past the basic multilingual plane (BMP) is supported
5479 9. Add `tcl::prefix`
5480 10. Add `history`
5481 11. Most extensions are now enabled by default
5482 12. Add support for namespaces and the `namespace` command
5483 13. Add `apply`
5485 === In v0.72 ===
5487 1. procs now allow 'args' and optional parameters in any position
5488 2. Add Tcl-compatible expr functions, `rand()`, `srand()` and `pow()`
5489 3. Add support for the '-force' option to `file delete`
5490 4. Better diagnostics when `source` fails to load a script with a missing quote or bracket
5491 5. New +tcl_platform(pathSeparator)+
5492 6. Add support settings the modification time with `file mtime`
5493 7. `exec` is now fully supported on win32 (mingw32)
5494 8. `file join`, `pwd`, `glob` etc. now work for mingw32
5495 9. Line editing is now supported for the win32 console (mingw32)
5496 10. Add `aio listen` command
5498 === In v0.71 ===
5500 1. Allow 'args' to be renamed in procs
5501 2. Add +$(...)+ shorthand syntax for expressions
5502 3. Add automatic reference variables in procs with +&var+ syntax
5503 4. Support +jimsh --version+
5504 5. Additional variables in +tcl_platform()+
5505 6. `local` procs now push existing commands and `upcall` can call them
5506 7. Add `loop` command (TclX compatible)
5507 8. Add `aio buffering` command
5508 9. `info complete` can now return the missing character
5509 10. `binary format` and `binary scan` are now (optionally) supported
5510 11. Add `string byterange`
5511 12. Built-in regexp now support non-greedy repetition (*?, +?, ??)
5514 === In v0.70 ===
5516 1. +platform_tcl()+ settings are now automatically determined
5517 2. Add aio `$handle filename`
5518 3. Add `info channels`
5519 4. The 'bio' extension is gone. Now `aio` supports 'copyto'.
5520 5. Add `exists` command
5521 6. Add the pure-Tcl 'oo' extension
5522 7. The `exec` command now only uses vfork(), not fork()
5523 8. Unit test framework is less verbose and more Tcl-compatible
5524 9. Optional UTF-8 support
5525 10. Optional built-in regexp engine for better Tcl compatibility and UTF-8 support
5526 11. Command line editing in interactive mode, e.g. 'jimsh'
5528 === In v0.63 ===
5530 1. `source` now checks that a script is complete (.i.e. not missing a brace)
5531 2. 'info complete' now uses the real parser and so is 100% accurate
5532 3. Better access to live stack frames with 'info frame', `stacktrace` and `stackdump`
5533 4. `tailcall` no longer loses stack trace information
5534 5. Add `alias` and `curry`
5535 6. `lambda`, `alias` and `curry` are implemented via `tailcall` for efficiency
5536 7. `local` allows procedures to be deleted automatically at the end of the current procedure
5537 8. udp sockets are now supported for both clients and servers.
5538 9. vfork-based exec is now working correctly
5539 10. Add 'file tempfile'
5540 11. Add 'socket pipe'
5541 12. Enhance 'try ... on ... finally' to be more Tcl 8.6 compatible
5542 13. It is now possible to `return` from within `try`
5543 14. IPv6 support is now included
5544 15. Add 'string is'
5545 16. Event handlers works better if an error occurs. eof handler has been removed.
5546 17. `exec` now sets $::errorCode, and catch sets opts(-errorcode) for exit status
5547 18. Command pipelines via open "|..." are now supported
5548 19. `pid` can now return pids of a command pipeline
5549 20. Add 'info references'
5550 21. Add support for 'after +'ms'+', 'after idle', 'after info', `update`
5551 22. `exec` now sets environment based on $::env
5552 23. Add 'dict keys'
5553 24. Add support for 'lsort -index'
5555 === In v0.62 ===
5557 1. Add support to `exec` for '>&', '>>&', '|&', '2>@1'
5558 2. Fix `exec` error messages when special token (e.g. '>') is the last token
5559 3. Fix `subst` handling of backslash escapes.
5560 4. Allow abbreviated options for `subst`
5561 5. Add support for `return`, `break`, `continue` in subst
5562 6. Many `expr` bug fixes
5563 7. Add support for functions in `expr` (e.g. int(), abs()), and also 'in', 'ni' list operations
5564 8. The variable name argument to `regsub` is now optional
5565 9. Add support for 'unset -nocomplain'
5566 10. Add support for list commands: `lassign`, `lrepeat`
5567 11. Fully-functional `lsearch` is now implemented
5568 12. Add 'info nameofexecutable' and 'info returncodes'
5569 13. Allow `catch` to determine what return codes are caught
5570 14. Allow `incr` to increment an unset variable by first setting to 0
5571 15. Allow 'args' and optional arguments to the left or required arguments in `proc`
5572 16. Add 'file copy'
5573 17. Add 'try ... finally' command
5576 LICENCE
5577 -------
5579  Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
5580  Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
5581  Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
5582  Copyright 2008 oharboe - Oyvind Harboe - oyvind.harboe@zylin.com
5583  Copyright 2008 Andrew Lunn <andrew@lunn.ch>
5584  Copyright 2008 Duane Ellis <openocd@duaneellis.com>
5585  Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
5586  Copyright 2009 Steve Bennett <steveb@workware.net.au>
5588 [literal]
5589  Redistribution and use in source and binary forms, with or without
5590  modification, are permitted provided that the following conditions
5591  are met:
5592  1. Redistributions of source code must retain the above copyright
5593     notice, this list of conditions and the following disclaimer.
5594  2. Redistributions in binary form must reproduce the above
5595     copyright notice, this list of conditions and the following
5596     disclaimer in the documentation and/or other materials
5597     provided with the distribution.
5599  THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
5600  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
5601  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
5602  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
5603  JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
5604  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
5605  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
5606  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
5607  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
5608  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
5609  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
5610  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5612  The views and conclusions contained in the software and documentation
5613  are those of the authors and should not be interpreted as representing
5614  official policies, either expressed or implied, of the Jim Tcl Project.