TclX(TCL)

๐Ÿ“ฆ
version 8.6.3 ยท 2 versions
, in alpine 3.24, nixos 26.05, nixpkgs unstable

๐Ÿฆ‹ TclX(TCL) โ€” Extended Tcl: Extended command set for Tcl โœจ

๐Ÿ“› NAME

TclX โ€” Extended Tcl: Extended command set for Tcl.

๐Ÿ’ป SYNOPSIS

package require Tclx

โœจ INTRODUCTION

Okay bestie, this man page is the whole glow-up guide for every extension that Extended Tcl (TclX) adds to Tcl ๐Ÿ’–. TclX extends Tclโ€™s capabilities by adding new commands to it, without changing the syntax of standard Tcl. Extended Tcl is a superset of standard Tcl and is built alongside the standard Tcl sources.

Extended Tcl was created by Karl Lehenbauer and Mark Diekhans and is freely redistributable for any use without license or fee. Iconic behavior, honestly ๐Ÿ‘‘.

Available since 1989, Extended Tcl, also known as TclX, not only adds capabilities to Tcl, but has also been the source of many of the capabilities of the baseline Tcl release, including arrays, files, sockets, file events, and date and time handling, among others. Itโ€™s giving โ€œmain character energyโ€ in the Tcl ecosystem fr fr ๐ŸŒˆ.

Extended Tcl introduces a set of new commands and a user-extensible library of useful Tcl procedures, any of which can be automatically loaded on the first attempt to execute it.

The command descriptions are separated into several sections:

  • General Commands
  • Debugging and Development Commands
  • Unix Access Commands
  • File Commands
  • Network Programming Support
  • File Scanning Commands
  • Math Commands
  • List Manipulation Commands
  • Keyed Lists
  • String and Character Manipulation Commands
  • XPG/3 Message Catalog Commands
  • Help Facility
  • Tcl Loadable Libraries and Packages

๐Ÿ› ๏ธ GENERAL COMMANDS

A set of general, useful Tcl commands, includes a command to begin an interactive session with Tcl, a facility for tracing execution, and a looping command.


๐ŸŒ€ dirs

This procedure lists the directories in the directory stack.

๐Ÿ’ฌ commandloop

commandloop ?-async? ?-interactive on | off | tty? ?-prompt1 cmd? ?-prompt2 cmd? ?-endcommand cmd?

Create an interactive command loop reading commands from stdin and writing results to stdout. Command loops can be blocking or event oriented. This command is useful for Tcl scripts that do not normally converse interactively with a user through a Tcl command interpreter, but which sometimes want to enter this mode, perhaps for debugging or user configuration. The command loop terminates on EOF.

The following options are available:

  • -async โ€” A command handler will be associated with stdin. When input is available on stdin, it will be read and accumulated until a full command is available. That command will then be evaluated. An event loop must be entered for input to be read and processed.
  • -interactive on | off | tty โ€” Enable or disable interactive command mode. In interactive mode, commands are prompted for and the results of comments are printed. The value may be any boolean value or tty. If tty is used, interactive mode is enabled if stdin is associated with a terminal or terminal emulator. The default is tty.
  • -prompt1 cmd โ€” If specified, cmd is evaluated and its result is used for the main command prompt. If not specified, the command in tcl_prompt1 is evaluated to output the prompt. Note the difference in behavior: cmd results are used, while tcl_prompt1 outputs. This is to allow for future expansion to command loops that write to other than stdout.
  • -prompt2 cmd โ€” If specified, cmd is evaluated and its result is used for the secondary (continuation) command prompt. If not specified, the command in tcl_prompt2 is evaluated to output the prompt.
  • -endcommand cmd โ€” If specified, cmd is evaluated when the command loop terminates.

In interactive mode, the results of set commands with two arguments are not printed.

If SIGINT is configured to generate a Tcl error, it can be used to delete the current command being typed without aborting the program in progress.

๐Ÿงƒ coalesce

coalesce ?-default value? var ?var...?

Iterate through one or more specified variable names. The first variable found that actually exists, return the value of that variable. If none of the variable names are found to exist, return the default value. If none of the variables exist and the default value wasnโ€™t specified using -default, returns the empty string.

๐Ÿ—ฃ๏ธ echo

echo ?str ...?

Writes zero or more strings to standard output, followed by a newline.

๐Ÿ”Ž infox

infox option

Return information about Extended Tcl, or the current application. The following infox command options are available:

  • version โ€” Return the version number of Extended Tcl. The version number for Extended Tcl is generated by combining the base version of the standard Tcl code with another number indicating the version of Extended Tcl being used.
  • patchlevel โ€” Return the patchlevel for Extended Tcl.
  • have_fchown โ€” Return 1 if the fchown system call is available. This supports the -fileid option on the chown and chgrp commands.
  • have_fchmod โ€” Return 1 if the fchmod system call is available. This supports the -fileid option on the chmod command.
  • have_flock โ€” Return 1 if the flock command defined, 0 if it is not available.
  • have_fsync โ€” Return 1 if the fsync system call is available and the sync command will sync individual files. 0 if it is not available and the sync command will always sync all file buffers.
  • have_ftruncate โ€” Return 1 if the ftruncate or chsize system call is available. If it is, the ftruncate command -fileid option may be used.
  • have_msgcats โ€” Return 1 if XPG message catalogs are available, 0 if they are not. catgets is designed to continue to function without message catalogs, always returning the default string.
  • have_posix_signals โ€” Return 1 if Posix signals are available (block and unblock options available for the signal command). 0 is returned if Posix signals are not available.
  • have_signal_restart โ€” Return 1 if restartable signals are available (-restart option available for the signal command). 0 is returned if restartable signals are not available.
  • have_truncate โ€” Return 1 if the truncate system call is available. If it is, the ftruncate command may truncate by file path.
  • have_waitpid โ€” Return 1 if the waitpid system call is available and the wait command has full functionality. 0 if the wait command has limited functionality.
  • appname โ€” Return the symbolic application name of the current application linked with the Extended Tcl library. The C variable tclAppName must be set by the application to return an application specific value for this variable.
  • applongname โ€” Return a natural language name for the current application. The C variable tclLongAppName must be set by the application to return an application specific value for this variable.
  • appversion โ€” Return the version number for the current application. The C variable tclAppVersion must be set by the application to return an application-specific value for this variable.
  • apppatchlevel โ€” Return the patchlevel for the current application. The C variable tclAppPatchlevel must be set by the application to return an application-specific value for this variable.

๐Ÿ”‘ for_array_keys

for_array_keys var array_name code

This procedure performs a foreach-style loop for each key in the named array. The break and continue statements work as with foreach.

๐ŸŒณ for_recursive_glob

for_recursive_glob var dirlist globlist code

This procedure performs a foreach-style loop over recursively matched files. All directories in dirlist are recursively searched (breadth-first), comparing each file found against the file glob patterns in globlist. For each matched file, the variable var is set to the file path and code is evaluated. Symbolic links are not followed.

๐Ÿ” loop

loop var first limit ?increment? body

loop is a looping command, similar in behavior to the Tcl for statement, except that the loop statement achieves substantially higher performance and is easier to code when the beginning and ending values of a loop are known, and the loop variable is to be incremented by a known, fixed amount every time through the loop.

The var argument is the name of a Tcl variable that will contain the loop index. The loop index is set to the value specified by first. The Tcl interpreter is invoked upon body zero or more times, where var is incremented by increment every time through the loop, or by one if increment is not specified. increment can be negative in which case the loop will count downwards.

When var reaches limit, the loop terminates without a subsequent execution of body. For instance, if the original loop parameters would cause loop to terminate, say first was one, limit was zero and increment was not specified or was non-negative, body is not executed at all and loop returns.

The first, limit and increment are integer expressions. They are only evaluated once at the beginning of the loop.

If a continue command is invoked within body then any remaining commands in the current execution of body are skipped, as in the for command. If a break command is invoked within body then the loop command will return immediately. loop returns an empty string.

  • popd โ€” pops the top directory entry off the directory stack and makes it the current directory. bye-bye old dir, hello new one ๐Ÿ’…
  • pushd ?dir? โ€” pushes the current directory onto the directory stack, then cds to the directory you named. If you donโ€™t name a directory, the current one gets pushed but nothing changes. lowkey a little โ€œcopy my vibeโ€ move ๐Ÿซถ
  • recursive_glob dirlist globlist โ€” returns a list of recursively matched files. Every directory in dirlist gets searched recursively, breadth-first, and each file it finds gets checked against the file glob patterns in globlist. Symbolic links are not followed โ€” no chasing rabbit holes ๐Ÿ‡๐Ÿšซ
  • showproc ?procname ...? โ€” lists the definition of the named procedures, loading them first if they arenโ€™t already loaded. If you pass no procedure names, it returns the definitions of all currently loaded procedures. itโ€™s giving โ€œshow me the receiptsโ€ ๐Ÿ“œโœจ
  • try_eval code catch ?finally? โ€” evaluates code in the current context.

If an error happens during that evaluation and catch is not empty, then catch gets evaluated to handle the error. The result of the command, containing the error message, is stored in a global variable errorResult. The global variables errorResult, errorInfo and errorCode are imported into the current scope โ€” no need to run a global command. The result of the catch command becomes the result of the try_eval command.

If you want to continue the error that caused catch to be evaluated, use this exact move:

error $errorResult $errorCode $errorInfo

If the finally argument is supplied and not empty, itโ€™s evaluated after both the code and catch commands. If an error happens during finally, that becomes the result of try_eval. Otherwise the result of either code or catch is preserved, as described above. final girl energy, but make it cleanup ๐ŸŽ€


๐Ÿž DEBUGGING AND DEVELOPMENT COMMANDS ๐Ÿž

This section is all about commands and procedures that are useful for developing and debugging Tcl scripts. ngl this is where the detective work happens ๐Ÿ”๐Ÿ’–

  • cmdtrace level | on ?noeval? ?notruncate? ?procs? ?fileid? ?command cmd? โ€” prints a trace statement for all commands executed at depth level or below (1 is the top level). If on is specified, all commands at any level are traced. The following options are available:
    • noeval โ€” causes arguments to be printed unevaluated. If noeval is specified, the arguments are printed before evaluation. Otherwise, theyโ€™re printed afterwards.

If the command line is longer than 60 characters, itโ€™s truncated to 60 and a ... is postpended to show there was more output than was displayed. If an evaluated argument contains a space, the entire argument gets enclosed inside braces ({}) so the reader can visually separate arguments from each other.

  • notruncate โ€” disables the truncation of commands and evaluated arguments. no more cutting off the fit, bestie โœ‚๏ธ๐Ÿšซ
  • procs โ€” enables tracing of procedure calls only. Commands that arenโ€™t procedure calls (i.e. calls to commands written in C, C++ or some object-compatible language) are not traced if procs is specified. This is especially useful for greatly reducing cmdtrace output while debugging. less noise, more clue ๐Ÿ•ต๏ธโ€โ™€๏ธ
  • fileid โ€” this is a file id as returned by the open command. If specified, trace output is written to the file instead of stdout. A stdio buffer flush is done after every line is written so the trace can be monitored externally or provide useful info for debugging problems that cause core dumps. ๐Ÿ’€โžก๏ธ๐Ÿ“„
  • command cmd โ€” calls the specified command cmd when each command is executed instead of tracing to a file. See the description of the functionality below. This option may not be specified with a fileid.

The most common use of this command is to enable tracing to a file during development. If a failure occurs, a trace is then available when needed. Command tracing slows down execution of code, so it should be removed when the code is debugged. The following command enables tracing to a file for the remainder of the program:

cmdtrace on [open cmd.log w]

The command option causes a user-specified trace command to be called for each command executed. That command gets the following arguments appended before evaluation:

  • command โ€” a string containing the text of the command, before any argument substitution.
  • argv โ€” a list of the final argument information that will be passed to the command after command, variable, and backslash substitution.
  • evalLevel โ€” the Tcl_Eval call level.
  • procLevel โ€” the procedure call level.

The command should be built so it still works if additional arguments are added in the future. Itโ€™s suggested that the command be a proc with the final argument being args. future-proof that icon ๐Ÿ”ฎ

Tracing is turned off while the command is being executed. The values of the errorInfo and errorCode variables are saved and restored on return from the command. Itโ€™s the commandโ€™s responsibility to preserve all other state.

If an error happens during execution of command, an error message is dumped to stderr and tracing is disabled. The underlying mechanism this functionality is built on does not support returning an error to the interpreter. thatโ€™s the lore, bestie ๐Ÿ˜ญ

  • cmdtrace off โ€” turns off all tracing. bye trace era ๐Ÿ‘‹
  • cmdtrace depth โ€” returns the current maximum trace level, or zero if tracing is disabled.
  • edprocs ?proc...? โ€” writes the named procedures, or all currently defined procedures if you donโ€™t name any, to a temporary file. Then it calls an editor on it (as specified by the EDITOR environment variable, or vi if none is specified), then sources the file back in if it was changed. editor-core ๐Ÿ’ปโœจ
  • profile ?-commands? ?-eval? on
  • profile off arrayVar

This command collects a performance profile of a Tcl script. It collects data at the Tcl procedure level: the number of calls to a procedure, and the amount of real and CPU time. Time is also collected for the global context. The procedure data is collected by bucketing it based on the procedure call stack, which lets you determine how much time is spent in a particular procedure in each of its calling contexts.

The on option enables profile data collection. If the -commands option is specified, data on all commands within a procedure is collected as well as procedures. Multiple occurrences of a command within a procedure are not distinguished, but this data may still be useful for analysis.

The off option turns off profiling and moves the collected data to the array arrayVar. The array is addressed by a list containing the procedure call stack. Element zero is the top of the stack, the procedure that the data is for. The data in each entry is a list consisting of the procedure call count and the real time and CPU time in milliseconds spent in the procedure (but not any procedures it calls). The list is in the form {count real cpu}.

Normally, the variable scope stack is used when reporting where time is spent. So upleveled code is reported in the context it was executed in, not the context where uplevel was called. If the -eval option is specified, the procedure evaluation (call) stack is used instead of the procedure scope stack. Upleveled code is reported in the context of the procedure that did the uplevel.

A Tcl procedure profrep is supplied for reducing the data and producing a report. data girl summer ๐Ÿ“Š๐Ÿ’…

On Windows, the profile command only reports elapsed real time. CPU time is not available and is reported as zero.

  • profrep profDataVar sortKey ?outFile? ?userTitle? โ€” generates a report from data collected by the profile command. profDataVar is the name of the array containing the data returned by profile. sortKey says which data value to sort by, and should be one of calls, cpu or real. outFile is the name of the file to write the report to; if omitted, stdout is assumed. userTitle is an optional title line added to the output.

Listed with indentation below each procedure or command is the procedure call stack. The first indented line is the procedure that invoked the reported procedure or command. The next line is the procedure that invoked the procedure above it, and so on. If no indented procedures are shown, the procedure or command was called from the global context. Time actually spent in the global context is listed on a line labeled <global>. Upleveled code is reported in the context it was executed in, not the context where the uplevel was called. stack trace but make it fashion ๐ŸŽ€

  • saveprocs fileName ?proc...? โ€” saves the definition of the named procedure, or all currently defined procedures if none is specified, to fileName. save file, slay file ๐Ÿ’พโœจ

๐ŸŒธ UNIX ACCESS COMMANDS ๐ŸŒธ

These commands give you access to lots of basic Unix facilities, including process handling, date and time processing, signal handling and executing commands via the shell. we love a Unix field trip ๐Ÿงš๐Ÿ’œ

  • alarm seconds โ€” tells the system to send a SIGALRM signal in the specified number of seconds. This is a floating point number, so fractions of a second may be specified. If seconds is 0.0, any previous alarm request is canceled. Only one alarm at a time may be active; the command returns the number of seconds left in the previous alarm. On systems without the setitimer system call, seconds is rounded up to an integer number of seconds. โฐ๐Ÿ”ฅ
The alarm command is not available on Windows. windows bestie, this one isnโ€™t for you ๐Ÿ˜ญ๐Ÿซถ

๐Ÿงต execl โ€” swap your whole self out for another program

execl ?-argv0 argv0? prog ?arglist?

Okay so this one literally does an execl โ€” it replaces the current program (either Extended Tcl, or some app that has Extended Tcl embedded in it โœจ) with prog, and hands prog the args sitting in the list arglist.

  • -argv0 argv0 โ€” tells it that argv0 should get passed to the program as argv [0] instead of prog. Cute little name-swap moment ๐Ÿ’…
โš ๏ธ Bestie, listen: if you use execl inside a Tk application and it fails, you cannot do anything that touches the X server โ€” otherwise the X server hits you with a BadWindow error. That includes running the Tk version of the exit command, no cap. The suggested way to abort Tk apps after a failed execl is this:
kill [id process]

On Windows, where fork isn't available, execl starts a new process and returns the process id. ๐ŸชŸ


๐ŸŒณ chroot โ€” new root, who dis

chroot dirname

Changes the root directory to dirname by invoking the POSIX chroot(2) system call. This only works if you're running as root โ€” sorry not sorry, that's just the vibe check the kernel enforces ๐Ÿ‘‘


๐Ÿด fork โ€” clone yourself, it's giving mitosis

fork

Forks the current Tcl process. fork returns zero to the child process, and the process number of the child to the parent process. If the fork fails, a Tcl error gets generated. ๐Ÿ’€

๐Ÿšจ Flush first, seriously: if you're not gonna do an execl before the child process does output, or if you're gonna do a close-and-dup sequence on stdout or stderr, then flush stdout, stderr, and any other open output file before the fork. Otherwise the characters from the parent process still chilling in the buffers get output by both the parent and the child. Double-printed chaos, we don't want that ๐Ÿ™ˆ

Also โ€” if you're forking in a Tk-based application, you must execl before doing any window operations in the child, or the X server will hit you with a BadWindow error.

fork is not available on Windows.


๐Ÿชช id โ€” who even am I

id options

This command is your whole little toolkit for getting, setting and converting user, group and process ids. The id command has these options:

  • id user ?name? โ€” user stuff, see below
  • id userid ?uid? โ€” sets the real and effective user ID to name or uid, if the name (or uid) is valid and permissions allow it. If the name (or uid) isn't specified, the current name (or uid) is returned โœจ
  • id convert userid uid โ€” convert a user ID number to a user name ๐Ÿซถ
  • id convert user name โ€” convert a user name to a user ID number, the other direction ๐Ÿ’…
  • id group ?name? โ€” group stuff, see below
  • id groupid ?gid? โ€” sets the real and effective group ID to name or gid, if the name (or gid) is valid and permissions allow it. If the group name (or gid) isn't specified, the current group name (or gid) is returned
  • id groups โ€” return the current group access list of the process, as group names
  • id groupids โ€” return the current group access list of the process, as id numbers
  • id convert groupid gid โ€” convert a group ID number to a group name
  • id convert group name โ€” convert a group name to a group ID number
  • id effective user โ€” return the effective user name ๐Ÿ‘‘
  • id effective userid โ€” return the effective user ID number
  • id effective group โ€” return the effective group name
  • id effective groupid โ€” return the effective group ID number
  • id effective groupids โ€” return all of the groupids the user is a member of ๐ŸŒˆ
  • id host โ€” return the hostname of the system the program is running on
  • id process โ€” return the process ID of the current process
  • id process parent โ€” return the process ID of the parent of the current process
  • id process group โ€” return the process group ID of the current process
  • id process group set โ€” set the process group ID of the current process to its process ID
  • id host โ€” returns the standard host name of the machine the process is executing on (yep, it's listed twice in the original, she contains multitudes ๐Ÿ’–)

On Windows, only the host and process options are implemented.


๐Ÿ’€ kill โ€” tell a process to go away

kill ?-pgroup ?signal? idlist

Sends a signal to each process in the list idlist, if permitted. signal, if present, is the signal number or the symbolic name of the signal โ€” see the signal system call manual page. The leading SIG is optional when you specify the signal by its symbolic name. The default for signo is 15, SIGTERM. ๐Ÿ”ฅ

  • -pgroup โ€” the numbers in idlist are taken as process group ids, and the signal gets sent to all of the processes in that process group. A process group id of 0 specifies the current process group ๐Ÿซถ

On Windows, kill is capable of terminating a process, but not of sending an arbitrary signal.


๐Ÿ”— link โ€” make a whole new directory entry

link ?-sym? srcpath destpath

Creates a directory entry, destpath, linking it to the existing file, srcpath. If -sym is specified, a symbolic link is created rather than a hard link. (The -sym option is only available on systems that support symbolic links. ๐Ÿงš)

link is not available on Windows. Use the Tcl 8.4+ file link command instead โ€” glow up ๐Ÿ’…


๐Ÿ˜‡ nice โ€” be a little kinder to the CPU

nice ?priorityincr?

Changes or returns the process priority. If priorityincr is omitted, the current priority is returned. If priorityincr is positive, it gets added to the current priority level, up to a system defined maximum (normally 19).

Negative priorityincr values cumulatively increase the program's priority down to a system defined minimum (normally -19) โ€” but increasing priority with negative niceness values will only work for the superuser ๐Ÿ‘‘ no shortcuts, bestie.

The new priority is returned.

nice is not available on Windows.


๐Ÿ“‚ readdir โ€” what's in this folder, fr fr

readdir ?-hidden? dirPath

Returns a list containing the contents of the directory dirPath. The directory entries "." and ".." are not returned, so no boring dot noise โœจ

  • -hidden โ€” on Windows, this may be specified to include hidden files in the result. This flag is ignored on Unix systems. ๐Ÿ™ˆ

๐Ÿ“ก signal โ€” the whole signals situation

signal ?-restart? action siglist ?command?
๐Ÿšจ Warning, and this one's important: if signals are being used as an event source (a trap action), rather than generating an error to terminate a task, you must use the -restart option. That causes a blocked system call โ€” like read or waitpid โ€” to be restarted rather than generate an error. Failing to do this may result in unexpected errors when a signal arrives while you're inside one of those system calls. When available, -restart can prevent this problem. ๐Ÿ’€

If -restart is specified, restart blocking system calls rather than generating an error. The signal will be handled once the Tcl command that issued the system call completes. The -restart option is not available on all operating systems, and using it will generate an error when it isn't supported. Use infox have_signal_restart to check for availability ๐Ÿ•ต๏ธโ€โ™€๏ธ

So this command specifies what action to take when a Unix signal is received by Extended Tcl, or by a program that embeds it. siglist is a list of either the symbolic or numeric Unix signals (the SIG prefix is optional). action is one of the following things to do when the signal shows up. To specify all modifiable signals, use * โ€” and note that this will not include SIGKILL and SIGSTOP, since they can not be modified, periodt. ๐Ÿ‘‘

  • default โ€” perform the system default action when the signal is received (see the signal system call documentation)
  • ignore โ€” ignore the signal. Nothing to see here ๐Ÿ™ˆ
  • error โ€” generate a catchable Tcl error. It'll be as if the command that was running returned an error. The error code will be in the form:
POSIX SIG signame

For the death-of-child signal, signame will always be SIGCHLD rather than SIGCLD, so you can write portable code ๐Ÿซถ

  • trap โ€” when the signal occurs, execute command and continue execution if command doesn't return an error. The command is executed in the global context. The command gets edited before execution, replacing occurrences of %S with the signal name, and occurrences of %% result in a single %. This editing happens just before the trap command is evaluated. If an error is returned, then follow the standard Tcl error mechanism. Often command will just do an exit ๐Ÿ’…
  • get โ€” retrieve the current settings of the specified signals. A keyed list is returned where the keys are one of the specified signals and the values are a list consisting of the action associated with the signal, a 0 if the signal may be delivered (not block) and a 1 if it is blocked, and a flag indicating if restarting of system calls is specified. The actions may be one of default, ignore, error or trap. If the action is trap, the third element is the command associated with the action. The action unknown is returned if a non-Tcl signal handler has been associated with the signal โญ
  • set โ€” set signals from a keyed list in the format returned by the get action. For this action, siglist is the keyed list of signal state. Signals with an action of unknown are not modified ๐ŸŽ€
  • block โ€” block the specified signals from being received. (Posix systems only.)
  • unblock โ€” allow the specified signal to be received. Pending signals will not occur. (Posix systems only.)

The signal action will remain enabled after the specified signal has occurred. The exception to this is SIGCHLD on systems without Posix signals โ€” for those systems, SIGCHLD is not automatically re-enabled. After a SIGCHLD signal is received, a call to wait must be performed to retrieve the exit status of the child process before issuing another signal SIGCHLD ... command. For code that's meant to be portable between both types of systems, use this approach ๐Ÿงšโœจ

Signals are not processed until after the Tcl command that's running when the signal arrives finishes up. Like, it waits its turn, no cutting in line ๐Ÿ’…. If an interactive Tcl shell is running, then SIGINT gets set to error; non-interactive Tcl sessions leave SIGINT unchanged from when the process started (which is normally the default for foreground processes, and ignore for processes chillin' in the background).

  • sleep seconds โ€” Sleeps the Extended Tcl process for seconds seconds. And lowkey important: if seconds is given as a decimal number, it gets truncated to an integer value. So no, sleep 2.9 is not giving you 2.9 seconds of nap time ๐Ÿ›Œ.
  • system cmdstr1 ?cmdstr2...? โ€” Concatenates cmdstr1, cmdstr2 etc. with space separators (see the concat command) into one single command, then evaluates it using the standard system shell. On Unix systems that's /bin/sh, and on Windows it's command.com. It returns the exit code of the command.

Fr fr, this is how it differs from exec: system does not return the executed command's standard output as the result string, and system goes through the Unix shell so you get wildcard expansion, redirection, etc., exactly like you'd expect from an sh command line. Iconic shell behaviour, no cap โœจ

  • sync ?fileId? โ€” If fileId isn't specified, or if it is specified and this system doesn't support the fsync system call, it issues a sync system call to flush all pending disk output. If fileId is specified and the system does support the fsync system call, it issues an fsync on the file corresponding to that Tcl fileId, forcing all pending output to that file out to disk ๐Ÿซถ

If fileId is specified, the file must be writable. A flush gets issued against the fileId before the sync.

Use the infox have_fsync command to figure out whether sync fileId is gonna do a sync or a fsync. Vibes only, bestie.

  • times โ€” Returns a list containing the process and child execution times, shaped like:
utime stime cutime cstime

Also peep the times(2) system call manual page. The values are in milliseconds โฑ๏ธ

  • umask ?octalmask? โ€” Sets the file-creation mode mask to the octal value of octalmask. If octalmask is omitted, the current mask is returned. Simple as ๐ŸŽ€
  • wait ?-nohang? ?-untraced? ?-pgroup? ?pid? โ€” Waits for a process created with the execl command to terminate, either from an untrapped signal or from a call to the exit system call. If the process id pid is specified, it waits on that process; otherwise it waits on any child process to terminate.

If -nohang is specified, then don't block waiting on a process to terminate โ€” and if no process is immediately available, it returns an empty list. If -untraced is specified, then the status of child processes that are stopped (and whose status hasn't been reported yet since they stopped) are also returned. If -pgroup is specified and pid is not specified, then it waits on any child process whose process group ID is the same as the calling process. If pid is specified along with -pgroup, then pid is taken as a process group ID, and it waits on any process in that process group to terminate ๐Ÿงš

wait returns a list containing three elements. First element: the process id of the process that terminated. If the process exited normally, the second element is EXIT, and the third contains the numeric exit code. If the process terminated due to a signal, the second element is SIG, and the third contains the signal name. If the process is currently stopped (on systems that support SIGSTP), the second element is STOP, followed by the signal name ๐Ÿ‘‘

Heads up bestie: it is possible to wait on processes that were created in the background with the exec command. BUT โ€” if any other exec command runs after the process terminates, then that process status gets reaped by the exec command and will not be available to the wait command ๐Ÿ˜ญ gone, reduced to atoms.

On systems without the waitpid system call, the -nohang, -untraced and -pgroup options are not available. The infox have_waitpid command may be used to determine whether this functionality exists on your system.


๐ŸŒธ FILE COMMANDS ๐ŸŒธ

These commands give you extended file access and manipulation โ€” it's giving main character energy for your filesystem ๐Ÿ’–. That includes searching ASCII-sorted data files, copying files, duplicating file descriptors, controlling file access options, retrieving open file status, and creating pipes with the pipe system call. Also linking files, setting file/process/user attributes, and truncating files. And there's an interface to the select system call available on Unix systems that support it โœจ

Real talk: Tcl file I/O is implemented on top of the stdio library, so by default the file is buffered. When you're communicating to a process through a pipe, a flush command should be issued to force the data out ๐Ÿซถ Alternatively, the fcntl command may be used to set the buffering mode of a file to line-buffered or unbuffered. iykyk.
  • bsearch fileId key ?retvar? ?compare_proc? โ€” Searches an opened file fileId containing lines of text sorted into ascending order for a match. key contains the string to match. If retvar is specified, then the line from the file is returned in retvar, and the command returns 1 if key was found, and 0 if it wasn't. If retvar is not specified or is a null name, then the command returns the line that was found, or an empty string if key wasn't found.

By default, the key is matched against the first white-space separated field in each line, and that field is treated as an ASCII string. If compare_proc is specified, then it defines the name of a Tcl procedure to evaluate against each line read from the sorted file during the execution of the bsearch command. compare_proc takes two arguments: the key and a line extracted from the file. The compare routine should return a number less than zero if the key is less than the line, zero if the key matches the line, or greater than zero if the key is greater than the line.

โš ๏ธ The file must be sorted in ascending order according to the same criteria compare_proc uses to compare the key with the line โ€” otherwise erroneous results will occur. Periodt. No shortcuts.

Also: this command does not work on files containing binary data (bytes of zero). Just so you know ๐Ÿ’€

  • channelfd channel โ€” Gets the unix file descriptor (an integer) for channel using the Tcl_GetChannelHandle API. On any error the return value is -1.

The channelfd command is not available on Windows ๐Ÿ™ˆ

  • chmod [-fileid] mode filelist โ€” Sets permissions of each of the files in the list filelist to mode, where mode is an absolute numeric mode or symbolic permissions as in the UNIX chmod(1) command. To specify a mode as octal, prefix it with a "0" (e.g. 0622) ๐ŸŽ€

If the option -fileid is specified, filelist is a list of open file identifiers rather than a list of file names. This option is not available on all Unix systems โ€” use the infox have_fchmod command to check if you've got it.

The chmod command is not available on Windows.

  • chown [-fileid] owner | {owner group} filelist โ€” Sets the owner of each file in the list filelist to owner, which can be a user name or numeric user id. If the first parameter is a list, then the owner is set to the first element of the list and the group is set to the second element. group can be a group name or numeric group id. If group is {}, then the file group will be set to the login group of the specified user ๐Ÿฆ‹

If the option -fileid is specified, filelist is a list of open file identifiers rather than a list of file names. This option is not available on all Unix systems โ€” use the infox have_fchown command to determine if this functionality is available.

The chown command is not available on Windows.

  • chgrp [-fileid] group filelist โ€” Sets the group id of each file in the list filelist to group, which can be either a group name or a numeric group id ๐Ÿงš

If the option -fileid is specified, filelist is a list of open file identifiers rather than a list of file names. This option is not available on all Unix systems โ€” use the infox have_fchown command to determine if this functionality is available.

The chgrp command is not available on Windows.

  • dup fileId ?targetFileId? โ€” Duplicates an open file. A new file id is opened that addresses the same file as fileId ๐Ÿ‘ฏ

If targetFileId is specified, then the file is dup'd to this specified file id. Normally this is stdin, stdout, or stderr. The dup command will handle flushing output and closing this file. The new file will be buffered โ€” if it needs to be unbuffered, use the fcntl command to set it unbuffered.

If fileId is a number rather than a Tcl file id, then the dup command will bind that file to a Tcl file id. Super useful for accessing files that are passed from the parent process ๐Ÿซถ The argument ?targetFileId? is not valid with this operation.

On Windows, only stdin, stdout, or stderr or a non-socket file handle number may be specified for targetFileId. The dup command does not work on sockets on Windows ๐Ÿ˜ญ

  • fcntl fileId attribute ?value? โ€” This command either sets or clears a file option or returns its current value. If value is not specified, then the current value of attribute is returned. All values are boolean. Some attributes may only be gotten, not modified. The following attributes may be specified:

โœจ the attributes, bestie โœจ

  • RDONLY โ€” The file is opened for reading only. (Get only)
  • WRONLY โ€” The file is opened for writing only. (Get only)
  • RDWR โ€” The file is opened for reading and writing. (Get only)
  • READ โ€” If the file is readable. (Get only)
  • WRITE โ€” If the file is writable. (Get only)
  • APPEND โ€” The file is opened for append-only writes. All writes will be forced to the end of the file. (Get or set)
  • NONBLOCK โ€” The file is to be accessed with non-blocking I/O. See the read system call for a description of how it affects the behavior of file reads ๐Ÿ”ฅ
  • CLOEXEC โ€” Close the file on a process exec. If the execl command or some other mechanism causes the process to do an exec, the file will be closed if this option is set.
  • NOBUF โ€” The file is not buffered. If set, then there's no buffering for the file. Zero buffer, zero vibes ๐Ÿ’…
  • LINEBUF โ€” the output file gets line buffered โœจ the buffer flushes when a newline gets written, when the buffer is full, or when input is requested. That's it, that's the whole vibe.
  • KEEPALIVE โ€” keeps a socket connection alive ๐Ÿซถ here's the tea: if SIGPIPE is enabled, then it gets sent when the connection breaks and data gets written to the socket. If SIGPIPE is ignored, an error is returned on the write instead. This attribute is valid only on sockets. And by default, SIGPIPE is ignored in Tcl.

So real talk: NONBLOCK, NOBUF and LINEBUF are all here for compatibility with older scripts ๐Ÿ’€ the fconfigure command is the preferred method of getting and setting these attributes. Use that one, bestie.

โš ๏ธ Heads up: the APPEND and CLOEXEC options are not available on Windows.

๐Ÿ”’ flock options fileId ?start? ?length? ?origin?

Okay so this one places a lock on all of a file or part of it ๐Ÿ’… the lock is either advisory or mandatory, depending on the mode bits of the file. It's placed beginning at relative byte offset start for length bytes. If start or length is omitted or empty, zero is assumed. If length is zero, then the lock always extends to the end of file โ€” even if the file grows ๐ŸŒฑ If origin is "start", the offset is relative to the beginning of the file. If it's "current", it's relative to the current access position in the file. If it's "end", it's relative to the end-of-file (negative is before the EOF, positive is after it). And if origin is omitted, start is assumed.

The following options are recognized, bestie:

  • -read โ€” place a read lock on the file ๐Ÿ‘€ multiple processes may be accessing the file with read-locks. Sharing is caring.
  • -write โ€” place a write lock on the file โœ๏ธ only one process may be accessing a file if there is a write lock. Sorry, main character energy only.
  • -nowait โ€” if specified, then the process will not block if the lock can't be obtained ๐Ÿƒโ€โ™€๏ธ with this option, the command returns 1 if the lock is obtained and 0 if it is not.

See your system's fcntl system call documentation for the full details of how file locking behaves, fr fr. And if locking is being done on ranges of a file, it's best to use unbuffered file access (see the fcntl command).

๐Ÿšจ The flock command is not available on Windows 95. It is available on Windows NT.

๐Ÿ“– for_file var filename code

This procedure implements a loop over the contents of a file, and honestly? iconic ๐ŸŽ€ for each line in filename, it sets var to the line and executes code.

The break and continue commands work exactly like they do with foreach.

For example, the command

for_file line /etc/passwd {echo $line}

would echo all the lines in the password file ๐Ÿ’–


๐Ÿ”“ funlock fileId ?start? ?length? ?origin?

Removes a lock from a file that was previously placed with the flock command โœจ the arguments are the same as for the flock command, so just go read that one for more details.

๐Ÿšจ The funlock command is not available on Windows 95. It is available on Windows NT.

๐Ÿ“Š fstat fileId ?item? | ?stat arrayvar?

Obtains status information about an open file ๐Ÿ‘‘

The following keys are used to identify data items:

  • atime โ€” the time of last access ๐Ÿ•
  • ctime โ€” the time of last file status change
  • dev โ€” the device containing a directory for the file. This value uniquely identifies the file system that contains the file.
  • gid โ€” the group ID of the file's group
  • ino โ€” the inode number. This field uniquely identifies the file in a given file system.
  • mode โ€” the mode of the file (see the mknod system call)
  • mtime โ€” time when the data in the file was last modified
  • nlink โ€” the number of links to the file
  • size โ€” the file size in bytes ๐Ÿ“
  • tty โ€” if the file is associated with a terminal, then 1, otherwise 0
  • type โ€” the type of the file in symbolic form, which is one of the following values: file, directory, characterSpecial, blockSpecial, fifo, link, or socket
  • uid โ€” the user ID of the file's owner

If one of these keys is specified as item, then that data item is returned ๐Ÿซถ

If stat arrayvar is specified, then the information is returned in the array arrayvar. Each of the above keys indexes an element of the array containing the data.

If only fileId is specified, the command returns the data as a keyed list.

The following values may be returned only if explicitly asked for โ€” they will not come back with the array or keyed list forms, so don't @ me:

  • remotehost โ€” if fileId is a TCP/IP socket connection, then a list is returned with the first element being the remote host IP address. If the remote host name can be found, it's returned as the second element of the list. The remote host IP port number is the third element ๐ŸŒ
  • localhost โ€” if fileId is a TCP/IP socket connection, then a list is returned with the first element being the local host IP address. If the local host name can be found, it's returned as the second element of the list. The local host IP port number is the third element ๐Ÿ’ป

โœ‚๏ธ ftruncate [-fileid] file newsize

Truncates a file to have a length of at most newsize bytes ๐Ÿ’…

If the option -fileid is specified, file is an open file identifier, otherwise it's a file path.

โš ๏ธ This command is not available or not fully functional if the underlying operating system support is not available. The command infox have_truncate will indicate if this command may truncate by file path. The command infox have_ftruncate will indicate if this command may truncate by file id.
๐Ÿšจ The -fileid option is not available on Windows.

๐Ÿ“œ lgets fileId ?varName?

Reads the next Tcl list from the file given by fileId and discards the terminating newline character โœจ this command differs from the gets command in that it reads Tcl lists rather than lines. If the list contains newlines or binary data, then that newline or bytes of zero will be returned as part of the result. Only a newline not quoted as part of the list indicates the end of the list. There's no corresponding command for outputting lists, because puts will do this correctly ๐Ÿ‘‘

If varName is specified, then the line is placed in the variable by that name and the return value is a count of the number of characters read (not including the newline). If the end of the file is reached before reading any characters, then -1 is returned and varName is set to an empty string. If varName is specified and an error occurs, whatever data was read will be returned in the variable โ€” however, the resulting string may not be a valid list ๐Ÿ˜ญ

If varName is not specified, then the return value will be the line (minus the newline character), or an empty string if the end of the file is reached before reading any characters. An empty string will also be returned if a line contains no characters except the newline, so eof may have to be used to determine what really happened ๐Ÿ™ˆ

The lgets command may be used to read and write lists containing binary data, however translation must be set to lf or the data may be corrupted ๐Ÿซ 

lgets is currently supported on non-blocking files.


๐Ÿงช pipe ?fileId_var_r fileId_var_w?

Creates a pipe ๐ŸŒˆ if fileId_var_r and fileId_var_w are specified, then pipe will set the variable named fileId_var_r to contain the fileId of the side of the pipe that was opened for reading, and fileId_var_w will contain the fileId of the side of the pipe that was opened for writing.

If the fileId variables are not specified, then a list containing the read and write fileIds is returned as the result of the command ๐Ÿ’–


๐Ÿ“‚ read_file ?-nonewline? fileName

๐Ÿ“‚ read_file fileName numBytes

This procedure reads the file fileName and returns the contents as a string ๐ŸŽ€ if -nonewline is specified, then the last character of the file is discarded if it's a newline. The second form specifies exactly how many bytes will be read and returned โ€” unless there are fewer than numBytes bytes left in the file, in which case all the remaining bytes are returned.


๐Ÿ‘€ select readfileIds ?writefileIds? ?exceptfileIds? ?timeout?

This command lets an Extended Tcl program wait on zero or more files being ready for reading, ready for writing, having an exceptional condition pending, or waiting for a timeout period to expire โœจ readFileIds, writeFileIds and exceptFileIds are each lists of fileIds, as returned from open, to query. An empty list ({}) may be specified if a category isn't used.

The files specified by the readFileIds list are checked to see if data is available for reading ๐Ÿ“– the writeFileIds are checked to see if the specified files are clear for writing โœ๏ธ the exceptFileIds are checked to see if an exceptional condition has occurred (typically, an error) ๐Ÿ’€ the write and exception checking is most useful on devices, however the read checking is very useful when communicating with multiple processes through pipes. select considers data pending in the stdio input buffer for read files as being ready for reading โ€” the files do not have to be unbuffered.

timeout is a floating point timeout value, in seconds โฑ๏ธ if an empty list is supplied (or the parameter is omitted), then no timeout is set. If the value is zero, then the select command functions as a poll of the files, returning immediately even if none are ready.

If the timeout period expires with none of the files becoming ready, then the command returns an empty list. Otherwise the command returns a list of three elements โ€” each of those elements is a list of the fileIds that are ready in the read, write and exception classes ๐Ÿซถ if none are ready in a class, then that element will be the null list. For example:

select {file3 file4 file5} {file6 file7} {} 10.5

could return

{file3 file4} {file6} {}

or perhaps

file3 {} {}
Quick heads-up for the Windows girlies: on Windows, only sockets can be used with the select command. Pipes, like the ones you get back from the open command, are not supported. No pipe dreams, sorry ๐Ÿ’€
  • write_file fileName string ?string...? โ€” this procedure writes the specified strings to the named file. That's it, that's the whole vibe: you point at a file, you hand it strings, it writes them. โœจ

๐ŸŒ NETWORK PROGRAMMING SUPPORT ๐ŸŒ

TclX is out here complementing the Tcl socket command, bestie โ€” it's giving supportive friend energy. ๐Ÿ’–

The host_info command is your go-to for getting info about a host by name or IP address. And that's not all โ€” the fstat and fcntl commands also give you options for querying and controlling connected sockets. Oh, and if you wanna grab the host name of the local system? Use the id host command. ๐Ÿซถ

host_info option host

Obtain information about an Internet host. The argument host can be either a host name or an IP address. ๐Ÿ‘‘

The following subcommands are recognized:

  • addresses โ€” returns the list of IP addresses for host. ๐Ÿ“
  • official_name โ€” returns the official name for host. ๐Ÿ’…
  • aliases โ€” returns the list of aliases for host. Just so you know (and this is the important little detail, don't skip it): these are IP number aliases, not DNS CNAME aliases. See ifconfig(2). ๐Ÿงš

๐Ÿ” FILE SCANNING COMMANDS ๐Ÿ”

Okay so this is the part where TclX lowkey becomes awk but make itโœจdeclarativeโœจ.

These commands give you a facility to scan files, matching lines of the file against regular expressions and executing Tcl code on a match. With this facility you can use Tcl to do the sort of file processing that is traditionally done with awk. And honestly? Since Tcl's approach is more declarative, some of the scripts that can be rather difficult to write in awk are simple to code in Tcl. Ate. ๐Ÿ”ฅ

File scanning in Tcl centers around the concept of a scan context. A scan context contains one or more match statements, which associate regular expressions to scan for with Tcl code to be executed when the expressions are matched. iykyk ๐ŸŒธ

scancontext ?option?

This command manages file scan contexts. A scan context is a collection of regular expressions and commands to execute when that regular expression matches a line of the file. A context may also have a single default match, to be applied against lines that do not match any of the regular expressions. Multiple scan contexts may be defined and they may be reused on multiple files. A scan context is identified by a context handle.

The scancontext command takes the following forms:

  • scancontext create โ€” create a new scan context. The scanmatch command is used to define patterns in the context. A contexthandle is returned, which the Tcl programmer uses to refer to the newly created scan context in calls to the Tcl file scanning commands. ๐ŸŽ€
  • scancontext delete contexthandle โ€” delete the scan context identified by contexthandle, and free all of the match statements and compiled regular expressions associated with the specified context. Cleanup slay. ๐Ÿงน
  • scancontext copyfile contexthandle ?filehandle? โ€” set or return the file handle that unmatched lines are copied to (see scanfile). If filehandle is omitted, the copy file handle is returned. If no copy file is associated with the context, {} is returned. If a file handle is specified, it becomes the copy file for this context. If filehandle is {}, then it removes any copy file specification for the context. ๐Ÿ’…

scanfile ?-copyfile copyFileId? contexthandle fileId

Scan the file specified by fileId, starting from the current file position. Check all patterns in the scan context specified by contexthandle against it, executing the match commands corresponding to patterns matched. ๐Ÿ“–

If the optional -copyfile argument is specified, the next argument is a file ID to which all lines not matched by any pattern (excluding the default pattern) are to be written. If the copy file is specified with this flag, instead of using the scancontext copyfile command, the file is disassociated from the scan context at the end of the scan. ๐Ÿ”„

โš ๏ธ Real talk: this command does not work on files containing binary data (bytes of zero). Don't come for it, it's just not built for that. ๐Ÿ’€

scanmatch ?-nocase? contexthandle ?regexp? commands

Specify Tcl commands to be evaluated when regexp is matched by a scanfile command. The match is added to the scan context specified by contexthandle. Any number of match statements may be specified for a given context. Regexp is a regular expression (see the regexp command). If -nocase is specified as the first argument, the pattern is matched regardless of alphabetic case. ๐Ÿ™ˆ

If regexp is not specified, then a default match is specified for the scan context. The default match will be executed when a line of the file does not match any of the regular expressions in the current scancontext. ๐ŸŽฏ

The array matchInfo is available to the Tcl code that is executed when an expression matches (or defaults). It contains information about the file being scanned and where within it the expression was matched. ๐ŸŒˆ

matchInfo is local to the top level of the match command unless declared global at that level by the Tcl global command. If it is to be used as a global, it must be declared global before scanfile is called (since scanfile sets the matchInfo before the match code is executed, a subsequent global will override the local variable). So like... order matters, bestie. ๐Ÿซถ

The following array entries are available:

  • matchInfo(line) โ€” contains the text of the line of the file that was matched. ๐Ÿ“
  • matchInfo(offset) โ€” the byte offset into the file of the first character of the line that was matched. ๐Ÿ“
  • matchInfo(linenum) โ€” the line number of the line that was matched. This is relative to the first line scanned, which is usually, but not necessarily, the first line of the file. The first line is line number one. 1๏ธโƒฃ
  • matchInfo(context) โ€” the context handle of the context that this scan is associated with. ๐Ÿ”—
  • matchInfo(handle) โ€” the file id (handle) of the file currently being scanned. ๐Ÿ“‚
  • matchInfo(copyHandle) โ€” the file id (handle) of the file specified by the -copyfile option. The element does not exist if -copyfile was not specified. ๐Ÿ™…
  • matchInfo(submatch0) โ€” will contain the characters matching the first parenthesized subexpression. The second will be contained in submatch1, etc. ๐Ÿ“
  • matchInfo(subindex0) โ€” will contain a list of the starting and ending indices of the string matching the first parenthesized subexpression. The second will be contained in subindex1, etc. ๐Ÿ“

All scanmatch patterns that match a line will be processed in the order in which their specifications were added to the scan context. The remainder of the scanmatch pattern-command pairs may be skipped for a file line if a continue is executed by the Tcl code of a preceding, matched pattern. โญ๏ธ

If a return is executed in the body of the match command, the scanfile command currently in progress returns, with the value passed to return as its return value. ๐Ÿ


๐Ÿงฎ MATH COMMANDS ๐Ÿงฎ

Several extended math commands make many additional math functions available in TclX. In addition, a set of procedures provide command access to the math functions supported by the expr command. Math girlies rise up, this is your moment. ๐Ÿ‘‘

The following procedures provide command interfaces to the expr math functions. They take the same arguments as the expr functions and may take expressions as arguments. โœจ

abs         acos        asin       atan2
atan        ceil        cos        cosh
double      exp         floor      fmod
hypot       int         log10      log
pow         round       sin        sinh
sqrt        tan         tanh

max num1 ?..numN?

expr max(num1, num2)

Returns the argument that has the highest numeric value. Each argument may be any integer or floating point value. ๐Ÿ”ผ

This functionality is also available as a math function max in the Tcl expr command.

min num1 ?..numN?

expr min(num1, num2)

Returns the argument that has the lowest numeric value. Each argument may be any integer or floating point value. ๐Ÿ”ฝ

This functionality is also available as a math function min in the Tcl expr command.

random limit | seed ?seedval?

Generate a pseudorandom integer number greater than or equal to zero and less than limit. ๐ŸŽฒ

If seed is specified, then the command resets the random number generator to a starting point derived from the seedval. This allows one to reproduce pseudorandom number sequences for testing purposes. If seedval is omitted, then the seed is set to a value based on current system state and the current time, providing a reasonably interesting and ever-changing seed. No cap, that's the chaotic energy we love. ๐ŸŒˆ

๐Ÿ’– LIST MANIPULATION COMMANDS ๐Ÿ’–

Extended Tcl is out here giving you extra list manipulation commands and procedures, and honestly? It ate. ๐Ÿ“


intersect lista listb

Procedure that returns the logical intersection of two lists. The returned list will be sorted โ€” no messy vibes, it's organized bestie. โœจ

intersect3 lista listb

Procedure that intersects two lists and hands you back a list containing three lists:

  1. The first list returned is everything in lista that wasn't in listb.
  2. The second list contains the intersection of the two lists.
  3. The third list contains all the elements that were in listb but weren't in lista.

The returned lists will be sorted. Three-for-one, we love a multitasker. ๐Ÿซถ

lassign list var ?var...?

Assigns successive elements of a list to the specified variables. If there are more variable names than fields, the remaining variables get set to the empty string. If there are more elements than variables, you get a list of the unassigned elements returned. Fancy.

For example:

lassign {dave 100 200 {Dave Foo}} name uid gid longName

That assigns name to "dave", uid to "100", gid to "200", and longName to "Dave Foo". Slay, everyone's seated and accounted for. ๐Ÿ’…

lcontain list element

Determines if the element is a list element of list. If the element is contained in the list, 1 is returned; otherwise, 0 is returned. Simple as. ๐Ÿ˜Œ

lempty list

Determines if the specified list is empty. If empty, 1 is returned; otherwise, 0 is returned. This command is an alternative to comparing a list to an empty string โ€” but here's the iconique part: it checks for a string of all whitespace, which counts as an empty list. No cap. ๐Ÿฆ‹

lmatch ?mode? list pattern

Searches the elements of list, returning a list of all elements matching pattern. If none match, an empty list is returned. Sad girl hours, but correct.

The mode argument tells Tcl how the elements of the list are to be matched against pattern, and it must have one of these values:

  • -exact โ€” The list element must contain exactly the same string as pattern.
  • -glob โ€” Pattern is a glob-style pattern which is matched against each list element using the same rules as the string match command.
  • -regexp โ€” Pattern is treated as a regular expression and matched against each list element using the same rules as the regexp command.

If mode is omitted then it defaults to -glob. ๐Ÿ‘‘

Heads up bestie: only the -exact comparison will work on binary data. The other two said nah to binary. ๐Ÿ’€

lrmdups list

Procedure that removes duplicate elements from a list. The returned list will be sorted. Decluttered, organized, healed. ๐ŸŒธ

lvarcat var string ?string...?

This command treats each string argument as a list and concatenates them to the end of the contents of var, forming a single list. The list is stored back into var and also returned as the result. If var does not exist, it is created. Growth mindset fr fr. ๐ŸŒฑ

lvarpop var ?indexExpr? ?string?

The lvarpop command pops (deletes) the element indexed by the expression indexExpr from the list contained in the variable var. If index is omitted, then 0 is assumed. If string is specified, then the deleted element is replaced by string. The replaced or deleted element is returned.

Thus lvarpop argv 0 returns the first element of argv, setting argv to contain the remainder of the string. Main character energy: takes the first one, keeps it, and just leaves. ๐Ÿ˜ญ

If the expression indexExpr starts with the string end, then end is replaced with the index of the last element in the list. If the expression starts with len, then len is replaced with the length of the list.

lvarpush var string ?indexExpr?

The lvarpush command pushes (inserts) string as an element in the list contained in the variable var. The element is inserted before position indexExpr in the list. If index is omitted, then 0 is assumed. If var does not exist, it is created. Making room for you in the group chat. ๐Ÿซถ

If the expression indexExpr starts with the string end, then end is replaced with the index of the last element in the list. If the expression starts with len, then len is replaced with the length of the list.

Note that a value of end means insert the string before the last element. Don't come for me, that's just what it does. ๐Ÿ™ˆ

union lista listb

Procedure that returns the logical union of the two specified lists. Any duplicate elements are removed. Two lists become one friend group. ๐ŸŒˆ


๐Ÿ”‘ KEYED LISTS ๐Ÿ”‘

Extended Tcl defines a special type of list referred to as keyed lists. These lists provide a structured data type built upon standard Tcl lists. It's giving functionality similar to structs in the C programming language, honestly.

A keyed list is a list in which each element contains a key and value pair. These element pairs are stored as lists themselves, where the key is the first element of the list and the value is the second. These key-value pairs are referred to as fields. Here's an example of a keyed list:

{{NAME {Frank Zappa}} {JOB {musician and composer}}}

If the variable person contained the above list, then keylget person NAME would return {Frank Zappa}. And if you execute this command:

keylset person ID 106

that would make person contain:

{{ID 106} {NAME {Frank Zappa}} {JOB {musician and composer}}

Fields may contain subfields; . is the separator character. Subfields are actually fields where the value is another keyed list. So the following list has the top level fields ID and NAME, and subfields NAME.FIRST and NAME.LAST:

{ID 106} {NAME {{FIRST Frank} {LAST Zappa}}}

There is no limit to the recursive depth of subfields, allowing you to build complex data structures. It's turtles all the way down bestie. ๐Ÿขโœจ

Keyed lists are constructed and accessed via a number of commands. All keyed list management commands take the name of the variable containing the keyed list as an argument (i.e. passed by reference), rather than passing the list directly. Important detail, don't forget it. ๐Ÿ’…


keyldel listvar key

Deletes the field specified by key from the keyed list in the variable listvar. This removes both the key and the value from the keyed list. Blocked and deleted, respectfully. ๐Ÿ’€

keylget listvar ?key? ?retvar | {}?

Returns the value associated with key from the keyed list in the variable listvar. If retvar is not specified, then the value will be returned as the result of the command. In this case, if key is not found in the list, an error will result. ๐Ÿ˜ฌ

If retvar is specified and key is in the list, then the value is returned in the variable retvar and the command returns 1 if the key was present within the list. If key isn't in the list, the command will return 0, and retvar will be left unchanged. If {} is specified for retvar, the value is not returned, allowing the Tcl programmer to determine if a key is present in a keyed list without setting a variable as a side-effect. No sneaky side effects, we love a clean boundary. ๐Ÿงš

If key is omitted, then a list of all the keys in the keyed list is returned.

keylkeys listvar ?key?

Returns a list of the keys in the keyed list in the variable listvar. If keys is specified, then it is the name of a key field whose subfield keys are to be retrieved. Yes bestie, keys within keys. ๐Ÿ”‘

keylset listvar key value ?key2 value2 ...?

Sets the value associated with key, in the keyed list contained in the variable listvar, to value. If listvar does not exist, it is created. If key is not currently in the list, it will be added. If it already exists, value replaces the existing value. Multiple keywords and values may be specified, if desired โ€” go off, set them all at once. ๐Ÿ”ฅ๐Ÿ‘‘

โœจ STRING AND CHARACTER MANIPULATION COMMANDS โœจ

okay bestie, this whole section is the glow-up era for strings ๐Ÿ’… these commands let you classify characters, convert characters between character and numeric values, index into a string, figure out the length of a string, pull out a range of characters from a string, replicate a string a bunch of times, and transliterate a string (basically the Unix tr program's cousin, iykyk). so many little icons, all here for you ๐ŸŽ€


  • ccollate ?-local? string1 string2 โ€” compares two strings, periodt. it returns -1 if string1 is less than string2, 0 if they're equal, and 1 if string1 is greater than string2.

if -local is specified, the strings get compared according to the collation environment of the current locale ๐ŸŒ

heads up bestie: this command does not work with binary or UTF data ๐Ÿ˜ญ
  • cconcat ?string1? ?string2? ?...? โ€” glues all the arguments together and returns the resulting string. normally the parser handles string concatenation, but sometimes it's genuinely useful to have a command that returns a string โ€” it's generally useful when a command to evaluate is required. and ngl, no separators get inserted between the strings, so it's giving clean seamless slay โœจ

this command is UTF-aware ๐Ÿฆ‹

  • cequal string string โ€” compares two strings for equality, no notes. returns 1 if string1 and string2 are the identical and 0 if they're not. it's a short-cut for string compare and avoids the problems that come with string expressions being treated unintentionally as numbers ๐Ÿ’€

this command is UTF-aware and will also work on binary data ๐Ÿ”ฅ

  • cindex string indexExpr โ€” returns the character indexed by the expression indexExpr (zero based) from string.

if the expression indexExpr starts with the string end, then end is replaced with the index of the last character in the string. if the expression starts with len, then len is replaced with the length of the string. the way that just works ๐Ÿงš

this command is UTF-aware ๐Ÿ’–

  • clength string โ€” returns the length of string in characters. it's literally just a shortcut for:
string length string

this command is UTF-aware โœจ

  • crange string firstExpr lastExpr โ€” returns a range of characters from string starting at the character indexed by the expression firstExpr (zero-based) until the character indexed by the expression lastExpr.

if the expression firstExpr or lastExpr starts with the string end, then end is replaced with the index of the last character in the string. if the expression starts with len, then len is replaced with the length of the string.

this command is UTF-aware ๐ŸŒธ

  • csubstr string firstExpr lengthExpr โ€” returns a range of characters from string starting at the character indexed by the expression firstExpr (zero-based) for lengthExpr characters.

same deal as before: if the expression firstExpr or lengthExpr starts with the string end, then end is replaced with the index of the last character in the string. if the expression starts with len, then len is replaced with the length of the string.

this command is UTF-aware ๐Ÿ‘‘

  • ctoken strvar separators โ€” parses a token out of a character string. the string to parse lives in the variable named strvar, and separators contains all of the valid separator characters for tokens in the string. all leading separators get skipped and the first token is returned. strvar then gets modified to contain the remainder of the string following the token ๐Ÿซถ
no cap, this command does not work with binary data ๐Ÿ™ˆ

๐ŸŽ€ ctype โ€” the character-classification queen ๐ŸŽ€

  • ctype ?-failindex var? class string โ€” determines whether all characters in string are of the specified class. returns 1 if they're all of class, and 0 if they're not, or if the string is empty. this command also gives you another method (besides format and scan) of converting between an ASCII character and its numeric value ๐Ÿงฎ

the following ctype commands are available:

  • ctype ?-failindex var? alnum string โ€” tests that all characters are alphabetic or numeric characters as defined by the character set.
  • ctype ?-failindex var? alpha string โ€” tests that all characters are alphabetic characters as defined by the character set.
  • ctype ?-failindex var? ascii string โ€” tests that all characters are an ASCII character (a non-negative number less than 0200).
  • ctype char number โ€” converts the numeric value, string, to an ASCII character. Number must be in the range 0 through the maximum Unicode values.
  • ctype ?-failindex var? cntrl string โ€” tests that all characters are "control characters" as defined by the character set.
  • ctype ?-failindex var? digit string โ€” tests that all characters are valid decimal digits, i.e. 0 through 9.
  • ctype ?-failindex var? graph string โ€” tests that all characters within are any character for which ctype print is true, except for space characters.
  • ctype ?-failindex var? lower string โ€” tests that all characters are lowercase letters as defined by the character set.
  • ctype ord character โ€” converts a character into its decimal numeric value. the first character of the string is converted to its numeric Unicode value.
  • ctype ?-failindex var? space string โ€” tests that all characters are either a space, horizontal-tab, carriage return, newline, vertical-tab, or form-feed.
  • ctype ?-failindex var? print string โ€” tests that all characters are a space or any character for which ctype alnum or ctype punct is true or other "printing character" as defined by the character set.
  • ctype ?-failindex var? punct string โ€” tests that all characters are made up of any of the characters other than the ones for which alnum, cntrl, or space is true.
  • ctype ?-failindex var? upper string โ€” tests that all characters are uppercase letters as defined by the character set.
  • ctype ?-failindex var? xdigit string โ€” tests that all characters are valid hexadecimal digits, that is 0 through 9, a through f or A through F.

if -failindex is specified, then the index into string of the first character that did not match the class is returned in var ๐Ÿ’… lowkey so useful for debugging.


  • replicate string countExpr โ€” returns string, replicated the number of times indicated by the expression countExpr. it's giving copy-paste but make it fashion โœจ

this command is UTF-aware and will work with binary data ๐Ÿ”ฅ

  • translit inrange outrange string โ€” translates characters in string, changing characters occurring in inrange to the corresponding character in outrange. inrange and outrange may be a list of characters or a range in the form A-M. for example:
translit a-z A-Z foobar
bestie, real talk: this command currently only supports characters in ASCII range; UTF-8 characters out of this range will generate an error ๐Ÿ’€

โœจ XPG/3 MESSAGE CATALOG COMMANDS โœจ

Okay bestie, this is the message-catalog era of the page, and itโ€™s genuinely iconic for anyone who wants their app to speak every language without rewriting source code every five minutes. These commands give you a Tcl interface to message catalogs that are compliant with the X/Open Portability Guide, Version 3 (XPG/3). ๐Ÿ’–

Tcl programmers can use message catalogs to create applications that are language-independent. Through message catalogs, prompts, messages, menus and so forth can exist for any number of languages, and they can be altered, and new languages added, without affecting any Tcl or C source code โ€” which greatly eases the maintenance difficulties incurred by supporting multiple languages. Slay, honestly. ๐ŸŒˆ

A default text message is passed to the command that fetches entries from message catalogs. This lets the Tcl programmer create message catalogs containing messages in various languages while still having a set of default messages available regardless of whether any message catalogs are present โ€” and it lets programs press on without difficulty when no catalogs are present. ๐Ÿซถ

So the normal approach to using message catalogs is to ignore errors on catopen, in which case catgets will return the default message that was specified in the call.

The Tcl message catalog commands normally ignore most errors. If itโ€™s desirable to detect errors, a special option is provided. This is normally used only during debugging, to insure that message catalogs are being used. If your Unix implementation does not have XPG/3 message catalog support, stubs will be compiled in that will create a version of catgets that always returns the default string. That allows for easy porting of software to environments that donโ€™t have support for message catalogs. ๐Ÿ’…

Message catalogs are global to the process, so an application with multiple Tcl interpreters within the same process may pass and share message catalog handles. No cap.

  • catopen ?-fail | -nofail? catname โ€” Opens the message catalog catname. This may be a relative path name, in which case the NLSPATH environment variable is searched to find an absolute path to the message catalog. A handle in the form msgcatN is returned. Normally, errors are ignored, and in the case of a failed call to catopen, a handle is returned to an unopened message catalog. That handle may still be passed to catgets and catclose, causing catgets to simply return the default string, as described above. If the -fail option is specified, an error is returned if the open fails. The option -nofail specifies the default behavior of not returning an error when catopen fails to open a specified message catalog. If the handle from a failed catopen is passed to catgets, the default string is returned. ๐ŸŽ€
  • catgets catHandle setnum msgnum defaultstr โ€” Retrieves a message from a message catalog. catHandle should be a Tcl message catalog handle that was returned by catopen. setnum is the message set number, and msgnum is the message number. If the message catalog was not opened, or the message set or message number cannot be found, then the default string, defaultstr, is returned. Lowkey the most forgiving lookup ever. ๐Ÿ˜ญ
  • catclose ?-fail | -nofail? cathandle โ€” Closes the message catalog specified by cathandle. Normally, errors are ignored. If -fail is specified, any errors closing the message catalog file are returned. The option -nofail specifies the default behavior of not returning an error. The use of -fail only makes sense if it was also specified in the call to catopen. Periodt.
  • mainloop โ€” This procedure sets up a top-level event loop. Events are processed until there are no more active event sources, at which time the process exits. It is used to build event-oriented programs using the TclX shell in a style similar to that used with wish. If the global variable tcl_interactive exists and has a true value, an interactive command handler is started as well. If the command handler is terminated by an EOF, the process will be exited. Main character energy for event loops, honestly. ๐Ÿ‘‘

๐ŸŒธ HELP FACILITY ๐ŸŒธ

The help facility lets you look up help pages which were extracted from the standard Tcl manual pages and Tcl scripts during Tcl installation. Help files are structured as a multilevel tree of subjects and help pages. Help files are found by searching directories named help in the directories listed in the auto_path variable. All of the files in the list of help directories form a virtual root of the help tree. This method allows multiple applications to provide help trees without having the files reside in the same directory. So clever. ๐Ÿงš

The help facility can be accessed in two ways: as interactive commands in the Extended Tcl shell, or as an interactive Tk-based program (if you have built Extended Tcl with Tk).

To run the Tk-based interactive help program:

tclhelp ?addpaths?

Where addpaths are additional paths to search for help directories. By default, only the auto_path used by tclhelp is searched. This will result in help on Tcl, Extended Tcl and Tk. ๐Ÿ’œ

The following interactive Tcl commands and options are provided with the help package:

  • help โ€” Help, without arguments, lists all the help subjects and pages under the current help subject.
  • help subject โ€” Displays all of the help pages and lower level subjects (if any exist) under the subject subject.
  • help subject/helppage โ€” Displays the specified help page. The help output is passed through a simple pager if output exceeds 23 lines, pausing waiting for a return to be entered. If any other character is entered, the output is terminated. Very โ€œread it or skip itโ€ of it. ๐Ÿ’…
  • helpcd ?subject? โ€” Changes the current subject, which is much like the Unix current directory. If subject is not specified, return to the top-level of the help tree. Help subject path names may also include .. elements.
  • helppwd โ€” Displays the current help subject.
  • help help | ? โ€” Displays help on the help facility at any directory level. Meta, but make it cute. ๐Ÿฆ‹
  • apropos pattern โ€” This command locates subjects by searching their one-line descriptions for a pattern. apropos is useful when you can remember part of the name or description of a command, and want to search through the one-line summaries for matching lines. Full regular expressions may be specified (see the regexp command). Obsessed with a good search moment. ๐Ÿ”ฅ

๐ŸŽ€ TCL LOADABLE LIBRARIES AND PACKAGES ๐ŸŽ€

Extended Tcl supports standard Tcl tclIndex libraries and package libraries. A package library file can contain multiple independent Tcl packages. A package is a named collection of related Tcl procedures and initialization code. Think of it as a little friend group of procedures, ngl.

The package library file is just a regular Unix text file, editable with your favorite text editor, containing packages of Tcl source code. The package library file name must have the suffix .tlib. An index file with the same prefix name and the suffix .tndx resides in the same directory as the .tlib file. The .tndx will be automatically created whenever it is out of date or missing (provided there is write access to the directory). Iconic little auto-maintenance behavior. โœจ

The variable auto_path contains a list of directories that are searched for libraries. The first time an unknown command trap is taken, the indexes for the libraries are loaded into memory. If the auto_path variable is changed during execution of a program, it will be re-searched. Only the first package of a given name found during the execution of a program is loaded. This can be overridden with the loadlibindex command. Okay, noted. ๐Ÿ’–

The start of a package is delimited by:

#@package: package_name proc1 ?..procN?

These lines must start in column one. Everything between the #@package: keyword and the next #@package: keyword or a #@packend keyword, or the end of the file, becomes part of the named package. The specified procedures, proc1..procN, are the entry points of the package. When a command named in a package specification is executed and detected as an unknown command, all code in the specified package will be sourced. This package should define all of the procedures named on the package line, define any support procedures required by the package and do any package-specific initialization. Package declarations may be continued on subsequent lines using standard Tcl backslash line continuations. The #@packend keyword is useful to make sure only the minimum required section of code is sourced. Thus, for example, a large comment block at the beginning of the next file wonโ€™t be loaded. So efficient. ๐ŸŒŸ

Care should be taken in defining package_name, as the first package found in the path with a given name is loaded. This can be useful in developing new versions of packages installed on the system. Big โ€œtest your new version without chaosโ€ energy. ๐Ÿ™ˆ

For example, in a package source file, the presence of the following line:

#@package: directory_stack pushd popd dirs

says that the text lines following that line in the package file up to the next package line or the end of the file is a package named directory_stack, and that an attempt to execute either pushd, popd or dirs when the routine is not already defined will cause the directory_stack portion of the package file to be loaded. And thatโ€™s literally the whole vibe of package entry points. ๐Ÿ“

๐ŸŽ€ PACKAGE LIBRARY MANAGEMENT COMMANDS ๐ŸŽ€

okay so this is the part where we talk about building and managing package libraries โ€” like, the whole infrastructure of it ๐Ÿ’… there's a bunch of commands for it, and the ones that are extended versions of the standard Tcl library commands are the ones listed here. also important: every single standard Tcl library management command and variable is supported too, so don't come for me thinking they got left out, they're just not re-explained here, iykyk โœจ


  • auto_commands ?-loaders? โ€” lists the names of all known loadable procedures and command procedures. and if you pass -loaders, it also hands you back the command that will be executed to load the command ๐Ÿซถ
  • buildpackageindex libfilelist โ€” builds index files for package libraries. libfilelist is a list of package libraries, and every name has to end with the suffix .tlib or it's a no. for each one, a corresponding .tndx file gets built. heads up: you must have write access to the directory containing each library, otherwise this whole thing is not happening bestie ๐Ÿ˜ญ
  • convert_lib tclIndex packagelib ?ignore? โ€” converts an old-school Ousterhout style tclIndex index file plus its associated source files into a package library called packagelib. if packagelib doesn't have a .tlib extension, one gets added for you, slay. any files listed in tclIndex that are also in the ignore list get skipped. and listen โ€” files in ignore should be just the base file names, not full paths โญ
  • loadlibindex libfile.tlib โ€” loads the package library index of the library file libfile (which must have the .tlib suffix). so here's the vibe: package library indexes along the auto_path get loaded automatically on the first demand_load, and this command exists for when you wanna explicitly load libraries that aren't in the path. if the index file (with the .tndx suffix) doesn't exist or is out of date, it gets rebuilt โ€” but only if you've got the directory permissions to create it ๐Ÿ™ˆ also: if a package with the same name as one in libfile.tlib is already loaded, its definition gets overridden by the new package. however (and this is the big however ๐Ÿ’€), if any procedure from the previously defined package has actually been used, then the procedures from libfile.tlib will not be loaded. no cap, that's the rule.
  • auto_packages ?-location? โ€” returns a list of the names of all defined packages ๐Ÿ‘‘ and if you throw -location in there, you get a list of pairs: package name plus the .tlib path name, offset and length of the package within the library. chef's kiss, so much info.
  • auto_load_file file โ€” sources a file exactly like the source command does, except it searches auto_path for the file instead of making you spell out where it lives. main character energy honestly ๐ŸŒˆ
  • searchpath path file โ€” searches every directory in the specified path (which is a Tcl list) for the specified file, and returns the full path name of the file. if the file you asked for can't be found? you get an empty string back, and that's just how it is ๐Ÿฆ‹

auto_commands ?-loaders?
buildpackageindex libfilelist
convert_lib tclIndex packagelib ?ignore?
loadlibindex libfile.tlib
auto_packages ?-location?
auto_load_file file
searchpath path file
ok genuine heads up bestie: loadlibindex has real consequences โ€” overriding a package definition is fine right up until somebody has used a proc from the old one, and then nothing from the new library loads. plan around it, don't be surprised by it ๐Ÿ’–

and that's a wrap on the whole page!! ๐ŸŽ€โœจ this was the TclX(TCL) page from the Tcl manual set โ€” you made it all the way to the end, so proud of you fr fr ๐Ÿซถ go build something iconic with it, mwah ๐Ÿ’œ

๐Ÿ“ฆ where this page comes from