diff options
Diffstat (limited to 'doc')
-rw-r--r-- | doc/Access.3 | 71 | ||||
-rw-r--r-- | doc/AddErrInfo.3 | 52 | ||||
-rw-r--r-- | doc/AppInit.3 | 10 | ||||
-rw-r--r-- | doc/AssocData.3 | 4 | ||||
-rw-r--r-- | doc/Async.3 | 4 | ||||
-rw-r--r-- | doc/BackgdErr.3 | 49 | ||||
-rw-r--r-- | doc/ByteArrObj.3 | 10 | ||||
-rw-r--r-- | doc/CallDel.3 | 14 | ||||
-rw-r--r-- | doc/Cancel.3 | 66 | ||||
-rw-r--r-- | doc/ChnlStack.3 | 2 | ||||
-rw-r--r-- | doc/Class.3 | 236 | ||||
-rw-r--r-- | doc/CrtChannel.3 | 117 | ||||
-rw-r--r-- | doc/CrtChnlHdlr.3 | 6 | ||||
-rw-r--r-- | doc/CrtCloseHdlr.3 | 5 | ||||
-rw-r--r-- | doc/CrtCommand.3 | 24 | ||||
-rw-r--r-- | doc/CrtFileHdlr.3 | 11 | ||||
-rw-r--r-- | doc/CrtInterp.3 | 62 | ||||
-rw-r--r-- | doc/CrtMathFnc.3 | 17 | ||||
-rw-r--r-- | doc/CrtObjCmd.3 | 15 | ||||
-rw-r--r-- | doc/CrtTimerHdlr.3 | 9 | ||||
-rw-r--r-- | doc/CrtTrace.3 | 10 | ||||
-rw-r--r-- | doc/DoWhenIdle.3 | 9 | ||||
-rw-r--r-- | doc/Encoding.3 | 43 | ||||
-rw-r--r-- | doc/Ensemble.3 | 73 | ||||
-rw-r--r-- | doc/Eval.3 | 5 | ||||
-rw-r--r-- | doc/Exit.3 | 25 | ||||
-rw-r--r-- | doc/FileSystem.3 | 715 | ||||
-rw-r--r-- | doc/FindExec.3 | 7 | ||||
-rwxr-xr-x[-rw-r--r--] | doc/GetCwd.3 | 0 | ||||
-rw-r--r-- | doc/GetIndex.3 | 7 | ||||
-rw-r--r-- | doc/GetStdChan.3 | 2 | ||||
-rw-r--r-- | doc/GetTime.3 | 51 | ||||
-rwxr-xr-x[-rw-r--r--] | doc/GetVersion.3 | 0 | ||||
-rw-r--r-- | doc/Hash.3 | 32 | ||||
-rw-r--r-- | doc/IntObj.3 | 9 | ||||
-rw-r--r-- | doc/Interp.3 | 40 | ||||
-rw-r--r-- | doc/Limit.3 | 6 | ||||
-rw-r--r-- | doc/LinkVar.3 | 28 | ||||
-rw-r--r-- | doc/ListObj.3 | 10 | ||||
-rw-r--r-- | doc/Load.3 | 69 | ||||
-rw-r--r-- | doc/Method.3 | 248 | ||||
-rw-r--r-- | doc/NRE.3 | 328 | ||||
-rw-r--r-- | doc/Namespace.3 | 12 | ||||
-rw-r--r-- | doc/Notifier.3 | 62 | ||||
-rw-r--r-- | doc/Object.3 | 53 | ||||
-rw-r--r-- | doc/ObjectType.3 | 24 | ||||
-rw-r--r-- | doc/OpenFileChnl.3 | 44 | ||||
-rw-r--r-- | doc/OpenTcp.3 | 24 | ||||
-rw-r--r-- | doc/Panic.3 | 27 | ||||
-rw-r--r-- | doc/ParseArgs.3 | 198 | ||||
-rw-r--r-- | doc/ParseCmd.3 | 45 | ||||
-rw-r--r-- | doc/PkgRequire.3 | 13 | ||||
-rw-r--r-- | doc/Preserve.3 | 8 | ||||
-rw-r--r-- | doc/PrintDbl.3 | 4 | ||||
-rw-r--r-- | doc/RegConfig.3 | 9 | ||||
-rw-r--r-- | doc/RegExp.3 | 14 | ||||
-rw-r--r-- | doc/SaveResult.3 | 4 | ||||
-rw-r--r-- | doc/SetChanErr.3 | 153 | ||||
-rw-r--r-- | doc/SetResult.3 | 59 | ||||
-rw-r--r-- | doc/SplitList.3 | 11 | ||||
-rw-r--r-- | doc/SplitPath.3 | 3 | ||||
-rw-r--r-- | doc/StaticPkg.3 | 11 | ||||
-rw-r--r-- | doc/StringObj.3 | 48 | ||||
-rw-r--r-- | doc/Tcl.n | 74 | ||||
-rw-r--r-- | doc/TclZlib.3 | 248 | ||||
-rw-r--r-- | doc/Tcl_Main.3 | 97 | ||||
-rw-r--r-- | doc/Thread.3 | 60 | ||||
-rw-r--r-- | doc/TraceCmd.3 | 4 | ||||
-rw-r--r-- | doc/TraceVar.3 | 6 | ||||
-rw-r--r-- | doc/Translate.3 | 11 | ||||
-rw-r--r-- | doc/Utf.3 | 2 | ||||
-rw-r--r-- | doc/WrongNumArgs.3 | 10 | ||||
-rw-r--r-- | doc/after.n | 31 | ||||
-rw-r--r-- | doc/append.n | 9 | ||||
-rw-r--r-- | doc/apply.n | 46 | ||||
-rw-r--r-- | doc/array.n | 14 | ||||
-rw-r--r-- | doc/bgerror.n | 8 | ||||
-rw-r--r-- | doc/binary.n | 144 | ||||
-rw-r--r-- | doc/break.n | 18 | ||||
-rw-r--r-- | doc/catch.n | 88 | ||||
-rw-r--r-- | doc/cd.n | 6 | ||||
-rw-r--r-- | doc/chan.n | 168 | ||||
-rw-r--r-- | doc/class.n | 136 | ||||
-rw-r--r-- | doc/clock.n | 44 | ||||
-rw-r--r-- | doc/close.n | 38 | ||||
-rw-r--r-- | doc/concat.n | 8 | ||||
-rw-r--r-- | doc/continue.n | 20 | ||||
-rw-r--r-- | doc/copy.n | 53 | ||||
-rw-r--r-- | doc/coroutine.n | 155 | ||||
-rw-r--r-- | doc/dde.n | 3 | ||||
-rw-r--r-- | doc/define.n | 297 | ||||
-rw-r--r-- | doc/dict.n | 85 | ||||
-rw-r--r-- | doc/encoding.n | 14 | ||||
-rw-r--r-- | doc/eof.n | 6 | ||||
-rw-r--r-- | doc/error.n | 20 | ||||
-rw-r--r-- | doc/eval.n | 25 | ||||
-rw-r--r-- | doc/exec.n | 140 | ||||
-rw-r--r-- | doc/exit.n | 6 | ||||
-rw-r--r-- | doc/expr.n | 100 | ||||
-rw-r--r-- | doc/fblocked.n | 3 | ||||
-rw-r--r-- | doc/fconfigure.n | 42 | ||||
-rw-r--r-- | doc/fcopy.n | 18 | ||||
-rw-r--r-- | doc/file.n | 98 | ||||
-rw-r--r-- | doc/fileevent.n | 39 | ||||
-rw-r--r-- | doc/filename.n | 2 | ||||
-rw-r--r-- | doc/flush.n | 5 | ||||
-rw-r--r-- | doc/for.n | 25 | ||||
-rw-r--r-- | doc/foreach.n | 7 | ||||
-rw-r--r-- | doc/format.n | 34 | ||||
-rw-r--r-- | doc/glob.n | 165 | ||||
-rw-r--r-- | doc/global.n | 8 | ||||
-rw-r--r-- | doc/http.n | 148 | ||||
-rw-r--r-- | doc/if.n | 26 | ||||
-rw-r--r-- | doc/incr.n | 12 | ||||
-rw-r--r-- | doc/info.n | 451 | ||||
-rw-r--r-- | doc/interp.n | 200 | ||||
-rw-r--r-- | doc/join.n | 6 | ||||
-rw-r--r-- | doc/lappend.n | 5 | ||||
-rw-r--r-- | doc/lassign.n | 21 | ||||
-rw-r--r-- | doc/library.n | 50 | ||||
-rw-r--r-- | doc/lindex.n | 57 | ||||
-rw-r--r-- | doc/linsert.n | 29 | ||||
-rw-r--r-- | doc/list.n | 16 | ||||
-rw-r--r-- | doc/llength.n | 8 | ||||
-rw-r--r-- | doc/load.n | 33 | ||||
-rw-r--r-- | doc/lrange.n | 12 | ||||
-rw-r--r-- | doc/lrepeat.n | 13 | ||||
-rw-r--r-- | doc/lreplace.n | 9 | ||||
-rw-r--r-- | doc/lreverse.n | 5 | ||||
-rw-r--r-- | doc/lsearch.n | 52 | ||||
-rwxr-xr-x[-rw-r--r--] | doc/lset.n | 50 | ||||
-rw-r--r-- | doc/lsort.n | 165 | ||||
-rw-r--r-- | doc/mathfunc.n | 46 | ||||
-rw-r--r-- | doc/mathop.n | 10 | ||||
-rw-r--r-- | doc/memory.n | 3 | ||||
-rw-r--r-- | doc/msgcat.n | 59 | ||||
-rw-r--r-- | doc/my.n | 56 | ||||
-rw-r--r-- | doc/namespace.n | 271 | ||||
-rw-r--r-- | doc/next.n | 203 | ||||
-rw-r--r-- | doc/object.n | 113 | ||||
-rw-r--r-- | doc/open.n | 85 | ||||
-rw-r--r-- | doc/package.n | 34 | ||||
-rw-r--r-- | doc/packagens.n | 10 | ||||
-rw-r--r-- | doc/pkgMkIndex.n | 11 | ||||
-rw-r--r-- | doc/prefix.n | 116 | ||||
-rw-r--r-- | doc/proc.n | 25 | ||||
-rw-r--r-- | doc/puts.n | 8 | ||||
-rw-r--r-- | doc/pwd.n | 4 | ||||
-rw-r--r-- | doc/re_syntax.n | 37 | ||||
-rw-r--r-- | doc/read.n | 17 | ||||
-rw-r--r-- | doc/refchan.n | 159 | ||||
-rw-r--r-- | doc/regexp.n | 35 | ||||
-rw-r--r-- | doc/registry.n | 19 | ||||
-rw-r--r-- | doc/regsub.n | 41 | ||||
-rw-r--r-- | doc/rename.n | 5 | ||||
-rw-r--r-- | doc/return.n | 144 | ||||
-rw-r--r-- | doc/safe.n | 19 | ||||
-rw-r--r-- | doc/scan.n | 82 | ||||
-rw-r--r-- | doc/seek.n | 13 | ||||
-rw-r--r-- | doc/self.n | 152 | ||||
-rw-r--r-- | doc/set.n | 5 | ||||
-rw-r--r-- | doc/socket.n | 163 | ||||
-rw-r--r-- | doc/source.n | 10 | ||||
-rw-r--r-- | doc/split.n | 29 | ||||
-rw-r--r-- | doc/string.n | 180 | ||||
-rw-r--r-- | doc/subst.n | 21 | ||||
-rw-r--r-- | doc/switch.n | 65 | ||||
-rw-r--r-- | doc/tailcall.n | 69 | ||||
-rw-r--r-- | doc/tclsh.1 | 22 | ||||
-rw-r--r-- | doc/tcltest.n | 505 | ||||
-rw-r--r-- | doc/tclvars.n | 160 | ||||
-rw-r--r-- | doc/tell.n | 5 | ||||
-rw-r--r-- | doc/throw.n | 48 | ||||
-rw-r--r-- | doc/time.n | 11 | ||||
-rw-r--r-- | doc/tm.n | 19 | ||||
-rw-r--r-- | doc/trace.n | 15 | ||||
-rw-r--r-- | doc/transchan.n | 160 | ||||
-rw-r--r-- | doc/try.n | 103 | ||||
-rw-r--r-- | doc/unknown.n | 2 | ||||
-rw-r--r-- | doc/unload.n | 12 | ||||
-rw-r--r-- | doc/unset.n | 16 | ||||
-rw-r--r-- | doc/update.n | 7 | ||||
-rw-r--r-- | doc/uplevel.n | 10 | ||||
-rw-r--r-- | doc/upvar.n | 28 | ||||
-rw-r--r-- | doc/variable.n | 11 | ||||
-rw-r--r-- | doc/vwait.n | 205 | ||||
-rw-r--r-- | doc/while.n | 8 | ||||
-rw-r--r-- | doc/zlib.n | 390 |
188 files changed, 8742 insertions, 2649 deletions
diff --git a/doc/Access.3 b/doc/Access.3 index 98d6635..1e82e07 100644 --- a/doc/Access.3 +++ b/doc/Access.3 @@ -23,52 +23,49 @@ int .AP char *path in Native name of the file to check the attributes of. .AP int mode in -Mask consisting of one or more of R_OK, W_OK, X_OK and F_OK. R_OK, -W_OK and X_OK request checking whether the file exists and has read, -write and execute permissions, respectively. F_OK just requests -checking for the existence of the file. +Mask consisting of one or more of \fBR_OK\fR, \fBW_OK\fR, \fBX_OK\fR and +\fBF_OK\fR. \fBR_OK\fR, \fBW_OK\fR and \fBX_OK\fR request checking whether the +file exists and has read, write and execute permissions, respectively. +\fBF_OK\fR just requests a check for the existence of the file. .AP "struct stat" *statPtr out The structure that contains the result. .BE - .SH DESCRIPTION .PP -As of Tcl 8.4, the object-based APIs \fBTcl_FSAccess\fR and -\fBTcl_FSStat\fR should be used in preference to \fBTcl_Access\fR and -\fBTcl_Stat\fR, wherever possible. +As of Tcl 8.4, the object-based APIs \fBTcl_FSAccess\fR and \fBTcl_FSStat\fR +should be used in preference to \fBTcl_Access\fR and \fBTcl_Stat\fR, wherever +possible. Those functions also support Tcl's virtual filesystem layer, which +these do not. +.SS "OBSOLETE FUNCTIONS" .PP -There are two reasons for calling \fBTcl_Access\fR and \fBTcl_Stat\fR -rather than calling system level functions \fBaccess\fR and \fBstat\fR -directly. First, the Windows implementation of both functions fixes -some bugs in the system level calls. Second, both \fBTcl_Access\fR -and \fBTcl_Stat\fR (as well as \fBTcl_OpenFileChannelProc\fR) hook -into a linked list of functions. This allows the possibility to reroute -file access to alternative media or access methods. +There are two reasons for calling \fBTcl_Access\fR and \fBTcl_Stat\fR rather +than calling system level functions \fBaccess\fR and \fBstat\fR directly. +First, the Windows implementation of both functions fixes some bugs in the +system level calls. Second, both \fBTcl_Access\fR and \fBTcl_Stat\fR (as well +as \fBTcl_OpenFileChannelProc\fR) hook into a linked list of functions. This +allows the possibility to reroute file access to alternative media or access +methods. .PP -\fBTcl_Access\fR checks whether the process would be allowed to read, -write or test for existence of the file (or other file system object) -whose name is pathname. If pathname is a symbolic link on Unix, -then permissions of the file referred by this symbolic link are -tested. +\fBTcl_Access\fR checks whether the process would be allowed to read, write or +test for existence of the file (or other file system object) whose name is +\fIpath\fR. If \fIpath\fR is a symbolic link on Unix, then permissions of the +file referred by this symbolic link are tested. .PP -On success (all requested permissions granted), zero is returned. On -error (at least one bit in mode asked for a permission that is denied, -or some other error occurred), -1 is returned. +On success (all requested permissions granted), zero is returned. On error (at +least one bit in mode asked for a permission that is denied, or some other +error occurred), -1 is returned. .PP -\fBTcl_Stat\fR fills the stat structure \fIstatPtr\fR with information -about the specified file. You do not need any access rights to the -file to get this information but you need search rights to all -directories named in the path leading to the file. The stat structure -includes info regarding device, inode (always 0 on Windows), -privilege mode, nlink (always 1 on Windows), user id (always 0 on -Windows), group id (always 0 on Windows), rdev (same as device on -Windows), size, last access time, last modification time, and creation -time. +\fBTcl_Stat\fR fills the stat structure \fIstatPtr\fR with information about +the specified file. You do not need any access rights to the file to get this +information but you need search rights to all directories named in the path +leading to the file. The stat structure includes info regarding device, inode +(always 0 on Windows), privilege mode, nlink (always 1 on Windows), user id +(always 0 on Windows), group id (always 0 on Windows), rdev (same as device on +Windows), size, last access time, last modification time, and creation time. .PP -If \fIpath\fR exists, \fBTcl_Stat\fR returns 0 and the stat structure -is filled with data. Otherwise, -1 is returned, and no stat info is -given. - +If \fIpath\fR exists, \fBTcl_Stat\fR returns 0 and the stat structure is +filled with data. Otherwise, -1 is returned, and no stat info is given. .SH KEYWORDS stat, access - +.SH "SEE ALSO" +Tcl_FSAccess(3), Tcl_FSStat(3) diff --git a/doc/AddErrInfo.3 b/doc/AddErrInfo.3 index 136a16f..e450a3e 100644 --- a/doc/AddErrInfo.3 +++ b/doc/AddErrInfo.3 @@ -9,24 +9,20 @@ .TH Tcl_AddErrorInfo 3 8.5 Tcl "Tcl Library Procedures" .BS .SH NAME -Tcl_GetReturnOptions, Tcl_SetReturnOptions, Tcl_AddErrorInfo, Tcl_AppendObjToErrorInfo, Tcl_AddObjErrorInfo, Tcl_SetObjErrorCode, Tcl_SetErrorCode, Tcl_SetErrorCodeVA, Tcl_PosixError, Tcl_LogCommandInfo \- retrieve or record information about errors and other return options +Tcl_GetReturnOptions, Tcl_SetReturnOptions, Tcl_AddErrorInfo, Tcl_AppendObjToErrorInfo, Tcl_AddObjErrorInfo, Tcl_SetObjErrorCode, Tcl_SetErrorCode, Tcl_SetErrorCodeVA, Tcl_SetErrorLine, Tcl_GetErrorLine, Tcl_PosixError, Tcl_LogCommandInfo \- retrieve or record information about errors and other return options .SH SYNOPSIS .nf \fB#include <tcl.h>\fR -.VS 8.5 .sp Tcl_Obj * \fBTcl_GetReturnOptions\fR(\fIinterp, code\fR) .sp int \fBTcl_SetReturnOptions\fR(\fIinterp, options\fR) -.VE 8.5 .sp \fBTcl_AddErrorInfo\fR(\fIinterp, message\fR) -.VS 8.5 .sp \fBTcl_AppendObjToErrorInfo\fR(\fIinterp, objPtr\fR) -.VE 8.5 .sp \fBTcl_AddObjErrorInfo\fR(\fIinterp, message, length\fR) .sp @@ -36,6 +32,10 @@ int .sp \fBTcl_SetErrorCodeVA\fR(\fIinterp, argList\fR) .sp +\fBTcl_GetErrorLine\fR(\fIinterp\fR) +.sp +\fBTcl_SetErrorLine\fR(\fIinterp, lineNum\fR) +.sp const char * \fBTcl_PosixError\fR(\fIinterp\fR) .sp @@ -57,11 +57,9 @@ this points to the first byte of an array of \fIlength\fR bytes containing a string to append to the \fB\-errorinfo\fR return option. This byte array may contain embedded null bytes unless \fIlength\fR is negative. -.VS 8.5 .AP Tcl_Obj *objPtr in A message to be appended to the \fB\-errorinfo\fR return option in the form of a Tcl_Obj value. -.VE 8.5 .AP int length in The number of bytes to copy from \fImessage\fR when appending to the \fB\-errorinfo\fR return option. @@ -74,6 +72,8 @@ Last \fIelement\fR argument must be NULL. .AP va_list argList in An argument list which must have been initialized using \fBva_start\fR, and cleared using \fBva_end\fR. +.AP int lineNum +The line number of a script where an error occurred. .AP "const char" *script in Pointer to first character in script containing command (must be <= command) .AP "const char" *command in @@ -81,10 +81,8 @@ Pointer to first character in command that generated the error .AP int commandLength in Number of bytes in command; -1 means use all bytes up to first null byte .BE - .SH DESCRIPTION .PP -.VS 8.5 The \fBTcl_SetReturnOptions\fR and \fBTcl_GetReturnOptions\fR routines expose the same capabilities as the \fBreturn\fR and \fBcatch\fR commands, respectively, in the form of a C interface. @@ -110,20 +108,27 @@ by \fBTcl_GetReturnOptions\fR points to an unshared \fBTcl_Obj\fR with reference count of zero. The dictionary may be written to, either adding, removing, or overwriting any entries in it, without the need to check for a shared object. +As with any \fBTcl_Obj\fR with reference count of zero, it is up to +the caller to arrange for its disposal with \fBTcl_DecrRefCount\fR or +to a reference to it via \fBTcl_IncrRefCount\fR (or one of the many +functions that call that, notably including \fBTcl_SetObjResult\fR and +\fBTcl_SetVar2Ex\fR). .PP A typical usage for \fBTcl_GetReturnOptions\fR is to retrieve the stack trace when script evaluation returns \fBTCL_ERROR\fR, like so: +.PP .CS int code = Tcl_Eval(interp, script); if (code == TCL_ERROR) { - Tcl_Obj *options = Tcl_GetReturnOptions(interp, code); + Tcl_Obj *options = \fBTcl_GetReturnOptions\fR(interp, code); Tcl_Obj *key = Tcl_NewStringObj("-errorinfo", -1); Tcl_Obj *stackTrace; Tcl_IncrRefCount(key); Tcl_DictObjGet(NULL, options, key, &stackTrace); Tcl_DecrRefCount(key); /* Do something with stackTrace */ + Tcl_DecrRefCount(options); } .CE .PP @@ -138,13 +143,15 @@ keys in \fIoptions\fR will be returned. As an example, Tcl's \fBreturn\fR command itself could be implemented in terms of \fBTcl_SetReturnOptions\fR like so: +.PP .CS if ((objc % 2) == 0) { /* explicit result argument */ objc--; Tcl_SetObjResult(interp, objv[objc]); } -return Tcl_SetReturnOptions(interp, Tcl_NewListObj(objc-1, objv+1)); +return \fBTcl_SetReturnOptions\fR(interp, Tcl_NewListObj(objc-1, objv+1)); .CE +.PP (It is not really implemented that way. Internal access privileges allow for a more efficient alternative that meshes better with the bytecode compiler.) @@ -159,9 +166,12 @@ to set any collection of return options, there are a handful of return options that are very frequently used. Most notably the \fB\-errorinfo\fR and \fB\-errorcode\fR return options should be set properly when the command procedure -of a command returns \fBTCL_ERROR\fR. Tcl provides several -simpler interfaces to more directly set these return options. -.VE 8.5 +of a command returns \fBTCL_ERROR\fR. The \fB\-errorline\fR +return option is also read by commands that evaluate scripts +and wish to supply detailed error location information in +the stack trace text they append to the \fB\-errorinfo\fR option. +Tcl provides several simpler interfaces to more directly set +these return options. .PP The \fB\-errorinfo\fR option holds a stack trace of the operations that were in progress when an error occurred, @@ -173,7 +183,7 @@ error that occurred (e.g. POSIX means an error occurred in a POSIX system call) and additional elements hold additional pieces of information that depend on the class. -See the tclvars manual entry for details on the various +See the \fBtclvars\fR manual entry for details on the various formats for the \fB\-errorcode\fR option used by Tcl's built-in commands. .PP @@ -207,12 +217,10 @@ The value of the \fB\-errorline\fR return option (retrieved via a call to \fBTcl_GetReturnOptions\fR) often makes up a useful part of the \fImessage\fR passed to \fBTcl_AddErrorInfo\fR. .PP -.VS 8.5 \fBTcl_AppendObjToErrorInfo\fR is an alternative interface to the same functionality as \fBTcl_AddErrorInfo\fR. \fBTcl_AppendObjToErrorInfo\fR is called when the string value to be appended to the \fB\-errorinfo\fR option is available as a \fBTcl_Obj\fR instead of as a \fBchar\fR array. -.VE 8.5 .PP \fBTcl_AddObjErrorInfo\fR is nearly identical to \fBTcl_AddErrorInfo\fR, except that it has an additional \fIlength\fR @@ -240,6 +248,11 @@ record instead of an object. Otherwise, it is similar to \fBTcl_SetErrorCodeVA\fR is the same as \fBTcl_SetErrorCode\fR except that instead of taking a variable number of arguments it takes an argument list. .PP +The procedure \fBTcl_GetErrorLine\fR is used to read the integer value +of the \fB\-errorline\fR return option without the overhead of a full +call to \fBTcl_GetReturnOptions\fR. Likewise, \fBTcl_SetErrorLine\fR +sets the \fB\-errorline\fR return option value. +.PP \fBTcl_PosixError\fR sets the \fB\-errorcode\fR variable after an error in a POSIX kernel call. It reads the value of the \fBerrno\fR C variable and calls @@ -292,9 +305,8 @@ The global variables \fBerrorInfo\fR and \fBerrorCode\fR are not modified by \fBTcl_ResetResult\fR so they continue to hold a record of information about the most recent error seen in an interpreter. - .SH "SEE ALSO" -Tcl_DecrRefCount, Tcl_IncrRefCount, Tcl_Interp, Tcl_ResetResult, Tcl_SetErrno - +Tcl_DecrRefCount(3), Tcl_IncrRefCount(3), Tcl_Interp(3), Tcl_ResetResult(3), +Tcl_SetErrno(3), tclvars(n) .SH KEYWORDS error, object, object result, stack, trace, variable diff --git a/doc/AppInit.3 b/doc/AppInit.3 index 0473090..e4ae971 100644 --- a/doc/AppInit.3 +++ b/doc/AppInit.3 @@ -48,6 +48,11 @@ Process command-line arguments, which can be accessed from the Tcl variables \fBargv\fR and \fBargv0\fR in \fIinterp\fR. .IP [3] Invoke a startup script to initialize the application. +.IP [4] +Use the routines \fBTcl_SetStartupScript\fR and +\fBTcl_GetStartupScript\fR to set or query the file and encoding +that the active \fBTcl_Main\fR or \fBTk_Main\fR routine will +use as a startup script. .LP \fBTcl_AppInit\fR returns \fBTCL_OK\fR or \fBTCL_ERROR\fR. If it returns \fBTCL_ERROR\fR then it must leave an error message in @@ -55,9 +60,11 @@ for the interpreter's result; otherwise the result is ignored. .PP In addition to \fBTcl_AppInit\fR, your application should also contain a procedure \fBmain\fR that calls \fBTcl_Main\fR as follows: +.PP .CS Tcl_Main(argc, argv, Tcl_AppInit); .CE +.PP The third argument to \fBTcl_Main\fR gives the address of the application-specific initialization procedure to invoke. This means that you do not have to use the name \fBTcl_AppInit\fR @@ -69,5 +76,8 @@ The best way to get started is to make a copy of the file It already contains a \fBmain\fR procedure and a template for \fBTcl_AppInit\fR that you can modify for your application. +.SH "SEE ALSO" +Tcl_Main(3) + .SH KEYWORDS application, argument, command, initialization, interpreter diff --git a/doc/AssocData.3 b/doc/AssocData.3 index e4c7bab..59c26a4 100644 --- a/doc/AssocData.3 +++ b/doc/AssocData.3 @@ -61,11 +61,13 @@ If the \fIdeleteProc\fR argument is non-NULL it specifies the address of a procedure to invoke if the interpreter is deleted before the association is deleted. \fIDeleteProc\fR should have arguments and result that match the type \fBTcl_InterpDeleteProc\fR: +.PP .CS -typedef void Tcl_InterpDeleteProc( +typedef void \fBTcl_InterpDeleteProc\fR( ClientData \fIclientData\fR, Tcl_Interp *\fIinterp\fR); .CE +.PP When \fIdeleteProc\fR is invoked the \fIclientData\fR and \fIinterp\fR arguments will be the same as the corresponding arguments passed to \fBTcl_SetAssocData\fR. diff --git a/doc/Async.3 b/doc/Async.3 index c4439a4..d02f76d 100644 --- a/doc/Async.3 +++ b/doc/Async.3 @@ -81,12 +81,14 @@ the world is in a safe state, and \fIproc\fR can then carry out the actions associated with the asynchronous event. \fIProc\fR should have arguments and result that match the type \fBTcl_AsyncProc\fR: +.PP .CS -typedef int Tcl_AsyncProc( +typedef int \fBTcl_AsyncProc\fR( ClientData \fIclientData\fR, Tcl_Interp *\fIinterp\fR, int \fIcode\fR); .CE +.PP The \fIclientData\fR will be the same as the \fIclientData\fR argument passed to \fBTcl_AsyncCreate\fR when the handler was created. diff --git a/doc/BackgdErr.3 b/doc/BackgdErr.3 index 1e46b03..3116671 100644 --- a/doc/BackgdErr.3 +++ b/doc/BackgdErr.3 @@ -9,53 +9,70 @@ .TH Tcl_BackgroundError 3 7.5 Tcl "Tcl Library Procedures" .BS .SH NAME -Tcl_BackgroundError \- report Tcl error that occurred in background processing +Tcl_BackgroundException, Tcl_BackgroundError \- report Tcl exception that occurred in background processing .SH SYNOPSIS .nf \fB#include <tcl.h>\fR .sp +\fBTcl_BackgroundException\fR(\fIinterp, code\fR) +.sp \fBTcl_BackgroundError\fR(\fIinterp\fR) .SH ARGUMENTS .AS Tcl_Interp *interp .AP Tcl_Interp *interp in -Interpreter in which the error occurred. +Interpreter in which the exception occurred. +.AP int code in +The exceptional return code to be reported. .BE .SH DESCRIPTION .PP -This procedure is typically invoked when a Tcl error occurs during +This procedure is typically invoked when a Tcl exception (any +return code other than TCL_OK) occurs during .QW "background processing" such as executing an event handler. -When such an error occurs, the error condition is reported to Tcl +When such an exception occurs, the condition is reported to Tcl or to a widget or some other C code, and there is not usually any -obvious way for that code to report the error to the user. -In these cases the code calls \fBTcl_BackgroundError\fR with an +obvious way for that code to report the exception to the user. +In these cases the code calls \fBTcl_BackgroundException\fR with an \fIinterp\fR argument identifying the interpreter in which the -error occurred. At the time \fBTcl_BackgroundError\fR is invoked, -the interpreter's result is expected to contain an error message. -\fBTcl_BackgroundError\fR will invoke the command registered +exception occurred, and a \fIcode\fR argument holding the return +code value of the exception. The state of the interpreter, including +any error message in the interpreter result, and the values of +any entries in the return options dictionary, is captured and +saved. \fBTcl_BackgroundException\fR then arranges for the event +loop to invoke at some later time the command registered in that interpreter to handle background errors by the -\fBinterp bgerror\fR command. -The registered handler command is meant to report the error +\fBinterp bgerror\fR command, passing the captured values as +arguments. +The registered handler command is meant to report the exception in an application-specific fashion. The handler command receives two arguments, the result of the interp, and the return options of the interp at the time the error occurred. If the application registers no handler command, the default handler command will attempt to call \fBbgerror\fR to report the error. If an error condition arises while invoking the -handler command, then \fBTcl_BackgroundError\fR reports the +handler command, then \fBTcl_BackgroundException\fR reports the error itself by printing a message on the standard error file. .PP -\fBTcl_BackgroundError\fR does not invoke the handler command immediately +\fBTcl_BackgroundException\fR does not invoke the handler command immediately because this could potentially interfere with scripts that are in process at the time the error occurred. Instead, it invokes the handler command later as an idle callback. .PP -It is possible for many background errors to accumulate before -the handler command is invoked. When this happens, each of the errors -is processed in order. However, if the handle command returns a +It is possible for many background exceptions to accumulate before +the handler command is invoked. When this happens, each of the exceptions +is processed in order. However, if the handler command returns a break exception, then all remaining error reports for the interpreter are skipped. +.PP +The \fBTcl_BackgroundError\fR routine is an older and simpler interface +useful when the exception code reported is \fBTCL_ERROR\fR. It is +equivalent to: +.PP +.CS +Tcl_BackgroundException(interp, TCL_ERROR); +.CE .SH KEYWORDS background, bgerror, error, interp diff --git a/doc/ByteArrObj.3 b/doc/ByteArrObj.3 index 738da32..77c94ac 100644 --- a/doc/ByteArrObj.3 +++ b/doc/ByteArrObj.3 @@ -27,7 +27,8 @@ unsigned char * .SH ARGUMENTS .AS "const unsigned char" *lengthPtr in/out .AP "const unsigned char" *bytes in -The array of bytes used to initialize or set a byte-array object. +The array of bytes used to initialize or set a byte-array object. May be NULL +even if \fIlength\fR is non-zero. .AP int length in The length of the array of bytes. It must be >= 0. .AP Tcl_Obj *objPtr in/out @@ -53,7 +54,7 @@ byte-array or to convert an arbitrary object to a byte-array. Obtaining the string representation of a byte-array object (by calling \fBTcl_GetStringFromObj\fR) produces a properly formed UTF-8 sequence with a one-to-one mapping between the bytes in the internal representation and the -UTF-8 characters in the string representation. +UTF-8 characters in the string representation. .PP \fBTcl_NewByteArrayObj\fR and \fBTcl_SetByteArrayObj\fR will create a new object of byte-array type or modify an existing object to have a @@ -63,7 +64,8 @@ array of bytes given by \fIbytes\fR. \fBTcl_NewByteArrayObj\fR returns a pointer to a newly allocated object with a reference count of zero. \fBTcl_SetByteArrayObj\fR invalidates any old string representation and, if the object is not already a byte-array object, frees any old internal -representation. +representation. If \fIbytes\fR is NULL then the new byte array contains +arbitrary values. .PP \fBTcl_GetByteArrayFromObj\fR converts a Tcl object to byte-array type and returns a pointer to the object's new internal representation as an array of @@ -71,7 +73,7 @@ bytes. The length of this array is stored in \fIlengthPtr\fR if \fIlengthPtr\fR is non-NULL. The storage for the array of bytes is owned by the object and should not be freed. The contents of the array may be modified by the caller only if the object is not shared and the caller -invalidates the string representation. +invalidates the string representation. .PP \fBTcl_SetByteArrayLength\fR converts the Tcl object to byte-array type and changes the length of the object's internal representation as an diff --git a/doc/CallDel.3 b/doc/CallDel.3 index 8e6445b..dec4392 100644 --- a/doc/CallDel.3 +++ b/doc/CallDel.3 @@ -26,7 +26,6 @@ Procedure to call when \fIinterp\fR is deleted. .AP ClientData clientData in Arbitrary one-word value to pass to \fIproc\fR. .BE - .SH DESCRIPTION .PP \fBTcl_CallWhenDeleted\fR arranges for \fIproc\fR to be called by @@ -36,11 +35,13 @@ is deleted, but the interpreter will still be valid at the time of the call. \fIProc\fR should have arguments and result that match the type \fBTcl_InterpDeleteProc\fR: +.PP .CS -typedef void Tcl_InterpDeleteProc( +typedef void \fBTcl_InterpDeleteProc\fR( ClientData \fIclientData\fR, Tcl_Interp *\fIinterp\fR); .CE +.PP The \fIclientData\fR and \fIinterp\fR parameters are copies of the \fIclientData\fR and \fIinterp\fR arguments given to \fBTcl_CallWhenDeleted\fR. @@ -56,6 +57,11 @@ deleted. If there is no deletion callback that matches \fIinterp\fR, \fIproc\fR, and \fIclientData\fR then the call to \fBTcl_DontCallWhenDeleted\fR has no effect. - +.PP +Note that if the callback is being used to delete a resource that \fImust\fR +be released on exit, \fBTcl_CreateExitHandler\fR should be used to ensure that +a callback is received even if the application terminates without deleting the interpreter. +.SH "SEE ALSO" +Tcl_CreateExitHandler(3), Tcl_CreateThreadExitHandler(3) .SH KEYWORDS -callback, delete, interpreter +callback, cleanup, delete, interpreter diff --git a/doc/Cancel.3 b/doc/Cancel.3 new file mode 100644 index 0000000..80db3a3 --- /dev/null +++ b/doc/Cancel.3 @@ -0,0 +1,66 @@ +'\" +'\" Copyright (c) 2006-2008 Joe Mistachkin. +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH Tcl_Cancel 3 8.6 Tcl "Tcl Library Procedures" +.BS +.SH NAME +Tcl_CancelEval, Tcl_Canceled \- cancel Tcl scripts +.SH SYNOPSIS +.nf +\fB#include <tcl.h>\fR +int +\fBTcl_CancelEval\fR(\fIinterp, clientData, flags\fR) +.sp +int +\fBTcl_Canceled\fR(\fIinterp, flags\fR) +.SH ARGUMENTS +.AP Tcl_Interp *interp in +Interpreter in which to cancel the script. +.AP int flags in +ORed combination of flag bits that specify additional options. +For \fBTcl_CancelEval\fR, only \fBTCL_CANCEL_UNWIND\fR is currently +supported. For \fBTcl_Canceled\fR, only \fBTCL_LEAVE_ERR_MSG\fR and +\fBTCL_CANCEL_UNWIND\fR are currently supported. +.AP ClientData clientData in +Currently, reserved for future use. +It should be set to NULL. +.BE +.SH DESCRIPTION +.PP +\fBTcl_CancelEval\fR cancels or unwinds the script in progress soon after +the next invocation of asynchronous handlers, causing \fBTCL_ERROR\fR to be +the return code for that script. This function is thread-safe and may be +called from any thread in the process. +.PP +\fBTcl_Canceled\fR checks if the script in progress has been canceled and +returns \fBTCL_ERROR\fR if it has. Otherwise, \fBTCL_OK\fR is returned. +Extensions can use this function to check to see if they should abort a long +running command. This function is thread sensitive and may only be called +from the thread the interpreter was created in. +.SH "FLAG BITS" +Any ORed combination of the following values may be used for the +\fIflags\fR argument to procedures such as \fBTcl_CancelEval\fR: +.TP 23 +\fBTCL_CANCEL_UNWIND\fR +This flag is used by \fBTcl_CancelEval\fR and \fBTcl_Canceled\fR. +For \fBTcl_CancelEval\fR, if this flag is set, the script in progress +is canceled and the evaluation stack for the interpreter is unwound. +For \fBTcl_Canceled\fR, if this flag is set, the script in progress +is considered to be canceled only if the evaluation stack for the +interpreter is being unwound. +.TP 23 +\fBTCL_LEAVE_ERR_MSG\fR +This flag is only used by \fBTcl_Canceled\fR; it is ignored by +other procedures. If an error is returned and this bit is set in +\fIflags\fR, then an error message will be left in the interpreter's +result, where it can be retrieved with \fBTcl_GetObjResult\fR or +\fBTcl_GetStringResult\fR. If this flag bit is not set then no error +message is left and the interpreter's result will not be modified. +.SH "SEE ALSO" +TIP 285 +.SH KEYWORDS +cancel, unwind diff --git a/doc/ChnlStack.3 b/doc/ChnlStack.3 index 8ac5a0d..9ec38b4 100644 --- a/doc/ChnlStack.3 +++ b/doc/ChnlStack.3 @@ -30,7 +30,7 @@ Tcl_Channel .AS Tcl_ChannelType clientData .AP Tcl_Interp *interp in Interpreter for error reporting. -.AP Tcl_ChannelType *typePtr in +.AP "const Tcl_ChannelType" *typePtr in The new channel I/O procedures to use for \fIchannel\fR. .AP ClientData clientData in Arbitrary one-word value to pass to channel I/O procedures. diff --git a/doc/Class.3 b/doc/Class.3 new file mode 100644 index 0000000..dbb5b99 --- /dev/null +++ b/doc/Class.3 @@ -0,0 +1,236 @@ +'\" +'\" Copyright (c) 2007 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH Tcl_Class 3 0.1 TclOO "TclOO Library Functions" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +Tcl_ClassGetMetadata, Tcl_ClassSetMetadata, Tcl_CopyObjectInstance, Tcl_GetClassAsObject, Tcl_GetObjectAsClass, Tcl_GetObjectCommand, Tcl_GetObjectFromObj, Tcl_GetObjectName, Tcl_GetObjectNamespace, Tcl_NewObjectInstance, Tcl_ObjectDeleted, Tcl_ObjectGetMetadata, Tcl_ObjectGetMethodNameMapper, Tcl_ObjectSetMetadata, Tcl_ObjectSetMethodNameMapper \- manipulate objects and classes +.SH SYNOPSIS +.nf +\fB#include <tclOO.h>\fR +.sp +Tcl_Object +\fBTcl_GetObjectFromObj\fR(\fIinterp, objPtr\fR) +.sp +Tcl_Object +\fBTcl_GetClassAsObject\fR(\fIclass\fR) +.sp +Tcl_Class +\fBTcl_GetObjectAsClass\fR(\fIobject\fR) +.sp +Tcl_Obj * +\fBTcl_GetObjectName\fR(\fIinterp, object\fR) +.sp +Tcl_Command +\fBTcl_GetObjectCommand\fR(\fIobject\fR) +.sp +Tcl_Namespace * +\fBTcl_GetObjectNamespace\fR(\fIobject\fR) +.sp +Tcl_Object +\fBTcl_NewObjectInstance\fR(\fIinterp, class, name, nsName, objc, objv, skip\fR) +.sp +Tcl_Object +\fBTcl_CopyObjectInstance\fR(\fIinterp, object, name, nsName\fR) +.sp +int +\fBTcl_ObjectDeleted\fR(\fIobject\fR) +.sp +ClientData +\fBTcl_ObjectGetMetadata\fR(\fIobject, metaTypePtr\fR) +.sp +\fBTcl_ObjectSetMetadata\fR(\fIobject, metaTypePtr, metadata\fR) +.sp +ClientData +\fBTcl_ClassGetMetadata\fR(\fIclass, metaTypePtr\fR) +.sp +\fBTcl_ClassSetMetadata\fR(\fIclass, metaTypePtr, metadata\fR) +.sp +Tcl_ObjectMapMethodNameProc +\fBTcl_ObjectGetMethodNameMapper\fR(\fIobject\fR) +.sp +\fBTcl_ObjectSetMethodNameMapper\fR(\fIobject\fR, \fImethodNameMapper\fR) +.SH ARGUMENTS +.AS ClientData metadata in/out +.AP Tcl_Interp *interp in/out +Interpreter providing the context for looking up or creating an object, and +into whose result error messages will be written on failure. +.AP Tcl_Obj *objPtr in +The name of the object to look up. +.AP Tcl_Object object in +Reference to the object to operate upon. +.AP Tcl_Class class in +Reference to the class to operate upon. +.AP "const char" *name in +The name of the object to create, or NULL if a new unused name is to be +automatically selected. +.AP "const char" *nsName in +The name of the namespace to create for the object's private use, or NULL if a +new unused name is to be automatically selected. +.AP int objc in +The number of elements in the \fIobjv\fR array. +.AP "Tcl_Obj *const" *objv in +The arguments to the command to create the instance of the class. +.AP int skip in +The number of arguments at the start of the argument array, \fIobjv\fR, that +are not arguments to any constructors. +.AP Tcl_ObjectMetadataType *metaTypePtr in +The type of \fImetadata\fR being set with \fBTcl_ClassSetMetadata\fR or +retrieved with \fBTcl_ClassGetMetadata\fR. +.AP ClientData metadata in +An item of metadata to attach to the class, or NULL to remove the metadata +associated with a particular \fImetaTypePtr\fR. +.AP "Tcl_ObjectMapMethodNameProc" "methodNameMapper" in +A pointer to a function to call to adjust the mapping of objects and method +names to implementations, or NULL when no such mapping is required. +.BE +.SH DESCRIPTION +.PP +Objects are typed entities that have a set of operations ("methods") +associated with them. Classes are objects that can manufacture objects. Each +class can be viewed as an object itself; the object view can be retrieved +using \fBTcl_GetClassAsObject\fR which always returns the object when applied +to a non-destroyed class, and an object can be viewed as a class with the aid +of the \fBTcl_GetObjectAsClass\fR (which either returns the class, or NULL if +the object is not a class). An object may be looked up using the +\fBTcl_GetObjectFromObj\fR function, which either returns an object or NULL +(with an error message in the interpreter result) if the object cannot be +found. The correct way to look up a class by name is to look up the object +with that name, and then to use \fBTcl_GetObjectAsClass\fR. +.PP +Every object has its own command and namespace associated with it. The command +may be retrieved using the \fBTcl_GetObjectCommand\fR function, the name of +the object (and hence the name of the command) with \fBTcl_GetObjectName\fR, +and the namespace may be retrieved using the \fBTcl_GetObjectNamespace\fR +function. Note that the Tcl_Obj reference returned by \fBTcl_GetObjectName\fR +is a shared reference. +.PP +Instances of classes are created using \fBTcl_NewObjectInstance\fR, which +takes creates an object from any class (and which is internally called by both +the \fBcreate\fR and \fBnew\fR methods of the \fBoo::class\fR class). It takes +parameters that optionally give the name of the object and namespace to +create, and which describe the arguments to pass to the class's constructor +(if any). The result of the function will be either a reference to the newly +created object, or NULL if the creation failed (when an error message will be +left in the interpreter result). In addition, objects may be copied by using +\fBTcl_CopyObjectInstance\fR which creates a copy of an object without running +any constructors. +.SH "OBJECT AND CLASS METADATA" +.PP +Every object and every class may have arbitrary amounts of metadata attached +to it, which the object or class attaches no meaning to beyond what is +described in a Tcl_ObjectMetadataType structure instance. Metadata to be +attached is described by the the type of the metadata (given in the +\fImetaTypePtr\fR argument) and an arbitrary pointer (the \fImetadata\fR +argument) that are given to \fBTcl_ObjectSetMetadata\fR and +\fBTcl_ClassSetMetadata\fR, and a particular piece of metadata can be +retrieved given its type using \fBTcl_ObjectGetMetadata\fR and +\fBTcl_ClassGetMetadata\fR. If the \fImetadata\fR parameter to either +\fBTcl_ObjectSetMetadata\fR or \fBTcl_ClassSetMetadata\fR is NULL, the +metadata is removed if it was attached, and the results of +\fBTcl_ObjectGetMetadata\fR and \fBTcl_ClassGetMetadata\fR are NULL if the +given type of metadata was not attached. It is not an error to request or +remove a piece of metadata that was not attached. +.SS "TCL_OBJECTMETADATATYPE STRUCTURE" +.PP +The contents of the Tcl_ObjectMetadataType structure are as follows: +.PP +.CS +typedef const struct { + int \fIversion\fR; + const char *\fIname\fR; + Tcl_ObjectMetadataDeleteProc *\fIdeleteProc\fR; + Tcl_CloneProc *\fIcloneProc\fR; +} \fBTcl_ObjectMetadataType\fR; +.CE +.PP +The \fIversion\fR field allows for future expansion of the structure, and +should always be declared equal to TCL_OO_METADATA_VERSION_CURRENT. The +\fIname\fR field provides a human-readable name for the type, and is reserved +for debugging. +.PP +The \fIdeleteProc\fR field gives a function of type +Tcl_ObjectMetadataDeleteProc that is used to delete a particular piece of +metadata, and is called when the attached metadata is replaced or removed; the +field must not be NULL. +.PP +The \fIcloneProc\fR field gives a function that is used to copy a piece of +metadata (used when a copy of an object is created using +\fBTcl_CopyObjectInstance\fR); if NULL, the metadata will be just directly +copied. +.SS "TCL_OBJECTMETADATADELETEPROC FUNCTION SIGNATURE" +.PP +Functions matching this signature are used to delete metadata associated with +a class or object. +.PP +.CS +typedef void \fBTcl_ObjectMetadataDeleteProc\fR( + ClientData \fImetadata\fR); +.CE +.PP +The \fImetadata\fR argument gives the address of the metadata to be +deleted. +.SS "TCL_CLONEPROC FUNCTION SIGNATURE" +.PP +Functions matching this signature are used to create copies of metadata +associated with a class or object. +.PP +.CS +typedef int \fBTcl_CloneProc\fR( + Tcl_Interp *\fIinterp\fR, + ClientData \fIsrcMetadata\fR, + ClientData *\fIdstMetadataPtr\fR); +.CE +.PP +The \fIinterp\fR argument gives a place to write an error message when the +attempt to clone the object is to fail, in which case the clone procedure must +also return TCL_ERROR; it should return TCL_OK otherwise. +The \fIsrcMetadata\fR argument gives the address of the metadata to be cloned, +and the cloned metadata should be written into the variable pointed to by +\fIdstMetadataPtr\fR; a NULL should be written if the metadata is to not be +cloned but the overall object copy operation is still to succeed. +.SH "OBJECT METHOD NAME MAPPING" +It is possible to control, on a per-object basis, what methods are invoked +when a particular method is invoked. Normally this is done by looking up the +method name in the object and then in the class hierarchy, but fine control of +exactly what the value used to perform the look up is afforded through the +ability to set a method name mapper callback via +\fBTcl_ObjectSetMethodNameMapper\fR (and its introspection counterpart, +\fBTcl_ObjectGetMethodNameMapper\fR, which returns the current mapper). The +current mapper (if any) is invoked immediately before looking up what chain of +method implementations is to be used. +.SS "TCL_OBJECTMAPMETHODNAMEPROC FUNCTION SIGNATURE" +The \fITcl_ObjectMapMethodNameProc\fR callback is defined as follows: +.PP +.CS +typedef int \fBTcl_ObjectMapMethodNameProc\fR( + Tcl_Interp *\fIinterp\fR, + Tcl_Object \fIobject\fR, + Tcl_Class *\fIstartClsPtr\fR, + Tcl_Obj *\fImethodNameObj\fR); +.CE +.PP +If the result is TCL_OK, the remapping is assumed to have been done. If the +result is TCL_ERROR, an error message will have been left in \fIinterp\fR and +the method call will fail. If the result is TCL_BREAK, the standard method +name lookup rules will be used; the behavior of other result codes is +currently undefined. The \fIobject\fR parameter says which object is being +processed. The \fIstartClsPtr\fR parameter points to a variable that contains +the first class to provide a definition in the method chain to process, or +NULL if the whole chain is to be processed (the argument itself is never +NULL); this variable may be updated by the callback. The \fImethodNameObj\fR +parameter gives an unshared object containing the name of the method being +invoked, as provided by the user; this object may be updated by the callback. +.SH "SEE ALSO" +Method(3), oo::class(n), oo::copy(n), oo::define(n), oo::object(n) +.SH KEYWORDS +class, constructor, object +.\" Local variables: +.\" mode: nroff +.\" fill-column: 78 +.\" End: diff --git a/doc/CrtChannel.3 b/doc/CrtChannel.3 index 212a239..9aadba2 100644 --- a/doc/CrtChannel.3 +++ b/doc/CrtChannel.3 @@ -20,7 +20,7 @@ Tcl_Channel ClientData \fBTcl_GetChannelInstanceData\fR(\fIchannel\fR) .sp -Tcl_ChannelType * +const Tcl_ChannelType * \fBTcl_GetChannelType\fR(\fIchannel\fR) .sp const char * @@ -96,10 +96,8 @@ Tcl_DriverWideSeekProc * Tcl_DriverThreadActionProc * \fBTcl_ChannelThreadActionProc\fR(\fItypePtr\fR) .sp -.VS 8.5 Tcl_DriverTruncateProc * \fBTcl_ChannelTruncateProc\fR(\fItypePtr\fR) -.VE 8.5 .sp Tcl_DriverSetOptionProc * \fBTcl_ChannelSetOptionProc\fR(\fItypePtr\fR) @@ -127,7 +125,9 @@ can be called to perform I/O and other functions on the channel. .AP "const char" *channelName in The name of this channel, such as \fBfile3\fR; must not be in use by any other channel. Can be NULL, in which case the channel is -created without a name. +created without a name. If the created channel is assigned to one +of the standard channels (\fBstdin\fR, \fBstdout\fR or \fBstderr\fR), +the assigned channel name will be the name of the standard channel. .AP ClientData instanceData in Arbitrary one-word value to be associated with this channel. This value is passed to procedures in \fItypePtr\fR when they are invoked. @@ -157,9 +157,7 @@ Specific options list (space separated words, without .QW \- ) to append to the standard generic options list. Can be NULL for generic options error message only. - .BE - .SH DESCRIPTION .PP Tcl uses a two-layered channel architecture. It provides a generic upper @@ -288,20 +286,16 @@ name is registered in the (thread)-global list of all channels (result (thread)global list of all channels (of the current thread). Application to a channel still registered in some interpreter is not allowed. -.VS 8.5 Also notifies the driver if the \fBTcl_ChannelType\fR version is \fBTCL_CHANNEL_VERSION_4\fR (or higher), and \fBTcl_DriverThreadActionProc\fR is defined for it. -.VE 8.5 .PP \fBTcl_SpliceChannel\fR adds the specified \fIchannel\fR to the (thread)global list of all channels (of the current thread). Application to a channel registered in some interpreter is not allowed. -.VS 8.5 Also notifies the driver if the \fBTcl_ChannelType\fR version is \fBTCL_CHANNEL_VERSION_4\fR (or higher), and \fBTcl_DriverThreadActionProc\fR is defined for it. -.VE 8.5 .PP \fBTcl_ClearChannelHandlers\fR removes all channel handlers and event scripts associated with the specified \fIchannel\fR, thus shutting @@ -316,9 +310,10 @@ channel drivers. See the \fBOLD CHANNEL TYPES\fR section below for details about the old structure. .PP The \fBTcl_ChannelType\fR structure contains the following fields: +.PP .CS typedef struct Tcl_ChannelType { - char *\fItypeName\fR; + const char *\fItypeName\fR; Tcl_ChannelTypeVersion \fIversion\fR; Tcl_DriverCloseProc *\fIcloseProc\fR; Tcl_DriverInputProc *\fIinputProc\fR; @@ -334,10 +329,8 @@ typedef struct Tcl_ChannelType { Tcl_DriverHandlerProc *\fIhandlerProc\fR; Tcl_DriverWideSeekProc *\fIwideSeekProc\fR; Tcl_DriverThreadActionProc *\fIthreadActionProc\fR; -.VS 8.5 Tcl_DriverTruncateProc *\fItruncateProc\fR; -.VE 8.5 -} Tcl_ChannelType; +} \fBTcl_ChannelType\fR; .CE .PP It is not necessary to provide implementations for all channel @@ -358,9 +351,7 @@ structure, the following functions should be used to obtain the values: \fBTcl_ChannelClose2Proc\fR, \fBTcl_ChannelInputProc\fR, \fBTcl_ChannelOutputProc\fR, \fBTcl_ChannelSeekProc\fR, \fBTcl_ChannelWideSeekProc\fR, \fBTcl_ChannelThreadActionProc\fR, -.VS 8.5 \fBTcl_ChannelTruncateProc\fR, -.VE 8.5 \fBTcl_ChannelSetOptionProc\fR, \fBTcl_ChannelGetOptionProc\fR, \fBTcl_ChannelWatchProc\fR, \fBTcl_ChannelGetHandleProc\fR, \fBTcl_ChannelFlushProc\fR, or \fBTcl_ChannelHandlerProc\fR. @@ -385,11 +376,9 @@ that you require. \fBTCL_CHANNEL_VERSION_2\fR is the minimum recommended. \fBTCL_CHANNEL_VERSION_3\fR must be set to specify the \fIwideSeekProc\fR member. \fBTCL_CHANNEL_VERSION_4\fR must be set to specify the \fIthreadActionProc\fR member (includes \fIwideSeekProc\fR). -.VS 8.5 \fBTCL_CHANNEL_VERSION_5\fR must be set to specify the \fItruncateProc\fR members (includes \fIwideSeekProc\fR and \fIthreadActionProc\fR). -.VE 8.5 If it is not set to any of these, then this \fBTcl_ChannelType\fR is assumed to have the original structure. See \fBOLD CHANNEL TYPES\fR for more details. While Tcl will recognize @@ -398,9 +387,7 @@ least \fBTCL_CHANNEL_VERSION_2\fR to function correctly. .PP This value can be retrieved with \fBTcl_ChannelVersion\fR, which returns one of -.VS 8.5 \fBTCL_CHANNEL_VERSION_5\fR, -.VE 8.5 \fBTCL_CHANNEL_VERSION_4\fR, \fBTCL_CHANNEL_VERSION_3\fR, \fBTCL_CHANNEL_VERSION_2\fR or \fBTCL_CHANNEL_VERSION_1\fR. @@ -411,7 +398,7 @@ the generic layer to set blocking and nonblocking mode on the device. \fIBlockModeProc\fR should match the following prototype: .PP .CS -typedef int Tcl_DriverBlockModeProc( +typedef int \fBTcl_DriverBlockModeProc\fR( ClientData \fIinstanceData\fR, int \fImode\fR); .CE @@ -446,7 +433,7 @@ generic layer to clean up driver-related information when the channel is closed. \fICloseProc\fR must match the following prototype: .PP .CS -typedef int Tcl_DriverCloseProc( +typedef int \fBTcl_DriverCloseProc\fR( ClientData \fIinstanceData\fR, Tcl_Interp *\fIinterp\fR); .CE @@ -468,7 +455,7 @@ independently may set \fIcloseProc\fR to \fBTCL_CLOSE2PROC\fR and set following prototype: .PP .CS -typedef int Tcl_DriverClose2Proc( +typedef int \fBTcl_DriverClose2Proc\fR( ClientData \fIinstanceData\fR, Tcl_Interp *\fIinterp\fR, int \fIflags\fR); @@ -499,7 +486,7 @@ generic layer to read data from the file or device and store it in an internal buffer. \fIInputProc\fR must match the following prototype: .PP .CS -typedef int Tcl_DriverInputProc( +typedef int \fBTcl_DriverInputProc\fR( ClientData \fIinstanceData\fR, char *\fIbuf\fR, int \fIbufSize\fR, @@ -543,7 +530,7 @@ generic layer to transfer data from an internal buffer to the output device. \fIOutputProc\fR must match the following prototype: .PP .CS -typedef int Tcl_DriverOutputProc( +typedef int \fBTcl_DriverOutputProc\fR( ClientData \fIinstanceData\fR, const char *\fIbuf\fR, int \fItoWrite\fR, @@ -582,7 +569,7 @@ operations will be applied. \fISeekProc\fR must match the following prototype: .PP .CS -typedef int Tcl_DriverSeekProc( +typedef int \fBTcl_DriverSeekProc\fR( ClientData \fIinstanceData\fR, long \fIoffset\fR, int \fIseekMode\fR, @@ -612,7 +599,7 @@ in preference to the \fIseekProc\fR, but both must be defined if the following prototype: .PP .CS -typedef Tcl_WideInt Tcl_DriverWideSeekProc( +typedef Tcl_WideInt \fBTcl_DriverWideSeekProc\fR( ClientData \fIinstanceData\fR, Tcl_WideInt \fIoffset\fR, int \fIseekMode\fR, @@ -634,7 +621,7 @@ the generic layer to set a channel type specific option on a channel. \fIsetOptionProc\fR must match the following prototype: .PP .CS -typedef int Tcl_DriverSetOptionProc( +typedef int \fBTcl_DriverSetOptionProc\fR( ClientData \fIinstanceData\fR, Tcl_Interp *\fIinterp\fR, const char *\fIoptionName\fR, @@ -675,7 +662,7 @@ the generic layer to get the value of a channel type specific option on a channel. \fIgetOptionProc\fR must match the following prototype: .PP .CS -typedef int Tcl_DriverGetOptionProc( +typedef int \fBTcl_DriverGetOptionProc\fR( ClientData \fIinstanceData\fR, Tcl_Interp *\fIinterp\fR, const char *\fIoptionName\fR, @@ -713,7 +700,7 @@ notice events of interest on this channel. \fIWatchProc\fR should match the following prototype: .PP .CS -typedef void Tcl_DriverWatchProc( +typedef void \fBTcl_DriverWatchProc\fR( ClientData \fIinstanceData\fR, int \fImask\fR); .CE @@ -744,7 +731,7 @@ the generic layer to retrieve a device-specific handle from the channel. \fIGetHandleProc\fR should match the following prototype: .PP .CS -typedef int Tcl_DriverGetHandleProc( +typedef int \fBTcl_DriverGetHandleProc\fR( ClientData \fIinstanceData\fR, int \fIdirection\fR, ClientData *\fIhandlePtr\fR); @@ -773,7 +760,7 @@ It should be set to NULL. \fIFlushProc\fR should match the following prototype: .PP .CS -typedef int Tcl_DriverFlushProc( +typedef int \fBTcl_DriverFlushProc\fR( ClientData \fIinstanceData\fR); .CE .PP @@ -788,7 +775,7 @@ that occur on the underlying (stacked) channel. \fIHandlerProc\fR should match the following prototype: .PP .CS -typedef int Tcl_DriverHandlerProc( +typedef int \fBTcl_DriverHandlerProc\fR( ClientData \fIinstanceData\fR, int \fIinterestMask\fR); .CE @@ -817,9 +804,9 @@ might be maintaining using the calling thread as the associate. See \fBTcl_CutChannel\fR and \fBTcl_SpliceChannel\fR for more detail. .PP .CS -typedef void Tcl_DriverThreadActionProc( +typedef void \fBTcl_DriverThreadActionProc\fR( ClientData \fIinstanceData\fR, - int \fIaction\fR); + int \fIaction\fR); .CE .PP \fIInstanceData\fR is the same as the value passed to @@ -834,7 +821,7 @@ called by the generic layer when a channel is truncated to some length. It can be NULL. .PP .CS -typedef int Tcl_DriverTruncateProc( +typedef int \fBTcl_DriverTruncateProc\fR( ClientData \fIinstanceData\fR, Tcl_WideInt \fIlength\fR); .CE @@ -889,18 +876,18 @@ the following fields: .PP .CS typedef struct Tcl_ChannelType { - char *\fItypeName\fR; - Tcl_DriverBlockModeProc *\fIblockModeProc\fR; - Tcl_DriverCloseProc *\fIcloseProc\fR; - Tcl_DriverInputProc *\fIinputProc\fR; - Tcl_DriverOutputProc *\fIoutputProc\fR; - Tcl_DriverSeekProc *\fIseekProc\fR; - Tcl_DriverSetOptionProc *\fIsetOptionProc\fR; - Tcl_DriverGetOptionProc *\fIgetOptionProc\fR; - Tcl_DriverWatchProc *\fIwatchProc\fR; - Tcl_DriverGetHandleProc *\fIgetHandleProc\fR; - Tcl_DriverClose2Proc *\fIclose2Proc\fR; -} Tcl_ChannelType; + const char *\fItypeName\fR; + Tcl_DriverBlockModeProc *\fIblockModeProc\fR; + Tcl_DriverCloseProc *\fIcloseProc\fR; + Tcl_DriverInputProc *\fIinputProc\fR; + Tcl_DriverOutputProc *\fIoutputProc\fR; + Tcl_DriverSeekProc *\fIseekProc\fR; + Tcl_DriverSetOptionProc *\fIsetOptionProc\fR; + Tcl_DriverGetOptionProc *\fIgetOptionProc\fR; + Tcl_DriverWatchProc *\fIwatchProc\fR; + Tcl_DriverGetHandleProc *\fIgetHandleProc\fR; + Tcl_DriverClose2Proc *\fIclose2Proc\fR; +} \fBTcl_ChannelType\fR; .CE .PP It is still possible to create channel with the above structure. The @@ -915,29 +902,27 @@ contained the following fields: .PP .CS typedef struct Tcl_ChannelType { - char *\fItypeName\fR; - Tcl_ChannelTypeVersion \fIversion\fR; - Tcl_DriverCloseProc *\fIcloseProc\fR; - Tcl_DriverInputProc *\fIinputProc\fR; - Tcl_DriverOutputProc *\fIoutputProc\fR; - Tcl_DriverSeekProc *\fIseekProc\fR; - Tcl_DriverSetOptionProc *\fIsetOptionProc\fR; - Tcl_DriverGetOptionProc *\fIgetOptionProc\fR; - Tcl_DriverWatchProc *\fIwatchProc\fR; - Tcl_DriverGetHandleProc *\fIgetHandleProc\fR; - Tcl_DriverClose2Proc *\fIclose2Proc\fR; - Tcl_DriverBlockModeProc *\fIblockModeProc\fR; - Tcl_DriverFlushProc *\fIflushProc\fR; - Tcl_DriverHandlerProc *\fIhandlerProc\fR; - Tcl_DriverTruncateProc *\fItruncateProc\fR; -} Tcl_ChannelType; + const char *\fItypeName\fR; + Tcl_ChannelTypeVersion \fIversion\fR; + Tcl_DriverCloseProc *\fIcloseProc\fR; + Tcl_DriverInputProc *\fIinputProc\fR; + Tcl_DriverOutputProc *\fIoutputProc\fR; + Tcl_DriverSeekProc *\fIseekProc\fR; + Tcl_DriverSetOptionProc *\fIsetOptionProc\fR; + Tcl_DriverGetOptionProc *\fIgetOptionProc\fR; + Tcl_DriverWatchProc *\fIwatchProc\fR; + Tcl_DriverGetHandleProc *\fIgetHandleProc\fR; + Tcl_DriverClose2Proc *\fIclose2Proc\fR; + Tcl_DriverBlockModeProc *\fIblockModeProc\fR; + Tcl_DriverFlushProc *\fIflushProc\fR; + Tcl_DriverHandlerProc *\fIhandlerProc\fR; + Tcl_DriverTruncateProc *\fItruncateProc\fR; +} \fBTcl_ChannelType\fR; .CE .PP When the above structure is registered as a channel type, the \fIversion\fR field should always be \fBTCL_CHANNEL_VERSION_2\fR. - .SH "SEE ALSO" Tcl_Close(3), Tcl_OpenFileChannel(3), Tcl_SetErrno(3), Tcl_QueueEvent(3), Tcl_StackChannel(3), Tcl_GetStdChannel(3) - .SH KEYWORDS blocking, channel driver, channel registration, channel type, nonblocking diff --git a/doc/CrtChnlHdlr.3 b/doc/CrtChnlHdlr.3 index f5fd1bd..1451e30 100644 --- a/doc/CrtChnlHdlr.3 +++ b/doc/CrtChnlHdlr.3 @@ -35,7 +35,6 @@ the conditions specified by \fImask\fR. .AP ClientData clientData in Arbitrary one-word value to pass to \fIproc\fR. .BE - .SH DESCRIPTION .PP \fBTcl_CreateChannelHandler\fR arranges for \fIproc\fR to be called in the @@ -46,8 +45,9 @@ invoked are specified by the \fImask\fR argument. See the manual entry for \fBfileevent\fR for a precise description of what it means for a channel to be readable or writable. \fIProc\fR must conform to the following prototype: +.PP .CS -typedef void Tcl_ChannelProc( +typedef void \fBTcl_ChannelProc\fR( ClientData \fIclientData\fR, int \fImask\fR); .CE @@ -83,9 +83,7 @@ so that the channel is no longer readable when the second handler is invoked. For this reason it may be useful to use nonblocking I/O on channels for which there are event handlers. - .SH "SEE ALSO" Notifier(3), Tcl_CreateChannel(3), Tcl_OpenFileChannel(3), vwait(n). - .SH KEYWORDS blocking, callback, channel, events, handler, nonblocking. diff --git a/doc/CrtCloseHdlr.3 b/doc/CrtCloseHdlr.3 index c8804b1..a114f9c 100644 --- a/doc/CrtCloseHdlr.3 +++ b/doc/CrtCloseHdlr.3 @@ -29,7 +29,6 @@ The procedure to call as the callback. .AP ClientData clientData in Arbitrary one-word value to pass to \fIproc\fR. .BE - .SH DESCRIPTION .PP \fBTcl_CreateCloseHandler\fR arranges for \fIproc\fR to be called when @@ -38,7 +37,7 @@ Arbitrary one-word value to pass to \fIproc\fR. \fIProc\fR should match the following prototype: .PP .CS -typedef void Tcl_CloseProc( +typedef void \fBTcl_CloseProc\fR( ClientData \fIclientData\fR); .CE .PP @@ -50,9 +49,7 @@ The \fIproc\fR and \fIclientData\fR identify which close callback to remove; \fBTcl_DeleteCloseHandler\fR does nothing if its \fIproc\fR and \fIclientData\fR arguments do not match the \fIproc\fR and \fIclientData\fR for a close handler for \fIchannel\fR. - .SH "SEE ALSO" close(n), Tcl_Close(3), Tcl_UnregisterChannel(3) - .SH KEYWORDS callback, channel closing diff --git a/doc/CrtCommand.3 b/doc/CrtCommand.3 index fcc04d5..f0a7b43 100644 --- a/doc/CrtCommand.3 +++ b/doc/CrtCommand.3 @@ -32,7 +32,6 @@ Procedure to call before \fIcmdName\fR is deleted from the interpreter; allows for command-specific cleanup. If NULL, then no procedure is called before the command is deleted. .BE - .SH DESCRIPTION .PP \fBTcl_CreateCommand\fR defines a new command in \fIinterp\fR and associates @@ -53,9 +52,7 @@ Also, Tcl's interpreter now uses objects internally. In order to invoke a string-based command procedure registered by \fBTcl_CreateCommand\fR, it must generate and fetch a string representation -from each argument object before the call -and create a new Tcl object to hold the string result returned by the -string-based command procedure. +from each argument object before the call. New commands should be defined using \fBTcl_CreateObjCommand\fR. We support \fBTcl_CreateCommand\fR for backwards compatibility. .PP @@ -75,13 +72,15 @@ the process of being deleted, then it does not create a new command and it returns NULL. \fIProc\fR should have arguments and result that match the type \fBTcl_CmdProc\fR: +.PP .CS -typedef int Tcl_CmdProc( +typedef int \fBTcl_CmdProc\fR( ClientData \fIclientData\fR, Tcl_Interp *\fIinterp\fR, int \fIargc\fR, const char *\fIargv\fR[]); .CE +.PP When \fIproc\fR is invoked the \fIclientData\fR and \fIinterp\fR parameters will be copies of the \fIclientData\fR and \fIinterp\fR arguments given to \fBTcl_CreateCommand\fR. @@ -105,7 +104,7 @@ version 8.1 of Tcl. \fBTCL_CONTINUE\fR. See the Tcl overview man page for details on what these codes mean. Most normal commands will only return \fBTCL_OK\fR or \fBTCL_ERROR\fR. In addition, \fIproc\fR must set -the interpreter result to point to a string value; +the interpreter result; in the case of a \fBTCL_OK\fR return code this gives the result of the command, and in the case of \fBTCL_ERROR\fR it gives an error message. The \fBTcl_SetResult\fR procedure provides an easy interface for setting @@ -122,22 +121,23 @@ anywhere within the \fIargv\fR values. Call \fBTcl_SetResult\fR with status \fBTCL_VOLATILE\fR if you want to return something from the \fIargv\fR array. .PP -\fIDeleteProc\fR will be invoked when (if) \fIcmdName\fR is deleted. -This can occur through a call to \fBTcl_DeleteCommand\fR or \fBTcl_DeleteInterp\fR, +\fIDeleteProc\fR will be invoked when (if) \fIcmdName\fR is deleted. This can +occur through a call to \fBTcl_DeleteCommand\fR or \fBTcl_DeleteInterp\fR, or by replacing \fIcmdName\fR in another call to \fBTcl_CreateCommand\fR. \fIDeleteProc\fR is invoked before the command is deleted, and gives the application an opportunity to release any structures associated with the command. \fIDeleteProc\fR should have arguments and result that match the type \fBTcl_CmdDeleteProc\fR: +.PP .CS -typedef void Tcl_CmdDeleteProc( +typedef void \fBTcl_CmdDeleteProc\fR( ClientData \fIclientData\fR); .CE +.PP The \fIclientData\fR argument will be the same as the \fIclientData\fR argument passed to \fBTcl_CreateCommand\fR. - .SH "SEE ALSO" -Tcl_CreateObjCommand, Tcl_DeleteCommand, Tcl_GetCommandInfo, Tcl_SetCommandInfo, Tcl_GetCommandName, Tcl_SetObjResult - +Tcl_CreateObjCommand, Tcl_DeleteCommand, Tcl_GetCommandInfo, +Tcl_SetCommandInfo, Tcl_GetCommandName, Tcl_SetObjResult .SH KEYWORDS bind, command, create, delete, interpreter, namespace diff --git a/doc/CrtFileHdlr.3 b/doc/CrtFileHdlr.3 index 5627bd4..cbc5e9f 100644 --- a/doc/CrtFileHdlr.3 +++ b/doc/CrtFileHdlr.3 @@ -32,7 +32,6 @@ by \fIfile\fR meets the conditions specified by \fImask\fR. .AP ClientData clientData in Arbitrary one-word value to pass to \fIproc\fR. .BE - .SH DESCRIPTION .PP \fBTcl_CreateFileHandler\fR arranges for \fIproc\fR to be @@ -49,11 +48,13 @@ as \fBvwait\fR. .PP \fIProc\fR should have arguments and result that match the type \fBTcl_FileProc\fR: +.PP .CS -typedef void Tcl_FileProc( +typedef void \fBTcl_FileProc\fR( ClientData \fIclientData\fR, int \fImask\fR); .CE +.PP The \fIclientData\fR parameter to \fIproc\fR is a copy of the \fIclientData\fR argument given to \fBTcl_CreateFileHandler\fR when the callback @@ -64,7 +65,6 @@ of the requested conditions actually exists for the file; it will contain a subset of the bits in the \fImask\fR argument to \fBTcl_CreateFileHandler\fR. .PP -.PP There may exist only one handler for a given file at a given time. If \fBTcl_CreateFileHandler\fR is called when a handler already exists for \fIfd\fR, then the new callback replaces the information @@ -84,7 +84,8 @@ complete the application will not be able to service other events. Use blocking or nonblocking mode as required. .PP Note that these interfaces are only supported by the Unix -implementation of the Tcl notifier. - +implementation of the Tcl notifier. +.SH "SEE ALSO" +fileevent(n), Tcl_CreateTimerHandler(3), Tcl_DoWhenIdle(3) .SH KEYWORDS callback, file, handler diff --git a/doc/CrtInterp.3 b/doc/CrtInterp.3 index 957e742..a248cf4 100644 --- a/doc/CrtInterp.3 +++ b/doc/CrtInterp.3 @@ -9,7 +9,7 @@ .TH Tcl_CreateInterp 3 7.5 Tcl "Tcl Library Procedures" .BS .SH NAME -Tcl_CreateInterp, Tcl_DeleteInterp, Tcl_InterpDeleted \- create and delete Tcl command interpreters +Tcl_CreateInterp, Tcl_DeleteInterp, Tcl_InterpActive, Tcl_InterpDeleted \- create and delete Tcl command interpreters .SH SYNOPSIS .nf \fB#include <tcl.h>\fR @@ -21,30 +21,34 @@ Tcl_Interp * .sp int \fBTcl_InterpDeleted\fR(\fIinterp\fR) +.sp +.VS 8.6 +int +\fBTcl_InterpActive\fR(\fIinterp\fR) +.VE 8.6 .SH ARGUMENTS .AS Tcl_Interp *interp .AP Tcl_Interp *interp in -Token for interpreter to be destroyed. +Token for interpreter to be destroyed or queried. .BE - .SH DESCRIPTION .PP \fBTcl_CreateInterp\fR creates a new interpreter structure and returns -a token for it. The token is required in calls to most other Tcl +a token for it. The token is required in calls to most other Tcl procedures, such as \fBTcl_CreateCommand\fR, \fBTcl_Eval\fR, and -\fBTcl_DeleteInterp\fR. -Clients are only allowed to access a few of the fields of -Tcl_Interp structures; see the \fBTcl_Interp\fR -and \fBTcl_CreateCommand\fR man pages for details. +\fBTcl_DeleteInterp\fR. The token returned by \fBTcl_CreateInterp\fR +may only be passed to Tcl routines called from the same thread as +the original \fBTcl_CreateInterp\fR call. It is not safe for multiple +threads to pass the same token to Tcl's routines. The new interpreter is initialized with the built-in Tcl commands -and with the variables documented in tclvars(n). To bind in +and with the variables documented in the \fBtclvars\fR manual page. To bind in additional commands, call \fBTcl_CreateCommand\fR. .PP \fBTcl_DeleteInterp\fR marks an interpreter as deleted; the interpreter will eventually be deleted when all calls to \fBTcl_Preserve\fR for it have been matched by calls to \fBTcl_Release\fR. At that time, all of the resources associated with it, including variables, procedures, and -application-specific command bindings, will be deleted. After +application-specific command bindings, will be deleted. After \fBTcl_DeleteInterp\fR returns any attempt to use \fBTcl_Eval\fR on the interpreter will fail and return \fBTCL_ERROR\fR. After the call to \fBTcl_DeleteInterp\fR it is safe to examine the interpreter's result, @@ -64,7 +68,15 @@ between when only the memory the callback is responsible for is being deleted and when the whole interpreter is being deleted. In the former case the callback may recreate the data being deleted, but this would lead to an infinite loop if the interpreter were being deleted. - +.PP +.VS 8.6 +\fBTcl_InterpActive\fR is useful for determining whether there is any +execution of scripts ongoing in an interpreter, which is a useful piece of +information when Tcl is embedded in a garbage-collected environment and it +becomes necessary to determine whether the interpreter is a candidate for +deletion. The function returns a true value if the interpreter has at least +one active execution running inside it, and a false value otherwise. +.VE 8.6 .SH "INTERPRETERS AND MEMORY MANAGEMENT" .PP \fBTcl_DeleteInterp\fR can be called at any time on an interpreter that may @@ -84,14 +96,16 @@ the last call to \fBTcl_Preserve\fR is matched by a call to The rules for when the user of an interpreter must call \fBTcl_Preserve\fR and \fBTcl_Release\fR are simple: .TP -Interpreters Passed As Arguments +\fBInterpreters Passed As Arguments\fR +. Functions that are passed an interpreter as an argument can safely use the interpreter without any special protection. Thus, when you write an extension consisting of new Tcl commands, no special code is needed to protect interpreters received as arguments. This covers the majority of all uses. .TP -Interpreter Creation And Deletion +\fBInterpreter Creation And Deletion\fR +. When a new interpreter is created and used in a call to \fBTcl_Eval\fR, \fBTcl_VarEval\fR, \fBTcl_GlobalEval\fR, \fBTcl_SetVar\fR, or \fBTcl_GetVar\fR, a pair of calls to \fBTcl_Preserve\fR and @@ -102,13 +116,16 @@ it is no longer needed, call \fBTcl_InterpDeleted\fR to test if some other code already called \fBTcl_DeleteInterp\fR; if not, call \fBTcl_DeleteInterp\fR before calling \fBTcl_Release\fR in your own code. .TP -Retrieving An Interpreter From A Data Structure +\fBRetrieving An Interpreter From A Data Structure\fR +. When an interpreter is retrieved from a data structure (e.g. the client -data of a callback) for use in \fBTcl_Eval\fR, \fBTcl_VarEval\fR, -\fBTcl_GlobalEval\fR, \fBTcl_SetVar\fR, or \fBTcl_GetVar\fR, a pair of +data of a callback) for use in one of the evaluation functions +(\fBTcl_Eval\fR, \fBTcl_VarEval\fR, \fBTcl_GlobalEval\fR, \fBTcl_EvalObjv\fR, +etc.) or variable access functions (\fBTcl_SetVar\fR, \fBTcl_GetVar\fR, +\fBTcl_SetVar2Ex\fR, etc.), a pair of calls to \fBTcl_Preserve\fR and \fBTcl_Release\fR should be wrapped around all uses of the interpreter; it is unsafe to reuse the interpreter once -\fBTcl_Release\fR has been called. If an interpreter is stored inside a +\fBTcl_Release\fR has been called. If an interpreter is stored inside a callback data structure, an appropriate deletion cleanup mechanism should be set up by the code that creates the data structure so that the interpreter is removed from the data structure (e.g. by setting the field @@ -119,9 +136,14 @@ reused. All uses of interpreters in Tcl and Tk have already been protected. Extension writers should ensure that their code also properly protects any additional interpreters used, as described above. - +.PP +.VS 8.6 +Note that the protection mechanisms do not work well with conventional garbage +collection systems. When in such a managed environment, \fBTcl_InterpActive\fR +should be used to determine when an interpreter is a candidate for deletion +due to inactivity. +.VE 8.6 .SH "SEE ALSO" -Tcl_Preserve(3), Tcl_Release(3) - +Tcl_Preserve(3), Tcl_Release(3), tclvars(n) .SH KEYWORDS command, create, delete, interpreter diff --git a/doc/CrtMathFnc.3 b/doc/CrtMathFnc.3 index 9629912..3f2c84e 100644 --- a/doc/CrtMathFnc.3 +++ b/doc/CrtMathFnc.3 @@ -57,7 +57,6 @@ created if the function is not implemented directly in bytecode. Pattern to match against function names so as to filter them (by passing to \fITcl_StringMatch\fR), or NULL to not apply any filter. .BE - .SH DESCRIPTION .PP Tcl allows a number of mathematical functions to be used in @@ -85,8 +84,9 @@ or any, respectively. Whenever the function is invoked in an expression Tcl will invoke \fIproc\fR. \fIProc\fR should have arguments and result that match the type \fBTcl_MathProc\fR: +.PP .CS -typedef int Tcl_MathProc( +typedef int \fBTcl_MathProc\fR( ClientData \fIclientData\fR, Tcl_Interp *\fIinterp\fR, Tcl_Value *\fIargs\fR, @@ -97,13 +97,14 @@ When \fIproc\fR is invoked the \fIclientData\fR and \fIinterp\fR arguments will be the same as those passed to \fBTcl_CreateMathFunc\fR. \fIArgs\fR will point to an array of \fInumArgs\fR Tcl_Value structures, which describe the actual arguments to the function: +.PP .CS typedef struct Tcl_Value { - Tcl_ValueType \fItype\fR; - long \fIintValue\fR; - double \fIdoubleValue\fR; - Tcl_WideInt \fIwideValue\fR; -} Tcl_Value; + Tcl_ValueType \fItype\fR; + long \fIintValue\fR; + double \fIdoubleValue\fR; + Tcl_WideInt \fIwideValue\fR; +} \fBTcl_Value\fR; .CE .PP The \fItype\fR field indicates the type of the argument and is @@ -148,9 +149,7 @@ pointed to by \fIargTypesPointer\fR. \fBTcl_ListMathFuncs\fR returns a Tcl object containing a list of all the math functions defined in the interpreter whose name matches \fIpattern\fR. The returned object has a reference count of zero. - .SH "SEE ALSO" expr(n), info(n), Tcl_CreateObjCommand(3), Tcl_Free(3), Tcl_NewListObj(3) - .SH KEYWORDS expression, mathematical function diff --git a/doc/CrtObjCmd.3 b/doc/CrtObjCmd.3 index a05efc2..343b3dd 100644 --- a/doc/CrtObjCmd.3 +++ b/doc/CrtObjCmd.3 @@ -88,13 +88,15 @@ the process of being deleted, then it does not create a new command and it returns NULL. \fIproc\fR should have arguments and result that match the type \fBTcl_ObjCmdProc\fR: +.PP .CS -typedef int Tcl_ObjCmdProc( +typedef int \fBTcl_ObjCmdProc\fR( ClientData \fIclientData\fR, Tcl_Interp *\fIinterp\fR, int \fIobjc\fR, Tcl_Obj *const \fIobjv\fR[]); .CE +.PP When \fIproc\fR is invoked, the \fIclientData\fR and \fIinterp\fR parameters will be copies of the \fIclientData\fR and \fIinterp\fR arguments given to \fBTcl_CreateObjCommand\fR. Typically, \fIclientData\fR points to an @@ -159,10 +161,12 @@ or by replacing \fIname\fR in another call to \fBTcl_CreateObjCommand\fR. application an opportunity to release any structures associated with the command. \fIDeleteProc\fR should have arguments and result that match the type \fBTcl_CmdDeleteProc\fR: +.PP .CS -typedef void Tcl_CmdDeleteProc( +typedef void \fBTcl_CmdDeleteProc\fR( ClientData \fIclientData\fR); .CE +.PP The \fIclientData\fR argument will be the same as the \fIclientData\fR argument passed to \fBTcl_CreateObjCommand\fR. .PP @@ -197,6 +201,7 @@ Otherwise it places information about the command in the \fBTcl_CmdInfo\fR structure pointed to by \fIinfoPtr\fR and returns 1. A \fBTcl_CmdInfo\fR structure has the following fields: +.PP .CS typedef struct Tcl_CmdInfo { int \fIisNativeObjectProc\fR; @@ -207,8 +212,9 @@ typedef struct Tcl_CmdInfo { Tcl_CmdDeleteProc *\fIdeleteProc\fR; ClientData \fIdeleteData\fR; Tcl_Namespace *\fInamespacePtr\fR; -} Tcl_CmdInfo; +} \fBTcl_CmdInfo\fR; .CE +.PP The \fIisNativeObjectProc\fR field has the value 1 if \fBTcl_CreateObjCommand\fR was called to register the command; it is 0 if only \fBTcl_CreateCommand\fR was called. @@ -291,7 +297,6 @@ specified by the name in a \fBTcl_Obj\fR. The command name is resolved relative to the current namespace. Returns NULL if the command is not found. .SH "SEE ALSO" -Tcl_CreateCommand, Tcl_ResetResult, Tcl_SetObjResult - +Tcl_CreateCommand(3), Tcl_ResetResult(3), Tcl_SetObjResult(3) .SH KEYWORDS bind, command, create, delete, namespace, object diff --git a/doc/CrtTimerHdlr.3 b/doc/CrtTimerHdlr.3 index e948728..2c9f90a 100644 --- a/doc/CrtTimerHdlr.3 +++ b/doc/CrtTimerHdlr.3 @@ -30,7 +30,6 @@ Arbitrary one-word value to pass to \fIproc\fR. Token for previously created timer handler (the return value from some previous call to \fBTcl_CreateTimerHandler\fR). .BE - .SH DESCRIPTION .PP \fBTcl_CreateTimerHandler\fR arranges for \fIproc\fR to be @@ -49,9 +48,12 @@ are other pending events to process before the call to .PP \fIProc\fR should have arguments and return value that match the type \fBTcl_TimerProc\fR: +.PP .CS -typedef void Tcl_TimerProc(ClientData \fIclientData\fR); +typedef void \fBTcl_TimerProc\fR( + ClientData \fIclientData\fR); .CE +.PP The \fIclientData\fR parameter to \fIproc\fR is a copy of the \fIclientData\fR argument given to \fBTcl_CreateTimerHandler\fR when the callback @@ -68,6 +70,7 @@ has been invoked then \fBTcl_DeleteTimerHandler\fR does nothing. The tokens returned by \fBTcl_CreateTimerHandler\fR never have a value of NULL, so if NULL is passed to \fBTcl_DeleteTimerHandler\fR then the procedure does nothing. - +.SH "SEE ALSO" +after(n), Tcl_CreateFileHandler(3), Tcl_DoWhenIdle(3) .SH KEYWORDS callback, clock, handler, timer diff --git a/doc/CrtTrace.3 b/doc/CrtTrace.3 index 076f47b..3689add 100644 --- a/doc/CrtTrace.3 +++ b/doc/CrtTrace.3 @@ -63,6 +63,7 @@ interpreter. .PP \fIobjProc\fR should have arguments and result that match the type, \fBTcl_CmdObjTraceProc\fR: +.PP .CS typedef int \fBTcl_CmdObjTraceProc\fR( \fBClientData\fR \fIclientData\fR, @@ -71,8 +72,9 @@ typedef int \fBTcl_CmdObjTraceProc\fR( const char *\fIcommand\fR, \fBTcl_Command\fR \fIcommandToken\fR, int \fIobjc\fR, - \fBTcl_Obj\fR *const \fIobjv\fR[] ); + \fBTcl_Obj\fR *const \fIobjv\fR[]); .CE +.PP The \fIclientData\fR and \fIinterp\fR parameters are copies of the corresponding arguments given to \fBTcl_CreateTrace\fR. \fIClientData\fR typically points to an application-specific data @@ -139,10 +141,12 @@ When \fBTcl_DeleteTrace\fR is called, the interpreter invokes the \fIdeleteProc\fR that was passed as a parameter to \fBTcl_CreateObjTrace\fR. The \fIdeleteProc\fR must match the type, \fBTcl_CmdObjTraceDeleteProc\fR: +.PP .CS typedef void \fBTcl_CmdObjTraceDeleteProc\fR( \fBClientData\fR \fIclientData\fR); .CE +.PP The \fIclientData\fR parameter will be the same as the \fIclientData\fR parameter that was originally passed to \fBTcl_CreateObjTrace\fR. @@ -153,8 +157,9 @@ compatibility with code that was developed for older versions of the Tcl interpreter. It is similar to \fBTcl_CreateObjTrace\fR, except that its \fIproc\fR parameter should have arguments and result that match the type \fBTcl_CmdTraceProc\fR: +.PP .CS -typedef void Tcl_CmdTraceProc( +typedef void \fBTcl_CmdTraceProc\fR( ClientData \fIclientData\fR, Tcl_Interp *\fIinterp\fR, int \fIlevel\fR, @@ -164,6 +169,7 @@ typedef void Tcl_CmdTraceProc( int \fIargc\fR, const char *\fIargv\fR[]); .CE +.PP The parameters to the \fIproc\fR callback are similar to those of the \fIobjProc\fR callback above. The \fIcommandToken\fR is replaced with \fIcmdProc\fR, a pointer to the (string-based) command diff --git a/doc/DoWhenIdle.3 b/doc/DoWhenIdle.3 index bfc19fb..27a4b8c 100644 --- a/doc/DoWhenIdle.3 +++ b/doc/DoWhenIdle.3 @@ -24,7 +24,6 @@ Procedure to invoke. .AP ClientData clientData in Arbitrary one-word value to pass to \fIproc\fR. .BE - .SH DESCRIPTION .PP \fBTcl_DoWhenIdle\fR arranges for \fIproc\fR to be invoked @@ -41,9 +40,12 @@ use \fBTcl_DoOneEvent\fR to dispatch events. .PP \fIProc\fR should have arguments and result that match the type \fBTcl_IdleProc\fR: +.PP .CS -typedef void Tcl_IdleProc(ClientData \fIclientData\fR); +typedef void \fBTcl_IdleProc\fR( + ClientData \fIclientData\fR); .CE +.PP The \fIclientData\fR parameter to \fIproc\fR is a copy of the \fIclientData\fR argument given to \fBTcl_DoWhenIdle\fR. Typically, \fIclientData\fR points to a data structure containing application-specific information about @@ -79,6 +81,7 @@ continuously. This will interact badly with certain features of Tk that attempt to wait for all idle callbacks to complete. If you would like for an idle callback to reschedule itself continuously, it is better to use a timer handler with a zero timeout period. - +.SH "SEE ALSO" +after(n), Tcl_CreateFileHandler(3), Tcl_CreateTimerHandler(3) .SH KEYWORDS callback, defer, idle callback diff --git a/doc/Encoding.3 b/doc/Encoding.3 index a940a5b..7bcb285 100644 --- a/doc/Encoding.3 +++ b/doc/Encoding.3 @@ -19,10 +19,8 @@ Tcl_Encoding void \fBTcl_FreeEncoding\fR(\fIencoding\fR) .sp -.VS 8.5 int \fBTcl_GetEncodingFromObj\fR(\fIinterp, objPtr, encodingPtr\fR) -.VE 8.5 .sp char * \fBTcl_ExternalToUtfDString\fR(\fIencoding, src, srcLen, dstPtr\fR) @@ -50,10 +48,8 @@ const char * int \fBTcl_SetSystemEncoding\fR(\fIinterp, name\fR) .sp -.VS 8.5 const char * \fBTcl_GetEncodingNameFromEnvironment\fR(\fIbufPtr\fR) -.VE 8.5 .sp void \fBTcl_GetEncodingNames\fR(\fIinterp\fR) @@ -61,13 +57,11 @@ void Tcl_Encoding \fBTcl_CreateEncoding\fR(\fItypePtr\fR) .sp -.VS 8.5 Tcl_Obj * \fBTcl_GetEncodingSearchPath\fR() .sp int \fBTcl_SetEncodingSearchPath\fR(\fIsearchPath\fR) -.VE 8.5 .sp const char * \fBTcl_GetDefaultEncodingDir\fR(\fIvoid\fR) @@ -85,13 +79,9 @@ Name of encoding to load. The encoding to query, free, or use for converting text. If \fIencoding\fR is NULL, the current system encoding is used. .AP Tcl_Obj *objPtr in -.VS 8.5 Name of encoding to get token for. -.VE 8.5 .AP Tcl_Encoding *encodingPtr out -.VS 8.5 Points to storage where encoding token is to be written. -.VE 8.5 .AP "const char" *src in For the \fBTcl_ExternalToUtf\fR functions, an array of bytes in the specified encoding that are to be converted to UTF-8. For the @@ -145,15 +135,11 @@ buffer as a result of the conversion. May be NULL. Filled with the number of characters that correspond to the number of bytes stored in the output buffer. May be NULL. .AP Tcl_DString *bufPtr out -.VS 8.5 Storage for the prescribed system encoding name. -.VE 8.5 .AP "const Tcl_EncodingType" *typePtr in Structure that defines a new type of encoding. .AP Tcl_Obj *searchPath in -.VS 8.5 List of filesystem directories in which to search for encoding data files. -.VE 8.5 .AP "const char" *path in A path to the location of the encoding file. .BE @@ -202,7 +188,6 @@ anywhere (i.e., it has been freed as many times as it has been gotten) \fBTcl_FreeEncoding\fR will release all storage the encoding was using and delete it from the database. .PP -.VS 8.5 \fBTcl_GetEncodingFromObj\fR treats the string representation of \fIobjPtr\fR as an encoding name, and finds an encoding with that name, just as \fBTcl_GetEncoding\fR does. When an encoding is found, @@ -214,7 +199,6 @@ writing to \fB*\fR\fIencodingPtr\fR takes place. Just as with \fBTcl_GetEncoding\fR, the caller should call \fBTcl_FreeEncoding\fR on the resulting encoding token when that token will no longer be used. -.VE 8.5 .PP \fBTcl_ExternalToUtfDString\fR converts a source buffer \fIsrc\fR from the specified \fIencoding\fR into UTF-8. The converted bytes are stored in @@ -296,6 +280,7 @@ and the interfaces when running on Windows 95, you would have to perform the following type of test over and over in your program (as represented in pseudo-code): +.PP .CS if (running NT) { encoding <- Tcl_GetEncoding("unicode"); @@ -305,6 +290,7 @@ if (running NT) { nativeBuffer <- Tcl_UtfToExternal(NULL, utfBuffer); } .CE +.PP \fBTcl_WinUtfToTChar\fR and \fBTcl_WinTCharToUtf\fR automatically handle this test and use the proper encoding based on the current operating system. \fBTcl_WinUtfToTChar\fR returns a pointer to @@ -329,14 +315,12 @@ procedure increments the reference count of the new system encoding, decrements the reference count of the old system encoding, and returns \fBTCL_OK\fR. .PP -.VS 8.5 \fBTcl_GetEncodingNameFromEnvironment\fR provides a means for the Tcl library to report the encoding name it believes to be the correct one to use as the system encoding, based on system calls and examination of the environment suitable for the platform. It accepts \fIbufPtr\fR, a pointer to an uninitialized or freed \fBTcl_DString\fR and writes the encoding name to it. The \fBTcl_DStringValue\fR is returned. -.VE 8.5 .PP \fBTcl_GetEncodingNames\fR sets the \fIinterp\fR result to a list consisting of the names of all the encodings that are currently defined @@ -364,13 +348,13 @@ convert between this encoding and UTF-8. It is defined as follows: .PP .CS typedef struct Tcl_EncodingType { - const char *\fIencodingName\fR; - Tcl_EncodingConvertProc *\fItoUtfProc\fR; - Tcl_EncodingConvertProc *\fIfromUtfProc\fR; - Tcl_EncodingFreeProc *\fIfreeProc\fR; - ClientData \fIclientData\fR; - int \fInullSize\fR; -} Tcl_EncodingType; + const char *\fIencodingName\fR; + Tcl_EncodingConvertProc *\fItoUtfProc\fR; + Tcl_EncodingConvertProc *\fIfromUtfProc\fR; + Tcl_EncodingFreeProc *\fIfreeProc\fR; + ClientData \fIclientData\fR; + int \fInullSize\fR; +} \fBTcl_EncodingType\fR; .CE .PP The \fIencodingName\fR provides a string name for the encoding, by @@ -398,7 +382,7 @@ The callback procedures \fItoUtfProc\fR and \fIfromUtfProc\fR should match the type \fBTcl_EncodingConvertProc\fR: .PP .CS -typedef int Tcl_EncodingConvertProc( +typedef int \fBTcl_EncodingConvertProc\fR( ClientData \fIclientData\fR, const char *\fIsrc\fR, int \fIsrcLen\fR, @@ -428,8 +412,9 @@ procedure will be a non-NULL location. .PP The callback procedure \fIfreeProc\fR, if non-NULL, should match the type \fBTcl_EncodingFreeProc\fR: +.PP .CS -typedef void Tcl_EncodingFreeProc( +typedef void \fBTcl_EncodingFreeProc\fR( ClientData \fIclientData\fR); .CE .PP @@ -437,7 +422,6 @@ This \fIfreeProc\fR function is called when the encoding is deleted. The \fIclientData\fR parameter is the same as the \fIclientData\fR field specified to \fBTcl_CreateEncoding\fR when the encoding was created. .PP -.VS 8.5 \fBTcl_GetEncodingSearchPath\fR and \fBTcl_SetEncodingSearchPath\fR are called to access and set the list of filesystem directories searched for encoding data files. @@ -465,7 +449,6 @@ list. Since Tcl searches \fIsearchPath\fR for encoding data files in list order, these routines establish the .QW default directory in which to find encoding data files. -.VE 8.5 .SH "ENCODING FILES" Space would prohibit precompiling into Tcl every possible encoding algorithm, so many encodings are stored on disk as dynamically-loadable @@ -506,6 +489,7 @@ Cases [1], [2], and [3] are collectively referred to as table-based encoding files. The lines in a table-based encoding file are in the same format as this example taken from the \fBshiftjis\fR encoding (this is not the complete file): +.PP .CS # Encoding file: shiftjis, multi-byte M @@ -571,6 +555,7 @@ If all characters on a page would map to 0000, that page can be omitted. Case [4] is the escape-sequence encoding file. The lines in an this type of file are in the same format as this example taken from the \fBiso2022-jp\fR encoding: +.PP .CS .ta 1.5i # Encoding file: iso2022-jp, escape-driven diff --git a/doc/Ensemble.3 b/doc/Ensemble.3 index 5a5842d..19c6099 100644 --- a/doc/Ensemble.3 +++ b/doc/Ensemble.3 @@ -10,7 +10,7 @@ .TH Tcl_Ensemble 3 8.5 Tcl "Tcl Library Procedures" .BS .SH NAME -Tcl_CreateEnsemble, Tcl_FindEnsemble, Tcl_GetEnsembleFlags, Tcl_GetEnsembleMappingDict, Tcl_GetEnsembleNamespace, Tcl_GetEnsembleUnknownHandler, Tcl_GetEnsembleSubcommandList, Tcl_IsEnsemble, Tcl_SetEnsembleFlags, Tcl_SetEnsembleMappingDict, Tcl_SetEnsembleSubcommandList, Tcl_SetEnsembleUnknownHandler \- manipulate ensemble commands +Tcl_CreateEnsemble, Tcl_FindEnsemble, Tcl_GetEnsembleFlags, Tcl_GetEnsembleMappingDict, Tcl_GetEnsembleNamespace, Tcl_GetEnsembleParameterList, Tcl_GetEnsembleUnknownHandler, Tcl_GetEnsembleSubcommandList, Tcl_IsEnsemble, Tcl_SetEnsembleFlags, Tcl_SetEnsembleMappingDict, Tcl_SetEnsembleParameterList, Tcl_SetEnsembleSubcommandList, Tcl_SetEnsembleUnknownHandler \- manipulate ensemble commands .SH SYNOPSIS .nf \fB#include <tcl.h>\fR @@ -36,6 +36,14 @@ int int \fBTcl_SetEnsembleMappingDict\fR(\fIinterp, token, dictObj\fR) .sp +.VS 8.6 +int +\fBTcl_GetEnsembleParameterList\fR(\fIinterp, token, listObjPtr\fR) +.sp +int +\fBTcl_SetEnsembleParameterList\fR(\fIinterp, token, listObj\fR) +.VE 8.6 +.sp int \fBTcl_GetEnsembleSubcommandList\fR(\fIinterp, token, listObjPtr\fR) .sp @@ -64,20 +72,20 @@ The namespace to which the ensemble command is to be bound, or NULL for the current namespace. .AP int ensFlags in An ORed set of flag bits describing the basic configuration of the -ensemble. Currently only one bit has meaning, TCL_ENSEMBLE_PREFIX, +ensemble. Currently only one bit has meaning, \fBTCL_ENSEMBLE_PREFIX\fR, which is present when the ensemble command should also match unambiguous prefixes of subcommands. .AP Tcl_Obj *cmdNameObj in A value holding the name of the ensemble command to look up. .AP int flags in An ORed set of flag bits controlling the behavior of -\fBTcl_FindEnsemble\fR. Currently only TCL_LEAVE_ERR_MSG is supported. +\fBTcl_FindEnsemble\fR. Currently only \fBTCL_LEAVE_ERR_MSG\fR is supported. .AP Tcl_Command token in A normal command token that refers to an ensemble command, or which you wish to use for testing as an ensemble command in \fBTcl_IsEnsemble\fR. .AP int *ensFlagsPtr out Pointer to a variable into which to write the current ensemble flag -bits; currently only the bit TCL_ENSEMBLE_PREFIX is defined. +bits; currently only the bit \fBTCL_ENSEMBLE_PREFIX\fR is defined. .AP Tcl_Obj *dictObj in A dictionary value to use for the subcommand to implementation command prefix mapping dictionary in the ensemble. May be NULL if the mapping @@ -86,17 +94,18 @@ dictionary is to be removed. Pointer to a variable into which to write the current ensemble mapping dictionary. .AP Tcl_Obj *listObj in -A list value to use for the defined list of subcommands in the -dictionary or the unknown subcommmand handler command prefix. May be -NULL if the subcommand list or unknown handler are to be removed. +A list value to use for the list of formal pre-subcommand parameters, the +defined list of subcommands in the dictionary or the unknown subcommmand +handler command prefix. May be NULL if the subcommand list or unknown handler +are to be removed. .AP Tcl_Obj **listObjPtr out -Pointer to a variable into which to write the current defiend list of -subcommands or the current unknown handler prefix. +Pointer to a variable into which to write the current list of formal +pre-subcommand parameters, the defined list of subcommands or the current +unknown handler prefix. .AP Tcl_Namespace **namespacePtrPtr out Pointer to a variable into which to write the handle of the namespace to which the ensemble is bound. .BE - .SH DESCRIPTION An ensemble is a command, bound to some namespace, which consists of a collection of subcommands implemented by other Tcl commands. The first @@ -108,13 +117,13 @@ arguments: the interpreter to work within, the name of the ensemble to create, the namespace within the interpreter to bind the ensemble to, and the default set of ensemble flags. The result of the function is the command token for the ensemble, which may be used to further -configure the ensemble using the API described below in \fBENSEMBLE -PROPERTIES\fR. +configure the ensemble using the API described below in +\fBENSEMBLE PROPERTIES\fR. .PP Given the name of an ensemble command, the token for that command may be retrieved using \fBTcl_FindEnsemble\fR. If the given command name (in \fIcmdNameObj\fR) does not refer to an ensemble command, the -result of the function is NULL and (if the TCL_LEAVE_ERR_MSG bit is +result of the function is NULL and (if the \fBTCL_LEAVE_ERR_MSG\fR bit is set in \fIflags\fR) an error message is left in the interpreter result. .PP @@ -126,16 +135,18 @@ Every ensemble has four read-write properties and a read-only property. The properties are: .TP \fBflags\fR (read-write) +. The set of flags for the ensemble, expressed as a -bit-field. Currently, the only public flag is TCL_ENSEMBLE_PREFIX +bit-field. Currently, the only public flag is \fBTCL_ENSEMBLE_PREFIX\fR which is set when unambiguous prefixes of subcommands are permitted to be resolved to implementations as well as exact matches. The flags may be read and written using \fBTcl_GetEnsembleFlags\fR and \fBTcl_SetEnsembleFlags\fR respectively. The result of both of those -functions is a Tcl result code (TCL_OK, or TCL_ERROR if the token does -not refer to an ensemble). +functions is a Tcl result code (\fBTCL_OK\fR, or \fBTCL_ERROR\fR if +the token does not refer to an ensemble). .TP \fBmapping dictionary\fR (read-write) +. A dictionary containing a mapping from subcommand names to lists of words to use as a command prefix (replacing the first two words of the command which are the ensemble command itself and the subcommand @@ -144,24 +155,41 @@ the same unqualified name in the ensemble's bound namespace. Defaults to NULL. May be read and written using \fBTcl_GetEnsembleMappingDict\fR and \fBTcl_SetEnsembleMappingDict\fR respectively. The result of both of those functions is a Tcl result -code (TCL_OK, or TCL_ERROR if the token does not refer to an +code (\fBTCL_OK\fR, or \fBTCL_ERROR\fR if the token does not refer to an ensemble) and the dictionary obtained from \fBTcl_GetEnsembleMappingDict\fR should always be treated as immutable even if it is unshared. .TP +\fBformal pre-subcommand parameter list\fR (read-write) +.VS 8.6 +A list of formal parameter names (the names only being used when generating +error messages) that come at invocation of the ensemble between the name of +the ensemble and the subcommand argument. NULL (the default) is equivalent to +the empty list. May be read and written using +\fBTcl_GetEnsembleParameterList\fR and \fBTcl_SetEnsembleParameterList\fR +respectively. The result of both of those functions is a Tcl result code +(\fBTCL_OK\fR, or \fBTCL_ERROR\fR if the token does not refer to an +ensemble) and the +dictionary obtained from \fBTcl_GetEnsembleParameterList\fR should always be +treated as immutable even if it is unshared. +.VE 8.6 +.TP \fBsubcommand list\fR (read-write) +. A list of all the subcommand names for the ensemble, or NULL if this is to be derived from either the keys of the mapping dictionary (see above) or (if that is also NULL) from the set of commands exported by the bound namespace. May be read and written using \fBTcl_GetEnsembleSubcommandList\fR and \fBTcl_SetEnsembleSubcommandList\fR respectively. The result of both -of those functions is a Tcl result code (TCL_OK, or TCL_ERROR if the +of those functions is a Tcl result code (\fBTCL_OK\fR, or +\fBTCL_ERROR\fR if the token does not refer to an ensemble) and the list obtained from \fBTcl_GetEnsembleSubcommandList\fR should always be treated as immutable even if it is unshared. .TP \fBunknown subcommand handler command prefix\fR (read-write) +. A list of words to prepend on the front of any subcommand when the subcommand is unknown to the ensemble (according to the current prefix handling rule); see the \fBnamespace ensemble\fR command for more @@ -169,18 +197,21 @@ details. If NULL, the default behavior \- generate a suitable error message \- will be used when an unknown subcommand is encountered. May be read and written using \fBTcl_GetEnsembleUnknownHandler\fR and \fBTcl_SetEnsembleUnknownHandler\fR respectively. The result of both -functions is a Tcl result code (TCL_OK, or TCL_ERROR if the token does +functions is a Tcl result code (\fBTCL_OK\fR, or \fBTCL_ERROR\fR if +the token does not refer to an ensemble) and the list obtained from \fBTcl_GetEnsembleUnknownHandler\fR should always be treated as immutable even if it is unshared. .TP \fBbound namespace\fR (read-only) +. The namespace to which the ensemble is bound; when the namespace is deleted, so too will the ensemble, and this namespace is also the namespace whose list of exported commands is used if both the mapping dictionary and the subcommand list properties are NULL. May be read using \fBTcl_GetEnsembleNamespace\fR which returns a Tcl result code -(TCL_OK, or TCL_ERROR if the token does not refer to an ensemble). - +(\fBTCL_OK\fR, or \fBTCL_ERROR\fR if the token does not refer to an ensemble). .SH "SEE ALSO" namespace(n), Tcl_DeleteCommandFromToken(3) +.SH KEYWORDS +command, ensemble @@ -159,10 +159,12 @@ instead of taking a variable number of arguments it takes an argument list. Like \fBTcl_VarEval\fR, \fBTcl_VarEvalVA\fR is deprecated. .SH "FLAG BITS" +.PP Any ORed combination of the following values may be used for the \fIflags\fR argument to procedures such as \fBTcl_EvalObjEx\fR: .TP 23 \fBTCL_EVAL_DIRECT\fR +. This flag is only used by \fBTcl_EvalObjEx\fR; it is ignored by other procedures. If this flag bit is set, the script is not compiled to bytecodes; instead it is executed directly @@ -173,10 +175,11 @@ bytecodes will not be reused in a future execution. In this case, it is faster to execute the script directly. .TP 23 \fBTCL_EVAL_GLOBAL\fR +. If this flag is set, the script is processed at global level. This means that it is evaluated in the global namespace and its variable context consists of global variables only (it ignores any Tcl -procedures at are active). +procedures that are active). .SH "MISCELLANEOUS DETAILS" .PP @@ -29,10 +29,8 @@ Tcl_Exit, Tcl_Finalize, Tcl_CreateExitHandler, Tcl_DeleteExitHandler, Tcl_ExitTh .sp \fBTcl_DeleteThreadExitHandler\fR(\fIproc, clientData\fR) .sp -.VS 8.5 Tcl_ExitProc * \fBTcl_SetExitProc\fR(\fIproc\fR) -.VE 8.5 .SH ARGUMENTS .AS Tcl_ExitProc clientData .AP int status in @@ -64,24 +62,18 @@ otherwise causes the application to terminate without calling \fBTcl_Exit\fR, the exit handlers will not be run. \fBTcl_Exit\fR internally invokes the \fBexit\fR system call, thus it never returns control to its caller. -.VS 8.5 If an application exit handler has been installed (see \fBTcl_SetExitProc\fR), that handler is invoked with an argument consisting of the exit status (cast to ClientData); the application exit handler should not return control to Tcl. -.VE 8.5 .PP \fBTcl_Finalize\fR is similar to \fBTcl_Exit\fR except that it does not exit from the current process. It is useful for cleaning up when a process is finished using \fBTcl\fR but wishes to continue executing, and when \fBTcl\fR is used in a dynamically loaded extension that is about to be unloaded. -On some systems \fBTcl\fR is automatically notified when it is being -unloaded, and it calls \fBTcl_Finalize\fR internally; on these systems it -not necessary for the caller to explicitly call \fBTcl_Finalize\fR. -However, to ensure portability, your code should always invoke -\fBTcl_Finalize\fR when \fBTcl\fR is being unloaded, to ensure that the -code will work on all platforms. \fBTcl_Finalize\fR can be safely called +Your code should always invoke \fBTcl_Finalize\fR when \fBTcl\fR is being +unloaded, to ensure proper cleanup. \fBTcl_Finalize\fR can be safely called more than once. .PP \fBTcl_ExitThread\fR is used to terminate the current thread and invoke @@ -98,9 +90,12 @@ by \fBTcl_FinalizeThread\fR and \fBTcl_ExitThread\fR. This provides a hook for cleanup operations such as flushing buffers and freeing global memory. \fIProc\fR should match the type \fBTcl_ExitProc\fR: +.PP .CS -typedef void Tcl_ExitProc(ClientData \fIclientData\fR); +typedef void \fBTcl_ExitProc\fR( + ClientData \fIclientData\fR); .CE +.PP The \fIclientData\fR parameter to \fIproc\fR is a copy of the \fIclientData\fR argument given to \fBTcl_CreateExitHandler\fR or \fBTcl_CreateThreadExitHandler\fR when @@ -116,7 +111,6 @@ indicated by \fIproc\fR and \fIclientData\fR so that no call to \fIproc\fR will be made. If no such handler exists then \fBTcl_DeleteExitHandler\fR or \fBTcl_DeleteThreadExitHandler\fR does nothing. .PP -.PP \fBTcl_Finalize\fR and \fBTcl_Exit\fR execute all registered exit handlers, in reverse order from the order in which they were registered. This matches the natural order in which extensions are loaded and unloaded; @@ -132,7 +126,6 @@ the process-wide exit handlers. This is because thread finalization shuts down the I/O channel system, so any attempt at I/O by the global exit handlers will vanish into the bitbucket. .PP -.VS 8.5 \fBTcl_SetExitProc\fR installs an application exit handler, returning the previously-installed application exit handler or NULL if no application handler was installed. If an application exit handler is @@ -141,7 +134,7 @@ finalization of Tcl's subsystems via \fBTcl_Finalize\fR at an appropriate time. The argument passed to \fIproc\fR when it is invoked will be the exit status code (as passed to \fBTcl_Exit\fR) cast to a ClientData value. -.VE 8.5 - +.SH "SEE ALSO" +exit(n) .SH KEYWORDS -callback, cleanup, dynamic loading, end application, exit, unloading, thread +abort, callback, cleanup, dynamic loading, end application, exit, unloading, thread diff --git a/doc/FileSystem.3 b/doc/FileSystem.3 index 32407d8..e3870c3 100644 --- a/doc/FileSystem.3 +++ b/doc/FileSystem.3 @@ -1,5 +1,6 @@ '\" '\" Copyright (c) 2001 Vincent Darley +'\" Copyright (c) 2008-2010 Donal K. Fellows '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. @@ -8,7 +9,7 @@ .TH Filesystem 3 8.4 Tcl "Tcl Library Procedures" .BS .SH NAME -Tcl_FSRegister, Tcl_FSUnregister, Tcl_FSData, Tcl_FSMountsChanged, Tcl_FSGetFileSystemForPath, Tcl_FSGetPathType, Tcl_FSCopyFile, Tcl_FSCopyDirectory, Tcl_FSCreateDirectory, Tcl_FSDeleteFile, Tcl_FSRemoveDirectory, Tcl_FSRenameFile, Tcl_FSListVolumes, Tcl_FSEvalFile, Tcl_FSEvalFileEx, Tcl_FSLoadFile, Tcl_FSMatchInDirectory, Tcl_FSLink, Tcl_FSLstat, Tcl_FSUtime, Tcl_FSFileAttrsGet, Tcl_FSFileAttrsSet, Tcl_FSFileAttrStrings, Tcl_FSStat, Tcl_FSAccess, Tcl_FSOpenFileChannel, Tcl_FSGetCwd, Tcl_FSChdir, Tcl_FSPathSeparator, Tcl_FSJoinPath, Tcl_FSSplitPath, Tcl_FSEqualPaths, Tcl_FSGetNormalizedPath, Tcl_FSJoinToPath, Tcl_FSConvertToPathType, Tcl_FSGetInternalRep, Tcl_FSGetTranslatedPath, Tcl_FSGetTranslatedStringPath, Tcl_FSNewNativePath, Tcl_FSGetNativePath, Tcl_FSFileSystemInfo, Tcl_AllocStatBuf \- procedures to interact with any filesystem +Tcl_FSRegister, Tcl_FSUnregister, Tcl_FSData, Tcl_FSMountsChanged, Tcl_FSGetFileSystemForPath, Tcl_FSGetPathType, Tcl_FSCopyFile, Tcl_FSCopyDirectory, Tcl_FSCreateDirectory, Tcl_FSDeleteFile, Tcl_FSRemoveDirectory, Tcl_FSRenameFile, Tcl_FSListVolumes, Tcl_FSEvalFile, Tcl_FSEvalFileEx, Tcl_FSLoadFile, Tcl_FSUnloadFile, Tcl_FSMatchInDirectory, Tcl_FSLink, Tcl_FSLstat, Tcl_FSUtime, Tcl_FSFileAttrsGet, Tcl_FSFileAttrsSet, Tcl_FSFileAttrStrings, Tcl_FSStat, Tcl_FSAccess, Tcl_FSOpenFileChannel, Tcl_FSGetCwd, Tcl_FSChdir, Tcl_FSPathSeparator, Tcl_FSJoinPath, Tcl_FSSplitPath, Tcl_FSEqualPaths, Tcl_FSGetNormalizedPath, Tcl_FSJoinToPath, Tcl_FSConvertToPathType, Tcl_FSGetInternalRep, Tcl_FSGetTranslatedPath, Tcl_FSGetTranslatedStringPath, Tcl_FSNewNativePath, Tcl_FSGetNativePath, Tcl_FSFileSystemInfo, Tcl_GetAccessTimeFromStat, Tcl_GetBlockSizeFromStat, Tcl_GetBlocksFromStat, Tcl_GetChangeTimeFromStat, Tcl_GetDeviceTypeFromStat, Tcl_GetFSDeviceFromStat, Tcl_GetFSInodeFromStat, Tcl_GetGroupIdFromStat, Tcl_GetLinkCountFromStat, Tcl_GetModeFromStat, Tcl_GetModificationTimeFromStat, Tcl_GetSizeFromStat, Tcl_GetUserIdFromStat, Tcl_AllocStatBuf \- procedures to interact with any filesystem .SH SYNOPSIS .nf \fB#include <tcl.h>\fR @@ -25,7 +26,7 @@ ClientData void \fBTcl_FSMountsChanged\fR(\fIfsPtr\fR) .sp -Tcl_Filesystem* +const Tcl_Filesystem * \fBTcl_FSGetFileSystemForPath\fR(\fIpathPtr\fR) .sp Tcl_PathType @@ -49,25 +50,28 @@ int int \fBTcl_FSRenameFile\fR(\fIsrcPathPtr, destPathPtr\fR) .sp -Tcl_Obj* +Tcl_Obj * \fBTcl_FSListVolumes\fR(\fIvoid\fR) .sp -.VS 8.5 int \fBTcl_FSEvalFileEx\fR(\fIinterp, pathPtr, encodingName\fR) -.VE 8.5 .sp int \fBTcl_FSEvalFile\fR(\fIinterp, pathPtr\fR) .sp int \fBTcl_FSLoadFile\fR(\fIinterp, pathPtr, sym1, sym2, proc1Ptr, proc2Ptr, - handlePtr, unloadProcPtr\fR) + loadHandlePtr, unloadProcPtr\fR) +.sp +.VS 8.6 +int +\fBTcl_FSUnloadFile\fR(\fIinterp, loadHandle\fR) +.VE 8.6 .sp int \fBTcl_FSMatchInDirectory\fR(\fIinterp, resultPtr, pathPtr, pattern, types\fR) .sp -Tcl_Obj* +Tcl_Obj * \fBTcl_FSLink\fR(\fIlinkNamePtr, toPtr, linkAction\fR) .sp int @@ -82,7 +86,7 @@ int int \fBTcl_FSFileAttrsSet\fR(\fIinterp, int index, pathPtr, Tcl_Obj *objPtr\fR) .sp -const char** +const char ** \fBTcl_FSFileAttrStrings\fR(\fIpathPtr, objPtrRef\fR) .sp int @@ -94,28 +98,28 @@ int Tcl_Channel \fBTcl_FSOpenFileChannel\fR(\fIinterp, pathPtr, modeString, permissions\fR) .sp -Tcl_Obj* +Tcl_Obj * \fBTcl_FSGetCwd\fR(\fIinterp\fR) .sp int \fBTcl_FSChdir\fR(\fIpathPtr\fR) .sp -Tcl_Obj* +Tcl_Obj * \fBTcl_FSPathSeparator\fR(\fIpathPtr\fR) .sp -Tcl_Obj* +Tcl_Obj * \fBTcl_FSJoinPath\fR(\fIlistObj, elements\fR) .sp -Tcl_Obj* +Tcl_Obj * \fBTcl_FSSplitPath\fR(\fIpathPtr, lenPtr\fR) .sp int \fBTcl_FSEqualPaths\fR(\fIfirstPtr, secondPtr\fR) .sp -Tcl_Obj* +Tcl_Obj * \fBTcl_FSGetNormalizedPath\fR(\fIinterp, pathPtr\fR) .sp -Tcl_Obj* +Tcl_Obj * \fBTcl_FSJoinToPath\fR(\fIbasePtr, objc, objv\fR) .sp int @@ -130,25 +134,66 @@ Tcl_Obj * const char * \fBTcl_FSGetTranslatedStringPath\fR(\fIinterp, pathPtr\fR) .sp -Tcl_Obj* +Tcl_Obj * \fBTcl_FSNewNativePath\fR(\fIfsPtr, clientData\fR) .sp -const char * +const void * \fBTcl_FSGetNativePath\fR(\fIpathPtr\fR) .sp -Tcl_Obj* +Tcl_Obj * \fBTcl_FSFileSystemInfo\fR(\fIpathPtr\fR) .sp -Tcl_StatBuf* +Tcl_StatBuf * \fBTcl_AllocStatBuf\fR() +.sp +.VS 8.6 +Tcl_WideInt +\fBTcl_GetAccessTimeFromStat\fR(\fIstatPtr\fR) +.sp +unsigned +\fBTcl_GetBlockSizeFromStat\fR(\fIstatPtr\fR) +.sp +Tcl_WideUInt +\fBTcl_GetBlocksFromStat\fR(\fIstatPtr\fR) +.sp +Tcl_WideInt +\fBTcl_GetChangeTimeFromStat\fR(\fIstatPtr\fR) +.sp +int +\fBTcl_GetDeviceTypeFromStat\fR(\fIstatPtr\fR) +.sp +unsigned +\fBTcl_GetFSDeviceFromStat\fR(\fIstatPtr\fR) +.sp +unsigned +\fBTcl_GetFSInodeFromStat\fR(\fIstatPtr\fR) +.sp +int +\fBTcl_GetGroupIdFromStat\fR(\fIstatPtr\fR) +.sp +int +\fBTcl_GetLinkCountFromStat\fR(\fIstatPtr\fR) +.sp +unsigned +\fBTcl_GetModeFromStat\fR(\fIstatPtr\fR) +.sp +Tcl_WideInt +\fBTcl_GetModificationTimeFromStat\fR(\fIstatPtr\fR) +.sp +Tcl_WideUInt +\fBTcl_GetSizeFromStat\fR(\fIstatPtr\fR) +.sp +int +\fBTcl_GetUserIdFromStat\fR(\fIstatPtr\fR) +.VE 8.6 .SH ARGUMENTS -.AS Tcl_FSUnloadFileProc **unloadProcPtr out -.AP Tcl_Filesystem *fsPtr in +.AS Tcl_GlobTypeData **srcPathPtr out +.AP "const Tcl_Filesystem" *fsPtr in Points to a structure containing the addresses of procedures that can be called to perform the various filesystem operations. .AP Tcl_Obj *pathPtr in The path represented by this object is used for the operation in -question. If the object does not already have an internal \fBpath\fR +question. If the object does not already have an internal \fBpath\fR representation, it will be converted to have one. .AP Tcl_Obj *srcPathPtr in As for \fIpathPtr\fR, but used for the source file for a copy or @@ -163,23 +208,23 @@ file identified by \fIpathPtr\fR and to be evaluated. Only files or directories matching this pattern will be returned. .AP Tcl_GlobTypeData *types in Only files or directories matching the type descriptions contained in -this structure will be returned. This parameter may be NULL. +this structure will be returned. This parameter may be NULL. .AP Tcl_Interp *interp in Interpreter to use either for results, evaluation, or reporting error messages. .AP ClientData clientData in The native description of the path object to create. .AP Tcl_Obj *firstPtr in -The first of two path objects to compare. The object may be converted +The first of two path objects to compare. The object may be converted to \fBpath\fR type. .AP Tcl_Obj *secondPtr in -The second of two path objects to compare. The object may be converted +The second of two path objects to compare. The object may be converted to \fBpath\fR type. .AP Tcl_Obj *listObj in The list of path elements to operate on with a \fBjoin\fR operation. .AP int elements in If non-negative, the number of elements in the \fIlistObj\fR which should -be joined together. If negative, then all elements are joined. +be joined together. If negative, then all elements are joined. .AP Tcl_Obj **errorPtr out In the case of an error, filled with an object containing the name of the file which caused an error in the various copy/rename operations. @@ -190,9 +235,9 @@ Pre-allocated object in which to store (using \fBTcl_ListObjAppendElement\fR) the list of files or directories which are successfully matched. .AP int mode in -Mask consisting of one or more of R_OK, W_OK, X_OK and F_OK. R_OK, +Mask consisting of one or more of R_OK, W_OK, X_OK and F_OK. R_OK, W_OK and X_OK request checking whether the file exists and has read, -write and execute permissions, respectively. F_OK just requests +write and execute permissions, respectively. F_OK just requests checking for the existence of the file. .AP Tcl_StatBuf *statPtr out The structure that contains the result of a stat or lstat operation. @@ -207,23 +252,25 @@ Filled with the safe-init function for this code. .AP ClientData *clientDataPtr out Filled with the clientData value to pass to this code's unload function when it is called. -.AP Tcl_LoadHandle *handlePtr out +.AP Tcl_LoadHandle *loadHandlePtr out Filled with an abstract token representing the loaded file. .AP Tcl_FSUnloadFileProc **unloadProcPtr out Filled with the function to use to unload this piece of code. +.AP Tcl_LoadHandle loadHandle in +Handle to the loaded library to be unloaded. .AP utimbuf *tval in The access and modification times in this structure are read and used to set those values for a given file. .AP "const char" *modeString in -Specifies how the file is to be accessed. May have any of the values +Specifies how the file is to be accessed. May have any of the values allowed for the \fImode\fR argument to the Tcl \fBopen\fR command. .AP int permissions in -POSIX-style permission flags such as 0644. If a new file is created, these +POSIX-style permission flags such as 0644. If a new file is created, these permissions will be set on the created file. .AP int *lenPtr out If non-NULL, filled with the number of elements in the split path. .AP Tcl_Obj *basePtr in -The base path on to which to join the given elements. May be NULL. +The base path on to which to join the given elements. May be NULL. .AP int objc in The number of elements in \fIobjv\fR. .AP "Tcl_Obj *const" objv[] in @@ -240,31 +287,30 @@ are \fBTCL_CREATE_SYMBOLIC_LINK\fR and \fBTCL_CREATE_HARD_LINK\fR. When both flags are set and the underlying filesystem can do either, symbolic links are preferred. .BE - .SH DESCRIPTION .PP There are several reasons for calling the \fBTcl_FS\fR API functions -(e.g. \fBTcl_FSAccess\fR and \fBTcl_FSStat\fR) +(e.g.\ \fBTcl_FSAccess\fR and \fBTcl_FSStat\fR) rather than calling system level functions like \fBaccess\fR and -\fBstat\fR directly. First, they will work cross-platform, so an +\fBstat\fR directly. First, they will work cross-platform, so an extension which calls them should work unmodified on Unix and -Windows. Second, the Windows implementation of some of these functions -fixes some bugs in the system level calls. Third, these function calls +Windows. Second, the Windows implementation of some of these functions +fixes some bugs in the system level calls. Third, these function calls deal with any .QW "Utf to platform-native" path conversions which may be required (and may cache the results of such conversions for greater -efficiency on subsequent calls). Fourth, and perhaps most importantly, +efficiency on subsequent calls). Fourth, and perhaps most importantly, all of these functions are .QW "virtual filesystem aware" . Any virtual filesystem (VFS for short) which has been registered (through \fBTcl_FSRegister\fR) may reroute file access to alternative -media or access methods. This means that all of these functions (and +media or access methods. This means that all of these functions (and therefore the corresponding \fBfile\fR, \fBglob\fR, \fBpwd\fR, \fBcd\fR, -\fBopen\fR, etc. Tcl commands) may be operate on +\fBopen\fR, etc.\ Tcl commands) may be operate on .QW files which are not -native files in the native filesystem. This also means that any Tcl +native files in the native filesystem. This also means that any Tcl extension which accesses the filesystem (FS for short) through this API is automatically .QW "virtual filesystem aware" . @@ -275,10 +321,10 @@ APIs, for example), then Tcl cannot intercept such calls. If appropriate VFSes have been registered, the .QW files may, to give two -examples, be remote (e.g. situated on a remote ftp server) or archived -(e.g. lying inside a .zip archive). Such registered filesystems provide +examples, be remote (e.g.\ situated on a remote ftp server) or archived +(e.g.\ lying inside a .zip archive). Such registered filesystems provide a lookup table of functions to implement all or some of the functionality -listed here. Finally, the \fBTcl_FSStat\fR and \fBTcl_FSLstat\fR calls +listed here. Finally, the \fBTcl_FSStat\fR and \fBTcl_FSLstat\fR calls abstract away from what the .QW "struct stat" buffer is actually @@ -286,9 +332,9 @@ declared to be, allowing the same code to be used both on systems with and systems without support for files larger than 2GB in size. .PP The \fBTcl_FS\fR API is objectified and may cache internal -representations and other path-related strings (e.g. the current working -directory). One side-effect of this is that one must not pass in objects -with a reference count of zero to any of these functions. If such calls were +representations and other path-related strings (e.g.\ the current working +directory). One side-effect of this is that one must not pass in objects +with a reference count of zero to any of these functions. If such calls were handled, they might result in memory leaks (under some circumstances, the filesystem code may wish to retain a reference to the passed in object, and so one must not assume @@ -297,21 +343,23 @@ zero - it may have been incremented) or in a direct segmentation fault (or other memory access error) due to the object being freed part way through the complex object manipulation required to ensure that the path is fully normalized and -absolute for filesystem determination. The practical lesson to learn +absolute for filesystem determination. The practical lesson to learn from this is that +.PP .CS Tcl_Obj *path = Tcl_NewStringObj(...); Tcl_FS\fIWhatever\fR(path); Tcl_DecrRefCount(path); .CE +.PP is wrong, and may cause memory errors. The \fIpath\fR must have its reference count incremented before passing it in, or -decrementing it. For this reason, objects with a reference count of zero are +decrementing it. For this reason, objects with a reference count of zero are considered not to be valid filesystem paths and calling any Tcl_FS API function with such an object will result in no action being taken. .SS "FS API FUNCTIONS" \fBTcl_FSCopyFile\fR attempts to copy the file given by \fIsrcPathPtr\fR to the -path name given by \fIdestPathPtr\fR. If the two paths given lie in the same +path name given by \fIdestPathPtr\fR. If the two paths given lie in the same filesystem (according to \fBTcl_FSGetFileSystemForPath\fR) then that filesystem's .QW "copy file" @@ -323,7 +371,7 @@ POSIX error code (which signifies a .QW "cross-domain link" ). .PP \fBTcl_FSCopyDirectory\fR attempts to copy the directory given by \fIsrcPathPtr\fR to the -path name given by \fIdestPathPtr\fR. If the two paths given lie in the same +path name given by \fIdestPathPtr\fR. If the two paths given lie in the same filesystem (according to \fBTcl_FSGetFileSystemForPath\fR) then that filesystem's .QW "copy file" @@ -350,11 +398,11 @@ function. function. .PP \fBTcl_FSRenameFile\fR attempts to rename the file or directory given by -\fIsrcPathPtr\fR to the path name given by \fIdestPathPtr\fR. If the two paths +\fIsrcPathPtr\fR to the path name given by \fIdestPathPtr\fR. If the two paths given lie in the same filesystem (according to \fBTcl_FSGetFileSystemForPath\fR) then that filesystem's .QW "rename file" -function is called (if it is non-NULL). Otherwise the function returns -1 +function is called (if it is non-NULL). Otherwise the function returns -1 and sets the \fBerrno\fR global C variable to the .QW EXDEV POSIX error code (which signifies a @@ -362,14 +410,13 @@ POSIX error code (which signifies a .PP \fBTcl_FSListVolumes\fR calls each filesystem which has a non-NULL .QW "list volumes" -function and asks them to return their list of root volumes. It +function and asks them to return their list of root volumes. It accumulates the return values in a list which is returned to the caller (with a reference count of 0). .PP -.VS 8.5 \fBTcl_FSEvalFileEx\fR reads the file given by \fIpathPtr\fR using the encoding identified by \fIencodingName\fR and evaluates -its contents as a Tcl script. It returns the same information as +its contents as a Tcl script. It returns the same information as \fBTcl_EvalObjEx\fR. If \fIencodingName\fR is NULL, the system encoding is used for reading the file contents. @@ -389,71 +436,83 @@ which will be safely substituted by the Tcl interpreter into \fBTcl_FSEvalFile\fR is a simpler version of \fBTcl_FSEvalFileEx\fR that always uses the system encoding when reading the file. -.VE 8.5 .PP \fBTcl_FSLoadFile\fR dynamically loads a binary code file into memory and returns the addresses of two procedures within that file, if they are -defined. The appropriate function for the filesystem to which \fIpathPtr\fR -belongs will be called. If that filesystem does not implement this +defined. The appropriate function for the filesystem to which \fIpathPtr\fR +belongs will be called. If that filesystem does not implement this function (most virtual filesystems will not, because of OS limitations in dynamically loading binary code), Tcl will attempt to copy the file to a temporary directory and load that temporary file. +.VS 8.6 +\fBTcl_FSUnloadFile\fR reverses the operation, asking for the library +indicated by the \fIloadHandle\fR to be removed from the process. Note that, +unlike with the \fBunload\fR command, this does not give the library any +opportunity to clean up. +.VE 8.6 +.PP +Both the above functions return a standard Tcl completion code. If an error +occurs, an error message is left in the \fIinterp\fR's result. .PP -Returns a standard Tcl completion code. If an error occurs, an error -message is left in the \fIinterp\fR's result. +.VS 8.6 +The token provided via the variable indicated by \fIloadHandlePtr\fR may be +used with \fBTcl_FindSymbol\fR. +.VE 8.6 .PP \fBTcl_FSMatchInDirectory\fR is used by the globbing code to search a -directory for all files which match a given pattern. The appropriate +directory for all files which match a given pattern. The appropriate function for the filesystem to which \fIpathPtr\fR belongs will be called. .PP The return value is a standard Tcl result indicating whether an error -occurred in globbing. Error messages are placed in interp (unless +occurred in globbing. Error messages are placed in interp (unless interp is NULL, which is allowed), but good results are placed in the resultPtr given. .PP Note that the \fBglob\fR code implements recursive patterns internally, so this function will only ever be passed simple patterns, which can be -matched using the logic of \fBstring match\fR. To handle recursion, Tcl +matched using the logic of \fBstring match\fR. To handle recursion, Tcl will call this function frequently asking only for directories to be -returned. A special case of being called with a NULL pattern indicates +returned. A special case of being called with a NULL pattern indicates that the path needs to be checked only for the correct type. .PP \fBTcl_FSLink\fR replaces the library version of \fBreadlink\fR, and -extends it to support the creation of links. The appropriate function +extends it to support the creation of links. The appropriate function for the filesystem to which \fIlinkNamePtr\fR belongs will be called. .PP If the \fItoPtr\fR is NULL, a .QW "read link" -action is performed. The result +action is performed. The result is a Tcl_Obj specifying the contents of the symbolic link given by -\fIlinkNamePtr\fR, or NULL if the link could not be read. The result is owned +\fIlinkNamePtr\fR, or NULL if the link could not be read. The result is owned by the caller, which should call Tcl_DecrRefCount when the result is no -longer needed. If the \fItoPtr\fR is not NULL, Tcl should create a link -of one of the types passed in in the \fIlinkAction\fR flag. This flag is +longer needed. If the \fItoPtr\fR is not NULL, Tcl should create a link +of one of the types passed in in the \fIlinkAction\fR flag. This flag is an ORed combination of \fBTCL_CREATE_SYMBOLIC_LINK\fR and \fBTCL_CREATE_HARD_LINK\fR. -Where a choice exists (i.e. more than one flag is passed in), the Tcl -convention is to prefer symbolic links. When a link is successfully +Where a choice exists (i.e.\ more than one flag is passed in), the Tcl +convention is to prefer symbolic links. When a link is successfully created, the return value should be \fItoPtr\fR (which is therefore -already owned by the caller). If unsuccessful, NULL is returned. +already owned by the caller). If unsuccessful, NULL is returned. .PP -\fBTcl_FSLstat\fR fills the stat structure \fIstatPtr\fR with information -about the specified file. You do not need any access rights to the +\fBTcl_FSLstat\fR fills the \fITcl_StatBuf\fR structure \fIstatPtr\fR with +information about the specified file. You do not need any access rights to the file to get this information but you need search rights to all -directories named in the path leading to the file. The stat structure -includes info regarding device, inode (always 0 on Windows), +directories named in the path leading to the file. The \fITcl_StatBuf\fR +structure includes info regarding device, inode (always 0 on Windows), privilege mode, nlink (always 1 on Windows), user id (always 0 on Windows), group id (always 0 on Windows), rdev (same as device on Windows), size, last access time, last modification time, and last metadata change time. +See \fBPORTABLE STAT RESULT API\fR for a description of how to write +portable code to allocate and access the \fITcl_StatBuf\fR structure. .PP If \fIpath\fR exists, \fBTcl_FSLstat\fR returns 0 and the stat structure -is filled with data. Otherwise, -1 is returned, and no stat info is +is filled with data. Otherwise, -1 is returned, and no stat info is given. .PP \fBTcl_FSUtime\fR replaces the library version of utime. .PP This returns 0 on success and -1 on error (as per the \fButime\fR -documentation). If successful, the function +documentation). If successful, the function will update the .QW atime and @@ -461,7 +520,7 @@ and values of the file given. .PP \fBTcl_FSFileAttrsGet\fR implements read access for the hookable \fBfile -attributes\fR subcommand. The appropriate function for the filesystem to +attributes\fR subcommand. The appropriate function for the filesystem to which \fIpathPtr\fR belongs will be called. .PP If the result is \fBTCL_OK\fR, then an object was placed in @@ -469,43 +528,45 @@ If the result is \fBTCL_OK\fR, then an object was placed in will only be temporarily valid (unless \fBTcl_IncrRefCount\fR is called). .PP \fBTcl_FSFileAttrsSet\fR implements write access for the hookable \fBfile -attributes\fR subcommand. The appropriate function for the filesystem to +attributes\fR subcommand. The appropriate function for the filesystem to which \fIpathPtr\fR belongs will be called. .PP \fBTcl_FSFileAttrStrings\fR implements part of the hookable \fBfile -attributes\fR subcommand. The appropriate function for the filesystem +attributes\fR subcommand. The appropriate function for the filesystem to which \fIpathPtr\fR belongs will be called. .PP The called procedure may either return an array of strings, or may -instead return NULL and place a Tcl list into the given \fIobjPtrRef\fR. Tcl +instead return NULL and place a Tcl list into the given \fIobjPtrRef\fR. Tcl will take that list and first increment its reference count before using it. -On completion of that use, Tcl will decrement its reference count. Hence if +On completion of that use, Tcl will decrement its reference count. Hence if the list should be disposed of by Tcl when done, it should have a reference count of zero, and if the list should not be disposed of, the filesystem should ensure it retains a reference count to the object. .PP \fBTcl_FSAccess\fR checks whether the process would be allowed to read, write or test for existence of the file (or other filesystem object) -whose name is \fIpathname\fR. If \fIpathname\fR is a symbolic link on Unix, +whose name is \fIpathname\fR. If \fIpathname\fR is a symbolic link on Unix, then permissions of the file referred by this symbolic link are tested. .PP -On success (all requested permissions granted), zero is returned. On +On success (all requested permissions granted), zero is returned. On error (at least one bit in mode asked for a permission that is denied, or some other error occurred), -1 is returned. .PP -\fBTcl_FSStat\fR fills the stat structure \fIstatPtr\fR with information -about the specified file. You do not need any access rights to the +\fBTcl_FSStat\fR fills the \fITcl_StatBuf\fR structure \fIstatPtr\fR with +information about the specified file. You do not need any access rights to the file to get this information but you need search rights to all -directories named in the path leading to the file. The stat structure -includes info regarding device, inode (always 0 on Windows), +directories named in the path leading to the file. The \fITcl_StatBuf\fR +structure includes info regarding device, inode (always 0 on Windows), privilege mode, nlink (always 1 on Windows), user id (always 0 on Windows), group id (always 0 on Windows), rdev (same as device on Windows), size, last access time, last modification time, and last metadata change time. +See \fBPORTABLE STAT RESULT API\fR for a description of how to write +portable code to allocate and access the \fITcl_StatBuf\fR structure. .PP If \fIpath\fR exists, \fBTcl_FSStat\fR returns 0 and the stat structure -is filled with data. Otherwise, -1 is returned, and no stat info is +is filled with data. Otherwise, -1 is returned, and no stat info is given. .PP \fBTcl_FSOpenFileChannel\fR opens a file specified by \fIpathPtr\fR and @@ -522,48 +583,48 @@ leaves an error message in \fIinterp\fR's result after any error. .PP The newly created channel is not registered in the supplied interpreter; to register it, use \fBTcl_RegisterChannel\fR, described below. -If one of the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was +If one of the standard channels, \fBstdin\fR, \fBstdout\fR or \fBstderr\fR was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. .PP \fBTcl_FSGetCwd\fR replaces the library version of \fBgetcwd\fR. .PP -It returns the Tcl library's current working directory. This may be +It returns the Tcl library's current working directory. This may be different to the native platform's working directory, which happens when the current working directory is not in the native filesystem. .PP The result is a pointer to a Tcl_Obj specifying the current directory, -or NULL if the current directory could not be determined. If NULL is +or NULL if the current directory could not be determined. If NULL is returned, an error message is left in the \fIinterp\fR's result. .PP -The result already has its reference count incremented for the caller. When -it is no longer needed, that reference count should be decremented. This is +The result already has its reference count incremented for the caller. When +it is no longer needed, that reference count should be decremented. This is needed for thread-safety purposes, to allow multiple threads to access this and related functions, while ensuring the results are always valid. .PP -\fBTcl_FSChdir\fR replaces the library version of \fBchdir\fR. The path is -normalized and then passed to the filesystem which claims it. If that +\fBTcl_FSChdir\fR replaces the library version of \fBchdir\fR. The path is +normalized and then passed to the filesystem which claims it. If that filesystem does not implement this function, Tcl will fallback to a combination of \fBstat\fR and \fBaccess\fR to check whether the directory exists and has appropriate permissions. .PP -For results, see \fBchdir\fR documentation. If successful, we keep a +For results, see \fBchdir\fR documentation. If successful, we keep a record of the successful path in \fIcwdPathPtr\fR for subsequent calls to \fBTcl_FSGetCwd\fR. .PP \fBTcl_FSPathSeparator\fR returns the separator character to be used for -most specific element of the path specified by \fIpathPtr\fR (i.e. the last +most specific element of the path specified by \fIpathPtr\fR (i.e.\ the last part of the path). .PP The separator is returned as a Tcl_Obj containing a string of length -1. If the path is invalid, NULL is returned. +1. If the path is invalid, NULL is returned. .PP \fBTcl_FSJoinPath\fR takes the given Tcl_Obj, which must be a valid list (which is allowed to have a reference count of zero), and returns the path object given by considering the first \fIelements\fR elements as valid path segments (each path segment may be a complete path, a partial path or -just a single possible directory or file name). If any path segment is +just a single possible directory or file name). If any path segment is actually an absolute path, then all prior path segments are discarded. If \fIelements\fR is less than 0, we use the entire list. .PP @@ -573,8 +634,8 @@ reference count of the result before freeing the list. .PP The returned object, typically with a reference count of zero (but it could be shared -under some conditions), contains the joined path. The caller must -add a reference count to the object before using it. In particular, the +under some conditions), contains the joined path. The caller must +add a reference count to the object before using it. In particular, the returned object could be an element of the given list, so freeing the list might free the object prematurely if no reference count has been taken. If the number of elements is zero, then the returned object will be @@ -583,14 +644,14 @@ an empty-string Tcl_Obj. \fBTcl_FSSplitPath\fR takes the given Tcl_Obj, which should be a valid path, and returns a Tcl list object containing each segment of that path as an element. -It returns a list object with a reference count of zero. If the +It returns a list object with a reference count of zero. If the passed in \fIlenPtr\fR is non-NULL, the variable it points to will be updated to contain the number of elements in the returned list. .PP \fBTcl_FSEqualPaths\fR tests whether the two paths given represent the same filesystem object .PP -It returns 1 if the paths are equal, and 0 if they are different. If +It returns 1 if the paths are equal, and 0 if they are different. If either path is NULL, 0 is always returned. .PP \fBTcl_FSGetNormalizedPath\fR this important function attempts to extract @@ -602,7 +663,7 @@ was invalid or could otherwise not be successfully converted. Extraction of absolute, normalized paths is very efficient (because the filesystem operates on these representations internally), although the result when the filesystem contains numerous symbolic links may not be -the most user-friendly version of a path. The return value is owned by +the most user-friendly version of a path. The return value is owned by Tcl and has a lifetime equivalent to that of the \fIpathPtr\fR passed in (unless that is a relative path, in which case the normalized path object may be freed any time the cwd changes) - the caller can of @@ -613,8 +674,8 @@ valid path or NULL, and joins onto it the array of paths segments given. .PP Returns object, typically with refCount of zero (but it could be shared -under some conditions), containing the joined path. The caller must -add a refCount to the object before using it. If any of the objects +under some conditions), containing the joined path. The caller must +add a refCount to the object before using it. If any of the objects passed into this function (pathPtr or path elements) have a refCount of zero, they will be freed when this function returns. .PP @@ -627,49 +688,49 @@ The filename may begin with .QW ~<user> (to indicate any user's home directory). .PP -If the conversion succeeds (i.e. the object is a valid path in one of -the current filesystems), then \fBTCL_OK\fR is returned. Otherwise +If the conversion succeeds (i.e.\ the object is a valid path in one of +the current filesystems), then \fBTCL_OK\fR is returned. Otherwise \fBTCL_ERROR\fR is returned, and an error message may be left in the interpreter. .PP \fBTcl_FSGetInternalRep\fR extracts the internal representation of a given -path object, in the given filesystem. If the path object belongs to a +path object, in the given filesystem. If the path object belongs to a different filesystem, we return NULL. If the internal representation is currently NULL, we attempt to generate it, by calling the filesystem's \fBTcl_FSCreateInternalRepProc\fR. .PP -Returns NULL or a valid internal path representation. This internal +Returns NULL or a valid internal path representation. This internal representation is cached, so that repeated calls to this function will not require additional conversions. .PP \fBTcl_FSGetTranslatedPath\fR attempts to extract the translated path from the given Tcl_Obj. .PP -If the translation succeeds (i.e. the object is a valid path), then it is -returned. Otherwise NULL will be returned, and an error message may be -left in the interpreter. A +If the translation succeeds (i.e.\ the object is a valid path), then it is +returned. Otherwise NULL will be returned, and an error message may be +left in the interpreter. A .QW translated path is one which contains no .QW ~ or .QW ~user sequences (these have been expanded to their current -representation in the filesystem). The object returned is owned by the +representation in the filesystem). The object returned is owned by the caller, which must store it or call Tcl_DecrRefCount to ensure memory is -freed. This function is of little practical use, and -\fBTcl_FSGetNormalizedPath\fR or \fBTcl_GetNativePath\fR are usually +freed. This function is of little practical use, and +\fBTcl_FSGetNormalizedPath\fR or \fBTcl_FSGetNativePath\fR are usually better functions to use for most purposes. .PP \fBTcl_FSGetTranslatedStringPath\fR does the same as \fBTcl_FSGetTranslatedPath\fR, but returns a character string or NULL. The string returned is dynamically allocated and owned by the caller, -which must store it or call \fBckfree\fR to ensure it is freed. Again, -\fBTcl_FSGetNormalizedPath\fR or \fBTcl_GetNativePath\fR are usually +which must store it or call \fBckfree\fR to ensure it is freed. Again, +\fBTcl_FSGetNormalizedPath\fR or \fBTcl_FSGetNativePath\fR are usually better functions to use for most purposes. .PP \fBTcl_FSNewNativePath\fR performs something like the reverse of the -usual obj->path->nativerep conversions. If some code retrieves a path -in native form (from, e.g. \fBreadlink\fR or a native dialog), and that path +usual obj->path->nativerep conversions. If some code retrieves a path +in native form (from, e.g.\ \fBreadlink\fR or a native dialog), and that path is to be used at the Tcl level, then calling this function is an efficient way of creating the appropriate path object type. .PP @@ -680,29 +741,28 @@ a UTF-8 string representation if that is required by some Tcl code. .PP \fBTcl_FSGetNativePath\fR is for use by the Win/Unix native filesystems, so that they can easily retrieve the native (char* or -TCHAR*) representation of a path. This function is a convenience -wrapper around \fBTcl_FSGetInternalRep\fR, and assumes the native -representation is string-based. It may be desirable in the future to -have non-string-based native representations (for example, on MacOSX, a -representation using a fileSpec of FSRef structure would probably be -more efficient). On Windows a full Unicode representation would allow -for paths of unlimited length. Currently the representation is simply a -character string which may contain either the relative path or a -complete, absolute normalized path in the native encoding (complex +TCHAR*) representation of a path. This function is a convenience +wrapper around \fBTcl_FSGetInternalRep\fR. It may be desirable in the +future to have non-string-based native representations (for example, +on MacOSX, a representation using a fileSpec of FSRef structure would +probably be more efficient). On Windows a full Unicode representation +would allow for paths of unlimited length. Currently the representation +is simply a character string which may contain either the relative path +or a complete, absolute normalized path in the native encoding (complex conditions dictate which of these will be provided, so neither can be -relied upon, unless the path is known to be absolute). If you need a +relied upon, unless the path is known to be absolute). If you need a native path which must be absolute, then you should ask for the native -version of a normalized path. If for some reason a non-absolute, +version of a normalized path. If for some reason a non-absolute, non-normalized version of the path is needed, that must be constructed -separately (e.g. using \fBTcl_FSGetTranslatedPath\fR). +separately (e.g.\ using \fBTcl_FSGetTranslatedPath\fR). .PP The native representation is cached so that repeated calls to this -function will not require additional conversions. The return value is +function will not require additional conversions. The return value is owned by Tcl and has a lifetime equivalent to that of the \fIpathPtr\fR passed in (unless that is a relative path, in which case the native representation may be freed any time the cwd changes). .PP -\fBTcl_FSFileSystemInfo\fR returns a list of two elements. The first +\fBTcl_FSFileSystemInfo\fR returns a list of two elements. The first element is the name of the filesystem (e.g. .QW native , .QW vfs , @@ -710,14 +770,14 @@ element is the name of the filesystem (e.g. or .QW prowrap , perhaps), and the second is the particular type of the -given path within that filesystem (which is filesystem dependent). The +given path within that filesystem (which is filesystem dependent). The second element may be empty if the filesystem does not provide a further categorization of files. .PP A valid list object is returned, unless the path object is not recognized, when NULL will be returned. .PP -\fBTcl_FSGetFileSystemForPath\fR returns the a pointer to the +\fBTcl_FSGetFileSystemForPath\fR returns a pointer to the \fBTcl_Filesystem\fR which accepts this path as valid. .PP If no filesystem will accept the path, NULL is returned. @@ -728,12 +788,38 @@ absolute. .PP It returns one of \fBTCL_PATH_ABSOLUTE\fR, \fBTCL_PATH_RELATIVE\fR, or \fBTCL_PATH_VOLUME_RELATIVE\fR -.PP -\fBTcl_AllocStatBuf\fR allocates a \fITcl_StatBuf\fR on the system -heap (which may be deallocated by being passed to \fBckfree\fR.) This -allows extensions to invoke \fBTcl_FSStat\fR and \fBTcl_FSLStat\fR -without being dependent on the size of the buffer. That in turn -depends on the flags used to build Tcl. +.SS "PORTABLE STAT RESULT API" +.PP +\fBTcl_AllocStatBuf\fR allocates a \fITcl_StatBuf\fR on the system heap (which +may be deallocated by being passed to \fBckfree\fR). This allows extensions to +invoke \fBTcl_FSStat\fR and \fBTcl_FSLstat\fR without being dependent on the +size of the buffer. That in turn depends on the flags used to build Tcl. +.PP +.VS 8.6 +The portable fields of a \fITcl_StatBuf\fR may be read using the following +functions, each of which returns the value of the corresponding field listed +in the table below. Note that on some platforms there may be other fields in +the \fITcl_StatBuf\fR as it is an alias for a suitable system structure, but +only the portable ones are made available here. See your system documentation +for a full description of these fields. +.DS +.ta \w'\fBTcl_GetModificationTimeFromStat\fR\0\0\0\0'u +\fIAccess Function\fR \fIField\fR + \fBTcl_GetFSDeviceFromStat\fR st_dev + \fBTcl_GetFSInodeFromStat\fR st_ino + \fBTcl_GetModeFromStat\fR st_mode + \fBTcl_GetLinkCountFromStat\fR st_nlink + \fBTcl_GetUserIdFromStat\fR st_uid + \fBTcl_GetGroupIdFromStat\fR st_gid + \fBTcl_GetDeviceTypeFromStat\fR st_rdev + \fBTcl_GetAccessTimeFromStat\fR st_atime + \fBTcl_GetModificationTimeFromStat\fR st_mtime + \fBTcl_GetChangeTimeFromStat\fR st_ctime + \fBTcl_GetSizeFromStat\fR st_size + \fBTcl_GetBlocksFromStat\fR st_blocks + \fBTcl_GetBlockSizeFromStat\fR st_blksize +.DE +.VE 8.6 .SH "THE VIRTUAL FILESYSTEM API" .PP A filesystem provides a \fBTcl_Filesystem\fR structure that contains @@ -745,18 +831,18 @@ The \fBTcl_Filesystem\fR structures are manipulated using the following methods. .PP \fBTcl_FSRegister\fR takes a pointer to a filesystem structure and an -optional piece of data to associated with that filesystem. On calling +optional piece of data to associated with that filesystem. On calling this function, Tcl will attach the filesystem to the list of known -filesystems, and it will become fully functional immediately. Tcl does +filesystems, and it will become fully functional immediately. Tcl does not check if the same filesystem is registered multiple times (and in -general that is not a good thing to do). \fBTCL_OK\fR will be returned. +general that is not a good thing to do). \fBTCL_OK\fR will be returned. .PP \fBTcl_FSUnregister\fR removes the given filesystem structure from -the list of known filesystems, if it is known, and returns \fBTCL_OK\fR. If +the list of known filesystems, if it is known, and returns \fBTCL_OK\fR. If the filesystem is not currently registered, \fBTCL_ERROR\fR is returned. .PP \fBTcl_FSData\fR will return the ClientData associated with the given -filesystem, if that filesystem is registered. Otherwise it will +filesystem, if that filesystem is registered. Otherwise it will return NULL. .PP \fBTcl_FSMountsChanged\fR is used to inform the Tcl's core that @@ -766,6 +852,7 @@ longer be correct. .SS "THE TCL_FILESYSTEM STRUCTURE" .PP The \fBTcl_Filesystem\fR structure contains the following fields: +.PP .CS typedef struct Tcl_Filesystem { const char *\fItypeName\fR; @@ -799,7 +886,7 @@ typedef struct Tcl_Filesystem { Tcl_FSLoadFileProc *\fIloadFileProc\fR; Tcl_FSGetCwdProc *\fIgetCwdProc\fR; Tcl_FSChdirProc *\fIchdirProc\fR; -} Tcl_Filesystem; +} \fBTcl_Filesystem\fR; .CE .PP Except for the first three fields in this structure which contain @@ -813,7 +900,7 @@ implemented), operational functions (which must be implemented if a complete filesystem is provided), and efficiency functions (which need only be implemented if they can be done so efficiently, or if they have side-effects which are required by the filesystem; Tcl has less -efficient emulations it can fall back on). It is important to note +efficient emulations it can fall back on). It is important to note that, in the current version of Tcl, most of these fallbacks are only used to handle commands initiated in Tcl, not in C. What this means is, that if a \fBfile rename\fR command is issued in Tcl, and the relevant @@ -821,14 +908,14 @@ filesystem(s) do not implement their \fITcl_FSRenameFileProc\fR, Tcl's core will instead fallback on a combination of other filesystem functions (it will use \fITcl_FSCopyFileProc\fR followed by \fITcl_FSDeleteFileProc\fR, and if \fITcl_FSCopyFileProc\fR is not -implemented there is a further fallback). However, if a +implemented there is a further fallback). However, if a \fITcl_FSRenameFileProc\fR command is issued at the C level, no such -fallbacks occur. This is true except for the last four entries in the +fallbacks occur. This is true except for the last four entries in the filesystem table (\fBlstat\fR, \fBload\fR, \fBgetcwd\fR and \fBchdir\fR) for which fallbacks do in fact occur at the C level. .PP Any functions which take path names in Tcl_Obj form take -those names in UTF\-8 form. The filesystem infrastructure API is +those names in UTF\-8 form. The filesystem infrastructure API is designed to support efficient, cached conversion of these UTF\-8 paths to other native representations. .SS "EXAMPLE FILESYSTEM DEFINITION" @@ -836,6 +923,7 @@ to other native representations. Here is the filesystem lookup table used by the .QW vfs extension which allows filesystem actions to be implemented in Tcl. +.PP .CS static Tcl_Filesystem vfsFilesystem = { "tclvfs", @@ -915,96 +1003,96 @@ The \fIversion\fR field should be set to \fBTCL_FILESYSTEM_VERSION_1\fR. .PP The \fIpathInFilesystemProc\fR field contains the address of a function which is called to determine whether a given path object belongs to this -filesystem or not. Tcl will only call the rest of the filesystem +filesystem or not. Tcl will only call the rest of the filesystem functions with a path for which this function has returned \fBTCL_OK\fR. If the path does not belong, -1 should be returned (the behaviour of Tcl -for any other return value is not defined). If \fBTCL_OK\fR is returned, +for any other return value is not defined). If \fBTCL_OK\fR is returned, then the optional \fIclientDataPtr\fR output parameter can be used to return an internal (filesystem specific) representation of the path, which will be cached inside the path object, and may be retrieved -efficiently by the other filesystem functions. Tcl will simultaneously -cache the fact that this path belongs to this filesystem. Such caches +efficiently by the other filesystem functions. Tcl will simultaneously +cache the fact that this path belongs to this filesystem. Such caches are invalidated when filesystem structures are added or removed from Tcl's internal list of known filesystems. .PP .CS -typedef int Tcl_FSPathInFilesystemProc( +typedef int \fBTcl_FSPathInFilesystemProc\fR( Tcl_Obj *\fIpathPtr\fR, ClientData *\fIclientDataPtr\fR); .CE .SS DUPINTERNALREPPROC .PP This function makes a copy of a path's internal representation, and is -called when Tcl needs to duplicate a path object. If NULL, Tcl will +called when Tcl needs to duplicate a path object. If NULL, Tcl will simply not copy the internal representation, which may then need to be regenerated later. .PP .CS -typedef ClientData Tcl_FSDupInternalRepProc( +typedef ClientData \fBTcl_FSDupInternalRepProc\fR( ClientData \fIclientData\fR); .CE .SS FREEINTERNALREPPROC -Free the internal representation. This must be implemented if internal -representations need freeing (i.e. if some memory is allocated when an +Free the internal representation. This must be implemented if internal +representations need freeing (i.e.\ if some memory is allocated when an internal representation is generated), but may otherwise be NULL. .PP .CS -typedef void Tcl_FSFreeInternalRepProc( +typedef void \fBTcl_FSFreeInternalRepProc\fR( ClientData \fIclientData\fR); .CE .SS INTERNALTONORMALIZEDPROC .PP -Function to convert internal representation to a normalized path. Only +Function to convert internal representation to a normalized path. Only required if the filesystem creates pure path objects with no string/path -representation. The return value is a Tcl object whose string +representation. The return value is a Tcl object whose string representation is the normalized path. .PP .CS -typedef Tcl_Obj* Tcl_FSInternalToNormalizedProc( +typedef Tcl_Obj *\fBTcl_FSInternalToNormalizedProc\fR( ClientData \fIclientData\fR); .CE .SS CREATEINTERNALREPPROC .PP Function to take a path object, and calculate an internal representation for it, and store that native representation in the -object. May be NULL if paths have no internal representation, or if +object. May be NULL if paths have no internal representation, or if the \fITcl_FSPathInFilesystemProc\fR for this filesystem always immediately creates an internal representation for paths it accepts. .PP .CS -typedef ClientData Tcl_FSCreateInternalRepProc( +typedef ClientData \fBTcl_FSCreateInternalRepProc\fR( Tcl_Obj *\fIpathPtr\fR); .CE .SS NORMALIZEPATHPROC .PP -Function to normalize a path. Should be implemented for all +Function to normalize a path. Should be implemented for all filesystems which can have multiple string representations for the same -path object. In Tcl, every +path object. In Tcl, every .QW path must have a single unique .QW normalized -string representation. Depending on the filesystem, +string representation. Depending on the filesystem, there may be more than one unnormalized string representation which -refers to that path (e.g. a relative path, a path with different +refers to that path (e.g.\ a relative path, a path with different character case if the filesystem is case insensitive, a path contain a reference to a home directory such as .QW ~ , a path containing symbolic -links, etc). If the very last component in the path is a symbolic +links, etc). If the very last component in the path is a symbolic link, it should not be converted into the object it points to (but -its case or other aspects should be made unique). All other path -components should be converted from symbolic links. This one +its case or other aspects should be made unique). All other path +components should be converted from symbolic links. This one exception is required to agree with Tcl's semantics with \fBfile delete\fR, \fBfile rename\fR, \fBfile copy\fR operating on symbolic links. This function may be called with \fInextCheckpoint\fR either -at the beginning of the path (i.e. zero), at the end of the path, or -at any intermediate file separator in the path. It will never +at the beginning of the path (i.e.\ zero), at the end of the path, or +at any intermediate file separator in the path. It will never point to any other arbitrary position in the path. In the last of the three valid cases, the implementation can assume that the path up to and including the file separator is known and normalized. .PP .CS -typedef int Tcl_FSNormalizePathProc( +typedef int \fBTcl_FSNormalizePathProc\fR( Tcl_Interp *\fIinterp\fR, Tcl_Obj *\fIpathPtr\fR, int \fInextCheckpoint\fR); @@ -1013,23 +1101,23 @@ typedef int Tcl_FSNormalizePathProc( .PP The fields in this section of the structure contain addresses of functions which are called to carry out the basic filesystem -operations. A filesystem which expects to be used with the complete -standard Tcl command set must implement all of these. If some of +operations. A filesystem which expects to be used with the complete +standard Tcl command set must implement all of these. If some of them are not implemented, then certain Tcl commands may fail when -operating on paths within that filesystem. However, in some instances +operating on paths within that filesystem. However, in some instances this may be desirable (for example, a read-only filesystem should not implement the last four functions, and a filesystem which does not support symbolic links need not implement the \fBreadlink\fR function, -etc. The Tcl core expects filesystems to behave in this way). +etc. The Tcl core expects filesystems to behave in this way). .SS FILESYSTEMPATHTYPEPROC .PP -Function to determine the type of a path in this filesystem. May be +Function to determine the type of a path in this filesystem. May be NULL, in which case no type information will be available to users of -the filesystem. The +the filesystem. The .QW type is used only for informational purposes, and should be returned as the string representation of the Tcl_Obj -which is returned. A typical return value might be +which is returned. A typical return value might be .QW networked , .QW zip or @@ -1039,7 +1127,7 @@ increment the refCount of that object if it wishes to retain a reference to it. .PP .CS -typedef Tcl_Obj* Tcl_FSFilesystemPathTypeProc( +typedef Tcl_Obj *\fBTcl_FSFilesystemPathTypeProc\fR( Tcl_Obj *\fIpathPtr\fR); .CE .SS FILESYSTEMSEPARATORPROC @@ -1049,30 +1137,30 @@ This need only be implemented if the filesystem wishes to use a different separator than the standard string .QW / . Amongst other -uses, it is returned by the \fBfile separator\fR command. The +uses, it is returned by the \fBfile separator\fR command. The return value should be an object with refCount of zero. .PP .CS -typedef Tcl_Obj* Tcl_FSFilesystemSeparatorProc( +typedef Tcl_Obj *\fBTcl_FSFilesystemSeparatorProc\fR( Tcl_Obj *\fIpathPtr\fR); .CE .SS STATPROC .PP -Function to process a \fBTcl_FSStat\fR call. Must be implemented for any +Function to process a \fBTcl_FSStat\fR call. Must be implemented for any reasonable filesystem, since many Tcl level commands depend crucially -upon it (e.g. \fBfile atime\fR, \fBfile isdirectory\fR, \fBfile size\fR, +upon it (e.g.\ \fBfile atime\fR, \fBfile isdirectory\fR, \fBfile size\fR, \fBglob\fR). .PP .CS -typedef int Tcl_FSStatProc( +typedef int \fBTcl_FSStatProc\fR( Tcl_Obj *\fIpathPtr\fR, Tcl_StatBuf *\fIstatPtr\fR); .CE .PP The \fBTcl_FSStatProc\fR fills the stat structure \fIstatPtr\fR with -information about the specified file. You do not need any access +information about the specified file. You do not need any access rights to the file to get this information but you need search rights -to all directories named in the path leading to the file. The stat +to all directories named in the path leading to the file. The stat structure includes info regarding device, inode (always 0 on Windows), privilege mode, nlink (always 1 on Windows), user id (always 0 on Windows), group id (always 0 on Windows), rdev (same as device on @@ -1081,37 +1169,37 @@ last metadata change time. .PP If the file represented by \fIpathPtr\fR exists, the \fBTcl_FSStatProc\fR returns 0 and the stat structure is filled with -data. Otherwise, -1 is returned, and no stat info is given. +data. Otherwise, -1 is returned, and no stat info is given. .SS ACCESSPROC .PP -Function to process a \fBTcl_FSAccess\fR call. Must be implemented for +Function to process a \fBTcl_FSAccess\fR call. Must be implemented for any reasonable filesystem, since many Tcl level commands depend crucially -upon it (e.g. \fBfile exists\fR, \fBfile readable\fR). +upon it (e.g.\ \fBfile exists\fR, \fBfile readable\fR). .PP .CS -typedef int Tcl_FSAccessProc( +typedef int \fBTcl_FSAccessProc\fR( Tcl_Obj *\fIpathPtr\fR, int \fImode\fR); .CE .PP The \fBTcl_FSAccessProc\fR checks whether the process would be allowed to read, write or test for existence of the file (or other filesystem -object) whose name is in \fIpathPtr\fR. If the pathname refers to a +object) whose name is in \fIpathPtr\fR. If the pathname refers to a symbolic link, then the permissions of the file referred by this symbolic link should be tested. .PP -On success (all requested permissions granted), zero is returned. On +On success (all requested permissions granted), zero is returned. On error (at least one bit in mode asked for a permission that is denied, or some other error occurred), -1 is returned. .SS OPENFILECHANNELPROC .PP -Function to process a \fBTcl_FSOpenFileChannel\fR call. Must be +Function to process a \fBTcl_FSOpenFileChannel\fR call. Must be implemented for any reasonable filesystem, since any operations which require open or accessing a file's contents will use it -(e.g. \fBopen\fR, \fBencoding\fR, and many Tk commands). +(e.g.\ \fBopen\fR, \fBencoding\fR, and many Tk commands). .PP .CS -typedef Tcl_Channel Tcl_FSOpenFileChannelProc( +typedef Tcl_Channel \fBTcl_FSOpenFileChannelProc\fR( Tcl_Interp *\fIinterp\fR, Tcl_Obj *\fIpathPtr\fR, int \fImode\fR, @@ -1120,11 +1208,11 @@ typedef Tcl_Channel Tcl_FSOpenFileChannelProc( .PP The \fBTcl_FSOpenFileChannelProc\fR opens a file specified by \fIpathPtr\fR and returns a channel handle that can be used to perform -input and output on the file. This API is modeled after the \fBfopen\fR -procedure of the Unix standard I/O library. The syntax and meaning of +input and output on the file. This API is modeled after the \fBfopen\fR +procedure of the Unix standard I/O library. The syntax and meaning of all arguments is similar to those given in the Tcl \fBopen\fR command when opening a file, where the \fImode\fR argument is a combination of -the POSIX flags O_RDONLY, O_WRONLY, etc. If an error occurs while +the POSIX flags O_RDONLY, O_WRONLY, etc. If an error occurs while opening the channel, the \fBTcl_FSOpenFileChannelProc\fR returns NULL and records a POSIX error code that can be retrieved with \fBTcl_GetErrno\fR. In addition, if \fIinterp\fR is non-NULL, the @@ -1133,19 +1221,19 @@ result after any error. .PP The newly created channel is not registered in the supplied interpreter; to register it, use \fBTcl_RegisterChannel\fR. If one of -the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was +the standard channels, \fBstdin\fR, \fBstdout\fR or \fBstderr\fR was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. .SS MATCHINDIRECTORYPROC .PP -Function to process a \fBTcl_FSMatchInDirectory\fR call. If not +Function to process a \fBTcl_FSMatchInDirectory\fR call. If not implemented, then glob and recursive copy functionality will be lacking in the filesystem (and this may impact commands like \fBencoding names\fR which use glob functionality internally). .PP .CS -typedef int Tcl_FSMatchInDirectoryProc( - Tcl_Interp* \fIinterp\fR, +typedef int \fBTcl_FSMatchInDirectoryProc\fR( + Tcl_Interp *\fIinterp\fR, Tcl_Obj *\fIresultPtr\fR, Tcl_Obj *\fIpathPtr\fR, const char *\fIpattern\fR, @@ -1154,22 +1242,22 @@ typedef int Tcl_FSMatchInDirectoryProc( .PP The function should return all files or directories (or other filesystem objects) which match the given pattern and accord with the \fItypes\fR -specification given. There are two ways in which this function may be -called. If \fIpattern\fR is NULL, then \fIpathPtr\fR is a full path +specification given. There are two ways in which this function may be +called. If \fIpattern\fR is NULL, then \fIpathPtr\fR is a full path specification of a single file or directory which should be checked for -existence and correct type. Otherwise, \fIpathPtr\fR is a directory, the +existence and correct type. Otherwise, \fIpathPtr\fR is a directory, the contents of which the function should search for files or directories -which have the correct type. In either case, \fIpathPtr\fR can be -assumed to be both non-NULL and non-empty. It is not currently +which have the correct type. In either case, \fIpathPtr\fR can be +assumed to be both non-NULL and non-empty. It is not currently documented whether \fIpathPtr\fR will have a file separator at its end of not, so code should be flexible to both possibilities. .PP The return value is a standard Tcl result indicating whether an error -occurred in the matching process. Error messages are placed in +occurred in the matching process. Error messages are placed in \fIinterp\fR, unless \fIinterp\fR in NULL in which case no error message need be generated; on a \fBTCL_OK\fR result, results should be added to the \fIresultPtr\fR object given (which can be assumed to be a -valid unshared Tcl list). The matches added +valid unshared Tcl list). The matches added to \fIresultPtr\fR should include any path prefix given in \fIpathPtr\fR (this usually means they will be absolute path specifications). Note that if no matches are found, that simply leads to an empty @@ -1178,39 +1266,40 @@ problems which may occur during the matching process. .PP The \fBTcl_GlobTypeData\fR structure passed in the \fItypes\fR parameter contains the following fields: +.PP .CS typedef struct Tcl_GlobTypeData { - /* Corresponds to bcdpfls as in 'find -t' */ - int \fItype\fR; - /* Corresponds to file permissions */ - int \fIperm\fR; - /* Acceptable mac type */ - Tcl_Obj *\fImacType\fR; - /* Acceptable mac creator */ - Tcl_Obj *\fImacCreator\fR; -} Tcl_GlobTypeData; + /* Corresponds to bcdpfls as in 'find -t' */ + int \fItype\fR; + /* Corresponds to file permissions */ + int \fIperm\fR; + /* Acceptable mac type */ + Tcl_Obj *\fImacType\fR; + /* Acceptable mac creator */ + Tcl_Obj *\fImacCreator\fR; +} \fBTcl_GlobTypeData\fR; .CE .PP There are two specific cases which it is important to handle correctly, both when \fItypes\fR is non-NULL. The two cases are when \fItypes->types & TCL_GLOB_TYPE_DIR\fR or \fItypes->types & TCL_GLOB_TYPE_MOUNT\fR are -true (and in particular when the other flags are false). In the first of -these cases, the function must list the contained directories. Tcl uses +true (and in particular when the other flags are false). In the first of +these cases, the function must list the contained directories. Tcl uses this to implement recursive globbing, so it is critical that filesystems -implement directory matching correctly. In the second of these cases, +implement directory matching correctly. In the second of these cases, with \fBTCL_GLOB_TYPE_MOUNT\fR, the filesystem must list the mount points which lie within the given \fIpathPtr\fR (and in this case, \fIpathPtr\fR need not lie within the same filesystem - different to all other cases in -which this function is called). Support for this is critical if Tcl is +which this function is called). Support for this is critical if Tcl is to have seamless transitions between from one filesystem to another. .SS UTIMEPROC .PP -Function to process a \fBTcl_FSUtime\fR call. Required to allow setting +Function to process a \fBTcl_FSUtime\fR call. Required to allow setting (not reading) of times with \fBfile mtime\fR, \fBfile atime\fR and the open-r/open-w/fcopy implementation of \fBfile copy\fR. .PP .CS -typedef int Tcl_FSUtimeProc( +typedef int \fBTcl_FSUtimeProc\fR( Tcl_Obj *\fIpathPtr\fR, struct utimbuf *\fItval\fR); .CE @@ -1222,26 +1311,26 @@ The return value should be 0 on success and -1 on an error, as with the system \fButime\fR. .SS LINKPROC .PP -Function to process a \fBTcl_FSLink\fR call. Should be implemented +Function to process a \fBTcl_FSLink\fR call. Should be implemented only if the filesystem supports links, and may otherwise be NULL. .PP .CS -typedef Tcl_Obj* Tcl_FSLinkProc( +typedef Tcl_Obj *\fBTcl_FSLinkProc\fR( Tcl_Obj *\fIlinkNamePtr\fR, Tcl_Obj *\fItoPtr\fR, int \fIlinkAction\fR); .CE .PP If \fItoPtr\fR is NULL, the function is being asked to read the -contents of a link. The result is a Tcl_Obj specifying the contents of +contents of a link. The result is a Tcl_Obj specifying the contents of the link given by \fIlinkNamePtr\fR, or NULL if the link could -not be read. The result is owned by the caller (and should therefore -have its ref count incremented before being returned). Any callers +not be read. The result is owned by the caller (and should therefore +have its ref count incremented before being returned). Any callers should call Tcl_DecrRefCount on this result when it is no longer needed. If \fItoPtr\fR is not NULL, the function should attempt to create a link. The result in this case should be \fItoPtr\fR if the link was successful -and NULL otherwise. In this case the result is not owned by the caller -(i.e. no ref count manipulation on either end is needed). See +and NULL otherwise. In this case the result is not owned by the caller +(i.e.\ no reference count manipulations on either end are needed). See the documentation for \fBTcl_FSLink\fR for the correct interpretation of the \fIlinkAction\fR flags. .SS LISTVOLUMESPROC @@ -1251,14 +1340,14 @@ Should be implemented only if the filesystem adds volumes at the head of the filesystem, so that they can be returned by \fBfile volumes\fR. .PP .CS -typedef Tcl_Obj* Tcl_FSListVolumesProc(void); +typedef Tcl_Obj *\fBTcl_FSListVolumesProc\fR(void); .CE .PP The result should be a list of volumes added by this filesystem, or -NULL (or an empty list) if no volumes are provided. The result object +NULL (or an empty list) if no volumes are provided. The result object is considered to be owned by the filesystem (not by Tcl's core), but -should be given a refCount for Tcl. Tcl will use the contents of the -list and then decrement that refCount. This allows filesystems to +should be given a refCount for Tcl. Tcl will use the contents of the +list and then decrement that refCount. This allows filesystems to choose whether they actually want to retain a .QW "master list" of volumes @@ -1272,22 +1361,22 @@ Therefore, Tcl considers return values from this proc to be read-only. .SS FILEATTRSTRINGSPROC .PP Function to list all attribute strings which are valid for this -filesystem. If not implemented the filesystem will not support -the \fBfile attributes\fR command. This allows arbitrary additional -information to be attached to files in the filesystem. If it is +filesystem. If not implemented the filesystem will not support +the \fBfile attributes\fR command. This allows arbitrary additional +information to be attached to files in the filesystem. If it is not implemented, there is no need to implement the \fBget\fR and \fBset\fR methods. .PP .CS -typedef const char** Tcl_FSFileAttrStringsProc( +typedef const char *const *\fBTcl_FSFileAttrStringsProc\fR( Tcl_Obj *\fIpathPtr\fR, - Tcl_Obj** \fIobjPtrRef\fR); + Tcl_Obj **\fIobjPtrRef\fR); .CE .PP The called function may either return an array of strings, or may -instead return NULL and place a Tcl list into the given \fIobjPtrRef\fR. Tcl +instead return NULL and place a Tcl list into the given \fIobjPtrRef\fR. Tcl will take that list and first increment its reference count before using it. -On completion of that use, Tcl will decrement its reference count. Hence if +On completion of that use, Tcl will decrement its reference count. Hence if the list should be disposed of by Tcl when done, it should have a reference count of zero, and if the list should not be disposed of, the filesystem should ensure it returns an object with a reference count @@ -1298,27 +1387,27 @@ Function to process a \fBTcl_FSFileAttrsGet\fR call, used by \fBfile attributes\fR. .PP .CS -typedef int Tcl_FSFileAttrsGetProc( +typedef int \fBTcl_FSFileAttrsGetProc\fR( Tcl_Interp *\fIinterp\fR, int \fIindex\fR, Tcl_Obj *\fIpathPtr\fR, Tcl_Obj **\fIobjPtrRef\fR); .CE .PP -Returns a standard Tcl return code. The attribute value retrieved, +Returns a standard Tcl return code. The attribute value retrieved, which corresponds to the \fIindex\fR'th element in the list returned by the \fBTcl_FSFileAttrStringsProc\fR, is a Tcl_Obj placed in \fIobjPtrRef\fR (if -\fBTCL_OK\fR was returned) and is likely to have a reference count of zero. Either -way we must either store it somewhere (e.g. the Tcl result), or +\fBTCL_OK\fR was returned) and is likely to have a reference count of zero. Either +way we must either store it somewhere (e.g.\ the Tcl result), or Incr/Decr its reference count to ensure it is properly freed. .SS FILEATTRSSETPROC .PP Function to process a \fBTcl_FSFileAttrsSet\fR call, used by \fBfile -attributes\fR. If the filesystem is read-only, there is no need +attributes\fR. If the filesystem is read-only, there is no need to implement this. .PP .CS -typedef int Tcl_FSFileAttrsSetProc( +typedef int \fBTcl_FSFileAttrsSetProc\fR( Tcl_Interp *\fIinterp\fR, int \fIindex\fR, Tcl_Obj *\fIpathPtr\fR, @@ -1329,53 +1418,53 @@ The attribute value of the \fIindex\fR'th element in the list returned by the Tcl_FSFileAttrStringsProc should be set to the \fIobjPtr\fR given. .SS CREATEDIRECTORYPROC .PP -Function to process a \fBTcl_FSCreateDirectory\fR call. Should be +Function to process a \fBTcl_FSCreateDirectory\fR call. Should be implemented unless the FS is read-only. .PP .CS -typedef int Tcl_FSCreateDirectoryProc( +typedef int \fBTcl_FSCreateDirectoryProc\fR( Tcl_Obj *\fIpathPtr\fR); .CE .PP The return value is a standard Tcl result indicating whether an error -occurred in the process. If successful, a new directory should have +occurred in the process. If successful, a new directory should have been added to the filesystem in the location specified by \fIpathPtr\fR. .SS REMOVEDIRECTORYPROC .PP -Function to process a \fBTcl_FSRemoveDirectory\fR call. Should be +Function to process a \fBTcl_FSRemoveDirectory\fR call. Should be implemented unless the FS is read-only. .PP .CS -typedef int Tcl_FSRemoveDirectoryProc( +typedef int \fBTcl_FSRemoveDirectoryProc\fR( Tcl_Obj *\fIpathPtr\fR, int \fIrecursive\fR, Tcl_Obj **\fIerrorPtr\fR); .CE .PP The return value is a standard Tcl result indicating whether an error -occurred in the process. If successful, the directory specified by -\fIpathPtr\fR should have been removed from the filesystem. If the +occurred in the process. If successful, the directory specified by +\fIpathPtr\fR should have been removed from the filesystem. If the \fIrecursive\fR flag is given, then a non-empty directory should be -deleted without error. If this flag is not given, then and the +deleted without error. If this flag is not given, then and the directory is non-empty a POSIX .QW EEXIST -error should be signaled. If an +error should be signaled. If an error does occur, the name of the file or directory which caused the error should be placed in \fIerrorPtr\fR. .SS DELETEFILEPROC .PP -Function to process a \fBTcl_FSDeleteFile\fR call. Should be implemented +Function to process a \fBTcl_FSDeleteFile\fR call. Should be implemented unless the FS is read-only. .PP .CS -typedef int Tcl_FSDeleteFileProc( +typedef int \fBTcl_FSDeleteFileProc\fR( Tcl_Obj *\fIpathPtr\fR); .CE .PP The return value is a standard Tcl result indicating whether an error -occurred in the process. If successful, the file specified by -\fIpathPtr\fR should have been removed from the filesystem. Note that, +occurred in the process. If successful, the file specified by +\fIpathPtr\fR should have been removed from the filesystem. Note that, if the filesystem supports symbolic links, Tcl will always call this function and not Tcl_FSRemoveDirectoryProc when needed to delete them (even if they are symbolic links to directories). @@ -1386,13 +1475,13 @@ because the core has a fallback implementation available. See each individual description for the consequences of leaving the field NULL. .SS LSTATPROC .PP -Function to process a \fBTcl_FSLstat\fR call. If not implemented, Tcl -will attempt to use the \fIstatProc\fR defined above instead. Therefore +Function to process a \fBTcl_FSLstat\fR call. If not implemented, Tcl +will attempt to use the \fIstatProc\fR defined above instead. Therefore it need only be implemented if a filesystem can differentiate between \fBstat\fR and \fBlstat\fR calls. .PP .CS -typedef int Tcl_FSLstatProc( +typedef int \fBTcl_FSLstatProc\fR( Tcl_Obj *\fIpathPtr\fR, Tcl_StatBuf *\fIstatPtr\fR); .CE @@ -1403,145 +1492,145 @@ to a symbolic link, it returns information about the link, not about the target file. .SS COPYFILEPROC .PP -Function to process a \fBTcl_FSCopyFile\fR call. If not implemented Tcl +Function to process a \fBTcl_FSCopyFile\fR call. If not implemented Tcl will fall back on \fBopen\fR-r, \fBopen\fR-w and \fBfcopy\fR as a copying mechanism. Therefore it need only be implemented if the filesystem can perform that action more efficiently. .PP .CS -typedef int Tcl_FSCopyFileProc( +typedef int \fBTcl_FSCopyFileProc\fR( Tcl_Obj *\fIsrcPathPtr\fR, Tcl_Obj *\fIdestPathPtr\fR); .CE .PP The return value is a standard Tcl result indicating whether an error -occurred in the copying process. Note that, \fIdestPathPtr\fR is the +occurred in the copying process. Note that, \fIdestPathPtr\fR is the name of the file which should become the copy of \fIsrcPathPtr\fR. It is never the name of a directory into which \fIsrcPathPtr\fR could be -copied (i.e. the function is much simpler than the Tcl level \fBfile -copy\fR subcommand). Note that, +copied (i.e.\ the function is much simpler than the Tcl level \fBfile +copy\fR subcommand). Note that, if the filesystem supports symbolic links, Tcl will always call this function and not \fIcopyDirectoryProc\fR when needed to copy them -(even if they are symbolic links to directories). Finally, if the +(even if they are symbolic links to directories). Finally, if the filesystem determines it cannot support the \fBfile copy\fR action, calling \fBTcl_SetErrno(EXDEV)\fR and returning a non-\fBTCL_OK\fR result will tell Tcl to use its standard fallback mechanisms. .SS RENAMEFILEPROC .PP -Function to process a \fBTcl_FSRenameFile\fR call. If not implemented, -Tcl will fall back on a copy and delete mechanism. Therefore it need +Function to process a \fBTcl_FSRenameFile\fR call. If not implemented, +Tcl will fall back on a copy and delete mechanism. Therefore it need only be implemented if the filesystem can perform that action more efficiently. .PP .CS -typedef int Tcl_FSRenameFileProc( +typedef int \fBTcl_FSRenameFileProc\fR( Tcl_Obj *\fIsrcPathPtr\fR, Tcl_Obj *\fIdestPathPtr\fR); .CE .PP The return value is a standard Tcl result indicating whether an error -occurred in the renaming process. If the +occurred in the renaming process. If the filesystem determines it cannot support the \fBfile rename\fR action, calling \fBTcl_SetErrno(EXDEV)\fR and returning a non-\fBTCL_OK\fR result will tell Tcl to use its standard fallback mechanisms. .SS COPYDIRECTORYPROC .PP -Function to process a \fBTcl_FSCopyDirectory\fR call. If not +Function to process a \fBTcl_FSCopyDirectory\fR call. If not implemented, Tcl will fall back on a recursive \fBfile mkdir\fR, \fBfile copy\fR -mechanism. Therefore it need only be implemented if the filesystem can +mechanism. Therefore it need only be implemented if the filesystem can perform that action more efficiently. .PP .CS -typedef int Tcl_FSCopyDirectoryProc( +typedef int \fBTcl_FSCopyDirectoryProc\fR( Tcl_Obj *\fIsrcPathPtr\fR, Tcl_Obj *\fIdestPathPtr\fR, Tcl_Obj **\fIerrorPtr\fR); .CE .PP The return value is a standard Tcl result indicating whether an error -occurred in the copying process. If an error does occur, the name of +occurred in the copying process. If an error does occur, the name of the file or directory which caused the error should be placed in \fIerrorPtr\fR. Note that, \fIdestPathPtr\fR is the name of the directory-name which should become the mirror-image of \fIsrcPathPtr\fR. It is not the name of a directory into which -\fIsrcPathPtr\fR should be copied (i.e. the function is much simpler -than the Tcl level \fBfile copy\fR subcommand). Finally, if the +\fIsrcPathPtr\fR should be copied (i.e.\ the function is much simpler +than the Tcl level \fBfile copy\fR subcommand). Finally, if the filesystem determines it cannot support the directory copy action, calling \fBTcl_SetErrno(EXDEV)\fR and returning a non-\fBTCL_OK\fR result will tell Tcl to use its standard fallback mechanisms. .SS LOADFILEPROC .PP -Function to process a \fBTcl_FSLoadFile\fR call. If not implemented, Tcl +Function to process a \fBTcl_FSLoadFile\fR call. If not implemented, Tcl will fall back on a copy to native-temp followed by a \fBTcl_FSLoadFile\fR on -that temporary copy. Therefore it need only be implemented if the +that temporary copy. Therefore it need only be implemented if the filesystem can load code directly, or it can be implemented simply to return \fBTCL_ERROR\fR to disable load functionality in this filesystem entirely. .PP .CS -typedef int Tcl_FSLoadFileProc( +typedef int \fBTcl_FSLoadFileProc\fR( Tcl_Interp *\fIinterp\fR, Tcl_Obj *\fIpathPtr\fR, Tcl_LoadHandle *\fIhandlePtr\fR, Tcl_FSUnloadFileProc *\fIunloadProcPtr\fR); .CE .PP -Returns a standard Tcl completion code. If an error occurs, an error -message is left in the \fIinterp\fR's result. The function dynamically loads a -binary code file into memory. On a successful load, the \fIhandlePtr\fR +Returns a standard Tcl completion code. If an error occurs, an error +message is left in the \fIinterp\fR's result. The function dynamically loads a +binary code file into memory. On a successful load, the \fIhandlePtr\fR should be filled with a token for the dynamically loaded file, and the \fIunloadProcPtr\fR should be filled in with the address of a procedure. The unload procedure will be called with the given \fBTcl_LoadHandle\fR as its -only parameter when Tcl needs to unload the file. For example, for the +only parameter when Tcl needs to unload the file. For example, for the native filesystem, the \fBTcl_LoadHandle\fR returned is currently a token which can be used in the private \fBTclpFindSymbol\fR to access functions -in the new code. Each filesystem is free to define the -\fBTcl_LoadHandle\fR as it requires. Finally, if the +in the new code. Each filesystem is free to define the +\fBTcl_LoadHandle\fR as it requires. Finally, if the filesystem determines it cannot support the file load action, calling \fBTcl_SetErrno(EXDEV)\fR and returning a non-\fBTCL_OK\fR result will tell Tcl to use its standard fallback mechanisms. .SS UNLOADFILEPROC .PP -Function to unload a previously successfully loaded file. If load was +Function to unload a previously successfully loaded file. If load was implemented, then this should also be implemented, if there is any cleanup action required. .PP .CS -typedef void Tcl_FSUnloadFileProc( +typedef void \fBTcl_FSUnloadFileProc\fR( Tcl_LoadHandle \fIloadHandle\fR); .CE -.SS GETCWDPROC +.SS GETCWDPROC .PP -Function to process a \fBTcl_FSGetCwd\fR call. Most filesystems need not -implement this. It will usually only be called once, if \fBgetcwd\fR is -called before \fBchdir\fR. May be NULL. +Function to process a \fBTcl_FSGetCwd\fR call. Most filesystems need not +implement this. It will usually only be called once, if \fBgetcwd\fR is +called before \fBchdir\fR. May be NULL. .PP .CS -typedef Tcl_Obj* Tcl_FSGetCwdProc( +typedef Tcl_Obj *\fBTcl_FSGetCwdProc\fR( Tcl_Interp *\fIinterp\fR); .CE .PP If the filesystem supports a native notion of a current working directory (which might perhaps change independent of Tcl), this function should return that cwd as the result, or NULL if the current -directory could not be determined (e.g. the user does not have -appropriate permissions on the cwd directory). If NULL is returned, an +directory could not be determined (e.g.\ the user does not have +appropriate permissions on the cwd directory). If NULL is returned, an error message is left in the \fIinterp\fR's result. .SS CHDIRPROC .PP -Function to process a \fBTcl_FSChdir\fR call. If filesystems do not +Function to process a \fBTcl_FSChdir\fR call. If filesystems do not implement this, it will be emulated by a series of directory access -checks. Otherwise, virtual filesystems which do implement it need only +checks. Otherwise, virtual filesystems which do implement it need only respond with a positive return result if the \fIpathPtr\fR is a valid, -accessible directory in their filesystem. They need not remember the +accessible directory in their filesystem. They need not remember the result, since that will be automatically remembered for use by \fBTcl_FSGetCwd\fR. -Real filesystems should carry out the correct action (i.e. call the +Real filesystems should carry out the correct action (i.e.\ call the correct system \fBchdir\fR API). .PP .CS -typedef int Tcl_FSChdirProc( +typedef int \fBTcl_FSChdirProc\fR( Tcl_Obj *\fIpathPtr\fR); .CE .PP @@ -1549,6 +1638,6 @@ The \fBTcl_FSChdirProc\fR changes the applications current working directory to the value specified in \fIpathPtr\fR. The function returns -1 on error or 0 on success. .SH "SEE ALSO" -cd(n), file(n), load(n), open(n), pwd(n), unload(n) +cd(n), file(n), filename(n), load(n), open(n), pwd(n), source(n), unload(n) .SH KEYWORDS -stat, access, filesystem, vfs, virtual +stat, access, filesystem, vfs, virtual filesystem diff --git a/doc/FindExec.3 b/doc/FindExec.3 index 0e225e9..66cc1f1 100644 --- a/doc/FindExec.3 +++ b/doc/FindExec.3 @@ -45,6 +45,13 @@ application's executable, if possible. If it fails to find the binary, then future calls to \fBinfo nameofexecutable\fR will return an empty string. .PP +On Windows platforms this procedure is typically invoked as the very +first thing in the application's main program as well; Its \fIargv[0]\fR +argument is only used to indicate wheter the executable has a stderr +channel (any non-null value) or not (the value null). If \fBTcl_SetPanicProc\fR +is never called and no debugger is running, this determines whether +the panic message is sent to stderr or to a standard system dialog. +.PP \fBTcl_GetNameOfExecutable\fR simply returns a pointer to the internal full path name of the executable file as computed by \fBTcl_FindExecutable\fR. This procedure call is the C API diff --git a/doc/GetCwd.3 b/doc/GetCwd.3 index 964e237..964e237 100644..100755 --- a/doc/GetCwd.3 +++ b/doc/GetCwd.3 diff --git a/doc/GetIndex.3 b/doc/GetIndex.3 index 82590fb..f60feb5 100644 --- a/doc/GetIndex.3 +++ b/doc/GetIndex.3 @@ -29,7 +29,7 @@ provided on errors. The string value of this object is used to search through \fItablePtr\fR. The internal representation is modified to hold the index of the matching table entry. -.AP "const char" **tablePtr in +.AP "const char *const" *tablePtr in An array of null-terminated strings. The end of the array is marked by a NULL string pointer. .AP "const void" *structTablePtr in @@ -49,7 +49,6 @@ operation. The only bit that is currently defined is \fBTCL_EXACT\fR. The index of the string in \fItablePtr\fR that matches the value of \fIobjPtr\fR is returned here. .BE - .SH DESCRIPTION .PP This procedure provides an efficient way for looking up keywords, @@ -93,9 +92,7 @@ array of characters at \fItablePtr\fR+\fIoffset\fR bytes, etc.) This is particularly useful when processing things like \fBTk_ConfigurationSpec\fR, whose string keys are in the same place in each of several array elements. - .SH "SEE ALSO" -Tcl_WrongNumArgs - +prefix(n), Tcl_WrongNumArgs(3) .SH KEYWORDS index, object, table lookup diff --git a/doc/GetStdChan.3 b/doc/GetStdChan.3 index 045d15a..7bc2e1b 100644 --- a/doc/GetStdChan.3 +++ b/doc/GetStdChan.3 @@ -53,9 +53,11 @@ set to NULL. .PP If a non-NULL value for \fIchannel\fR is passed to \fBTcl_SetStdChannel\fR, then that same value should be passed to \fBTcl_RegisterChannel\fR, like so: +.PP .CS Tcl_RegisterChannel(NULL, channel); .CE +.PP This is a workaround for a misfeature in \fBTcl_SetStdChannel\fR that it fails to do some reference counting housekeeping. This misfeature cannot be corrected without contradicting the assumptions of some existing diff --git a/doc/GetTime.3 b/doc/GetTime.3 index 14a9e8c..d902f90 100644 --- a/doc/GetTime.3 +++ b/doc/GetTime.3 @@ -19,27 +19,21 @@ Tcl_GetTime, Tcl_SetTimeProc, Tcl_QueryTimeProc \- get date and time .sp \fBTcl_QueryTimeProc\fR(\fIgetProcPtr, scaleProcPtr, clientDataPtr\fR) .SH ARGUMENTS -.AS "Tcl_Time *" timePtr out -.AP "Tcl_Time *" timePtr out +.AS Tcl_GetTimeProc *getProc in +.AP Tcl_Time *timePtr out Points to memory in which to store the date and time information. -.AS "Tcl_GetTimeProc *" getProc in -.AP "Tcl_GetTimeProc *" getProc in +.AP Tcl_GetTimeProc getProc in Pointer to handler function replacing \fBTcl_GetTime\fR's access to the OS. -.AS "Tcl_ScaleTimeProc *" scaleProc in -.AP "Tcl_ScaleTimeProc *" scaleProc in +.AP Tcl_ScaleTimeProc scaleProc in Pointer to handler function for the conversion of time delays in the virtual domain to real-time. -.AS "ClientData *" clientData in -.AP "ClientData *" clientData in +.AP ClientData clientData in Value passed through to the two handler functions. -.AS "Tcl_GetTimeProc **" getProcPtr inout -.AP "Tcl_GetTimeProc **" getProcPtr inout +.AP Tcl_GetTimeProc *getProcPtr out Pointer to place the currently registered get handler function into. -.AS "Tcl_ScaleTimeProc **" scaleProcPtr inout -.AP "Tcl_ScaleTimeProc **" scaleProcPtr inout +.AP Tcl_ScaleTimeProc *scaleProcPtr out Pointer to place the currently registered scale handler function into. -.AS "ClientData **" clientDataPtr inout -.AP "ClientData **" clientDataPtr inout +.AP ClientData *clientDataPtr out Pointer to place the currently registered pass-through value into. .BE .SH DESCRIPTION @@ -47,11 +41,12 @@ Pointer to place the currently registered pass-through value into. The \fBTcl_GetTime\fR function retrieves the current time as a \fITcl_Time\fR structure in memory the caller provides. This structure has the following definition: +.PP .CS typedef struct Tcl_Time { - long sec; - long usec; -} Tcl_Time; + long \fIsec\fR; + long \fIusec\fR; +} \fBTcl_Time\fR; .CE .PP On return, the \fIsec\fR member of the structure is filled in with the @@ -68,20 +63,36 @@ computer system. On multiprocessor variants of Windows, this number may be limited to the 10- or 20-ms granularity of the system clock. (On single-processor Windows systems, the \fIusec\fR field is derived from a performance counter and is highly precise.) +.SS "VIRTUALIZED TIME" .PP -The \fBTcl_SetTime\fR function registers two related handler functions +The \fBTcl_SetTimeProc\fR function registers two related handler functions with the core. The first handler function is a replacement for \fBTcl_GetTime\fR, or rather the OS access made by \fBTcl_GetTime\fR. The other handler function is used by the Tcl notifier to convert wait/block times from the virtual domain into real time. .PP -The \fBTcl_QueryTime\fR function returns the currently registered +The \fBTcl_QueryTimeProc\fR function returns the currently registered handler functions. If no external handlers were set then this will return the standard handlers accessing and processing the native time of the OS. The arguments to the function are allowed to be NULL; and any argument which is NULL is ignored and not set. .PP +The signatures of the handler functions are as follows: +.PP +.CS +typedef void \fBTcl_GetTimeProc\fR( + Tcl_Time *\fItimebuf\fR, + ClientData \fIclientData\fR); +typedef void \fBTcl_ScaleTimeProc\fR( + Tcl_Time *\fItimebuf\fR, + ClientData \fIclientData\fR); +.CE +.PP +The \fItimebuf\fR fields contain the time to manipulate, and the +\fIclientData\fR fields contain a pointer supplied at the time the +handler functions were registered. +.PP Any handler pair specified has to return data which is consistent between them. In other words, setting one handler of the pair to something assuming a 10-times slowdown, and the other handler of the @@ -95,6 +106,6 @@ time one way or other. Note that the insertion of the hooks will not change the behaviour of the Tcl core with regard to this situation, i.e. the existing behaviour is retained. .SH "SEE ALSO" -clock +clock(n) .SH KEYWORDS date, time diff --git a/doc/GetVersion.3 b/doc/GetVersion.3 index 47034d0..47034d0 100644..100755 --- a/doc/GetVersion.3 +++ b/doc/GetVersion.3 @@ -35,7 +35,7 @@ ClientData .sp \fBTcl_SetHashValue\fR(\fIentryPtr, value\fR) .sp -char * +void * \fBTcl_GetHashKey\fR(\fItablePtr, entryPtr\fR) .sp Tcl_HashEntry * @@ -47,7 +47,7 @@ Tcl_HashEntry * char * \fBTcl_HashStats\fR(\fItablePtr\fR) .SH ARGUMENTS -.AS Tcl_HashKeyType *searchPtr out +.AS "const Tcl_HashKeyType" *searchPtr out .AP Tcl_HashTable *tablePtr in Address of hash table structure (for all procedures but \fBTcl_InitHashTable\fR, this must have been initialized by @@ -58,7 +58,7 @@ Kind of keys to use for new hash table. Must be either \fBTCL_CUSTOM_PTR_KEYS\fR, or an integer value greater than 1. .AP Tcl_HashKeyType *typePtr in Address of structure which defines the behaviour of the hash table. -.AP "const char" *key in +.AP "const void" *key in Key to use for probe into table. Exact form depends on \fIkeyType\fR used to create table. .AP int *newPtr out @@ -81,8 +81,8 @@ very quickly locate the entry, and hence its value. There may be at most one entry in a hash table with a particular key, but many entries may have the same value. Keys can take one of four forms: strings, one-word values, integer arrays, or custom keys defined by a -Tcl_HashKeyType structure (See section \fBTHE TCL_HASHKEYTYPE -STRUCTURE\fR below). All of the keys in a given table have the same +Tcl_HashKeyType structure (See section \fBTHE TCL_HASHKEYTYPE STRUCTURE\fR +below). All of the keys in a given table have the same form, which is specified when the table is initialized. .PP The value of a hash table entry can be anything that fits in the same @@ -245,6 +245,7 @@ Extension writers can define new hash key types by defining four procedures, initializing a \fBTcl_HashKeyType\fR structure to describe the type, and calling \fBTcl_InitCustomHashTable\fR. The \fBTcl_HashKeyType\fR structure is defined as follows: +.PP .CS typedef struct Tcl_HashKeyType { int \fIversion\fR; @@ -253,7 +254,7 @@ typedef struct Tcl_HashKeyType { Tcl_CompareHashKeysProc *\fIcompareKeysProc\fR; Tcl_AllocHashEntryProc *\fIallocEntryProc\fR; Tcl_FreeHashEntryProc *\fIfreeEntryProc\fR; -} Tcl_HashKeyType; +} \fBTcl_HashKeyType\fR; .CE .PP The \fIversion\fR member is the version of the table. If this structure is @@ -268,7 +269,6 @@ they do not use the lower bits. If this flag is set then the hash table will attempt to rectify this by randomizing the bits and then using the upper N bits as the index into the table. .IP \fBTCL_HASH_KEY_SYSTEM_HASH\fR 25 -.VS 8.5 This flag forces Tcl to use the memory allocation procedures provided by the operating system when allocating and freeing memory used to store the hash table data structures, and not any of Tcl's own customized memory allocation @@ -276,35 +276,40 @@ routines. This is important if the hash table is to be used in the implementation of a custom set of allocation routines, or something that a custom set of allocation routines might depend on, in order to avoid any circular dependency. -.VE 8.5 .PP The \fIhashKeyProc\fR member contains the address of a function called to calculate a hash value for the key. +.PP .CS -typedef unsigned int (Tcl_HashKeyProc) ( +typedef unsigned int \fBTcl_HashKeyProc\fR( Tcl_HashTable *\fItablePtr\fR, void *\fIkeyPtr\fR); .CE +.PP If this is NULL then \fIkeyPtr\fR is used and \fBTCL_HASH_KEY_RANDOMIZE_HASH\fR is assumed. .PP The \fIcompareKeysProc\fR member contains the address of a function called to compare two keys. +.PP .CS -typedef int (Tcl_CompareHashKeysProc) ( +typedef int \fBTcl_CompareHashKeysProc\fR( void *\fIkeyPtr\fR, Tcl_HashEntry *\fIhPtr\fR); .CE +.PP If this is NULL then the \fIkeyPtr\fR pointers are compared. If the keys do not match then the function returns 0, otherwise it returns 1. .PP The \fIallocEntryProc\fR member contains the address of a function called to allocate space for an entry and initialize the key and clientData. +.PP .CS -typedef Tcl_HashEntry *(Tcl_AllocHashEntryProc) ( +typedef Tcl_HashEntry *\fBTcl_AllocHashEntryProc\fR( Tcl_HashTable *\fItablePtr\fR, void *\fIkeyPtr\fR); .CE +.PP If this is NULL then Tcl_Alloc is used to allocate enough space for a Tcl_HashEntry, the key pointer is assigned to key.oneWordValue and the clientData is set to NULL. String keys and array keys use this function to @@ -316,9 +321,12 @@ object. .PP The \fIfreeEntryProc\fR member contains the address of a function called to free space for an entry. +.PP .CS -typedef void (Tcl_FreeHashEntryProc) (Tcl_HashEntry *\fIhPtr\fR); +typedef void \fBTcl_FreeHashEntryProc\fR( + Tcl_HashEntry *\fIhPtr\fR); .CE +.PP If this is NULL then Tcl_Free is used to free the space for the entry. Tcl_Obj* keys use this function to decrement the reference count on the object. diff --git a/doc/IntObj.3 b/doc/IntObj.3 index 5cf677d..cde96f8 100644 --- a/doc/IntObj.3 +++ b/doc/IntObj.3 @@ -38,7 +38,6 @@ int \fBTcl_GetWideIntFromObj\fR(\fIinterp, objPtr, widePtr\fR) .sp .sp -.VS 8.5 \fB#include <tclTomMath.h>\fR .sp Tcl_Obj * @@ -54,7 +53,6 @@ int .sp int \fBTcl_InitBignumFromDouble\fR(\fIinterp, doubleValue, bigValue\fR) -.VE 8.5 .SH ARGUMENTS .AS Tcl_WideInt doubleValue in/out .AP int intValue in @@ -80,20 +78,14 @@ Points to place to store the long integer value retrieved from \fIobjPtr\fR. .AP Tcl_WideInt *widePtr out Points to place to store the wide integer value retrieved from \fIobjPtr\fR. .AP mp_int *bigValue in/out -.VS 8.5 Points to a multi-precision integer structure declared by the LibTomMath library. -.VE 8.5 .AP double doubleValue in -.VS 8.5 Double value from which the integer part is determined and used to initialize a multi-precision integer value. -.VE 8.5 .BE - .SH DESCRIPTION .PP -.VS 8.5 These procedures are used to create, modify, and read Tcl objects that hold integral values. .PP @@ -153,7 +145,6 @@ If anything later in the caller requires The \fBTcl_InitBignumFromDouble\fR routine is a utility procedure that extracts the integer part of \fIdoubleValue\fR and stores that integer value in the \fBmp_int\fR value \fIbigValue\fR. -.VE 8.5 .SH "SEE ALSO" Tcl_NewObj, Tcl_DecrRefCount, Tcl_IncrRefCount, Tcl_GetObjResult .SH KEYWORDS diff --git a/doc/Interp.3 b/doc/Interp.3 index 0b1de03..d908057 100644 --- a/doc/Interp.3 +++ b/doc/Interp.3 @@ -15,28 +15,36 @@ Tcl_Interp \- client-visible fields of interpreter structures \fB#include <tcl.h>\fR .sp typedef struct { - char *\fIresult\fR; - Tcl_FreeProc *\fIfreeProc\fR; - int \fIerrorLine\fR; -} Tcl_Interp; + char *\fIresult\fR; + Tcl_FreeProc *\fIfreeProc\fR; + int \fIerrorLine\fR; +} \fBTcl_Interp\fR; -typedef void Tcl_FreeProc(char *\fIblockPtr\fR); +typedef void \fBTcl_FreeProc\fR( + char *\fIblockPtr\fR); .BE - .SH DESCRIPTION .PP The \fBTcl_CreateInterp\fR procedure returns a pointer to a Tcl_Interp -structure. This pointer is then passed into other Tcl procedures -to process commands in the interpreter and perform other operations -on the interpreter. Interpreter structures contain many fields -that are used by Tcl, but only three that may be accessed by -clients: \fIresult\fR, \fIfreeProc\fR, and \fIerrorLine\fR. +structure. Callers of \fBTcl_CreateInterp\fR should use this pointer +as an opaque token, suitable for nothing other than passing back to +other routines in the Tcl interface. Accessing fields directly through +the pointer as described below is no longer supported. The supported +public routines \fBTcl_SetResult\fR, \fBTcl_GetResult\fR, +\fBTcl_SetErrorLine\fR, \fBTcl_GetErrorLine\fR must be used instead. .PP -.VS 8.5 -\fBNote that access to all three fields, \fIresult\fB, \fIfreeProc\fB and -\fIerrorLine\fB is deprecated.\fR Use \fBTcl_SetResult\fR, -\fBTcl_GetResult\fR, and \fBTcl_GetReturnOptions\fR instead. -.VE 8.5 +For legacy programs and extensions no longer being maintained, compiles +against the Tcl 8.6 header files are only possible with the compiler +directives +.CS +#define USE_INTERP_RESULT +.CE +and/or +.CS +#define USE_INTERP_ERRORLINE +.CE +depending on which fields of the \fBTcl_Interp\fR struct are accessed. +These directives may be embedded in code or supplied via compiler options. .PP The \fIresult\fR and \fIfreeProc\fR fields are used to return results or error messages from commands. diff --git a/doc/Limit.3 b/doc/Limit.3 index 928ebe1..2941ee8 100644 --- a/doc/Limit.3 +++ b/doc/Limit.3 @@ -90,7 +90,6 @@ Arbitrary pointer-sized word used to pass some context to the Function to call whenever a handler is deleted. May be NULL if the \fIclientData\fR requires no deletion. .BE - .SH DESCRIPTION .PP Tcl's interpreter resource limit subsystem allows for close control @@ -162,7 +161,7 @@ the function that will actually be called; it should have the following prototype: .PP .CS -typedef void Tcl_LimitHandlerProc( +typedef void \fBTcl_LimitHandlerProc\fR( ClientData \fIclientData\fR, Tcl_Interp *\fIinterp\fR); .CE @@ -179,7 +178,7 @@ function to call to delete the \fIclientData\fR value. It may be following prototype: .PP .CS -typedef void Tcl_LimitHandlerDeleteProc( +typedef void \fBTcl_LimitHandlerDeleteProc\fR( ClientData \fIclientData\fR); .CE .PP @@ -189,6 +188,5 @@ with \fBTcl_LimitAddHandler\fR) with exactly matching \fItype\fR, \fIhandlerProc\fR and \fIclientData\fR arguments. This function always invokes the \fIdeleteProc\fR on the \fIclientData\fR (unless the \fIdeleteProc\fR was NULL or \fBTCL_STATIC\fR). - .SH KEYWORDS interpreter, resource, limit, commands, time, callback diff --git a/doc/LinkVar.3 b/doc/LinkVar.3 index 6361fb4..dc71a45 100644 --- a/doc/LinkVar.3 +++ b/doc/LinkVar.3 @@ -31,20 +31,14 @@ Name of global variable. Address of C variable that is to be linked to \fIvarName\fR. .AP int type in Type of C variable. Must be one of \fBTCL_LINK_INT\fR, -.VS 8.5 \fBTCL_LINK_UINT\fR, \fBTCL_LINK_CHAR\fR, \fBTCL_LINK_UCHAR\fR, \fBTCL_LINK_SHORT\fR, \fBTCL_LINK_USHORT\fR, \fBTCL_LINK_LONG\fR, -\fBTCL_LINK_ULONG\fR, -.VE 8.5 -\fBTCL_LINK_WIDE_INT\fR, -.VS 8.5 +\fBTCL_LINK_ULONG\fR, \fBTCL_LINK_WIDE_INT\fR, \fBTCL_LINK_WIDE_UINT\fR, \fBTCL_LINK_FLOAT\fR, -.VE 8.5 \fBTCL_LINK_DOUBLE\fR, \fBTCL_LINK_BOOLEAN\fR, or \fBTCL_LINK_STRING\fR, optionally OR'ed with \fBTCL_LINK_READ_ONLY\fR to make Tcl variable read-only. .BE - .SH DESCRIPTION .PP \fBTcl_LinkVar\fR uses variable traces to keep the Tcl variable @@ -68,7 +62,6 @@ Any value written into the Tcl variable must have a proper integer form acceptable to \fBTcl_GetIntFromObj\fR; attempts to write non-integer values into \fIvarName\fR will be rejected with Tcl errors. -.VS 8.5 .TP \fBTCL_LINK_UINT\fR The C variable is of type \fBunsigned int\fR. @@ -122,7 +115,6 @@ integer form acceptable to \fBTcl_GetWideIntFromObj\fR and in the platform's defined range for the \fBunsigned long\fR type; attempts to write non-integer values (or values outside the range) into \fIvarName\fR will be rejected with Tcl errors. -.VE 8.5 .TP \fBTCL_LINK_DOUBLE\fR The C variable is of type \fBdouble\fR. @@ -130,7 +122,6 @@ Any value written into the Tcl variable must have a proper real form acceptable to \fBTcl_GetDoubleFromObj\fR; attempts to write non-real values into \fIvarName\fR will be rejected with Tcl errors. -.VS 8.5 .TP \fBTCL_LINK_FLOAT\fR The C variable is of type \fBfloat\fR. @@ -139,7 +130,6 @@ form acceptable to \fBTcl_GetDoubleFromObj\fR and must be within the range acceptable for a \fBfloat\fR; attempts to write non-real values (or values outside the range) into \fIvarName\fR will be rejected with Tcl errors. -.VE 8.5 .TP \fBTCL_LINK_WIDE_INT\fR The C variable is of type \fBTcl_WideInt\fR (which is an integer type @@ -148,7 +138,6 @@ Any value written into the Tcl variable must have a proper integer form acceptable to \fBTcl_GetWideIntFromObj\fR; attempts to write non-integer values into \fIvarName\fR will be rejected with Tcl errors. -.VS 8.5 .TP \fBTCL_LINK_WIDE_UINT\fR The C variable is of type \fBTcl_WideUInt\fR (which is an unsigned @@ -160,7 +149,6 @@ cast to unsigned); .\" FIXME! Use bignums instead. attempts to write non-integer values into \fIvarName\fR will be rejected with Tcl errors. -.VE 8.5 .TP \fBTCL_LINK_BOOLEAN\fR The C variable is of type \fBint\fR. @@ -204,6 +192,16 @@ Tk widget that wishes to display the value of the variable), the trace will not trigger when the C variable has changed. \fBTcl_UpdateLinkedVar\fR ensures that any traces on the Tcl variable are invoked. - +.PP +Note that, as with any call to a Tcl interpreter, \fBTcl_UpdateLinkedVar\fR +must be called from the same thread that created the interpreter. The safest +mechanism is to ensure that the C variable is only ever updated from the same +thread that created the interpreter (possibly in response to an event posted +with \fBTcl_ThreadQueueEvent\fR), but when it is necessary to update the +variable in a separate thread, it is advised that \fBTcl_AsyncMark\fR be used +to indicate to the thread hosting the interpreter that it is ready to run +\fBTcl_UpdateLinkedVar\fR. +.SH "SEE ALSO" +Tcl_TraceVar(3) .SH KEYWORDS -boolean, integer, link, read-only, real, string, traces, variable +boolean, integer, link, read-only, real, string, trace, variable diff --git a/doc/ListObj.3 b/doc/ListObj.3 index 443eafe..b93e52b 100644 --- a/doc/ListObj.3 +++ b/doc/ListObj.3 @@ -220,7 +220,7 @@ referenced by the array of object pointers \fIobjv\fR just before the element \fIindex\fR of the list referenced by \fIlistPtr\fR: .PP .CS -result = Tcl_ListObjReplace(interp, listPtr, index, 0, +result = \fBTcl_ListObjReplace\fR(interp, listPtr, index, 0, objc, objv); .CE .PP @@ -229,9 +229,9 @@ referenced by the array \fIobjv\fR to the end of the list \fIlistPtr\fR: .PP .CS -result = Tcl_ListObjLength(interp, listPtr, &length); +result = \fBTcl_ListObjLength\fR(interp, listPtr, &length); if (result == TCL_OK) { - result = Tcl_ListObjReplace(interp, listPtr, length, 0, + result = \fBTcl_ListObjReplace\fR(interp, listPtr, length, 0, objc, objv); } .CE @@ -241,10 +241,10 @@ by simply calling \fBTcl_ListObjReplace\fR with a NULL \fIobjvPtr\fR: .PP .CS -result = Tcl_ListObjReplace(interp, listPtr, first, count, +result = \fBTcl_ListObjReplace\fR(interp, listPtr, first, count, 0, NULL); .CE .SH "SEE ALSO" -Tcl_NewObj, Tcl_DecrRefCount, Tcl_IncrRefCount, Tcl_GetObjResult +Tcl_NewObj(3), Tcl_DecrRefCount(3), Tcl_IncrRefCount(3), Tcl_GetObjResult(3) .SH KEYWORDS append, index, insert, internal representation, length, list, list object, list type, object, object type, replace, string representation diff --git a/doc/Load.3 b/doc/Load.3 new file mode 100644 index 0000000..c088f32 --- /dev/null +++ b/doc/Load.3 @@ -0,0 +1,69 @@ +'\" +'\" Copyright (c) 2009-2010 Kevin B. Kenny +'\" Copyright (c) 2010 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH Load 3 8.6 Tcl "Tcl Library Procedures" +.BS +.SH NAME +Tcl_LoadFile, Tcl_FindSymbol \- platform-independent dynamic library loading +.SH SYNOPSIS +.nf +\fB#include <tcl.h>\fR +.sp +int +\fBTcl_LoadFile\fR(\fIinterp, pathPtr, symbols, flags, procPtrs, loadHandlePtr\fR) +.sp +void * +\fBTcl_FindSymbol\fR(\fIinterp, loadHandle, symbol\fR) +.SH ARGUMENTS +.AS Tcl_LoadHandle loadHandle in +.AP Tcl_Interp *interp in +Interpreter to use for reporting error messages. +.AP Tcl_Obj *pathPtr in +The name of the file to load. If it is a single name, the library search path +of the current environment will be used to resolve it. +.AP "const char *const" symbols[] in +Array of names of symbols to be resolved during the load of the library, or +NULL if no symbols are to be resolved. If an array is given, the last entry in +the array must be NULL. +.AP int flags in +Reserved for future expansion. Must be 0. +.AP void *procPtrs out +Points to an array that will hold the addresses of the functions described in +the \fIsymbols\fR argument. Should be NULL if no symbols are to be resolved. +.AP Tcl_LoadHandle *loadHandlePtr out +Points to a variable that will hold the handle to the abstract token +describing the library that has been loaded. +.AP Tcl_LoadHandle loadHandle in +Abstract token describing the library to look up a symbol in. +.AP "const char" *symbol in +The name of the symbol to look up. +.BE +.SH DESCRIPTION +.PP +\fBTcl_LoadFile\fR loads a file from the filesystem (including potentially any +virtual filesystem that has been installed) and provides a handle to it that +may be used in further operations. The \fIsymbols\fR array, if non-NULL, +supplies a set of names of symbols (typically functions) that must be resolved +from the library and which will be stored in the array indicated by +\fIprocPtrs\fR. If any of the symbols is not resolved, the loading of the file +will fail with an error message left in the interpreter (if that is non-NULL). +The result of \fBTcl_LoadFile\fR is a standard Tcl error code. The library may +be unloaded with \fBTcl_FSUnloadFile\fR. +.PP +\fBTcl_FindSymbol\fR locates a symbol in a loaded library and returns it. If +the symbol cannot be found, it returns NULL and sets an error message in the +given \fIinterp\fR (if that is non-NULL). Note that it is unsafe to use this +operation on a handle that has been passed to \fBTcl_FSUnloadFile\fR. +.SH "SEE ALSO" +Tcl_FSLoadFile(3), Tcl_FSUnloadFile(3), load(n), unload(n) +.SH KEYWORDS +binary code, loading, shared library +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: diff --git a/doc/Method.3 b/doc/Method.3 new file mode 100644 index 0000000..43b3609 --- /dev/null +++ b/doc/Method.3 @@ -0,0 +1,248 @@ +'\" +'\" Copyright (c) 2007 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH Tcl_Method 3 0.1 TclOO "TclOO Library Functions" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +Tcl_ClassSetConstructor, Tcl_ClassSetDestructor, Tcl_MethodDeclarerClass, Tcl_MethodDeclarerObject, Tcl_MethodIsPublic, Tcl_MethodIsType, Tcl_MethodName, Tcl_NewInstanceMethod, Tcl_NewMethod, Tcl_ObjectContextInvokeNext, Tcl_ObjectContextIsFiltering, Tcl_ObjectContextMethod, Tcl_ObjectContextObject, Tcl_ObjectContextSkippedArgs \- manipulate methods and method-call contexts +.SH SYNOPSIS +.nf +\fB#include <tclOO.h>\fR +.sp +Tcl_Method +\fBTcl_NewMethod\fR(\fIinterp, class, nameObj, isPublic, + methodTypePtr, clientData\fR) +.sp +Tcl_Method +\fBTcl_NewInstanceMethod\fR(\fIinterp, object, nameObj, isPublic, + methodTypePtr, clientData\fR) +.sp +\fBTcl_ClassSetConstructor\fR(\fIinterp, class, method\fR) +.sp +\fBTcl_ClassSetDestructor\fR(\fIinterp, class, method\fR) +.sp +Tcl_Class +\fBTcl_MethodDeclarerClass\fR(\fImethod\fR) +.sp +Tcl_Object +\fBTcl_MethodDeclarerObject\fR(\fImethod\fR) +.sp +Tcl_Obj * +\fBTcl_MethodName\fR(\fImethod\fR) +.sp +int +\fBTcl_MethodIsPublic\fR(\fImethod\fR) +.sp +int +\fBTcl_MethodIsType\fR(\fImethod, methodTypePtr, clientDataPtr\fR) +.sp +int +\fBTcl_ObjectContextInvokeNext\fR(\fIinterp, context, objc, objv, skip\fR) +.sp +int +\fBTcl_ObjectContextIsFiltering\fR(\fIcontext\fR) +.sp +Tcl_Method +\fBTcl_ObjectContextMethod\fR(\fIcontext\fR) +.sp +Tcl_Object +\fBTcl_ObjectContextObject\fR(\fIcontext\fR) +.sp +int +\fBTcl_ObjectContextSkippedArgs\fR(\fIcontext\fR) +.SH ARGUMENTS +.AS ClientData clientData in +.AP Tcl_Interp *interp in/out +The interpreter holding the object or class to create or update a method in. +.AP Tcl_Object object in +The object to create the method in. +.AP Tcl_Class class in +The class to create the method in. +.AP Tcl_Obj *nameObj in +The name of the method to create. Should not be NULL unless creating +constructors or destructors. +.AP int isPublic in +A boolean flag saying whether the method is to be exported. +.AP Tcl_MethodType *methodTypePtr in +A description of the type of the method to create, or the type of method to +compare against. +.AP ClientData clientData in +A piece of data that is passed to the implementation of the method without +interpretation. +.AP ClientData *clientDataPtr out +A pointer to a variable in which to write the \fIclientData\fR value supplied +when the method was created. If NULL, the \fIclientData\fR value will not be +retrieved. +.AP Tcl_Method method in +A reference to a method to query. +.AP Tcl_ObjectContext context in +A reference to a method-call context. Note that client code \fImust not\fR +retain a reference to a context. +.AP int objc in +The number of arguments to pass to the method implementation. +.AP "Tcl_Obj *const" *objv in +An array of arguments to pass to the method implementation. +.AP int skip in +The number of arguments passed to the method implementation that do not +represent "real" arguments. +.BE +.SH DESCRIPTION +.PP +A method is an operation carried out on an object that is associated with the +object. Every method must be attached to either an object or a class; methods +attached to a class are associated with all instances (direct and indirect) of +that class. +.PP +Given a method, the entity that declared it can be found using +\fBTcl_MethodDeclarerClass\fR which returns the class that the method is +attached to (or NULL if the method is not attached to any class) and +\fBTcl_MethodDeclarerObject\fR which returns the object that the method is +attached to (or NULL if the method is not attached to an object). The name of +the method can be retrieved with \fBTcl_MethodName\fR and whether the method +is exported is retrieved with \fBTcl_MethodIsPublic\fR. The type of the method +can also be introspected upon to a limited degree; the function +\fBTcl_MethodIsType\fR returns whether a method is of a particular type, +assigning the per-method \fIclientData\fR to the variable pointed to by +\fIclientDataPtr\fR if (that is non-NULL) if the type is matched. +.SS "METHOD CREATION" +.PP +Methods are created by \fBTcl_NewMethod\fR and \fBTcl_NewInstanceMethod\fR, +which +create a method attached to a class or an object respectively. In both cases, +the \fInameObj\fR argument gives the name of the method to create, the +\fIisPublic\fR argument states whether the method should be exported +initially, the \fImethodTypePtr\fR argument describes the implementation of +the method (see the \fBMETHOD TYPES\fR section below) and the \fIclientData\fR +argument gives some implementation-specific data that is passed on to the +implementation of the method when it is called. +.PP +When the \fInameObj\fR argument to \fBTcl_NewMethod\fR is NULL, an +unnamed method is created, which is used for constructors and destructors. +Constructors should be installed into their class using the +\fBTcl_ClassSetConstructor\fR function, and destructors (which must not +require any arguments) should be installed into their class using the +\fBTcl_ClassSetDestructor\fR function. Unnamed methods should not be used for +any other purpose, and named methods should not be used as either constructors +or destructors. Also note that a NULL \fImethodTypePtr\fR is used to provide +internal signaling, and should not be used in client code. +.SS "METHOD CALL CONTEXTS" +.PP +When a method is called, a method-call context reference is passed in as one +of the arguments to the implementation function. This context can be inspected +to provide information about the caller, but should not be retained beyond the +moment when the method call terminates. +.PP +The method that is being called can be retrieved from the context by using +\fBTcl_ObjectContextMethod\fR, and the object that caused the method to be +invoked can be retrieved with \fBTcl_ObjectContextObject\fR. The number of +arguments that are to be skipped (e.g. the object name and method name in a +normal method call) is read with \fBTcl_ObjectContextSkippedArgs\fR, and the +context can also report whether it is working as a filter for another method +through \fBTcl_ObjectContextIsFiltering\fR. +.PP +During the execution of a method, the method implementation may choose to +invoke the stages of the method call chain that come after the current method +implementation. This (the core of the \fBnext\fR command) is done using +\fBTcl_ObjectContextInvokeNext\fR. Note that this function does not manipulate +the call-frame stack, unlike the \fBnext\fR command; if the method +implementation has pushed one or more extra frames on the stack as part of its +implementation, it is also responsible for temporarily popping those frames +from the stack while the \fBTcl_ObjectContextInvokeNext\fR function is +executing. Note also that the method-call context is \fInever\fR deleted +during the execution of this function. +.SH "METHOD TYPES" +.PP +The types of methods are described by a pointer to a Tcl_MethodType structure, +which is defined as: +.PP +.CS +typedef struct { + int \fIversion\fR; + const char *\fIname\fR; + Tcl_MethodCallProc *\fIcallProc\fR; + Tcl_MethodDeleteProc *\fIdeleteProc\fR; + Tcl_CloneProc *\fIcloneProc\fR; +} \fBTcl_MethodType\fR; +.CE +.PP +The \fIversion\fR field allows for future expansion of the structure, and +should always be declared equal to TCL_OO_METHOD_VERSION_CURRENT. The +\fIname\fR field provides a human-readable name for the type, and is reserved +for debugging. +.PP +The \fIcallProc\fR field gives a function that is called when the method is +invoked; it must never be NULL. +.PP +The \fIdeleteProc\fR field gives a function that is used to delete a +particular method, and is called when the method is replaced or removed; if +the field is NULL, it is assumed that the method's \fIclientData\fR needs no +special action to delete. +.PP +The \fIcloneProc\fR field is either a function that is used to copy a method's +\fIclientData\fR (as part of \fBTcl_CopyObjectInstance\fR) or NULL to indicate +that the \fIclientData\fR can just be copied directly. +.SS "TCL_METHODCALLPROC FUNCTION SIGNATURE" +.PP +Functions matching this signature are called when the method is invoked. +.PP +.CS +typedef int \fBTcl_MethodCallProc\fR( + ClientData \fIclientData\fR, + Tcl_Interp *\fIinterp\fR, + Tcl_ObjectContext \fIobjectContext\fR, + int \fIobjc\fR, + Tcl_Obj *const *\fIobjv\fR); +.CE +.PP +The \fIclientData\fR argument to a Tcl_MethodCallProc is the value that was +given when the method was created, the \fIinterp\fR is a place in which to +execute scripts and access variables as well as being where to put the result +of the method, and the \fIobjc\fR and \fIobjv\fR fields give the parameter +objects to the method. The calling context of the method can be discovered +through the \fIobjectContext\fR argument, and the return value from a +Tcl_MethodCallProc is any Tcl return code (e.g. TCL_OK, TCL_ERROR). +.SS "TCL_METHODDELETEPROC FUNCTION SIGNATURE" +.PP +Functions matching this signature are used when a method is deleted, whether +through a new method being created or because the object or class is deleted. +.PP +.CS +typedef void \fBTcl_MethodDeleteProc\fR( + ClientData \fIclientData\fR); +.CE +.PP +The \fIclientData\fR argument to a Tcl_MethodDeleteProc will be the same as +the value passed to the \fIclientData\fR argument to \fBTcl_NewMethod\fR or +\fBTcl_NewInstanceMethod\fR when the method was created. +.SS "TCL_CLONEPROC FUNCTION SIGNATURE" +.PP +Functions matching this signature are used to copy a method when the object or +class is copied using \fBTcl_CopyObjectInstance\fR (or \fBoo::copy\fR). +.PP +.CS +typedef int \fBTcl_CloneProc\fR( + Tcl_Interp *\fIinterp\fR, + ClientData \fIoldClientData\fR, + ClientData *\fInewClientDataPtr\fR); +.CE +.PP +The \fIinterp\fR argument gives a place to write an error message when the +attempt to clone the object is to fail, in which case the clone procedure must +also return TCL_ERROR; it should return TCL_OK otherwise. +The \fIoldClientData\fR field to a Tcl_CloneProc gives the value from the +method being copied from, and the \fInewClientDataPtr\fR field will point to +a variable in which to write the value for the method being copied to. +.SH "SEE ALSO" +Class(3), oo::class(n), oo::define(n), oo::object(n) +.SH KEYWORDS +constructor, method, object + +.\" Local variables: +.\" mode: nroff +.\" fill-column: 78 +.\" End: diff --git a/doc/NRE.3 b/doc/NRE.3 new file mode 100644 index 0000000..5c27491 --- /dev/null +++ b/doc/NRE.3 @@ -0,0 +1,328 @@ +.\" +.\" Copyright (c) 2008 by Kevin B. Kenny. +.\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH NRE 3 8.6 Tcl "Tcl Library Procedures" +.BS +.SH NAME +Tcl_NRCreateCommand, Tcl_NRCallObjProc, Tcl_NREvalObj, Tcl_NREvalObjv, Tcl_NRCmdSwap, Tcl_NRAddCallback \- Non-Recursive (stackless) evaluation of Tcl scripts. +.SH SYNOPSIS +.nf +\fB#include <tcl.h>\fR +.sp +Tcl_Command +\fBTcl_NRCreateCommand\fR(\fIinterp, cmdName, proc, nreProc, clientData, + deleteProc\fR) +.sp +int +\fBTcl_NRCallObjProc\fR(\fIinterp, nreProc, clientData, objc, objv\fR) +.sp +int +\fBTcl_NREvalObj\fR(\fIinterp, objPtr, flags\fR) +.sp +int +\fBTcl_NREvalObjv\fR(\fIinterp, objc, objv, flags\fR) +.sp +int +\fBTcl_NRCmdSwap\fR(\fIinterp, cmd, objc, objv, flags\fR) +.sp +int +\fBTcl_NRExprObj\fR(\fIinterp, objPtr, resultPtr\fR) +.sp +void +\fBTcl_NRAddCallback\fR(\fIinterp, postProcPtr, data0, data1, data2, data3\fR) +.fi +.SH ARGUMENTS +.AS Tcl_CmdDeleteProc *interp in +.AP Tcl_Interp *interp in +Interpreter in which to create or evaluate a command. +.AP char *cmdName in +Name of a new command to create. +.AP Tcl_ObjCmdProc *proc in +Implementation of a command that will be called whenever \fIcmdName\fR +is invoked as a command in the unoptimized way. +.AP Tcl_ObjCmdProc *nreProc in +Implementation of a command that will be called whenever \fIcmdName\fR +is invoked and requested to conserve the C stack. +.AP ClientData clientData in +Arbitrary one-word value that will be passed to \fIproc\fR, \fInreProc\fR, +\fIdeleteProc\fR and \fIobjProc\fR. +.AP Tcl_CmdDeleteProc *deleteProc in/out +Procedure to call before \fIcmdName\fR is deleted from the interpreter. +This procedure allows for command-specific cleanup. If \fIdeleteProc\fR +is \fBNULL\fR, then no procedure is called before the command is deleted. +.AP int objc in +Count of parameters provided to the implementation of a command. +.AP Tcl_Obj **objv in +Pointer to an array of Tcl objects. Each object holds the value of a +single word in the command to execute. +.AP Tcl_Obj *objPtr in +Pointer to a Tcl_Obj whose value is a script or expression to execute. +.AP int flags in +ORed combination of flag bits that specify additional options. +\fBTCL_EVAL_GLOBAL\fR is the only flag that is currently supported. +.\" TODO: This is a lie. But kbk didn't grasp TCL_EVAL_INVOKE and +.\" TCL_EVAL_NOERR well enough to document them. +.AP Tcl_Command cmd in +Token for a command that is to be used instead of the currently +executing command. +.AP Tcl_Obj *resultPtr out +Pointer to an unshared Tcl_Obj where the result of expression +evaluation is written. +.AP Tcl_NRPostProc *postProcPtr in +Pointer to a function that will be invoked when the command currently +executing in the interpreter designated by \fIinterp\fR completes. +.AP ClientData data0 in +.AP ClientData data1 in +.AP ClientData data2 in +.AP ClientData data3 in +\fIdata0\fR through \fIdata3\fR are four one-word values that will be passed +to the function designated by \fIpostProcPtr\fR when it is invoked. +.BE +.SH DESCRIPTION +.PP +This series of C functions provides an interface whereby commands that +are implemented in C can be evaluated, and invoke Tcl commands scripts +and scripts, without consuming space on the C stack. The non-recursive +evaluation is done by installing a \fItrampoline\fR, a small piece of +code that invokes a command or script, and then executes a series of +callbacks when the command or script returns. +.PP +The \fBTcl_NRCreateCommand\fR function creates a Tcl command in the +interpreter designated by \fIinterp\fR that is prepared to handle +nonrecursive evaluation with a trampoline. The \fIcmdName\fR argument +gives the name of the new command. If \fIcmdName\fR contains any +namespace qualifiers, then the new command is added to the specified +namespace; otherwise, it is added to the global namespace. \fIproc\fR +gives the procedure that will be called when the interpreter wishes to +evaluate the command in an unoptimized manner, and \fInreProc\fR is +the procedure that will be called when the interpreter wishes to +evaluate the command using a trampoline. \fIdeleteProc\fR is a +function that will be called before the command is deleted from the +interpreter. When any of the three functions is invoked, it is passed +the \fIclientData\fR parameter. +.PP +\fBTcl_NRCreateCommand\fR deletes any existing command +\fIname\fR already associated with the interpreter +(however see below for an exception where the existing command +is not deleted). +It returns a token that may be used to refer +to the command in subsequent calls to \fBTcl_GetCommandName\fR. +If \fBTcl_NRCreateCommand\fR is called for an interpreter that is in +the process of being deleted, then it does not create a new command, +does not delete any existing command of the same name, and returns NULL. +.PP +The \fIproc\fR and \fInreProc\fR function are expected to conform to +all the rules set forth for the \fIproc\fR argument to +\fBTcl_CreateObjCommand\fR(3) (\fIq.v.\fR). +.PP +When a command that is written to cope with evaluation via trampoline +is invoked without a trampoline on the stack, it will usually respond +to the invocation by creating a trampoline and calling the +trampoline-enabled implementation of the same command. This call is done by +means of \fBTcl_NRCallObjProc\fR. In the call to +\fBTcl_NRCallObjProc\fR, the \fIinterp\fR, \fIclientData\fR, +\fIobjc\fR and \fIobjv\fR parameters should be the same ones that were +passed to \fIproc\fR. The \fInreProc\fR parameter should designate the +trampoline-enabled implementation of the command. +.PP +\fBTcl_NREvalObj\fR arranges for the script contained in \fIobjPtr\fR +to be evaluated in the interpreter designated by \fIinterp\fR after +the current command (which must be trampoline-enabled) returns. It is +the method by which a command may invoke a script without consuming +space on the C stack. Similarly, \fBTcl_NREvalObjv\fR arranges to +invoke a single Tcl command whose words have already been separated +and substituted. The \fIobjc\fR and \fIobjv\fR parameters give the +words of the command to be evaluated when execution reaches the +trampoline. +.PP +\fBTcl_NRCmdSwap\fR allows for trampoline evaluation of a command whose +resolution is already known. The \fIcmd\fR parameter gives a +\fBTcl_Command\fR object (returned from \fBTcl_CreateObjCommand\fR or +\fBTcl_GetCommandFromObj\fR) identifying the command to be invoked in +the trampoline; this command must match the word in \fIobjv[0]\fR. +The remaining arguments are as for \fBTcl_NREvalObj\fR. +.PP +\fBTcl_NREvalObj\fR, \fBTcl_NREvalObjv\fR and \fBTcl_NRCmdSwap\fR +all accept a \fIflags\fR parameter, which is an OR-ed-together set of +bits to control evaluation. At the present time, the only supported flag +available to callers is \fBTCL_EVAL_GLOBAL\fR. +.\" TODO: Again, this is a lie. Do we want to explain TCL_EVAL_INVOKE +.\" and TCL_EVAL_NOERR? +If the \fBTCL_EVAL_GLOBAL\fR flag is set, the script or command is +evaluated in the global namespace. If it is not set, it is evaluated +in the current namespace. +.PP +\fBTcl_NRExprObj\fR arranges for the expression contained in \fIobjPtr\fR +to be evaluated in the interpreter designated by \fIinterp\fR after +the current command (which must be trampoline-enabled) returns. It is +the method by which a command may evaluate a Tcl expression without consuming +space on the C stack. The argument \fIresultPtr\fR is a pointer to an +unshared Tcl_Obj where the result of expression evaluation is to be written. +If expression evaluation returns any code other than TCL_OK, the +\fIresultPtr\fR value is left untouched. +.PP +All of the routines return \fBTCL_OK\fR if command or expression invocation +has been scheduled successfully. If for any reason the scheduling cannot +be completed (for example, if the interpreter is unable to find +the requested command), they return \fBTCL_ERROR\fR with an +appropriate message left in the interpreter's result. +.PP +\fBTcl_NRAddCallback\fR arranges to have a C function called when the +current trampoline-enabled command in the Tcl interpreter designated +by \fIinterp\fR returns. The \fIpostProcPtr\fR argument is a pointer +to the callback function, which must have arguments and return value +consistent with the \fBTcl_NRPostProc\fR data type: +.PP +.CS +typedef int +\fBTcl_NRPostProc\fR( + \fBClientData\fR \fIdata\fR[], + \fBTcl_Interp\fR *\fIinterp\fR, + int \fIresult\fR); +.CE +.PP +When the trampoline invokes the callback function, the \fIdata\fR +parameter will point to an array containing the four one-word +quantities that were passed to \fBTcl_NRAddCallback\fR in the +\fIdata0\fR through \fIdata3\fR parameters. The Tcl interpreter will +be designated by the \fIinterp\fR parameter, and the \fIresult\fR +parameter will contain the result (\fBTCL_OK\fR, \fBTCL_ERROR\fR, +\fBTCL_RETURN\fR, \fBTCL_BREAK\fR or \fBTCL_CONTINUE\fR) that was +returned by the command evaluation. The callback function is expected, +in turn, either to return a \fIresult\fR to control further evaluation. +.PP +Multiple \fBTcl_NRAddCallback\fR invocations may request multiple +callbacks, which may be to the same or different callback +functions. If multiple callbacks are requested, they are executed in +last-in, first-out order, that is, the most recently requested +callback is executed first. +.SH EXAMPLE +.PP +The usual pattern for Tcl commands that invoke other Tcl commands +is something like: +.PP +.CS +int +\fITheCmdObjProc\fR( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const objv[]) +{ + int result; + Tcl_Obj *objPtr; + + \fI... preparation ...\fR + + result = \fBTcl_EvalObjEx\fR(interp, objPtr, 0); + + \fI... postprocessing ...\fR + + return result; +} +\fBTcl_CreateObjCommand\fR(interp, "theCommand", + \fITheCmdObjProc\fR, clientData, TheCmdDeleteProc); +.CE +.PP +To enable a command like this one for trampoline-based evaluation, +it must be split into three pieces: +.IP \(bu +A non-trampoline implementation, \fITheCmdNewObjProc\fR, +which will simply create a trampoline +and invoke the trampoline-based implementation. +.IP \(bu +A trampoline-enabled implementation, \fITheCmdNRObjProc\fR. This +function will perform the initialization, request that the trampoline +call the postprocessing routine after command evaluation, and finally, +request that the trampoline call the inner command. +.IP \(bu +A postprocessing routine, \fITheCmdPostProc\fR. This function will +perform the postprocessing formerly done after the return from the +inner command in \fITheCmdObjProc\fR. +.PP +The non-trampoline implementation is simple and stylized, containing +a single statement: +.PP +.CS +int +\fITheCmdNewObjProc\fR( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const objv[]) +{ + return \fBTcl_NRCallObjProc\fR(interp, name, + \fITheCmdNRObjProc\fR, clientData, objc, objv); +} +.CE +.PP +The trampoline-enabled implementation requests postprocessing, +and returns to the trampoline requesting command evaluation. +.PP +.CS +int +\fITheCmdNRObjProc\fR + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const objv[]) +{ + Tcl_Obj *objPtr; + + \fI... preparation ...\fR + + \fBTcl_NRAddCallback\fR(interp, \fITheCmdPostProc\fR, + data0, data1, data2, data3); + /* \fIdata0 .. data3\fR are up to four one-word items to + * pass to the postprocessing procedure */ + + return \fBTcl_NREvalObj\fR(interp, objPtr, 0); +} +.CE +.PP +The postprocessing procedure does whatever the original command did +upon return from the inner evaluation. +.PP +.CS +int +\fITheCmdNRPostProc\fR( + ClientData data[], + Tcl_Interp *interp, + int result) +{ + /* \fIdata[0] .. data[3]\fR are the four words of data + * passed to \fBTcl_NREvalObj\fR */ + + \fI... postprocessing ...\fR + + return result; +} +.CE +.PP +If \fItheCommand\fR is a command that results in multiple commands or +scripts being evaluated, its postprocessing routine may schedule +additional postprocessing and then request another command evaluation +by means of \fBTcl_NREvalObj\fR or one of the other evaluation +routines. Looping and sequencing constructs may be implemented in this way. +.PP +Finally, to install a trampoline-enabled command in the interpreter, +\fBTcl_NRCreateCommand\fR is used in place of +\fBTcl_CreateObjCommand\fR. It accepts two command procedures instead +of one. The first is for use when no trampoline is yet on the stack, +and the second is for use when there is already a trampoline in place. +.PP +.CS +\fBTcl_NRCreateCommand\fR(interp, "theCommand", + \fITheCmdObjProc\fR, \fITheCmdNRObjProc\fR, clientData, + TheCmdDeleteProc); +.CE +.SH "SEE ALSO" +Tcl_CreateCommand(3), Tcl_CreateObjCommand(3), Tcl_EvalObjEx(3), Tcl_GetCommandFromObj(3), Tcl_ExprObj(3) +.SH KEYWORDS +stackless, nonrecursive, execute, command, global, object, result, script +.SH COPYRIGHT +Copyright (c) 2008 by Kevin B. Kenny diff --git a/doc/Namespace.3 b/doc/Namespace.3 index 5477329..50cc559 100644 --- a/doc/Namespace.3 +++ b/doc/Namespace.3 @@ -95,7 +95,6 @@ message should be left in the interpreter if the search fails.) A script fragment to be installed as the unknown command handler for the namespace, or NULL to reset the handler to its default. .BE - .SH DESCRIPTION .PP Namespaces are hierarchic naming contexts that can contain commands @@ -115,11 +114,14 @@ the global namespace.) .PP \fBTcl_CreateNamespace\fR creates a new namespace. The \fIdeleteProc\fR will have the following type signature: +.PP .CS -typedef void (Tcl_NamespaceDeleteProc) (ClientData clientData); +typedef void \fBTcl_NamespaceDeleteProc\fR( + ClientData \fIclientData\fR); .CE .PP -\fBTcl_DeleteNamespace\fR deletes a namespace. +\fBTcl_DeleteNamespace\fR deletes a namespace, calling the +\fIdeleteProc\fR defined for the namespace (if any). .PP \fBTcl_AppendExportList\fR retrieves the export patterns for a namespace given namespace and appends them (as list items) to @@ -157,9 +159,7 @@ for the namespace, or NULL if none is set. \fBTcl_SetNamespaceUnknownHandler\fR sets the unknown command handler for the namespace. If \fIhandlerPtr\fR is NULL, then the handler is reset to its default. - .SH "SEE ALSO" -Tcl_CreateCommand, Tcl_ListObjAppendElements, Tcl_SetVar - +Tcl_CreateCommand(3), Tcl_ListObjAppendList(3), Tcl_SetVar(3) .SH KEYWORDS namespace, command diff --git a/doc/Notifier.3 b/doc/Notifier.3 index 7858a8c..435f779 100644 --- a/doc/Notifier.3 +++ b/doc/Notifier.3 @@ -81,7 +81,7 @@ queues them. .AP ClientData clientData in Arbitrary one-word value to pass to \fIsetupProc\fR, \fIcheckProc\fR, or \fIdeleteProc\fR. -.AP Tcl_Time *timePtr in +.AP "const Tcl_Time" *timePtr in Indicates the maximum amount of time to wait for an event. This is specified as an interval (how long to wait), not an absolute time (when to wakeup). If the pointer passed to \fBTcl_WaitForEvent\fR @@ -108,7 +108,6 @@ Structure of function pointers describing notifier procedures that are to replace the ones installed in the executable. See \fBREPLACING THE NOTIFIER\fR for details. .BE - .SH INTRODUCTION .PP The interfaces described here are used to customize the Tcl event @@ -215,7 +214,6 @@ return. .IP [7] Either return 0 to indicate that no events were ready, or go back to step [2] if blocking was requested by the caller. - .SH "CREATING A NEW EVENT SOURCE" .PP An event source consists of three procedures invoked by the notifier, @@ -229,11 +227,13 @@ The procedure \fBTcl_CreateEventSource\fR creates a new event source. Its arguments specify the setup procedure and check procedure for the event source. \fISetupProc\fR should match the following prototype: +.PP .CS -typedef void Tcl_EventSetupProc( +typedef void \fBTcl_EventSetupProc\fR( ClientData \fIclientData\fR, int \fIflags\fR); .CE +.PP The \fIclientData\fR argument will be the same as the \fIclientData\fR argument to \fBTcl_CreateEventSource\fR; it is typically used to point to private information managed by the event source. @@ -268,12 +268,14 @@ connection. The \fItimePtr\fR argument to \fBTcl_WaitForEvent\fR points to a structure that describes a time interval in seconds and microseconds: +.PP .CS typedef struct Tcl_Time { - long \fIsec\fR; - long \fIusec\fR; -} Tcl_Time; + long \fIsec\fR; + long \fIusec\fR; +} \fBTcl_Time\fR; .CE +.PP The \fIusec\fR field should be less than 1000000. .PP Information provided to \fBTcl_SetMaxBlockTime\fR @@ -303,11 +305,13 @@ The second procedure provided by each event source is its check procedure, indicated by the \fIcheckProc\fR argument to \fBTcl_CreateEventSource\fR. \fICheckProc\fR must match the following prototype: +.PP .CS -typedef void Tcl_EventCheckProc( +typedef void \fBTcl_EventCheckProc\fR( ClientData \fIclientData\fR, int \fIflags\fR); .CE +.PP The arguments to this procedure are the same as those for \fIsetupProc\fR. \fBCheckProc\fR is invoked by \fBTcl_DoOneEvent\fR after it has waited for events. Presumably at least one event source is now prepared to @@ -326,12 +330,14 @@ to that event source. However, the first element of the structure must be a structure of type \fBTcl_Event\fR, and the address of this structure is used when communicating between the event source and the rest of the notifier. A \fBTcl_Event\fR has the following definition: +.PP .CS typedef struct { Tcl_EventProc *\fIproc\fR; struct Tcl_Event *\fInextPtr\fR; -} Tcl_Event; +} \fBTcl_Event\fR; .CE +.PP The event source must fill in the \fIproc\fR field of the event before calling \fBTcl_QueueEvent\fR. The \fInextPtr\fR is used to link together the events in the queue @@ -359,11 +365,13 @@ When it is time to handle an event from the queue (steps 1 and 4 above) \fBTcl_ServiceEvent\fR will invoke the \fIproc\fR specified in the first queued \fBTcl_Event\fR structure. \fIProc\fR must match the following prototype: +.PP .CS -typedef int Tcl_EventProc( +typedef int \fBTcl_EventProc\fR( Tcl_Event *\fIevPtr\fR, int \fIflags\fR); .CE +.PP The first argument to \fIproc\fR is a pointer to the event, which will be the same as the first argument to the \fBTcl_QueueEvent\fR call that added the event to the queue. @@ -403,7 +411,7 @@ an event to the current thread's queue. To add an event to another thread's queue, use \fBTcl_ThreadQueueEvent\fR. \fBTcl_ThreadQueueEvent\fR accepts as an argument a Tcl_ThreadId argument, which uniquely identifies a thread in a Tcl application. To obtain the -Tcl_ThreadID for the current thread, use the \fBTcl_GetCurrentThread\fR +Tcl_ThreadId for the current thread, use the \fBTcl_GetCurrentThread\fR procedure. (A thread would then need to pass this identifier to other threads for those threads to be able to add events to its queue.) After adding an event to another thread's queue, you then typically @@ -416,11 +424,13 @@ events from the event queue. \fBTcl_DeleteEvents\fR calls \fIproc\fR for each event in the queue, deleting those for with the procedure returns 1. Events for which the procedure returns 0 are left in the queue. \fIProc\fR should match the following prototype: +.PP .CS -typedef int Tcl_EventDeleteProc( +typedef int \fBTcl_EventDeleteProc\fR( Tcl_Event *\fIevPtr\fR, ClientData \fIclientData\fR); .CE +.PP The \fIclientData\fR argument will be the same as the \fIclientData\fR argument to \fBTcl_DeleteEvents\fR; it is typically used to point to private information managed by the event source. The \fIevPtr\fR will @@ -430,7 +440,6 @@ point to the next event in the queue. \fIcheckProc\fR, and \fIclientData\fR arguments must exactly match those provided to the \fBTcl_CreateEventSource\fR for the event source to be deleted. If no such source exists, \fBTcl_DeleteEventSource\fR has no effect. - .SH "CREATING A NEW NOTIFIER" .PP The notifier consists of all the procedures described in this manual @@ -526,7 +535,6 @@ in their respective manual pages. The easiest way to create a new notifier is to look at the code for an existing notifier, such as the files \fBunix/tclUnixNotfy.c\fR or \fBwin/tclWinNotify.c\fR in the Tcl source distribution. - .SH "REPLACING THE NOTIFIER" .PP A notifier that has been written according to the conventions above @@ -539,18 +547,20 @@ to another program, such as a Web browser plugin. To do this, the extension makes a call to \fBTcl_SetNotifier\fR passing a pointer to a \fBTcl_NotifierProcs\fR data structure. The structure has the following layout: +.PP .CS typedef struct Tcl_NotifierProcs { - Tcl_SetTimerProc *setTimerProc; - Tcl_WaitForEventProc *waitForEventProc; - Tcl_CreateFileHandlerProc *createFileHandlerProc; - Tcl_DeleteFileHandlerProc *deleteFileHandlerProc; - Tcl_InitNotifierProc *initNotifierProc; - Tcl_FinalizeNotifierProc *finalizeNotifierProc; - Tcl_AlertNotifierProc *alertNotifierProc; - Tcl_ServiceModeHookProc *serviceModeHookProc; -} Tcl_NotifierProcs; + Tcl_SetTimerProc *\fIsetTimerProc\fR; + Tcl_WaitForEventProc *\fIwaitForEventProc\fR; + Tcl_CreateFileHandlerProc *\fIcreateFileHandlerProc\fR; + Tcl_DeleteFileHandlerProc *\fIdeleteFileHandlerProc\fR; + Tcl_InitNotifierProc *\fIinitNotifierProc\fR; + Tcl_FinalizeNotifierProc *\fIfinalizeNotifierProc\fR; + Tcl_AlertNotifierProc *\fIalertNotifierProc\fR; + Tcl_ServiceModeHookProc *\fIserviceModeHookProc\fR; +} \fBTcl_NotifierProcs\fR; .CE +.PP Following the call to \fBTcl_SetNotifier\fR, the pointers given in the \fBTcl_NotifierProcs\fR structure replace whatever notifier had been installed in the process. @@ -558,7 +568,6 @@ been installed in the process. It is extraordinarily unwise to replace a running notifier. Normally, \fBTcl_SetNotifier\fR should be called at process initialization time before the first call to \fBTcl_InitNotifier\fR. - .SH "EXTERNAL EVENT LOOPS" .PP The notifier interfaces are designed so that Tcl can be embedded into @@ -619,9 +628,8 @@ then calls to \fBTcl_ServiceAll\fR will behave normally. mode, which should be restored when the recursive loop exits. \fBTcl_GetServiceMode\fR returns the current value of the service mode. - .SH "SEE ALSO" -\fBTcl_CreateFileHandler\fR, \fBTcl_DeleteFileHandler\fR, \fBTcl_Sleep\fR, -\fBTcl_DoOneEvent\fR, \fBThread(3)\fR +Tcl_CreateFileHandler(3), Tcl_DeleteFileHandler(3), Tcl_Sleep(3), +Tcl_DoOneEvent(3), Thread(3) .SH KEYWORDS event, notifier, event queue, event sources, file events, timer, idle, service mode, threads diff --git a/doc/Object.3 b/doc/Object.3 index 4817b9b..1c60449 100644 --- a/doc/Object.3 +++ b/doc/Object.3 @@ -33,7 +33,6 @@ int Points to an object; must have been the result of a previous call to \fBTcl_NewObj\fR. .BE - .SH INTRODUCTION .PP This man page presents an overview of Tcl objects and how they are used. @@ -108,28 +107,30 @@ by defining their own \fBTcl_ObjType\fR structs. .PP Each Tcl object is represented by a \fBTcl_Obj\fR structure which is defined as follows. +.PP .CS typedef struct Tcl_Obj { - int \fIrefCount\fR; - char *\fIbytes\fR; - int \fIlength\fR; - Tcl_ObjType *\fItypePtr\fR; - union { - long \fIlongValue\fR; - double \fIdoubleValue\fR; - void *\fIotherValuePtr\fR; - Tcl_WideInt \fIwideValue\fR; - struct { - void *\fIptr1\fR; - void *\fIptr2\fR; - } \fItwoPtrValue\fR; - struct { - void *\fIptr\fR; - unsigned long \fIvalue\fR; - } \fIptrAndLongRep\fR; - } \fIinternalRep\fR; -} Tcl_Obj; + int \fIrefCount\fR; + char *\fIbytes\fR; + int \fIlength\fR; + const Tcl_ObjType *\fItypePtr\fR; + union { + long \fIlongValue\fR; + double \fIdoubleValue\fR; + void *\fIotherValuePtr\fR; + Tcl_WideInt \fIwideValue\fR; + struct { + void *\fIptr1\fR; + void *\fIptr2\fR; + } \fItwoPtrValue\fR; + struct { + void *\fIptr\fR; + unsigned long \fIvalue\fR; + } \fIptrAndLongRep\fR; + } \fIinternalRep\fR; +} \fBTcl_Obj\fR; .CE +.PP The \fIbytes\fR and the \fIlength\fR members together hold an object's UTF-8 string representation, which is a \fIcounted string\fR not containing null bytes (UTF-8 null @@ -231,20 +232,26 @@ to see how to create a new object type. .PP As an example of the lifetime of an object, consider the following sequence of commands: +.PP .CS \fBset x 123\fR .CE +.PP This assigns to \fIx\fR an untyped object whose \fIbytes\fR member points to \fB123\fR and \fIlength\fR member contains 3. The object's \fItypePtr\fR member is NULL. +.PP .CS \fBputs "x is $x"\fR .CE +.PP \fIx\fR's string representation is valid (since \fIbytes\fR is non-NULL) and is fetched for the command. +.PP .CS \fBincr x\fR .CE +.PP The \fBincr\fR command first gets an integer from \fIx\fR's object by calling \fBTcl_GetIntFromObj\fR. This procedure checks whether the object is already an integer object. @@ -259,9 +266,11 @@ then invalidates its string representation (by calling \fBTcl_InvalidateStringRep\fR) since the string representation no longer corresponds to the internal representation. +.PP .CS \fBputs "x is now $x"\fR .CE +.PP The string representation of \fIx\fR's object is needed and is recomputed. The string representation is now \fB124\fR @@ -323,8 +332,8 @@ by inserting \fIobjc-3\fR new elements before \fIindex\fR. .PP .CS listPtr = objv[1]; -if (Tcl_IsShared(listPtr)) { - listPtr = Tcl_DuplicateObj(listPtr); +if (\fBTcl_IsShared\fR(listPtr)) { + listPtr = \fBTcl_DuplicateObj\fR(listPtr); } result = Tcl_ListObjReplace(interp, listPtr, index, 0, (objc-3), &(objv[3])); diff --git a/doc/ObjectType.3 b/doc/ObjectType.3 index 974ea6c..0c11187 100644 --- a/doc/ObjectType.3 +++ b/doc/ObjectType.3 @@ -15,7 +15,7 @@ Tcl_RegisterObjType, Tcl_GetObjType, Tcl_AppendAllObjTypes, Tcl_ConvertToType \ .sp \fBTcl_RegisterObjType\fR(\fItypePtr\fR) .sp -Tcl_ObjType * +const Tcl_ObjType * \fBTcl_GetObjType\fR(\fItypeName\fR) .sp int @@ -25,7 +25,7 @@ int \fBTcl_ConvertToType\fR(\fIinterp, objPtr, typePtr\fR) .SH ARGUMENTS .AS "const char" *typeName -.AP Tcl_ObjType *typePtr in +.AP "const Tcl_ObjType" *typePtr in Points to the structure containing information about the Tcl object type. This storage must live forever, typically by being statically allocated. @@ -105,12 +105,12 @@ The \fBTcl_ObjType\fR structure is defined as follows: .PP .CS typedef struct Tcl_ObjType { - char *\fIname\fR; + const char *\fIname\fR; Tcl_FreeInternalRepProc *\fIfreeIntRepProc\fR; Tcl_DupInternalRepProc *\fIdupIntRepProc\fR; Tcl_UpdateStringProc *\fIupdateStringProc\fR; Tcl_SetFromAnyProc *\fIsetFromAnyProc\fR; -} Tcl_ObjType; +} \fBTcl_ObjType\fR; .CE .SS "THE NAME FIELD" .PP @@ -127,7 +127,8 @@ called to create a valid internal representation from an object's string representation. .PP .CS -typedef int (Tcl_SetFromAnyProc) (Tcl_Interp *\fIinterp\fR, +typedef int \fBTcl_SetFromAnyProc\fR( + Tcl_Interp *\fIinterp\fR, Tcl_Obj *\fIobjPtr\fR); .CE .PP @@ -161,7 +162,7 @@ replace it with a new one or reset the \fItypePtr\fR member to NULL. The \fIsetFromAnyProc\fR member may be set to NULL, if the routines making use of the internal representation have no need to derive that internal representation from an arbitrary string value. However, in -this case, passing a pointer to the type to Tcl_ConvertToType() will +this case, passing a pointer to the type to \fBTcl_ConvertToType\fR will lead to a panic, so to avoid this possibility, the type should \fInot\fR be registered. .SS "THE UPDATESTRINGPROC FIELD" @@ -171,7 +172,8 @@ called to create a valid string representation from an object's internal representation. .PP .CS -typedef void (Tcl_UpdateStringProc) (Tcl_Obj *\fIobjPtr\fR); +typedef void \fBTcl_UpdateStringProc\fR( + Tcl_Obj *\fIobjPtr\fR); .CE .PP \fIobjPtr\fR's \fIbytes\fR member is always NULL when it is called. @@ -204,7 +206,8 @@ The \fIdupIntRepProc\fR member contains the address of a function called to copy an internal representation from one object to another. .PP .CS -typedef void (Tcl_DupInternalRepProc) (Tcl_Obj *\fIsrcPtr\fR, +typedef void \fBTcl_DupInternalRepProc\fR( + Tcl_Obj *\fIsrcPtr\fR, Tcl_Obj *\fIdupPtr\fR); .CE .PP @@ -226,7 +229,8 @@ The \fIfreeIntRepProc\fR member contains the address of a function that is called when an object is freed. .PP .CS -typedef void (Tcl_FreeInternalRepProc) (Tcl_Obj *\fIobjPtr\fR); +typedef void \fBTcl_FreeInternalRepProc\fR( + Tcl_Obj *\fIobjPtr\fR); .CE .PP The \fIfreeIntRepProc\fR function can deallocate the storage @@ -246,6 +250,6 @@ uses of that field during object deletion. The defined tasks for the \fIfreeIntRepProc\fR have no need to consult the \fIbytes\fR member. .SH "SEE ALSO" -Tcl_NewObj, Tcl_DecrRefCount, Tcl_IncrRefCount +Tcl_NewObj(3), Tcl_DecrRefCount(3), Tcl_IncrRefCount(3) .SH KEYWORDS internal representation, object, object type, string representation, type conversion diff --git a/doc/OpenFileChnl.3 b/doc/OpenFileChnl.3 index 0d722f6..337a9a9 100644 --- a/doc/OpenFileChnl.3 +++ b/doc/OpenFileChnl.3 @@ -98,10 +98,8 @@ Tcl_WideInt Tcl_WideInt \fBTcl_Tell\fR(\fIchannel\fR) .sp -.VS 8.5 int \fBTcl_TruncateChannel\fR(\fIchannel, length\fR) -.VE 8.5 .sp int \fBTcl_GetChannelOption\fR(\fIinterp, channel, optionName, optionValue\fR) @@ -211,7 +209,6 @@ values. Must have been initialized by the caller. .AP "const char" *newValue in New value for the option given by \fIoptionName\fR. .BE - .SH DESCRIPTION .PP The Tcl channel mechanism provides a device-independent and @@ -229,7 +226,6 @@ The procedures described in this manual entry comprise the C APIs of the generic layer of the channel architecture. For a description of the channel driver architecture and how to implement channel drivers for new types of channels, see the manual entry for \fBTcl_CreateChannel\fR. - .SH TCL_OPENFILECHANNEL .PP \fBTcl_OpenFileChannel\fR opens a file specified by \fIfileName\fR and @@ -248,10 +244,9 @@ be used in preference to \fBTcl_OpenFileChannel\fR wherever possible. .PP The newly created channel is not registered in the supplied interpreter; to register it, use \fBTcl_RegisterChannel\fR, described below. -If one of the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was +If one of the standard channels, \fBstdin\fR, \fBstdout\fR or \fBstderr\fR was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. - .SH TCL_OPENCOMMANDCHANNEL .PP \fBTcl_OpenCommandChannel\fR provides a C-level interface to the @@ -286,20 +281,18 @@ the interpreter's result if \fIinterp\fR is not NULL. .PP The newly created channel is not registered in the supplied interpreter; to register it, use \fBTcl_RegisterChannel\fR, described below. -If one of the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was +If one of the standard channels, \fBstdin\fR, \fBstdout\fR or \fBstderr\fR was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. - .SH TCL_MAKEFILECHANNEL .PP \fBTcl_MakeFileChannel\fR makes a \fBTcl_Channel\fR from an existing, platform-specific, file handle. The newly created channel is not registered in the supplied interpreter; to register it, use \fBTcl_RegisterChannel\fR, described below. -If one of the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was +If one of the standard channels, \fBstdin\fR, \fBstdout\fR or \fBstderr\fR was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. - .SH TCL_GETCHANNEL .PP \fBTcl_GetChannel\fR returns a channel given the \fIchannelName\fR used to @@ -317,7 +310,6 @@ according to the \fIpattern\fR. If \fIpattern\fR is NULL, then it will not do any filtering. The return value is \fBTCL_OK\fR if no errors occurred writing to the result, otherwise it is \fBTCL_ERROR\fR, and the error message is left in the interpreter's result. - .SH TCL_REGISTERCHANNEL .PP \fBTcl_RegisterChannel\fR adds a channel to the set of channels accessible @@ -342,7 +334,6 @@ call to \fBTcl_RegisterChannel\fR, they will get initialized by that call. See \fBTcl_StandardChannels\fR for a general treatise about standard channels and the behaviour of the Tcl library with regard to them. - .SH TCL_UNREGISTERCHANNEL .PP \fBTcl_UnregisterChannel\fR removes a channel from the set of channels @@ -357,14 +348,13 @@ that it no longer holds a reference to that channel. If this is the last reference to the channel, it will now be closed. \fBTcl_UnregisterChannel\fR is very similar to \fBTcl_DetachChannel\fR except that it will also close the channel if no further references to it exist. - .SH TCL_DETACHCHANNEL .PP \fBTcl_DetachChannel\fR removes a channel from the set of channels accessible in \fIinterp\fR. After this call, Tcl programs will no longer be able to use the channel's name to refer to the channel in that interpreter. Beyond that, this command has no further effect. It cannot be used on -the standard channels (stdout, stderr, stdin), and will return +the standard channels (\fBstdout\fR, \fBstderr\fR, \fBstdin\fR), and will return \fBTCL_ERROR\fR if passed one of those channels. .PP Code not associated with a Tcl interpreter can call @@ -372,16 +362,14 @@ Code not associated with a Tcl interpreter can call that it no longer holds a reference to that channel. If this is the last reference to the channel, unlike \fBTcl_UnregisterChannel\fR, it will not be closed. - .SH TCL_ISSTANDARDCHANNEL .PP \fBTcl_IsStandardChannel\fR tests whether a channel is one of the -three standard channels, stdin, stdout or stderr. If so, it returns -1, otherwise 0. +three standard channels, \fBstdin\fR, \fBstdout\fR or \fBstderr\fR. +If so, it returns 1, otherwise 0. .PP No attempt is made to check whether the given channel or the standard channels are initialized or otherwise valid. - .SH TCL_CLOSE .PP \fBTcl_Close\fR destroys the channel \fIchannel\fR, which must denote a @@ -411,7 +399,6 @@ been given as the \fBchan\fR argument in a call to \fBTcl_UnregisterChannel\fR, which will internally call \fBTcl_Close\fR when all calls to \fBTcl_RegisterChannel\fR have been matched by corresponding calls to \fBTcl_UnregisterChannel\fR. - .SH "TCL_READCHARS AND TCL_READ" .PP \fBTcl_ReadChars\fR consumes bytes from \fIchannel\fR, converting the bytes @@ -472,7 +459,6 @@ stack the supplied channel is part of, \fBTcl_ReadRaw\fR does not. Thus this function is \fBonly\fR usable for transformational channel drivers, i.e. drivers used in the middle of a stack of channels, to move data from the channel below into the transformation. - .SH "TCL_GETSOBJ AND TCL_GETS" .PP \fBTcl_GetsObj\fR consumes bytes from \fIchannel\fR, converting the bytes to @@ -499,7 +485,6 @@ of input unavailability. \fBTcl_Gets\fR is the same as \fBTcl_GetsObj\fR except the resulting characters are appended to the dynamic string given by \fIlineRead\fR rather than a Tcl object. - .SH "TCL_UNGETS" .PP \fBTcl_Ungets\fR is used to add data to the input queue of a channel, @@ -512,7 +497,6 @@ head of the queue. If \fIchannel\fR has a EOF set, no data will be added to the input queue. \fBTcl_Ungets\fR returns \fIinputLen\fR or \-1 if an error occurs. - .SH "TCL_WRITECHARS, TCL_WRITEOBJ, AND TCL_WRITE" .PP \fBTcl_WriteChars\fR accepts \fIbytesToWrite\fR bytes of character data at @@ -567,7 +551,6 @@ not. Thus this function is \fBonly\fR usable for transformational channel drivers, i.e. drivers used in the middle of a stack of channels, to move data from the transformation into the channel below it. - .SH TCL_FLUSH .PP \fBTcl_Flush\fR causes all of the buffered output data for \fIchannel\fR @@ -581,7 +564,6 @@ eventually, as fast as the channel is able to absorb it. The return value is normally \fBTCL_OK\fR. If an error occurs, \fBTcl_Flush\fR returns \fBTCL_ERROR\fR and records a POSIX error code that can be retrieved with \fBTcl_GetErrno\fR. - .SH TCL_SEEK .PP \fBTcl_Seek\fR moves the access point in \fIchannel\fR where subsequent @@ -592,20 +574,15 @@ buffered input is discarded, prior to the seek operation. If an error occurs, \fBTcl_Seek\fR returns \-1 and records a POSIX error code that can be retrieved with \fBTcl_GetErrno\fR. After an error, the access point may or may not have been moved. - .SH TCL_TELL .PP \fBTcl_Tell\fR returns the current access point for a channel. The returned value is \-1 if the channel does not support seeking. - .SH TCL_TRUNCATECHANNEL .PP -.VS 8.5 \fBTcl_TruncateChannel\fR truncates the file underlying \fIchannel\fR to a given \fIlength\fR of bytes. It returns \fBTCL_OK\fR if the operation succeeded, and \fBTCL_ERROR\fR otherwise. -.VE 8.5 - .SH TCL_GETCHANNELOPTION .PP \fBTcl_GetChannelOption\fR retrieves, in \fIoptionValue\fR, the value of one of @@ -627,7 +604,6 @@ for the Tcl \fBsocket\fR command. The procedure normally returns \fBTCL_OK\fR. If an error occurs, it returns \fBTCL_ERROR\fR and calls \fBTcl_SetErrno\fR to store an appropriate POSIX error code. - .SH TCL_SETCHANNELOPTION .PP \fBTcl_SetChannelOption\fR sets a new value \fInewValue\fR @@ -635,30 +611,26 @@ for an option \fIoptionName\fR on \fIchannel\fR. The procedure normally returns \fBTCL_OK\fR. If an error occurs, it returns \fBTCL_ERROR\fR; in addition, if \fIinterp\fR is non-NULL, \fBTcl_SetChannelOption\fR leaves an error message in the interpreter's result. - .SH TCL_EOF .PP \fBTcl_Eof\fR returns a nonzero value if \fIchannel\fR encountered an end of file during the last input operation. - .SH TCL_INPUTBLOCKED .PP \fBTcl_InputBlocked\fR returns a nonzero value if \fIchannel\fR is in nonblocking mode and the last input operation returned less data than requested because there was insufficient data available. The call always returns zero if the channel is in blocking mode. - .SH TCL_INPUTBUFFERED .PP \fBTcl_InputBuffered\fR returns the number of bytes of input currently buffered in the internal buffers for a channel. If the channel is not open for reading, this function always returns zero. - .SH TCL_OUTPUTBUFFERED +.PP \fBTcl_OutputBuffered\fR returns the number of bytes of output currently buffered in the internal buffers for a channel. If the channel is not open for writing, this function always returns zero. - .SH "PLATFORM ISSUES" .PP The handles returned from \fBTcl_GetChannelHandle\fR depend on the @@ -669,10 +641,8 @@ the channel was created with \fBTcl_OpenFileChannel\fR, \fBTcl_OpenCommandChannel\fR, or \fBTcl_MakeFileChannel\fR. Other channel types may return a different type of handle on Windows platforms. - .SH "SEE ALSO" DString(3), fconfigure(n), filename(n), fopen(3), Tcl_CreateChannel(3) - .SH KEYWORDS access point, blocking, buffered I/O, channel, channel driver, end of file, flush, input, nonblocking, output, read, seek, write diff --git a/doc/OpenTcp.3 b/doc/OpenTcp.3 index 98d8cb0..78ac70b 100644 --- a/doc/OpenTcp.3 +++ b/doc/OpenTcp.3 @@ -49,15 +49,13 @@ accepted via the socket. .AP ClientData clientData in Arbitrary one-word value to pass to \fIproc\fR. .BE - .SH DESCRIPTION .PP These functions are convenience procedures for creating channels that communicate over TCP sockets. The operations on a channel are described in the manual entry for \fBTcl_OpenFileChannel\fR. - -.SH TCL_OPENTCPCLIENT +.SS TCL_OPENTCPCLIENT .PP \fBTcl_OpenTcpClient\fR opens a client TCP socket connected to a \fIport\fR on a specific \fIhost\fR, and returns a channel that can be used to @@ -94,22 +92,20 @@ is left in the interpreter's result. .PP The newly created channel is not registered in the supplied interpreter; to register it, use \fBTcl_RegisterChannel\fR. -If one of the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was +If one of the standard channels, \fBstdin\fR, \fBstdout\fR or \fBstderr\fR was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. - -.SH TCL_MAKETCPCLIENTCHANNEL +.SS TCL_MAKETCPCLIENTCHANNEL .PP \fBTcl_MakeTcpClientChannel\fR creates a \fBTcl_Channel\fR around an existing, platform specific, handle for a client TCP socket. .PP The newly created channel is not registered in the supplied interpreter; to register it, use \fBTcl_RegisterChannel\fR. -If one of the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was +If one of the standard channels, \fBstdin\fR, \fBstdout\fR or \fBstderr\fR was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. - -.SH TCL_OPENTCPSERVER +.SS TCL_OPENTCPSERVER .PP \fBTcl_OpenTcpServer\fR opens a TCP socket on the local host on a specified \fIport\fR and uses the Tcl event mechanism to accept requests from clients @@ -119,8 +115,9 @@ allow connections from any network interface. Each time a client connects to this socket, Tcl creates a channel for the new connection and invokes \fIproc\fR with information about the channel. \fIProc\fR must match the following prototype: +.PP .CS -typedef void Tcl_TcpAcceptProc( +typedef void \fBTcl_TcpAcceptProc\fR( ClientData \fIclientData\fR, Tcl_Channel \fIchannel\fR, char *\fIhostName\fR, @@ -158,18 +155,15 @@ a remote client is pending. .PP The newly created channel is not registered in the supplied interpreter; to register it, use \fBTcl_RegisterChannel\fR. -If one of the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was +If one of the standard channels, \fBstdin\fR, \fBstdout\fR or \fBstderr\fR was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. - .SH "PLATFORM ISSUES" .PP On Unix platforms, the socket handle is a Unix file descriptor as returned by the \fBsocket\fR system call. On the Windows platform, the socket handle is a \fBSOCKET\fR as defined in the WinSock API. - .SH "SEE ALSO" Tcl_OpenFileChannel(3), Tcl_RegisterChannel(3), vwait(n) - .SH KEYWORDS -client, server, TCP +channel, client, server, socket, TCP diff --git a/doc/Panic.3 b/doc/Panic.3 index b53ca11..48aed2b 100644 --- a/doc/Panic.3 +++ b/doc/Panic.3 @@ -33,9 +33,7 @@ Must have been initialized using \fBva_start\fR, and cleared using \fBva_end\fR. .AP Tcl_PanicProc *panicProc in Procedure to report fatal error message and abort. - .BE - .SH DESCRIPTION .PP When the Tcl library detects that its internal data structures are in an @@ -51,33 +49,31 @@ same formatting rules are also used by the built-in Tcl command In a freshly loaded Tcl library, \fBTcl_Panic\fR prints the formatted error message to the standard error file of the process, and then calls \fBabort\fR to terminate the process. \fBTcl_Panic\fR does not -return. +return. On Windows, when a debugger is running, the formatted error +message is sent to the debugger in stead. If the windows executable +does not have a stderr channel (e.g. \fBwish.exe\fR), then a +system dialog box is used to display the panic message. .PP \fBTcl_SetPanicProc\fR may be used to modify the behavior of \fBTcl_Panic\fR. The \fIpanicProc\fR argument should match the type \fBTcl_PanicProc\fR: .PP .CS -typedef void Tcl_PanicProc( +typedef void \fBTcl_PanicProc\fR( const char *\fBformat\fR, \fBarg\fR, \fBarg\fR,...); .CE .PP After \fBTcl_SetPanicProc\fR returns, any future calls to \fBTcl_Panic\fR will call \fIpanicProc\fR, passing along the -\fIformat\fR and \fIarg\fR arguments. To maintain consistency with the -callers of \fBTcl_Panic\fR, \fIpanicProc\fR must not return; it must -call \fBabort\fR. \fIpanicProc\fR should avoid making calls into the -Tcl library, or into other libraries that may call the Tcl library, -since the original call to \fBTcl_Panic\fR indicates the Tcl library is -not in a state of reliable operation. +\fIformat\fR and \fIarg\fR arguments. \fIpanicProc\fR should avoid +making calls into the Tcl library, or into other libraries that may +call the Tcl library, since the original call to \fBTcl_Panic\fR +indicates the Tcl library is not in a state of reliable operation. .PP The typical use of \fBTcl_SetPanicProc\fR arranges for the error message to be displayed or reported in a manner more suitable for the -application or the platform. As an example, the Windows implementation -of \fBwish\fR calls \fBTcl_SetPanicProc\fR to force all panic messages -to be displayed in a system dialog box, rather than to be printed to the -standard error file (usually not visible under Windows). +application or the platform. .PP Although the primary callers of \fBTcl_Panic\fR are the procedures of the Tcl library, \fBTcl_Panic\fR is a public function and may be called @@ -87,10 +83,7 @@ will be displayed. .PP \fBTcl_PanicVA\fR is the same as \fBTcl_Panic\fR except that instead of taking a variable number of arguments it takes an argument list. - .SH "SEE ALSO" abort(3), printf(3), exec(n), format(n) - .SH KEYWORDS abort, fatal, error - diff --git a/doc/ParseArgs.3 b/doc/ParseArgs.3 new file mode 100644 index 0000000..dd33830 --- /dev/null +++ b/doc/ParseArgs.3 @@ -0,0 +1,198 @@ +'\" +'\" Copyright (c) 2008 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH Tcl_ParseArgsObjv 3 8.6 Tcl "Tcl Library Procedures" +.BS +.SH NAME +Tcl_ParseArgsObjv \- parse arguments according to a tabular description +.SH SYNOPSIS +.nf +\fB#include <tcl.h>\fR +.sp +int +\fBTcl_ParseArgsObjv\fR(\fIinterp, argTable, objcPtr, objv, remObjv\fR) +.SH ARGUMENTS +.AS "const Tcl_ArgvInfo" ***remObjv in/out +.AP Tcl_Interp *interp out +Where to store error messages. +.AP "const Tcl_ArgvInfo" *argTable in +Pointer to array of option descriptors. +.AP int *objcPtr in/out +A pointer to variable holding number of arguments in \fIobjv\fR. Will be +modified to hold number of arguments left in the unprocessed argument list +stored in \fIremObjv\fR. +.AP "Tcl_Obj *const" *objv in +The array of arguments to be parsed. +.AP Tcl_Obj ***remObjv out +Pointer to a variable that will hold the array of unprocessed arguments. +Should be NULL if no return of unprocessed arguments is required. If +\fIobjcPtr\fR is updated to a non-zero value, the array returned through this +must be deallocated using \fBckfree\fR. +.BE +.SH DESCRIPTION +.PP +The \fBTcl_ParseArgsObjv\fR function provides a system for parsing argument +lists of the form +.QW "\fB\-someName \fIsomeValue\fR ..." . +Such argument lists are commonly found both in the arguments to a program and +in the arguments to an individual Tcl command. This parser assumes that the +order of the arguments does not matter, other than in so far as later copies +of a duplicated option overriding earlier ones. +.PP +The argument array is described by the \fIobjcPtr\fR and \fIobjv\fR +parameters, and an array of unprocessed arguments is returned through the +\fIobjcPtr\fR and \fIremObjv\fR parameters; if no return of unprocessed +arguments is desired, the \fIremObjv\fR parameter should be NULL. If any +problems happen, including if the +.QW "generate help" +option is selected, an error message is left in the interpreter result and +TCL_ERROR is returned. Otherwise, the interpreter result is left unchanged and +TCL_OK is returned. +.PP +The collection of arguments to be parsed is described by the \fIargTable\fR +parameter. This points to a table of descriptor structures that is terminated +by an entry with the \fItype\fR field set to TCL_ARGV_END. As convenience, the +following prototypical entries are provided: +.TP +\fBTCL_ARGV_AUTO_HELP\fR +. +Enables the argument processor to provide help when passed the argument +.QW \fB\-help\fR . +.TP +\fBTCL_ARGV_AUTO_REST\fR +. +Instructs the argument processor that arguments after +.QW \fB\-\-\fR +are to be unprocessed. +.TP +\fBTCL_ARGV_TABLE_END\fR +. +Marks the end of the table of argument descriptors. +.SS "ARGUMENT DESCRIPTOR ENTRIES" +.PP +Each entry of the argument descriptor table must be a structure of type +\fBTcl_ArgvInfo\fR. The structure is defined as this: +.PP +.CS +typedef struct { + int \fItype\fR; + const char *\fIkeyStr\fR; + void *\fIsrcPtr\fR; + void *\fIdstPtr\fR; + const char *\fIhelpStr\fR; + ClientData \fIclientData\fR; +} \fBTcl_ArgvInfo\fR; +.CE +.PP +The \fIkeyStr\fR field contains the name of the option; by convention, this +will normally begin with a +.QW \fB\-\fR +character. The \fItype\fR, \fIsrcPtr\fR, \fIdstPtr\fR and \fIclientData\fR +fields describe the interpretation of the value of the argument, as described +below. The \fIhelpStr\fR field gives some text that is used to provide help to +users when they request it. +.PP +As noted above, the \fItype\fR field is used to describe the interpretation of +the argument's value. The following values are acceptable values for +\fItype\fR: +.TP +\fBTCL_ARGV_CONSTANT\fR +. +The argument does not take any following value argument. If this argument is +present, the int pointed to by the \fIsrcPtr\fR field is copied to the +\fIdstPtr\fR field. The \fIclientData\fR field is ignored. +.TP +\fBTCL_ARGV_END\fR +. +This value marks the end of all option descriptors in the table. All other +fields are ignored. +.TP +\fBTCL_ARGV_FLOAT\fR +. +This argument takes a following floating point value argument. The value (once +parsed by \fBTcl_GetDoubleFromObj\fR) will be stored as a double-precision +value in the variable pointed to by the \fIdstPtr\fR field. The \fIsrcPtr\fR +and \fIclientData\fR fields are ignored. +.TP +\fBTCL_ARGV_FUNC\fR +. +This argument optionally takes a following value argument; it is up to the +handler callback function passed in \fIsrcPtr\fR to decide. That function will +have the following signature: +.RS +.PP +.CS +typedef int (\fBTcl_ArgvFuncProc\fR)( + ClientData \fIclientData\fR, + Tcl_Obj *\fIobjPtr\fR, + void *\fIdstPtr\fR); +.CE +.PP +The result is a boolean value indicating whether to consume the following +argument. The \fIclientData\fR is the value from the table entry, the +\fIobjPtr\fR is the object that represents the following argument or NULL if +there are no following arguments at all, and the \fIdstPtr\fR argument to the +\fBTcl_ArgvFuncProc\fR is the location to write the parsed value to. +.RE +.TP +\fBTCL_ARGV_GENFUNC\fR +. +This argument takes zero or more following arguments; the handler callback +function passed in \fIsrcPtr\fR returns how many (or a negative number to +signal an error, in which case it should also set the interpreter result). The +function will have the following signature: +.RS +.PP +.CS +typedef int (\fBTcl_ArgvGenFuncProc\fR)( + ClientData \fIclientData\fR, + Tcl_Interp *\fIinterp\fR, + int \fIobjc\fR, + Tcl_Obj *const *\fIobjv\fR, + void *\fIdstPtr\fR); +.CE +.PP +The \fIclientData\fR is the value from the table entry, the \fIinterp\fR is +where to store any error messages, the \fIkeyStr\fR is the name of the +argument, \fIobjc\fR and \fIobjv\fR describe an array of all the remaining +arguments, and \fIdstPtr\fR argument to the \fBTcl_ArgvGenFuncProc\fR is the +location to write the parsed value (or values) to. +.RE +.TP +\fBTCL_ARGV_HELP\fR +. +This special argument does not take any following value argument, but instead +causes \fBTcl_ParseArgsObjv\fR to generate an error message describing the +arguments supported. All other fields except the \fIhelpStr\fR field are +ignored. +.TP +\fBTCL_ARGV_INT\fR +. +This argument takes a following integer value argument. The value (once parsed +by \fBTcl_GetIntFromObj\fR) will be stored as an int in the variable pointed +to by the \fIdstPtr\fR field. The \fIsrcPtr\fR field is ignored. +.TP +\fBTCL_ARGV_REST\fR +. +This special argument does not take any following value argument, but instead +marks all following arguments to be left unprocessed. The \fIsrcPtr\fR, +\fIdstPtr\fR and \fIclientData\fR fields are ignored. +.TP +\fBTCL_ARGV_STRING\fR +. +This argument takes a following string value argument. A pointer to the string +will be stored at \fIdstPtr\fR; the string inside will have a lifetime linked +to the lifetime of the string representation of the argument object that it +came from, and so should be copied if it needs to be retained. The +\fIsrcPtr\fR and \fIclientData\fR fields are ignored. +.SH "SEE ALSO" +Tcl_GetIndexFromObj(3), Tcl_Main(3), Tcl_CreateObjCommand(3) +.SH KEYWORDS +argument, parse +'\" Local Variables: +'\" fill-column: 78 +'\" End: diff --git a/doc/ParseCmd.3 b/doc/ParseCmd.3 index b5fc6d0..f3b3aeb 100644 --- a/doc/ParseCmd.3 +++ b/doc/ParseCmd.3 @@ -80,7 +80,6 @@ if the parse was successful. Points to structure that was filled in by a previous call to \fBTcl_ParseCommand\fR, \fBTcl_ParseExpr\fR, \fBTcl_ParseVarName\fR, etc. .BE - .SH DESCRIPTION .PP These procedures parse Tcl commands or portions of Tcl commands such as @@ -202,30 +201,30 @@ If an error or other exception occurs while evaluating the tokens (such as a reference to a non-existent variable) then the return value is NULL and an error message is left in \fIinterp\fR's result. The use of \fBTcl_EvalTokens\fR is deprecated. - .SH "TCL_PARSE STRUCTURE" .PP \fBTcl_ParseCommand\fR, \fBTcl_ParseExpr\fR, \fBTcl_ParseBraces\fR, \fBTcl_ParseQuotedString\fR, and \fBTcl_ParseVarName\fR return parse information in two data structures, Tcl_Parse and Tcl_Token: +.PP .CS typedef struct Tcl_Parse { - const char *\fIcommentStart\fR; - int \fIcommentSize\fR; - const char *\fIcommandStart\fR; - int \fIcommandSize\fR; - int \fInumWords\fR; - Tcl_Token *\fItokenPtr\fR; - int \fInumTokens\fR; - ... -} Tcl_Parse; + const char *\fIcommentStart\fR; + int \fIcommentSize\fR; + const char *\fIcommandStart\fR; + int \fIcommandSize\fR; + int \fInumWords\fR; + Tcl_Token *\fItokenPtr\fR; + int \fInumTokens\fR; + ... +} \fBTcl_Parse\fR; typedef struct Tcl_Token { - int \fItype\fR; - const char *\fIstart\fR; - int \fIsize\fR; - int \fInumComponents\fR; -} Tcl_Token; + int \fItype\fR; + const char *\fIstart\fR; + int \fIsize\fR; + int \fInumComponents\fR; +} \fBTcl_Token\fR; .CE .PP The first five fields of a Tcl_Parse structure @@ -267,6 +266,7 @@ the \fInumComponents\fR field describes how many of these there are. The \fItype\fR field has one of the following values: .TP 20 \fBTCL_TOKEN_WORD\fR +. This token ordinarily describes one word of a command but it may also describe a quoted or braced string in an expression. The token describes a component of the script that is @@ -281,29 +281,32 @@ number of sub-tokens that make up the word, including sub-tokens of \fBTCL_TOKEN_VARIABLE\fR and \fBTCL_TOKEN_BS\fR tokens. .TP \fBTCL_TOKEN_SIMPLE_WORD\fR +. This token has the same meaning as \fBTCL_TOKEN_WORD\fR, except that the word is guaranteed to consist of a single \fBTCL_TOKEN_TEXT\fR sub-token. The \fInumComponents\fR field is always 1. .TP \fBTCL_TOKEN_EXPAND_WORD\fR -.VS 8.5 +. This token has the same meaning as \fBTCL_TOKEN_WORD\fR, except that the command parser notes this word began with the expansion prefix \fB{*}\fR, indicating that after substitution, the list value of this word should be expanded to form multiple arguments in command evaluation. This token type can only be created by Tcl_ParseCommand. -.VE 8.5 .TP \fBTCL_TOKEN_TEXT\fR +. The token describes a range of literal text that is part of a word. The \fInumComponents\fR field is always 0. .TP \fBTCL_TOKEN_BS\fR +. The token describes a backslash sequence such as \fB\en\fR or \fB\e0xa3\fR. The \fInumComponents\fR field is always 0. .TP \fBTCL_TOKEN_COMMAND\fR +. The token describes a command whose result must be substituted into the word. The token includes the square brackets that surround the command. The \fInumComponents\fR field is always 0 (the nested command @@ -311,6 +314,7 @@ is not parsed; call \fBTcl_ParseCommand\fR recursively if you want to see its tokens). .TP \fBTCL_TOKEN_VARIABLE\fR +. The token describes a variable substitution, including the \fB$\fR, variable name, and array index (if there is one) up through the close parenthesis that terminates the index. This token is followed @@ -326,6 +330,7 @@ array index. The \fInumComponents\fR field includes nested sub-tokens that are part of \fBTCL_TOKEN_VARIABLE\fR tokens in the array index. .TP \fBTCL_TOKEN_SUB_EXPR\fR +. The token describes one subexpression of an expression (or an entire expression). A subexpression may consist of a value @@ -352,6 +357,7 @@ counts the total number of sub-tokens that make up the subexpression; this includes the sub-tokens for any nested \fBTCL_TOKEN_SUB_EXPR\fR tokens. .TP \fBTCL_TOKEN_OPERATOR\fR +. The token describes one operator of an expression such as \fB&&\fR or \fBhypot\fR. A \fBTCL_TOKEN_OPERATOR\fR token is always preceded by a @@ -383,7 +389,6 @@ is always 0. After \fBTcl_ParseCommand\fR returns, the first token pointed to by the \fItokenPtr\fR field of the Tcl_Parse structure always has type \fBTCL_TOKEN_WORD\fR or -.VS 8.5 \fBTCL_TOKEN_SIMPLE_WORD\fR or \fBTCL_TOKEN_EXPAND_WORD\fR. It is followed by the sub-tokens that must be concatenated to produce the value of that word. @@ -392,7 +397,6 @@ of \fBTCL_TOKEN_EXPAND_WORD\fR token for the second word, followed by sub-tokens for that word, and so on until all \fInumWords\fR have been accounted for. -.VE 8.5 .PP After \fBTcl_ParseExpr\fR returns, the first token pointed to by the \fItokenPtr\fR field of the @@ -459,6 +463,5 @@ There are additional fields in the Tcl_Parse structure after the \fBTcl_ParseCommand\fR, \fBTcl_ParseExpr\fR, \fBTcl_ParseBraces\fR, \fBTcl_ParseQuotedString\fR, and \fBTcl_ParseVarName\fR; they should not be referenced by code outside of these procedures. - .SH KEYWORDS backslash substitution, braces, command, expression, parse, token, variable substitution diff --git a/doc/PkgRequire.3 b/doc/PkgRequire.3 index 810947d..d54d7af 100644 --- a/doc/PkgRequire.3 +++ b/doc/PkgRequire.3 @@ -34,7 +34,7 @@ int int \fBTcl_PkgProvideEx\fR(\fIinterp, name, version, clientData\fR) .SH ARGUMENTS -.AS ClientData clientDataPtr out +.AS void *clientDataPtr out .AP Tcl_Interp *interp in Interpreter where package is needed or available. .AP "const char" *name in @@ -48,18 +48,18 @@ Non-zero means that only the particular version specified by Zero means that newer versions than \fIversion\fR are also acceptable as long as they have the same major version number as \fIversion\fR. -.AP ClientData clientData in +.AP "const void" *clientData in Arbitrary value to be associated with the package. -.AP ClientData *clientDataPtr out +.AP void *clientDataPtr out Pointer to place to store the value associated with the matching package. It is only changed if the pointer is not NULL and the -function completed successfully. +function completed successfully. The storage can be any pointer +type with the same size as a void pointer. .AP int objc in Number of requirements. .AP Tcl_Obj* objv[] in Array of requirements. .BE - .SH DESCRIPTION .PP These procedures provide C-level interfaces to Tcl's package and @@ -91,6 +91,7 @@ functions. \fBTcl_PkgRequireProc\fR is the form of \fBpackage require\fR handling multiple requirements. The other forms are present for backward compatibility and translate their invocations to this form. - .SH KEYWORDS package, present, provide, require, version +.SH "SEE ALSO" +package(n), Tcl_StaticPackage(3) diff --git a/doc/Preserve.3 b/doc/Preserve.3 index 2b3edc0..905a31d 100644 --- a/doc/Preserve.3 +++ b/doc/Preserve.3 @@ -27,7 +27,6 @@ to memory for structure. .AP Tcl_FreeProc *freeProc in Procedure to invoke to free \fIclientData\fR. .BE - .SH DESCRIPTION .PP These three procedures help implement a simple reference count mechanism @@ -78,9 +77,12 @@ calls to \fBTcl_Release\fR then \fIfreeProc\fR will be called by All the work of freeing the object is carried out by \fIfreeProc\fR. \fIFreeProc\fR must have arguments and result that match the type \fBTcl_FreeProc\fR: +.PP .CS -typedef void Tcl_FreeProc(char *\fIblockPtr\fR); +typedef void \fBTcl_FreeProc\fR( + char *\fIblockPtr\fR); .CE +.PP The \fIblockPtr\fR argument to \fIfreeProc\fR will be the same as the \fIclientData\fR argument to \fBTcl_EventuallyFree\fR. The type of \fIblockPtr\fR (\fBchar *\fR) is different than the type of the @@ -102,9 +104,7 @@ mechanism for long-term reference counts. The implementation does not depend in any way on the internal structure of the objects being freed; it keeps the reference counts in a separate structure. - .SH "SEE ALSO" Tcl_Interp, Tcl_Alloc - .SH KEYWORDS free, reference count, storage diff --git a/doc/PrintDbl.3 b/doc/PrintDbl.3 index 279b4d5..99b0113 100644 --- a/doc/PrintDbl.3 +++ b/doc/PrintDbl.3 @@ -28,7 +28,6 @@ Floating-point value to be converted. Where to store the string representing \fIvalue\fR. Must have at least \fBTCL_DOUBLE_SPACE\fR characters of storage. .BE - .SH DESCRIPTION .PP \fBTcl_PrintDouble\fR generates a string that represents the value @@ -41,7 +40,6 @@ or an so that it does not look like an integer. Where \fB%g\fR would generate an integer with no decimal point, \fBTcl_PrintDouble\fR adds .QW .0 . -.VS 8.5 .PP If the \fBtcl_precision\fR value is non-zero, the result will have precisely that many digits of significance. If the value is zero @@ -49,7 +47,5 @@ precisely that many digits of significance. If the value is zero represent the number in such a way that \fBTcl_NewDoubleObj\fR will generate the same number when presented with the given string. IEEE semantics of rounding to even apply to the conversion. -.VE - .SH KEYWORDS conversion, double-precision, floating-point, string diff --git a/doc/RegConfig.3 b/doc/RegConfig.3 index 19c0bb0..7c41350 100644 --- a/doc/RegConfig.3 +++ b/doc/RegConfig.3 @@ -26,7 +26,7 @@ registered for. Must not be NULL. Contains the name of the package registering the embedded configuration as ASCII string. This means that this information is in UTF-8 too. Must not be NULL. -.AP Tcl_Config *configuration in +.AP "const Tcl_Config" *configuration in Refers to an array of Tcl_Config entries containing the information embedded in the binary library. Must not be NULL. The end of the array is signaled by either a key identical to NULL, or a key referring to @@ -36,7 +36,6 @@ Contains the name of the encoding used to store the configuration values as ASCII string. This means that this information is in UTF-8 too. Must not be NULL. .BE - .SH DESCRIPTION .PP The function described here has its base in TIP 59 and provides @@ -102,9 +101,9 @@ The \fBTcl_Config\fR structure contains the following fields: .PP .CS typedef struct Tcl_Config { - const char* key; - const char* value; -} Tcl_Config; + const char *\fIkey\fR; + const char *\fIvalue\fR; +} \fBTcl_Config\fR; .CE .\" No cross references yet. .\" .SH "SEE ALSO" diff --git a/doc/RegExp.3 b/doc/RegExp.3 index 0ac091c..e10314a 100644 --- a/doc/RegExp.3 +++ b/doc/RegExp.3 @@ -337,10 +337,10 @@ defined as follows: .PP .CS typedef struct Tcl_RegExpInfo { - int \fInsubs\fR; - Tcl_RegExpIndices *\fImatches\fR; - long \fIextendStart\fR; -} Tcl_RegExpInfo; + int \fInsubs\fR; + Tcl_RegExpIndices *\fImatches\fR; + long \fIextendStart\fR; +} \fBTcl_RegExpInfo\fR; .CE .PP The \fInsubs\fR field contains a count of the number of parenthesized @@ -355,9 +355,9 @@ follows: .PP .CS typedef struct Tcl_RegExpIndices { - long \fIstart\fR; - long \fIend\fR; -} Tcl_RegExpIndices; + long \fIstart\fR; + long \fIend\fR; +} \fBTcl_RegExpIndices\fR; .CE .PP The \fIstart\fR and \fIend\fR values are Unicode character indices diff --git a/doc/SaveResult.3 b/doc/SaveResult.3 index f47500e..d6ea48d 100644 --- a/doc/SaveResult.3 +++ b/doc/SaveResult.3 @@ -38,10 +38,8 @@ Saved state token to be restored or discarded. .AP Tcl_SavedResult *savedPtr in Pointer to location where interpreter result should be saved or restored. .BE - .SH DESCRIPTION .PP -.VS 8.5 These routines allows a C procedure to take a snapshot of the current state of an interpreter so that it can be restored after a call to \fBTcl_Eval\fR or some other routine that modifies the interpreter @@ -97,7 +95,6 @@ must eventually be passed to either \fBTcl_RestoreInterpState\fR or \fBTcl_DiscardInterpState\fR to avoid a memory leak. Once the \fBTcl_InterpState\fR token is passed to one of them, the token is no longer valid and should not be used anymore. -.VE 8.5 .PP \fBTcl_SaveResult\fR moves the string and object results of \fIinterp\fR into the location specified by \fIstatePtr\fR. @@ -119,6 +116,5 @@ Once \fBTcl_SaveResult\fR is called to save the interpreter result, either \fBTcl_RestoreResult\fR or \fBTcl_DiscardResult\fR must be called to properly clean up the memory associated with the saved state. - .SH KEYWORDS result, state, interp diff --git a/doc/SetChanErr.3 b/doc/SetChanErr.3 index 13bd94a..b6c1975 100644 --- a/doc/SetChanErr.3 +++ b/doc/SetChanErr.3 @@ -33,65 +33,60 @@ Refers to the Tcl channel whose bypass area is accessed. .AP Tcl_Interp* interp in Refers to the Tcl interpreter whose bypass area is accessed. .AP Tcl_Obj* msg in -Error message put into a bypass area. A list of return options and -values, followed by a string message. Both message and the -option/value information are optional. +Error message put into a bypass area. A list of return options and values, +followed by a string message. Both message and the option/value information +are optional. .AP Tcl_Obj** msgPtr out -Reference to a place where the message stored in the accessed bypass -area can be stored in. +Reference to a place where the message stored in the accessed bypass area can +be stored in. .BE .SH DESCRIPTION .PP -The current definition of a Tcl channel driver does not permit the -direct return of arbitrary error messages, except for the setting and -retrieval of channel options. All other functions are restricted to -POSIX error codes. +The current definition of a Tcl channel driver does not permit the direct +return of arbitrary error messages, except for the setting and retrieval of +channel options. All other functions are restricted to POSIX error codes. .PP -The functions described here overcome this limitation. Channel drivers -are allowed to use \fBTcl_SetChannelError\fR and -\fBTcl_SetChannelErrorInterp\fR to place arbitrary error messages in -\fBbypass areas\fI defined for channels and interpreters. And the -generic I/O layer uses \fBTcl_GetChannelError\fR and -\fBTcl_GetChannelErrorInterp\fR to look for messages in the bypass -areas and arrange for their return as errors. The posix error codes -set by a driver are used now if and only if no messages are present. +The functions described here overcome this limitation. Channel drivers are +allowed to use \fBTcl_SetChannelError\fR and \fBTcl_SetChannelErrorInterp\fR +to place arbitrary error messages in \fBbypass areas\fR defined for channels +and interpreters. And the generic I/O layer uses \fBTcl_GetChannelError\fR and +\fBTcl_GetChannelErrorInterp\fR to look for messages in the bypass areas and +arrange for their return as errors. The posix error codes set by a driver are +used now if and only if no messages are present. .PP -\fBTcl_SetChannelError\fR stores error information in the bypass area -of the specified channel. The number of references to the \fBmsg\fR -object goes up by one. Previously stored information will be -discarded, by releasing the reference held by the channel. The channel -reference must not be NULL. +\fBTcl_SetChannelError\fR stores error information in the bypass area of the +specified channel. The number of references to the \fBmsg\fR object goes up by +one. Previously stored information will be discarded, by releasing the +reference held by the channel. The channel reference must not be NULL. .PP -\fBTcl_SetChannelErrorInterp\fR stores error information in the bypass -area of the specified interpreter. The number of references to the -\fBmsg\fR object goes up by one. Previously stored information will be -discarded, by releasing the reference held by the interpreter. The -interpreter reference must not be NULL. +\fBTcl_SetChannelErrorInterp\fR stores error information in the bypass area of +the specified interpreter. The number of references to the \fBmsg\fR object +goes up by one. Previously stored information will be discarded, by releasing +the reference held by the interpreter. The interpreter reference must not be +NULL. .PP -\fBTcl_GetChannelError\fR places either the error message held in the -bypass area of the specified channel into \fImsgPtr\fR, or NULL; and -resets the bypass. I.e. after an invocation all following invocations -will return NULL, until an intervening invocation of -\fBTcl_SetChannelError\fR with a non-NULL message. The \fImsgPtr\fR -must not be NULL. The reference count of the message is not touched. -The reference previously held by the channel is now held by the caller -of the function and it is its responsibility to release that reference -when it is done with the object. +\fBTcl_GetChannelError\fR places either the error message held in the bypass +area of the specified channel into \fImsgPtr\fR, or NULL; and resets the +bypass, that is, after an invocation all following invocations will return +NULL, until an intervening invocation of \fBTcl_SetChannelError\fR with a +non-NULL message. The \fImsgPtr\fR must not be NULL. The reference count of +the message is not touched. The reference previously held by the channel is +now held by the caller of the function and it is its responsibility to release +that reference when it is done with the object. .PP -\fBTcl_GetChannelErrorInterp\fR places either the error message held -in the bypass area of the specified interpreter into \fImsgPtr\fR, or -NULL; and resets the bypass. I.e. after an invocation all following -invocations will return NULL, until an intervening invocation of -\fBTcl_SetChannelErrorInterp\fR with a non-NULL message. The -\fImsgPtr\fR must not be NULL. The reference count of the message is -not touched. The reference previously held by the interpreter is now -held by the caller of the function and it is its responsibility to -release that reference when it is done with the object. -.PP -Which functions of a channel driver are allowed to use which bypass -function is listed below, as is which functions of the public channel -API may leave a messages in the bypass areas. +\fBTcl_GetChannelErrorInterp\fR places either the error message held in the +bypass area of the specified interpreter into \fImsgPtr\fR, or NULL; and +resets the bypass, that is, after an invocation all following invocations will +return NULL, until an intervening invocation of +\fBTcl_SetChannelErrorInterp\fR with a non-NULL message. The \fImsgPtr\fR must +not be NULL. The reference count of the message is not touched. The reference +previously held by the interpreter is now held by the caller of the function +and it is its responsibility to release that reference when it is done with +the object. .PP +Which functions of a channel driver are allowed to use which bypass function +is listed below, as is which functions of the public channel API may leave a +messages in the bypass areas. .IP \fBTcl_DriverCloseProc\fR May use \fBTcl_SetChannelErrorInterp\fR, and only this function. .IP \fBTcl_DriverInputProc\fR @@ -103,51 +98,43 @@ May use \fBTcl_SetChannelError\fR, and only this function. .IP \fBTcl_DriverWideSeekProc\fR May use \fBTcl_SetChannelError\fR, and only this function. .IP \fBTcl_DriverSetOptionProc\fR -Has already the ability to pass arbitrary error messages. Must -\fBnot\fR use any of the new functions. +Has already the ability to pass arbitrary error messages. Must \fInot\fR use +any of the new functions. .IP \fBTcl_DriverGetOptionProc\fR Has already the ability to pass arbitrary error messages. Must -\fBnot\fR use any of the new functions. +\fInot\fR use any of the new functions. .IP \fBTcl_DriverWatchProc\fR -Must \fBnot\fR use any of the new functions. Is internally called and -has no ability to return any type of error whatsoever. +Must \fInot\fR use any of the new functions. Is internally called and has no +ability to return any type of error whatsoever. .IP \fBTcl_DriverBlockModeProc\fR May use \fBTcl_SetChannelError\fR, and only this function. .IP \fBTcl_DriverGetHandleProc\fR -Must \fBnot\fR use any of the new functions. It is only a low-level -function, and not used by Tcl commands. +Must \fInot\fR use any of the new functions. It is only a low-level function, +and not used by Tcl commands. .IP \fBTcl_DriverHandlerProc\fR -Must \fBnot\fR use any of the new functions. Is internally called and -has no ability to return any type of error whatsoever. +Must \fInot\fR use any of the new functions. Is internally called and has no +ability to return any type of error whatsoever. .PP -Given the information above the following public functions of the Tcl -C API are affected by these changes. I.e. when these functions are -called the channel may now contain a stored arbitrary error message -requiring processing by the caller. +Given the information above the following public functions of the Tcl C API +are affected by these changes; when these functions are called, the channel +may now contain a stored arbitrary error message requiring processing by the +caller. +.DS +.ta 1.9i 4i +\fBTcl_Flush\fR \fBTcl_GetsObj\fR \fBTcl_Gets\fR +\fBTcl_ReadChars\fR \fBTcl_ReadRaw\fR \fBTcl_Read\fR +\fBTcl_Seek\fR \fBTcl_StackChannel\fR \fBTcl_Tell\fR +\fBTcl_WriteChars\fR \fBTcl_WriteObj\fR \fBTcl_WriteRaw\fR +\fBTcl_Write\fR +.DE .PP -.IP \fBTcl_StackChannel\fR -.IP \fBTcl_Seek\fR -.IP \fBTcl_Tell\fR -.IP \fBTcl_ReadRaw\fR -.IP \fBTcl_Read\fR -.IP \fBTcl_ReadChars\fR -.IP \fBTcl_Gets\fR -.IP \fBTcl_GetsObj\fR -.IP \fBTcl_Flush\fR -.IP \fBTcl_WriteRaw\fR -.IP \fBTcl_WriteObj\fR -.IP \fBTcl_Write\fR -.IP \fBTcl_WriteChars\fR -.PP -All other API functions are unchanged. Especially the functions below +All other API functions are unchanged. In particular, the functions below leave all their error information in the interpreter result. -.PP -.IP \fBTcl_Close\fR -.IP \fBTcl_UnregisterChannel\fR -.IP \fBTcl_UnstackChannel\fR - +.DS +.ta 1.9i 4i +\fBTcl_Close\fR \fBTcl_UnstackChannel\fR \fBTcl_UnregisterChannel\fR +.DE .SH "SEE ALSO" Tcl_Close(3), Tcl_OpenFileChannel(3), Tcl_SetErrno(3) - .SH KEYWORDS channel driver, error messages, channel type diff --git a/doc/SetResult.3 b/doc/SetResult.3 index 2245794..c308193 100644 --- a/doc/SetResult.3 +++ b/doc/SetResult.3 @@ -9,7 +9,7 @@ .TH Tcl_SetResult 3 8.0 Tcl "Tcl Library Procedures" .BS .SH NAME -Tcl_SetObjResult, Tcl_GetObjResult, Tcl_SetResult, Tcl_GetStringResult, Tcl_AppendResult, Tcl_AppendResultVA, Tcl_AppendElement, Tcl_ResetResult, Tcl_FreeResult \- manipulate Tcl result +Tcl_SetObjResult, Tcl_GetObjResult, Tcl_SetResult, Tcl_GetStringResult, Tcl_AppendResult, Tcl_AppendResultVA, Tcl_AppendElement, Tcl_ResetResult, Tcl_TransferResult, Tcl_FreeResult \- manipulate Tcl result .SH SYNOPSIS .nf \fB#include <tcl.h>\fR @@ -28,13 +28,17 @@ const char * .sp \fBTcl_AppendResultVA\fR(\fIinterp, argList\fR) .sp -\fBTcl_AppendElement\fR(\fIinterp, element\fR) -.sp \fBTcl_ResetResult\fR(\fIinterp\fR) .sp +.VS 8.6 +\fBTcl_TransferResult\fR(\fIsourceInterp, result, targetInterp\fR) +.VE 8.6 +.sp +\fBTcl_AppendElement\fR(\fIinterp, element\fR) +.sp \fBTcl_FreeResult\fR(\fIinterp\fR) .SH ARGUMENTS -.AS Tcl_FreeProc freeProc out +.AS Tcl_FreeProc sourceInterp out .AP Tcl_Interp *interp out Interpreter whose result is to be modified or read. .AP Tcl_Obj *objPtr in @@ -42,7 +46,7 @@ Object value to become result for \fIinterp\fR. .AP char *result in String value to become result for \fIinterp\fR or to be appended to the existing result. -.AP char *element in +.AP "const char" *element in String value to append as a list element to the existing result of \fIinterp\fR. .AP Tcl_FreeProc *freeProc in @@ -52,6 +56,19 @@ Address of procedure to call to release storage at .AP va_list argList in An argument list which must have been initialized using \fBva_start\fR, and cleared using \fBva_end\fR. +.AP Tcl_Interp *sourceInterp in +.VS 8.6 +Interpreter that the result and error information should be copied from. +.VE 8.6 +.AP Tcl_Interp *targetInterp in +.VS 8.6 +Interpreter that the result and error information should be copied to. +.VE 8.6 +.AP int result in +.VS 8.6 +If \fBTCL_OK\fR, only copy the result. If \fBTCL_ERROR\fR, copy the error +information as well. +.VE 8.6 .BE .SH DESCRIPTION .PP @@ -137,7 +154,15 @@ call; the last argument in the list must be a NULL pointer. .PP \fBTcl_AppendResultVA\fR is the same as \fBTcl_AppendResult\fR except that instead of taking a variable number of arguments it takes an argument list. -.SH "OLD STRING PROCEDURES" +.PP +.VS 8.6 +\fBTcl_TransferResult\fR moves a result from one interpreter to another, +optionally (dependent on the \fIresult\fR parameter) including the error +information dictionary as well. The interpreters must be in the same thread. +The source interpreter will have its result reset by this operation. +.VE 8.6 +.SH "DEPRECATED INTERFACES" +.SS "OLD STRING PROCEDURES" .PP Use of the following procedures (is deprecated since they manipulate the Tcl result as a string. @@ -172,16 +197,19 @@ It also sets \fIinterp->freeProc\fR to zero, but does not change \fIinterp->result\fR or clear error state. \fBTcl_FreeResult\fR is most commonly used when a procedure is about to replace one result value with another. -.SH "DIRECT ACCESS TO INTERP->RESULT IS DEPRECATED" +.SS "DIRECT ACCESS TO INTERP->RESULT" .PP It used to be legal for programs to directly read and write \fIinterp->result\fR -to manipulate the interpreter result. -Direct access to \fIinterp->result\fR is now strongly deprecated -because it can make the result's string and object forms inconsistent. -Programs should always read the result -using the procedures \fBTcl_GetObjResult\fR or \fBTcl_GetStringResult\fR, -and write the result using \fBTcl_SetObjResult\fR or \fBTcl_SetResult\fR. +to manipulate the interpreter result. The Tcl headers no longer +permit this access by default, and C code still doing this must +be updated to use supported routines \fBTcl_GetObjResult\fR, +\fBTcl_GetStringResult\fR, \fBTcl_SetObjResult\fR, and \fBTcl_SetResult\fR. +As a migration aid, access can be restored with the compiler directive +.CS +#define USE_INTERP_RESULT +.CE +but this is meant only to offer life support to otherwise dead code. .SH "THE TCL_FREEPROC ARGUMENT TO TCL_SETRESULT" .PP \fBTcl_SetResult\fR's \fIfreeProc\fR argument specifies how @@ -213,9 +241,12 @@ This allows applications to use non-standard storage allocators. When Tcl no longer needs the storage for the string, it will call \fIfreeProc\fR. \fIFreeProc\fR should have arguments and result that match the type \fBTcl_FreeProc\fR: +.PP .CS -typedef void Tcl_FreeProc(char *\fIblockPtr\fR); +typedef void \fBTcl_FreeProc\fR( + char *\fIblockPtr\fR); .CE +.PP When \fIfreeProc\fR is called, its \fIblockPtr\fR will be set to the value of \fIresult\fR passed to \fBTcl_SetResult\fR. .SH "SEE ALSO" diff --git a/doc/SplitList.3 b/doc/SplitList.3 index fd6ec8b..219dfc7 100644 --- a/doc/SplitList.3 +++ b/doc/SplitList.3 @@ -65,7 +65,6 @@ Information about \fIsrc\fR. Must be value returned by previous call to \fBTcl_ScanElement\fR, possibly OR-ed with \fBTCL_DONT_USE_BRACES\fR. .BE - .SH DESCRIPTION .PP These procedures may be used to disassemble and reassemble Tcl lists. @@ -80,15 +79,18 @@ also holds copies of all the list elements. It is the caller's responsibility to free up all of this storage. For example, suppose that you have called \fBTcl_SplitList\fR with the following code: +.PP .CS int argc, code; char *string; char **argv; \&... -code = Tcl_SplitList(interp, string, &argc, &argv); +code = \fBTcl_SplitList\fR(interp, string, &argc, &argv); .CE +.PP Then you should eventually free the storage with a call like the following: +.PP .CS Tcl_Free((char *) argv); .CE @@ -164,7 +166,6 @@ used to generate a portion of an argument for a Tcl command. In this case, surrounding \fIsrc\fR with curly braces would cause the command not to be parsed correctly. .PP -.VS 8.5 By default, \fBTcl_ConvertElement\fR will use quoting in its output to be sure the first character of an element is not the hash character @@ -176,12 +177,12 @@ is not necessary. When the caller can be sure that the element is not the first element of a list, it can disable quoting of the leading hash character by OR-ing the flag value returned by \fBTcl_ScanElement\fR with \fBTCL_DONT_QUOTE_HASH\fR. -.VE 8.5 .PP \fBTcl_ScanCountedElement\fR and \fBTcl_ConvertCountedElement\fR are the same as \fBTcl_ScanElement\fR and \fBTcl_ConvertElement\fR, except the length of string \fIsrc\fR is specified by the \fIlength\fR argument, and the string may contain embedded nulls. - +.SH "SEE ALSO" +Tcl_ListObjGetElements(3) .SH KEYWORDS backslash, convert, element, list, merge, split, strings diff --git a/doc/SplitPath.3 b/doc/SplitPath.3 index 6578e3d..ec8f96b 100644 --- a/doc/SplitPath.3 +++ b/doc/SplitPath.3 @@ -59,6 +59,7 @@ holds copies of all the path elements. It is the caller's responsibility to free all of this storage. For example, suppose that you have called \fBTcl_SplitPath\fR with the following code: +.PP .CS int argc; char *path; @@ -66,8 +67,10 @@ char **argv; \&... Tcl_SplitPath(string, &argc, &argv); .CE +.PP Then you should eventually free the storage with a call like the following: +.PP .CS Tcl_Free((char *) argv); .CE diff --git a/doc/StaticPkg.3 b/doc/StaticPkg.3 index 0dd67d1..fa6c32f 100644 --- a/doc/StaticPkg.3 +++ b/doc/StaticPkg.3 @@ -29,10 +29,9 @@ Procedure to invoke to incorporate this package into a trusted interpreter. .AP Tcl_PackageInitProc *safeInitProc in Procedure to call to incorporate this package into a safe interpreter -(one that will execute untrusted scripts). NULL means the package +(one that will execute untrusted scripts). NULL means the package cannot be used in safe interpreters. .BE - .SH DESCRIPTION .PP This procedure may be invoked to announce that a package has been @@ -52,9 +51,12 @@ be invoked, depending on whether the target interpreter is safe or not. \fIinitProc\fR and \fIsafeInitProc\fR must both match the following prototype: +.PP .CS -typedef int Tcl_PackageInitProc(Tcl_Interp *\fIinterp\fR); +typedef int \fBTcl_PackageInitProc\fR( + Tcl_Interp *\fIinterp\fR); .CE +.PP The \fIinterp\fR argument identifies the interpreter in which the package is to be loaded. The initialization procedure must return \fBTCL_OK\fR or \fBTCL_ERROR\fR to indicate whether or not it completed successfully; in @@ -62,6 +64,7 @@ the event of an error it should set the interpreter's result to point to an error message. The result or error from the initialization procedure will be returned as the result of the \fBload\fR command that caused the initialization procedure to be invoked. - .SH KEYWORDS initialization procedure, package, static linking +.SH "SEE ALSO" +load(n), package(n), Tcl_PkgRequire(3) diff --git a/doc/StringObj.3 b/doc/StringObj.3 index e451c61..371cdff 100644 --- a/doc/StringObj.3 +++ b/doc/StringObj.3 @@ -60,7 +60,6 @@ void .sp void \fBTcl_AppendStringsToObjVA\fR(\fIobjPtr, argList\fR) -.VS 8.5 .sp void \fBTcl_AppendLimitedToObj\fR(\fIobjPtr, bytes, length, limit, ellipsis\fR) @@ -74,9 +73,8 @@ int Tcl_Obj * \fBTcl_ObjPrintf\fR(\fIformat, ...\fR) .sp -int +void \fBTcl_AppendPrintfToObj\fR(\fIobjPtr, format, ...\fR) -.VE 8.5 .sp void \fBTcl_SetObjLength\fR(\fIobjPtr, newLength\fR) @@ -133,7 +131,9 @@ An argument list which must have been initialised using Maximum number of bytes to be appended. .AP "const char" *ellipsis in Suffix to append when the limit leads to string truncation. -If NULL is passed then the suffix "..." is used. +If NULL is passed then the suffix +.QW "..." +is used. .AP "const char" *format in Format control string including % conversion specifiers. .AP int objc in @@ -144,7 +144,6 @@ The array of objects to format or concatenate. New length for the string value of \fIobjPtr\fR, not including the final null character. .BE - .SH DESCRIPTION .PP The procedures described in this manual entry allow Tcl objects to @@ -251,7 +250,6 @@ must be a NULL pointer to indicate the end of the list. except that instead of taking a variable number of arguments it takes an argument list. .PP -.VS 8.5 \fBTcl_AppendLimitedToObj\fR is similar to \fBTcl_AppendToObj\fR except that it imposes a limit on how many bytes are appended. This can be handy when the string to be appended might be @@ -275,9 +273,11 @@ bytes is necessary to append only whole multi-byte characters. \fBTcl_Format\fR is the C-level interface to the engine of the \fBformat\fR command. The actual command procedure for \fBformat\fR is little more than +.PP .CS -Tcl_Format(interp, Tcl_GetString(objv[1]), objc-2, objv+2); +\fBTcl_Format\fR(interp, \fBTcl_GetString\fR(objv[1]), objc-2, objv+2); .CE +.PP The \fIobjc\fR Tcl_Obj values in \fIobjv\fR are formatted into a string according to the conversion specification in \fIformat\fR argument, following the documentation for the \fBformat\fR command. The resulting formatted @@ -287,22 +287,26 @@ returned, and an error message is recorded in \fIinterp\fR, if \fIinterp\fR is non-NULL. .PP \fBTcl_AppendFormatToObj\fR is an appending alternative form -of \fBTcl_Format\fR with functionality equivalent to +of \fBTcl_Format\fR with functionality equivalent to: +.PP .CS -Tcl_Obj *newPtr = Tcl_Format(interp, format, objc, objv); +Tcl_Obj *newPtr = \fBTcl_Format\fR(interp, format, objc, objv); if (newPtr == NULL) return TCL_ERROR; -Tcl_AppendObjToObj(objPtr, newPtr); +\fBTcl_AppendObjToObj\fR(objPtr, newPtr); return TCL_OK; .CE +.PP but with greater convenience and efficiency when the appending functionality is needed. .PP \fBTcl_ObjPrintf\fR serves as a replacement for the common sequence +.PP .CS char buf[SOME_SUITABLE_LENGTH]; sprintf(buf, format, ...); -Tcl_NewStringObj(buf, -1); +\fBTcl_NewStringObj\fR(buf, -1); .CE +.PP but with greater convenience and no need to determine \fBSOME_SUITABLE_LENGTH\fR. The formatting is done with the same core formatting engine used by \fBTcl_Format\fR. This means the set of @@ -315,23 +319,29 @@ assumption that C code is more likely to know how many bytes it is passing around than the number of encoded characters those bytes happen to represent. The variable number of arguments passed in should be of the types that would be suitable for passing to \fBsprintf\fR. Note in -this example usage, \fIx\fR is of type \fBlong\fR. +this example usage, \fIx\fR is of type \fBint\fR. +.PP .CS -long x = 5; -Tcl_Obj *objPtr = Tcl_ObjPrintf("Value is %d", x); +int x = 5; +Tcl_Obj *objPtr = \fBTcl_ObjPrintf\fR("Value is %d", x); .CE +.PP If the value of \fIformat\fR contains internal inconsistencies or invalid specifier formats, the formatted string result produced by -\fBTcl_ObjPrintf\fR will be an error message describing the error. +\fBTcl_ObjPrintf\fR will be an error message describing the error. +It is impossible however to provide runtime protection against +mismatches between the format and any subsequent arguments. +Compile-time protection may be provided by some compilers. .PP \fBTcl_AppendPrintfToObj\fR is an appending alternative form of \fBTcl_ObjPrintf\fR with functionality equivalent to +.PP .CS -Tcl_AppendObjToObj(objPtr, Tcl_ObjPrintf(format, ...)); +\fBTcl_AppendObjToObj\fR(objPtr, \fBTcl_ObjPrintf\fR(format, ...)); .CE +.PP but with greater convenience and efficiency when the appending functionality is needed. -.VE 8.5 .PP The \fBTcl_SetObjLength\fR procedure changes the length of the string value of its \fIobjPtr\fR argument. If the \fInewLength\fR @@ -367,10 +377,8 @@ white space, then that object is ignored entirely. This white-space removal was added to make the output of the \fBconcat\fR command cleaner-looking. \fBTcl_ConcatObj\fR returns a pointer to a newly-created object whose ref count is zero. - .SH "SEE ALSO" -Tcl_NewObj, Tcl_IncrRefCount, Tcl_DecrRefCount, format, sprintf - +Tcl_NewObj(3), Tcl_IncrRefCount(3), Tcl_DecrRefCount(3), format(n), sprintf(3) .SH KEYWORDS append, internal representation, object, object type, string object, string type, string representation, concat, concatenate, unicode @@ -6,7 +6,7 @@ '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" .so man.macros -.TH Tcl n "8.5" Tcl "Tcl Built-In Commands" +.TH Tcl n "8.6" Tcl "Tcl Built-In Commands" .BS .SH NAME Tcl \- Tool Command Language @@ -48,7 +48,6 @@ as ordinary characters and included in the word. Command substitution, variable substitution, and backslash substitution are performed on the characters between the quotes as described below. The double-quotes are not retained as part of the word. -.VS 8.5 br .IP "[5] \fBArgument expansion.\fR" If a word starts with the string .QW {*} @@ -60,10 +59,9 @@ variable substitutions; backslash substitutions are performed as is normal for a list and individual internal words may be surrounded by either braces or double-quote characters), and its words are added to the command being substituted. For instance, -.QW "cmd a {*}{b [c]} d {*}{$e f \N'34'g h\N'34'}" +.QW "cmd a {*}{b [c]} d {*}{$e f {g h}}" is equivalent to -.QW "cmd a b {[c]} d {$e} f \N'34'g h\N'34'" . -.VE 8.5 +.QW "cmd a b {[c]} d {$e} f {g h}" . .IP "[6] \fBBraces.\fR" If the first character of a word is an open brace .PQ { @@ -106,24 +104,44 @@ Variable substitution may take any of the following forms: .RS .TP 15 \fB$\fIname\fR +. \fIName\fR is the name of a scalar variable; the name is a sequence of one or more characters that are a letter, digit, underscore, or namespace separators (two or more colons). +Letters and digits are \fIonly\fR the standard ASCII ones (\fB0\fR\-\fB9\fR, +\fBA\fR\-\fBZ\fR and \fBa\fR\-\fBz\fR). .TP 15 \fB$\fIname\fB(\fIindex\fB)\fR +. \fIName\fR gives the name of an array variable and \fIindex\fR gives the name of an element within that array. \fIName\fR must contain only letters, digits, underscores, and namespace separators, and may be an empty string. +Letters and digits are \fIonly\fR the standard ASCII ones (\fB0\fR\-\fB9\fR, +\fBA\fR\-\fBZ\fR and \fBa\fR\-\fBz\fR). Command substitutions, variable substitutions, and backslash substitutions are performed on the characters of \fIindex\fR. .TP 15 \fB${\fIname\fB}\fR -\fIName\fR is the name of a scalar variable. It may contain any -characters whatsoever except for close braces. -.LP +. +\fIName\fR is the name of a scalar variable or array element. It may contain +any characters whatsoever except for close braces. It indicates an array +element if \fIname\fR is in the form +.QW \fIarrayName\fB(\fIindex\fB)\fR +where \fIarrayName\fR does not contain any open parenthesis characters, +.QW \fB(\fR , +or close brace characters, +.QW \fB}\fR , +and \fIindex\fR can be any sequence of characters except for close brace +characters. No further +substitutions are performed during the parsing of \fIname\fR. +.PP There may be any number of variable substitutions in a single word. Variable substitution is not performed on words enclosed in braces. +.PP +Note that variables may contain character sequences other than those listed +above, but in that case other mechanisms must be used to access them (e.g., +via the \fBset\fR command's single-argument form). .RE .IP "[9] \fBBackslash substitution.\fR" If a backslash @@ -175,24 +193,34 @@ Backslash .TP 7 \e\fIooo\fR . -The digits \fIooo\fR (one, two, or three of them) give an eight-bit octal -value for the Unicode character that will be inserted. The upper bits of the -Unicode character will be 0. +The digits \fIooo\fR (one, two, or three of them) give a eight-bit octal +value for the Unicode character that will be inserted, in the range \fI000\fR +- \fI377\fR. The parser will stop just before this range overflows, or when +the maximum of three digits is reached. The upper bits of the Unicode +character will be 0. .TP 7 \e\fBx\fIhh\fR . -The hexadecimal digits \fIhh\fR give an eight-bit hexadecimal value for the -Unicode character that will be inserted. Any number of hexadecimal digits -may be present; however, all but the last two are ignored (the result is -always a one-byte quantity). The upper bits of the Unicode character will -be 0. +The hexadecimal digits \fIhh\fR (one or two of them) give an eight-bit +hexadecimal value for the Unicode character that will be inserted. The upper +bits of the Unicode character will be 0. .TP 7 \e\fBu\fIhhhh\fR . The hexadecimal digits \fIhhhh\fR (one, two, three, or four of them) give a sixteen-bit hexadecimal value for the Unicode character that will be -inserted. -.LP +inserted. The upper bits of the Unicode character will be 0. +.TP 7 +\e\fBU\fIhhhhhhhh\fR +. +The hexadecimal digits \fIhhhhhhhh\fR (one up to eight of them) give a +twentiy-one-bit hexadecimal value for the Unicode character that will be +inserted, in the range U+0000..U+10FFFF. The parser will stop just +before this range overflows, or when the maximum of eight digits +is reached. The upper bits of the Unicode character will be 0. +.PP +The range U+010000..U+10FFFD is reserved for the future. +.PP Backslash substitution is not performed on words enclosed in braces, except for backslash-newline as described above. .RE @@ -217,13 +245,15 @@ no substitutions are performed before making the recursive call and no additional substitutions are performed on the result of the nested script. .RS -.LP +.PP Substitutions take place from left to right, and each substitution is evaluated completely before attempting to evaluate the next. Thus, a sequence like +.PP .CS set y [set x 0][incr x][incr x] .CE +.PP will always set the variable \fIy\fR to the value, \fI012\fR. .RE .IP "[12] \fBSubstitution and word boundaries.\fR" @@ -232,3 +262,9 @@ except for argument expansion as specified in rule [5]. For example, during variable substitution the entire value of the variable becomes part of a single word, even if the variable's value contains spaces. +.SH KEYWORDS +backslash, command, comment, script, substitution, variable +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: diff --git a/doc/TclZlib.3 b/doc/TclZlib.3 new file mode 100644 index 0000000..1b5e892 --- /dev/null +++ b/doc/TclZlib.3 @@ -0,0 +1,248 @@ +'\" +'\" Copyright (c) 2008 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH TclZlib 3 8.6 Tcl "Tcl Library Procedures" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +Tcl_ZlibAdler32, Tcl_ZlibCRC32, Tcl_ZlibDeflate, Tcl_ZlibInflate, Tcl_ZlibStreamChecksum, Tcl_ZlibStreamClose, Tcl_ZlibStreamEof, Tcl_ZlibStreamGet, Tcl_ZlibStreamGetCommandName, Tcl_ZlibStreamInit, Tcl_ZlibStreamPut \- compression and decompression functions +.SH SYNOPSIS +.nf +#include <tcl.h> +.sp +int +\fBTcl_ZlibDeflate\fR(\fIinterp, format, dataObj, level, dictObj\fR) +.sp +int +\fBTcl_ZlibInflate\fR(\fIinterp, format, dataObj, dictObj\fR) +.sp +unsigned int +\fBTcl_ZlibCRC32\fR(\fIinitValue, bytes, length\fR) +.sp +unsigned int +\fBTcl_ZlibAdler32\fR(\fIinitValue, bytes, length\fR) +.sp +int +\fBTcl_ZlibStreamInit\fR(\fIinterp, mode, format, level, dictObj, zshandlePtr\fR) +.sp +Tcl_Obj * +\fBTcl_ZlibStreamGetCommandName\fR(\fIzshandle\fR) +.sp +int +\fBTcl_ZlibStreamEof\fR(\fIzshandle\fR) +.sp +int +\fBTcl_ZlibStreamClose\fR(\fIzshandle\fR) +.sp +int +\fBTcl_ZlibStreamReset\fR(\fIzshandle\fR) +.sp +int +\fBTcl_ZlibStreamChecksum\fR(\fIzshandle\fR) +.sp +int +\fBTcl_ZlibStreamPut\fR(\fIzshandle, dataObj, flush\fR) +.sp +int +\fBTcl_ZlibStreamGet\fR(\fIzshandle, dataObj, count\fR) +.fi +.SH ARGUMENTS +.AS Tcl_ZlibStream *zshandlePtr out +.AP Tcl_Interp *interp in +The interpreter to store resulting compressed or uncompressed data in. Also +where any error messages are written. For \fBTcl_ZlibStreamInit\fR, this can +be NULL to create a stream that is not bound to a command. +.AP int format in +What format of compressed data to work with. Must be one of +\fBTCL_ZLIB_FORMAT_ZLIB\fR for zlib-format data, \fBTCL_ZLIB_FORMAT_GZIP\fR +for gzip-format data, or \fBTCL_ZLIB_FORMAT_RAW\fR for raw compressed data. In +addition, for decompression only, \fBTCL_ZLIB_FORMAT_AUTO\fR may also be +chosen which can automatically detect whether the compressed data was in zlib +or gzip format. +.AP Tcl_Obj *dataObj in/out +A byte-array object containing the data to be compressed or decompressed, or +to which the data extracted from the stream is appended when passed to +\fBTcl_ZlibStreamGet\fR. +.AP int level in +What level of compression to use. Should be a number from 0 to 9 or one of the +following: \fBTCL_ZLIB_COMPRESS_NONE\fR for no compression, +\fBTCL_ZLIB_COMPRESS_FAST\fR for fast but inefficient compression, +\fBTCL_ZLIB_COMPRESS_BEST\fR for slow but maximal compression, or +\fBTCL_ZLIB_COMPRESS_DEFAULT\fR for the level recommended by the zlib library. +.AP Tcl_Obj *dictObj in/out +A dictionary that contains, or which will be updated to contain, a description +of the gzip header associated with the compressed data. Only useful when the +\fIformat\fR is \fBTCL_ZLIB_FORMAT_GZIP\fR or \fBTCL_ZLIB_FORMAT_AUTO\fR. If +a NULL is passed, a default header will be used on compression and the header +will be ignored (apart from integrity checks) on decompression. See the +section \fBGZIP OPTIONS DICTIONARY\fR for details about the contents of this +dictionary. +.AP "unsigned int" initValue in +The initial value for the checksum algorithm. +.AP "unsigned char" *bytes in +An array of bytes to run the checksum algorithm over, or NULL to get the +recommended initial value for the checksum algorithm. +.AP int length in +The number of bytes in the array. +.AP int mode in +What mode to operate the stream in. Should be either +\fBTCL_ZLIB_STREAM_DEFLATE\fR for a compressing stream or +\fBTCL_ZLIB_STREAM_INFLATE\fR for a decompressing stream. +.AP Tcl_ZlibStream *zshandlePtr out +A pointer to a variable in which to write the abstract token for the stream +upon successful creation. +.AP Tcl_ZlibStream zshandle in +The abstract token for the stream to operate on. +.AP int flush in +Whether and how to flush the stream after writing the data to it. Must be one +of: \fBTCL_ZLIB_NO_FLUSH\fR if no flushing is to be done, \fBTCL_ZLIB_FLUSH\fR +if the currently compressed data must be made available for access using +\fBTcl_ZlibStreamGet\fR, \fBTCL_ZLIB_FULLFLUSH\fR if the stream must be put +into a state where the decompressor can recover from on corruption, or +\fBTCL_ZLIB_FINALIZE\fR to ensure that the stream is finished and that any +trailer demanded by the format is written. +.AP int count in +The maximum number of bytes to get from the stream, or -1 to get all remaining +bytes from the stream's buffers. +.BE +.SH DESCRIPTION +These functions form the interface from the Tcl library to the Zlib +library by Jean-loup Gailly and Mark Adler. +.PP +\fBTcl_ZlibDeflate\fR and \fBTcl_ZlibInflate\fR respectively compress and +decompress the data contained in the \fIdataObj\fR argument, according to the +\fIformat\fR and, for compression, \fIlevel\fR arguments. The dictionary in +the \fIdictObj\fR parameter is used to convey additional header information +about the compressed data when the compression format supports it; currently, +the dictionary is only used when the \fIformat\fR parameter is +\fBTCL_ZLIB_FORMAT_GZIP\fR or \fBTCL_ZLIB_FORMAT_AUTO\fR. For details of the +contents of the dictionary, see the \fBGZIP OPTIONS DICTIONARY\fR section +below. Upon success, both functions leave the resulting compressed or +decompressed data in a byte-array object that is the Tcl interpreter's result; +the returned value is a standard Tcl result code. +.PP +\fBTcl_ZlibAdler32\fR and \fBTcl_ZlibCRC32\fR compute checksums on arrays of +bytes, returning the computed checksum. Checksums are computed incrementally, +allowing data to be processed one block at a time, but this requires the +caller to maintain the current checksum and pass it in as the \fIinitValue\fR +parameter; the initial value to use for this can be obtained by using NULL for +the \fIbytes\fR parameter instead of a pointer to the array of bytes to +compute the checksum over. Thus, typical usage in the single data block case +is like this: +.PP +.CS +checksum = \fBTcl_ZlibCRC32\fR(\fBTcl_ZlibCRC32\fR(0,NULL,0), data, length); +.CE +.PP +Note that the Adler-32 algorithm is not a real checksum, but instead is a +related type of hash that works best on longer data. +.SS "ZLIB STREAMS" +.PP +\fBTcl_ZlibStreamInit\fR creates a compressing or decompressing stream that is +linked to a Tcl command, according to its arguments, and provides an abstract +token for the stream and returns a normal Tcl result code; +\fBTcl_ZlibStreamGetCommandName\fR returns the name of that command given the +stream token, or NULL if the stream has no command. Streams are not designed +to be thread-safe; each stream should only ever be used from the thread that +created it. When working with gzip streams, a dictionary (fields as given in +the \fBGZIP OPTIONS DICTIONARY\fR section below) can be given via the +\fIdictObj\fR parameter that on compression allows control over the generated +headers, and on decompression allows discovery of the existing headers. Note +that the dictionary will be written to on decompression once sufficient data +has been read to have a complete header. This means that the dictionary must +be an unshared object in that case; a blank object created with +\fBTcl_NewObj\fR is suggested. +.PP +Once a stream has been constructed, \fBTcl_ZlibStreamPut\fR is used to add +data to the stream and \fBTcl_ZlibStreamGet\fR is used to retrieve data from +the stream after processing. Both return normal Tcl result codes and leave an +error message in the result of the interpreter that the stream is registered +with in the error case (if such a registration has been performed). With +\fBTcl_ZlibStreamPut\fR, the data buffer object passed to it should not be +modified afterwards. With \fBTcl_ZlibStreamGet\fR, the data buffer object +passed to it will have the data bytes appended to it. Internally to the +stream, data is kept compressed so as to minimize the cost of buffer space. +.PP +\fBTcl_ZlibStreamChecksum\fR returns the checksum computed over the +uncompressed data according to the format, and \fBTcl_ZlibStreamEof\fR returns +a boolean value indicating whether the end of the uncompressed data has been +reached. +.PP +If you wish to clear a stream and reuse it for a new compression or +decompression action, \fBTcl_ZlibStreamReset\fR will do this and return a +normal Tcl result code to indicate whether it was successful; if the stream is +registered with an interpreter, an error message will be left in the +interpreter result when this function returns TCL_ERROR. +Finally, \fBTcl_ZlibStreamClose\fR will clean up the stream and delete the +associated command: using \fBTcl_DeleteCommand\fR on the stream's command is +equivalent (when such a command exists). +.SH "GZIP OPTIONS DICTIONARY" +.PP +The \fIdictObj\fR parameter to \fBTcl_ZlibDeflate\fR, \fBTcl_ZlibInflate\fR +and \fBTcl_ZlibStreamInit\fR is used to pass a dictionary of options about +that is used to describe the gzip header in the compressed data. When creating +compressed data, the dictionary is read and when unpacking compressed data the +dictionary is written (in which case the \fIdictObj\fR parameter must refer to +an unshared dictionary object). +.PP +The following fields in the dictionary object are understood. All other fields +are ignored. No field is required when creating a gzip-format stream. +.TP +\fBcomment\fR +. +This holds the comment field of the header, if present. If absent, no comment +was supplied (on decompression) or will be created (on compression). +.TP +\fBcrc\fR +. +A boolean value describing whether a CRC of the header is computed. Note that +the \fBgzip\fR program does \fInot\fR use or allow a CRC on the header. +.TP +\fBfilename\fR +. +The name of the file that held the uncompressed data. This should not contain +any directory separators, and should be sanitized before use on decompression +with \fBfile tail\fR. +.TP +\fBos\fR +. +The operating system type code field from the header (if not the +.QW unknown +value). See RFC 1952 for the meaning of these codes. On compression, if this +is absent then the field will be set to the +.QW unknown +value. +.TP +\fBsize\fR +. +The size of the uncompressed data. This is ignored on compression; the size +of the data compressed depends on how much data is supplied to the +compression engine. +.TP +\fBtime\fR +. +The time field from the header if non-zero, expected to be the time that the +file named by the \fBfilename\fR field was modified. Suitable for use with +\fBclock format\fR. On creation, the right value to use is that from +\fBclock seconds\fR or \fBfile mtime\fR. +.TP +\fBtype\fR +. +The type of the uncompressed data (either \fBbinary\fR or \fBtext\fR) if +known. +.SH "PORTABILITY NOTES" +These functions will fail gracefully if Tcl is not linked with the zlib +library. +.SH "SEE ALSO" +Tcl_NewByteArrayObj(3), zlib(n) +'\"Tcl_StackChannel(3) +.SH "KEYWORDS" +compress, decompress, deflate, gzip, inflate +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: diff --git a/doc/Tcl_Main.3 b/doc/Tcl_Main.3 index 54b2e84..0a69835 100644 --- a/doc/Tcl_Main.3 +++ b/doc/Tcl_Main.3 @@ -10,27 +10,39 @@ .TH Tcl_Main 3 8.4 Tcl "Tcl Library Procedures" .BS .SH NAME -Tcl_Main, Tcl_SetMainLoop \- main program and event loop definition for Tcl-based applications +Tcl_Main, Tcl_SetStartupScript, Tcl_GetStartupScript, Tcl_SetMainLoop \- main program, startup script, and event loop definition for Tcl-based applications .SH SYNOPSIS .nf \fB#include <tcl.h>\fR .sp \fBTcl_Main\fR(\fIargc, argv, appInitProc\fR) .sp +\fBTcl_SetStartupScript\fR(\fIpath, encoding\fR) +.sp +Tcl_Obj * +\fBTcl_GetStartupScript\fR(\fIencodingPtr\fR) +.sp \fBTcl_SetMainLoop\fR(\fImainLoopProc\fR) .SH ARGUMENTS .AS Tcl_MainLoopProc *mainLoopProc .AP int argc in Number of elements in \fIargv\fR. .AP char *argv[] in -Array of strings containing command-line arguments. +Array of strings containing command-line arguments. On Windows, when +using -DUNICODE, the parameter type changes to wchar_t *. .AP Tcl_AppInitProc *appInitProc in Address of an application-specific initialization procedure. The value for this argument is usually \fBTcl_AppInit\fR. +.AP Tcl_Obj *path in +Name of file to use as startup script, or NULL. +.AP "const char" *encoding in +Encoding of file to use as startup script, or NULL. +.AP "const char" **encodingPtr out +If non-NULL, location to write a copy of the (const char *) +pointing to the encoding name. .AP Tcl_MainLoopProc *mainLoopProc in Address of an application-specific event loop procedure. .BE - .SH DESCRIPTION .PP \fBTcl_Main\fR can serve as the main program for Tcl-based shell @@ -46,7 +58,7 @@ library and interactive shell operation. Other styles of embedding Tcl in an application are not supported by \fBTcl_Main\fR. Those must be achieved by calling lower level functions in the Tcl library directly. - +.PP The \fBTcl_Main\fR function has been offered by the Tcl library since release Tcl 7.4. In older releases of Tcl, the Tcl library itself defined a function \fBmain\fR, but that lacks flexibility @@ -75,17 +87,46 @@ restriction is not a problem with normal use described above. channels to their default values. See \fBTcl_StandardChannels\fR for more information. .PP -\fBTcl_Main\fR supports two modes of operation, depending on the -values of \fIargc\fR and \fIargv\fR. If the first few arguments -in \fIargv\fR match ?\fB\-encoding \fIname\fR? \fIfileName\fR, +\fBTcl_Main\fR supports two modes of operation, depending on +whether the filename and encoding of a startup script has been +established. The routines \fBTcl_SetStartupScript\fR and +\fBTcl_GetStartupScript\fR are the tools for controlling this +configuration of \fBTcl_Main\fR. +.PP +\fBTcl_SetStartupScript\fR registers the value \fIpath\fR +as the name of the file for \fBTcl_Main\fR to evaluate as +its startup script. The value \fIencoding\fR is Tcl's name +for the encoding used to store the text in that file. A +value of \fBNULL\fR for \fIencoding\fR is a signal to use +the system encoding. A value of \fBNULL\fR for \fIpath\fR +erases any existing registration so that \fBTcl_Main\fR +will not evaluate any startup script. +.PP +\fBTcl_GetStartupScript\fR queries the registered file name +and encoding set by the most recent \fBTcl_SetStartupScript\fR +call in the same thread. The stored file name is returned, +and the stored encoding name is written to space pointed to +by \fIencodingPtr\fR, when that is not NULL. +.PP +The file name and encoding values managed by the routines +\fBTcl_SetStartupScript\fR and \fBTcl_GetStartupScript\fR +are stored per-thread. Although the storage and retrieval +functions of these routines work in any thread, only those +calls in the same master thread as \fBTcl_Main\fR can have +any influence on it. +.PP +The caller of \fBTcl_Main\fR may call \fBTcl_SetStartupScript\fR +first to establish its desired startup script. If \fBTcl_Main\fR +finds that no such startup script has been established, it consults +the first few arguments in \fIargv\fR. If they match +?\fB\-encoding \fIname\fR? \fIfileName\fR, where \fIfileName\fR does not begin with the character \fI\-\fR, then \fIfileName\fR is taken to be the name of a file containing a \fIstartup script\fR, and \fIname\fR is taken to be the name -of the encoding of the contents of that file, which \fBTcl_Main\fR -will attempt to evaluate. Otherwise, \fBTcl_Main\fR will enter an -interactive mode. +of the encoding of the contents of that file. \fBTcl_Main\fR +then calls \fBTcl_SetStartupScript\fR with these values. .PP -In either mode, \fBTcl_Main\fR will define in its master interpreter +\fBTcl_Main\fR then defines in its master interpreter the Tcl variables \fIargc\fR, \fIargv\fR, \fIargv0\fR, and \fItcl_interactive\fR, as described in the documentation for \fBtclsh\fR. .PP @@ -95,22 +136,27 @@ commands, \fBTcl_Main\fR calls the procedure given by the .QW hook for the application to perform its own initialization of the interpreter created by \fBTcl_Main\fR, such as defining application-specific -commands. The procedure must have an interface that matches the -type \fBTcl_AppInitProc\fR: +commands. The application initialization routine might also +call \fBTcl_SetStartupScript\fR to (re-)set the file and encoding +to be used as a startup script. The procedure must have an interface +that matches the type \fBTcl_AppInitProc\fR: +.PP .CS -typedef int Tcl_AppInitProc(Tcl_Interp *\fIinterp\fR); +typedef int \fBTcl_AppInitProc\fR( + Tcl_Interp *\fIinterp\fR); .CE - +.PP \fIAppInitProc\fR is almost always a pointer to \fBTcl_AppInit\fR; for more details on this procedure, see the documentation for \fBTcl_AppInit\fR. .PP -When the \fIappInitProc\fR is finished, \fBTcl_Main\fR enters one -of its two modes. If a startup script has been provided, \fBTcl_Main\fR -attempts to evaluate it. Otherwise, interactive mode begins with -examination of the variable \fItcl_rcFileName\fR in the master -interpreter. If that variable exists and holds the name of a readable -file, the contents of that file are evaluated in the master interpreter. -Then interactive operations begin, +When the \fIappInitProc\fR is finished, \fBTcl_Main\fR calls +\fBTcl_GetStartupScript\fR to determine what startup script has +been requested, if any. If a startup script has been provided, +\fBTcl_Main\fR attempts to evaluate it. Otherwise, interactive +mode begins with examination of the variable \fItcl_rcFileName\fR +in the master interpreter. If that variable exists and holds the +name of a readable file, the contents of that file are evaluated +in the master interpreter. Then interactive operations begin, with prompts and command evaluation results written to the standard output channel, and commands read from the standard input channel and then evaluated. The prompts written to the standard output @@ -129,8 +175,9 @@ When the loop procedure returns in interactive mode, interactive operation will continue. The main loop procedure must have an interface that matches the type \fBTcl_MainLoopProc\fR: +.PP .CS -typedef void Tcl_MainLoopProc(void); +typedef void \fBTcl_MainLoopProc\fR(void); .CE .PP \fBTcl_Main\fR does not return. Normally a program based on @@ -142,10 +189,8 @@ procedure (if any) returns. In non-interactive mode, after \fBTcl_Main\fR evaluates the startup script, and the main loop procedure (if any) returns, \fBTcl_Main\fR will also evaluate the \fBexit\fR command. - .SH "SEE ALSO" tclsh(1), Tcl_GetStdChannel(3), Tcl_StandardChannels(3), Tcl_AppInit(3), -exit(n) - +exit(n), encoding(n) .SH KEYWORDS application-specific initialization, command-line arguments, main program diff --git a/doc/Thread.3 b/doc/Thread.3 index 80d34ad..4b5e7c3 100644 --- a/doc/Thread.3 +++ b/doc/Thread.3 @@ -36,17 +36,17 @@ void \fBTcl_MutexFinalize\fR(\fImutexPtr\fR) .sp int -\fBTcl_CreateThread\fR(\fIidPtr, threadProc, clientData, stackSize, flags\fR) +\fBTcl_CreateThread\fR(\fIidPtr, proc, clientData, stackSize, flags\fR) .sp int \fBTcl_JoinThread\fR(\fIid, result\fR) .SH ARGUMENTS -.AS Tcl_CreateThreadProc threadProc out +.AS Tcl_CreateThreadProc proc out .AP Tcl_Condition *condPtr in A condition variable, which must be associated with a mutex lock. .AP Tcl_Mutex *mutexPtr in A mutex lock. -.AP Tcl_Time *timePtr in +.AP "const Tcl_Time" *timePtr in A time limit on the condition wait. NULL to wait forever. Note that a polling value of 0 seconds does not make much sense. .AP Tcl_ThreadDataKey *keyPtr in @@ -62,11 +62,11 @@ The referred storage will contain the id of the newly created thread as returned by the operating system. .AP Tcl_ThreadId id in Id of the thread waited upon. -.AP Tcl_ThreadCreateProc threadProc in +.AP Tcl_ThreadCreateProc *proc in This procedure will act as the \fBmain()\fR of the newly created thread. The specified \fIclientData\fR will be its sole argument. .AP ClientData clientData in -Arbitrary information. Passed as sole argument to the \fIthreadProc\fR. +Arbitrary information. Passed as sole argument to the \fIproc\fR. .AP int stackSize in The size of the stack given to the new thread. .AP int flags in @@ -180,13 +180,59 @@ explicitly by calls to \fBTcl_MutexFinalize\fR or \fBTcl_ConditionFinalize\fR. Thread local storage is reclaimed during \fBTcl_FinalizeThread\fR. .SH "SCRIPT-LEVEL ACCESS TO THREADS" -.VS 8.5 +.PP Tcl provides no built-in commands for scripts to use to create, manage, or join threads, nor any script-level access to mutex or condition variables. It provides such facilities only via C interfaces, and leaves it up to packages to expose these matters to the script level. One such package is the \fBThread\fR package. -.VE 8.5 +.SH EXAMPLE +.PP +To create a thread with portable code, its implementation function should be +declared as follows: +.PP +.CS +static \fBTcl_ThreadCreateProc\fR MyThreadImplFunc; +.CE +.PP +It should then be defined like this example, which just counts up to a given +value and then finishes. +.PP +.CS +static \fBTcl_ThreadCreateType\fR +MyThreadImplFunc( + ClientData clientData) +{ + int i, limit = (int) clientData; + for (i=0 ; i<limit ; i++) { + /* doing nothing at all here */ + } + \fBTCL_THREAD_CREATE_RETURN\fR; +} +.CE +.PP +To create the above thread, make it execute, and wait for it to finish, we +would do this: +.PP +.CS +int limit = 1000000000; +ClientData limitData = (void*)((intptr_t) limit); +Tcl_ThreadId id; \fI/* holds identity of thread created */\fR +int result; + +if (\fBTcl_CreateThread\fR(&id, MyThreadImplFunc, limitData, + \fBTCL_THREAD_STACK_DEFAULT\fR, + \fBTCL_THREAD_JOINABLE\fR) != TCL_OK) { + \fI/* Thread did not create correctly */\fR + return; +} +\fI/* Do something else for a while here */\fR +if (\fBTcl_JoinThread\fR(id, &result) != TCL_OK) { + \fI/* Thread did not finish properly */\fR + return; +} +\fI/* All cleaned up nicely */\fR +.CE .SH "SEE ALSO" Tcl_GetCurrentThread(3), Tcl_ThreadQueueEvent(3), Tcl_ThreadAlert(3), Tcl_ExitThread(3), Tcl_FinalizeThread(3), Tcl_CreateThreadExitHandler(3), diff --git a/doc/TraceCmd.3 b/doc/TraceCmd.3 index 020f1ca..5cc1337 100644 --- a/doc/TraceCmd.3 +++ b/doc/TraceCmd.3 @@ -62,14 +62,16 @@ Invoke \fIproc\fR when the command is deleted. Whenever one of the specified operations occurs to the command, \fIproc\fR will be invoked. It should have arguments and result that match the type \fBTcl_CommandTraceProc\fR: +.PP .CS -typedef void Tcl_CommandTraceProc( +typedef void \fBTcl_CommandTraceProc\fR( ClientData \fIclientData\fR, Tcl_Interp *\fIinterp\fR, const char *\fIoldName\fR, const char *\fInewName\fR, int \fIflags\fR); .CE +.PP The \fIclientData\fR and \fIinterp\fR parameters will have the same values as those passed to \fBTcl_TraceCommand\fR when the trace was created. \fIClientData\fR typically points to an application-specific diff --git a/doc/TraceVar.3 b/doc/TraceVar.3 index f80d86f..6201a4f 100644 --- a/doc/TraceVar.3 +++ b/doc/TraceVar.3 @@ -121,14 +121,16 @@ Whenever one of the specified operations occurs on the variable, \fIproc\fR will be invoked. It should have arguments and result that match the type \fBTcl_VarTraceProc\fR: +.PP .CS -typedef char *Tcl_VarTraceProc( +typedef char *\fBTcl_VarTraceProc\fR( ClientData \fIclientData\fR, Tcl_Interp *\fIinterp\fR, char *\fIname1\fR, char *\fIname2\fR, int \fIflags\fR); .CE +.PP The \fIclientData\fR and \fIinterp\fR parameters will have the same values as those passed to \fBTcl_TraceVar\fR when the trace was created. @@ -372,5 +374,7 @@ set. .PP Array traces are not yet integrated with the Tcl \fBinfo exists\fR command, nor is there Tcl-level access to array traces. +.SH "SEE ALSO" +trace(n) .SH KEYWORDS clientData, trace, variable diff --git a/doc/Translate.3 b/doc/Translate.3 index d434cda..55233c3 100644 --- a/doc/Translate.3 +++ b/doc/Translate.3 @@ -29,7 +29,6 @@ At the time of the call it should be uninitialized or free. The caller must eventually call \fBTcl_DStringFree\fR to free up anything stored here. .BE - .SH DESCRIPTION .PP This utility procedure translates a file name to a platform-specific form @@ -38,11 +37,11 @@ passing to the local operating system. In particular, it converts network names into native form and does tilde substitution. .PP However, with the advent of the newer \fBTcl_FSGetNormalizedPath\fR and -\fBTcl_GetNativePath\fR, there is no longer any need to use this -procedure. In particular, \fBTcl_GetNativePath\fR performs all the +\fBTcl_FSGetNativePath\fR, there is no longer any need to use this +procedure. In particular, \fBTcl_FSGetNativePath\fR performs all the necessary translation and encoding conversion, is virtual-filesystem aware, and caches the native result for faster repeated calls. -Finally \fBTcl_GetNativePath\fR does not require you to free anything +Finally \fBTcl_FSGetNativePath\fR does not require you to free anything afterwards. .PP If @@ -66,9 +65,7 @@ frees the dynamic string itself so that the caller need not call .PP The caller is responsible for making sure that the interpreter's result has its default empty value when \fBTcl_TranslateFileName\fR is invoked. - .SH "SEE ALSO" -filename - +filename(n) .SH KEYWORDS file name, home directory, tilde, translate, user @@ -13,7 +13,7 @@ Tcl_UniChar, Tcl_UniCharCaseMatch, Tcl_UniCharNcasecmp, Tcl_UniCharToUtf, Tcl_Ut .nf \fB#include <tcl.h>\fR .sp -typedef ... Tcl_UniChar; +typedef ... \fBTcl_UniChar\fR; .sp int \fBTcl_UniCharToUtf\fR(\fIch, buf\fR) diff --git a/doc/WrongNumArgs.3 b/doc/WrongNumArgs.3 index 2175858..a2908e9 100644 --- a/doc/WrongNumArgs.3 +++ b/doc/WrongNumArgs.3 @@ -29,7 +29,6 @@ Additional error information to print after leading arguments from \fIobjv\fR. This typically gives the acceptable syntax of the command. This argument may be NULL. .BE - .SH DESCRIPTION .PP \fBTcl_WrongNumArgs\fR is a utility procedure that is invoked by @@ -43,13 +42,17 @@ elements of \fIobjv\fR plus \fImessage\fR. For example, if .QW "\fBfileName count\fR" then \fIinterp\fR's result object will be set to the following string: +.PP .CS wrong # args: should be "foo fileName count" .CE +.PP If \fIobjc\fR is 2, the result will be set to the following string: +.PP .CS wrong # args: should be "foo bar fileName count" .CE +.PP \fIObjc\fR is usually 1, but may be 2 or more for commands like \fBstring\fR and the Tk widget commands, which use the first argument as a subcommand. @@ -66,12 +69,11 @@ originally passed in. Using the above example, let us assume that \fIbar\fR is actually an abbreviation for \fIbarfly\fR and the object is now an indexObject because it was passed to \fBTcl_GetIndexFromObj\fR. In this case the error message would be: +.PP .CS wrong # args: should be "foo barfly fileName count" .CE - .SH "SEE ALSO" -Tcl_GetIndexFromObj - +Tcl_GetIndexFromObj(3) .SH KEYWORDS command, error message, wrong number of arguments diff --git a/doc/after.n b/doc/after.n index 21961d3..d6181c6 100644 --- a/doc/after.n +++ b/doc/after.n @@ -24,7 +24,6 @@ after \- Execute a command after a time delay .sp \fBafter info \fR?\fIid\fR? .BE - .SH DESCRIPTION .PP This command is used to delay execution of the program or to execute @@ -32,12 +31,14 @@ a command in background sometime in the future. It has several forms, depending on the first argument to the command: .TP \fBafter \fIms\fR +. \fIMs\fR must be an integer giving a time in milliseconds. The command sleeps for \fIms\fR milliseconds and then returns. While the command is sleeping the application does not respond to events. .TP \fBafter \fIms \fR?\fIscript script script ...\fR? +. In this form the command returns immediately, but it arranges for a Tcl command to be executed \fIms\fR milliseconds later as an event handler. @@ -48,11 +49,12 @@ The command will be executed at global level (outside the context of any Tcl procedure). If an error occurs while executing the delayed command then the background error will be reported by the command -registered with \fB interp bgerror\fR. +registered with \fBinterp bgerror\fR. The \fBafter\fR command returns an identifier that can be used to cancel the delayed command using \fBafter cancel\fR. .TP \fBafter cancel \fIid\fR +. Cancels the execution of a delayed command that was previously scheduled. \fIId\fR indicates which command should be canceled; it must have @@ -61,14 +63,16 @@ If the command given by \fIid\fR has already been executed then the \fBafter cancel\fR command has no effect. .TP \fBafter cancel \fIscript script ...\fR +. This command also cancels the execution of a delayed command. The \fIscript\fR arguments are concatenated together with space separators (just as in the \fBconcat\fR command). If there is a pending command that matches the string, it is -cancelled and will never be executed; if no such command is +canceled and will never be executed; if no such command is currently pending then the \fBafter cancel\fR command has no effect. .TP \fBafter idle \fIscript \fR?\fIscript script ...\fR? +. Concatenates the \fIscript\fR arguments together with space separators (just as in the \fBconcat\fR command), and arranges for the resulting script to be evaluated later as an idle callback. @@ -78,9 +82,10 @@ The command returns an identifier that can be used to cancel the delayed command using \fBafter cancel\fR. If an error occurs while executing the script then the background error will be reported by the command -registered with \fB interp bgerror\fR. +registered with \fBinterp bgerror\fR. .TP \fBafter info \fR?\fIid\fR? +. This command returns information about existing event handlers. If no \fIid\fR argument is supplied, the command returns a list of the identifiers for all existing @@ -88,7 +93,7 @@ event handlers created by the \fBafter\fR command for this interpreter. If \fIid\fR is supplied, it specifies an existing handler; \fIid\fR must have been the return value from some previous call -to \fBafter\fR and it must not have triggered yet or been cancelled. +to \fBafter\fR and it must not have triggered yet or been canceled. In this case the command returns a list with two elements. The first element of the list is the script associated with \fIid\fR, and the second element is either @@ -104,14 +109,16 @@ and \fBupdate\fR commands. .SH "EXAMPLES" This defines a command to make Tcl do nothing at all for \fIN\fR seconds: +.PP .CS proc sleep {N} { - \fBafter\fR [expr {int($N * 1000)}] + \fBafter\fR [expr {int($N * 1000)}] } .CE .PP This arranges for the command \fIwake_up\fR to be run in eight hours (providing the event loop is active at that time): +.PP .CS \fBafter\fR [expr {1000 * 60 * 60 * 8}] wake_up .CE @@ -126,17 +133,19 @@ processing steps (arranging for the next step to be done using an already-triggered timer event only when the event queue has been drained) and is useful when you want to ensure that a Tk GUI remains responsive during a slow task. +.PP .CS proc doOneStep {} { - if {[::my_calc::one_step]} { - \fBafter idle\fR [list \fBafter\fR 0 doOneStep] - } + if {[::my_calc::one_step]} { + \fBafter idle\fR [list \fBafter\fR 0 doOneStep] + } } doOneStep .CE - .SH "SEE ALSO" concat(n), interp(n), update(n), vwait(n) - .SH KEYWORDS cancel, delay, idle callback, sleep, time +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/append.n b/doc/append.n index dc9adbe..034068d 100644 --- a/doc/append.n +++ b/doc/append.n @@ -14,7 +14,6 @@ append \- Append to variable .SH SYNOPSIS \fBappend \fIvarName \fR?\fIvalue value value ...\fR? .BE - .SH DESCRIPTION .PP Append all of the \fIvalue\fR arguments to the current value @@ -32,17 +31,19 @@ is much more efficient than if \fB$a\fR is long. .SH EXAMPLE Building a string of comma-separated numbers piecemeal using a loop. +.PP .CS set var 0 for {set i 1} {$i<=10} {incr i} { - \fBappend\fR var "," $i + \fBappend\fR var "," $i } puts $var # Prints 0,1,2,3,4,5,6,7,8,9,10 .CE - .SH "SEE ALSO" concat(n), lappend(n) - .SH KEYWORDS append, variable +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/apply.n b/doc/apply.n index 8a38aac..9d373e1 100644 --- a/doc/apply.n +++ b/doc/apply.n @@ -48,30 +48,32 @@ The semantics of \fBapply\fR can also be described by: .PP .CS proc apply {fun args} { - set len [llength $fun] - if {($len < 2) || ($len > 3)} { - error "can't interpret \e"$fun\e" as anonymous function" - } - lassign $fun argList body ns - set name ::$ns::[getGloballyUniqueName] - set body0 { - rename [lindex [info level 0] 0] {} - } - proc $name $argList ${body0}$body - set code [catch {uplevel 1 $name $args} res opt] - return -options $opt $res + set len [llength $fun] + if {($len < 2) || ($len > 3)} { + error "can't interpret \e"$fun\e" as anonymous function" + } + lassign $fun argList body ns + set name ::$ns::[getGloballyUniqueName] + set body0 { + rename [lindex [info level 0] 0] {} + } + proc $name $argList ${body0}$body + set code [catch {uplevel 1 $name $args} res opt] + return -options $opt $res } .CE .SH EXAMPLES +.PP This shows how to make a simple general command that applies a transformation to each element of a list. +.PP .CS proc map {lambda list} { - set result {} - foreach item $list { - lappend result [\fBapply\fR $lambda $item] - } - return $result + set result {} + foreach item $list { + lappend result [\fBapply\fR $lambda $item] + } + return $result } map {x {return [string length $x]:$x}} {a bb ccc dddd} \fI\(-> 1:a 2:bb 3:ccc 4:dddd\fR @@ -81,11 +83,12 @@ map {x {expr {$x**2 + 3*$x - 2}}} {-4 -3 -2 -1 0 1 2 3 4} .PP The \fBapply\fR command is also useful for defining callbacks for use in the \fBtrace\fR command: +.PP .CS set vbl "123abc" trace add variable vbl write {\fBapply\fR {{v1 v2 op} { - upvar 1 $v1 v - puts "updated variable to \e"$v\e"" + upvar 1 $v1 v + puts "updated variable to \e"$v\e"" }}} set vbl 123 set vbl abc @@ -93,4 +96,7 @@ set vbl abc .SH "SEE ALSO" proc(n), uplevel(n) .SH KEYWORDS -argument, procedure, anonymous function +anonymous function, argument, lambda, procedure, +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/array.n b/doc/array.n index e112c23..47f9624 100644 --- a/doc/array.n +++ b/doc/array.n @@ -136,14 +136,14 @@ The command always returns an empty string. .SH EXAMPLES .CS \fBarray set\fR colorcount { - red 1 - green 5 - blue 4 - white 9 + red 1 + green 5 + blue 4 + white 9 } foreach {color count} [\fBarray get\fR colorcount] { - puts "Color: $color Count: $count" + puts "Color: $color Count: $count" } \fB\(->\fR Color: blue Count: 4 Color: white Count: 9 @@ -151,7 +151,7 @@ foreach {color count} [\fBarray get\fR colorcount] { Color: red Count: 1 foreach color [\fBarray names\fR colorcount] { - puts "Color: $color Count: $colorcount($color)" + puts "Color: $color Count: $colorcount($color)" } \fB\(->\fR Color: blue Count: 4 Color: white Count: 9 @@ -159,7 +159,7 @@ foreach color [\fBarray names\fR colorcount] { Color: red Count: 1 foreach color [lsort [\fBarray names\fR colorcount]] { - puts "Color: $color Count: $colorcount($color)" + puts "Color: $color Count: $colorcount($color)" } \fB\(->\fR Color: blue Count: 4 Color: green Count: 5 diff --git a/doc/bgerror.n b/doc/bgerror.n index cb91351..ac53eca 100644 --- a/doc/bgerror.n +++ b/doc/bgerror.n @@ -14,9 +14,8 @@ bgerror \- Command invoked to process background errors .SH SYNOPSIS \fBbgerror \fImessage\fR .BE - .SH DESCRIPTION -.VS 8.5 +.PP Release 8.5 of Tcl supports the \fBinterp bgerror\fR command, which allows applications to register in an interpreter the command that will handle background errors in that interpreter. In older @@ -28,7 +27,6 @@ describes the interface requirements of the \fBbgerror\fR command an application might define to retain compatibility with pre-8.5 releases of Tcl. Applications intending to support only Tcl releases 8.5 and later should simply make use of \fBinterp bgerror\fR. -.VE 8.5 .PP The \fBbgerror\fR command does not exist as built-in part of Tcl. Instead, individual applications or users can define a \fBbgerror\fR @@ -75,7 +73,9 @@ The reason for this is that the application programmer may also want to define a \fBbgerror\fR, or use other code that does and thus will have trouble integrating your code. .SH "EXAMPLE" +.PP This \fBbgerror\fR procedure appends errors to a file, with a timestamp. +.PP .CS proc bgerror {message} { set timestamp [clock format [clock seconds]] @@ -84,9 +84,7 @@ proc bgerror {message} { close $fl } .CE - .SH "SEE ALSO" after(n), interp(n), tclvars(n) - .SH KEYWORDS background error, reporting diff --git a/doc/binary.n b/doc/binary.n index 6b2150e..8133829 100644 --- a/doc/binary.n +++ b/doc/binary.n @@ -1,5 +1,6 @@ '\" '\" Copyright (c) 1997 by Sun Microsystems, Inc. +'\" Copyright (c) 2008 by Donal K. Fellows '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. @@ -11,6 +12,12 @@ .SH NAME binary \- Insert and extract fields from binary strings .SH SYNOPSIS +.VS 8.6 +\fBbinary decode \fIformat\fR ?\fI\-option value ...\fR? \fIdata\fR +.br +\fBbinary encode \fIformat\fR ?\fI\-option value ...\fR? \fIdata\fR +.br +.VE 8.6 \fBbinary format \fIformatString \fR?\fIarg arg ...\fR? .br \fBbinary scan \fIstring formatString \fR?\fIvarName varName ...\fR? @@ -18,12 +25,98 @@ binary \- Insert and extract fields from binary strings .SH DESCRIPTION .PP This command provides facilities for manipulating binary data. The -first form, \fBbinary format\fR, creates a binary string from normal +subcommand \fBbinary format\fR creates a binary string from normal Tcl values. For example, given the values 16 and 22, on a 32-bit architecture, it might produce an 8-byte binary string consisting of -two 4-byte integers, one for each of the numbers. The second form of -the command, \fBbinary scan\fR, does the opposite: it extracts data +two 4-byte integers, one for each of the numbers. The subcommand +\fBbinary scan\fR, does the opposite: it extracts data from a binary string and returns it as ordinary Tcl string values. +.VS 8.6 +The \fBbinary encode\fR and \fBbinary decode\fR subcommands convert +binary data to or from string encodings such as base64 (used in MIME +messages for example). +.VE 8.6 +.SH "BINARY ENCODE AND DECODE" +.VS 8.6 +.PP +When encoding binary data as a readable string, the starting binary data is +passed to the \fBbinary encode\fR command, together with the name of the +encoding to use and any encoding-specific options desired. Data which has been +encoded can be converted back to binary form using \fBbinary decode\fR. The +following formats and options are supported. +.TP +\fBbase64\fR +. +The \fBbase64\fR binary encoding is commonly used in mail messages and XML +documents, and uses mostly upper and lower case letters and digits. It has the +distinction of being able to be rewrapped arbitrarily without losing +information. +.RS +.PP +During encoding, the following options are supported: +.TP +\fB\-maxlen \fIlength\fR +. +Indicates that the output should be split into lines of no more than +\fIlength\fR characters. By default, lines are not split. +.TP +\fB\-wrapchar \fIcharacter\fR +. +Indicates that, when lines are split because of the \fB\-maxlen\fR option, +\fIcharacter\fR should be used to separate lines. By default, this is a +newline character, +.QW \en . +.PP +During decoding, the following options are supported: +.TP +\fB\-strict\fR +. +Instructs the decoder to throw an error if it encounters whitespace characters. Otherwise it ignores them. +.RE +.TP +\fBhex\fR +. +The \fBhex\fR binary encoding converts each byte to a pair of hexadecimal +digits in big-endian form. +.RS +.PP +No options are supported during encoding. During decoding, the following +options are supported: +.TP +\fB\-strict\fR +. +Instructs the decoder to throw an error if it encounters whitespace characters. Otherwise it ignores them. +.RE +.TP +\fBuuencode\fR +. +The \fBuuencode\fR binary encoding used to be common for transfer of data +between Unix systems and on USENET, but is less common these days, having been +largely superceded by the \fBbase64\fR binary encoding. +.RS +.PP +During encoding, the following options are supported: +'\" This is wrong! The uuencode format had more complexity than this! +.TP +\fB\-maxlen \fIlength\fR +. +Indicates that the output should be split into lines of no more than +\fIlength\fR characters. By default, lines are not split. +.TP +\fB\-wrapchar \fIcharacter\fR +. +Indicates that, when lines are split because of the \fB\-maxlen\fR option, +\fIcharacter\fR should be used to separate lines. By default, this is a +newline character, +.QW \en . +.PP +During decoding, the following options are supported: +.TP +\fB\-strict\fR +. +Instructs the decoder to throw an error if it encounters whitespace characters. Otherwise it ignores them. +.RE +.VE 8.6 .SH "BINARY FORMAT" .PP The \fBbinary format\fR command generates a binary string whose layout @@ -210,13 +303,11 @@ will return a string equivalent to \fB\ex00\ex03\exff\exfd\ex01\ex02\fR. .RE .IP \fBt\fR 5 -.VS 8.5 This form (mnemonically \fItiny\fR) is the same as \fBs\fR and \fBS\fR except that it stores the 16-bit integers in the output string in the native byte order of the machine where the Tcl script is running. To determine what the native byte order of the machine is, refer to the \fBbyteOrder\fR element of the \fBtcl_platform\fR array. -.VE 8.5 .IP \fBi\fR 5 This form is the same as \fBc\fR except that it stores one or more 32-bit integers in little-endian byte order in the output string. The @@ -242,14 +333,12 @@ will return a string equivalent to \fB\ex00\ex00\ex00\ex03\exff\exff\exff\exfd\ex00\ex01\ex00\ex00\fR .RE .IP \fBn\fR 5 -.VS 8.5 This form (mnemonically \fInumber\fR or \fInormal\fR) is the same as \fBi\fR and \fBI\fR except that it stores the 32-bit integers in the output string in the native byte order of the machine where the Tcl script is running. To determine what the native byte order of the machine is, refer to the \fBbyteOrder\fR element of the \fBtcl_platform\fR array. -.VE 8.5 .IP \fBw\fR 5 This form is the same as \fBc\fR except that it stores one or more 64-bit integers in little-endian byte order in the output string. The @@ -273,14 +362,12 @@ For example, will return the string \fBBigEndian\fR .RE .IP \fBm\fR 5 -.VS 8.5 This form (mnemonically the mirror of \fBw\fR) is the same as \fBw\fR and \fBW\fR except that it stores the 64-bit integers in the output string in the native byte order of the machine where the Tcl script is running. To determine what the native byte order of the machine is, refer to the \fBbyteOrder\fR element of the \fBtcl_platform\fR array. -.VE 8.5 .IP \fBf\fR 5 This form is the same as \fBc\fR except that it stores one or more one or more single-precision floating point numbers in the machine's native @@ -302,18 +389,14 @@ will return a string equivalent to \fB\excd\excc\excc\ex3f\ex9a\ex99\ex59\ex40\fR. .RE .IP \fBr\fR 5 -.VS 8.5 This form (mnemonically \fIreal\fR) is the same as \fBf\fR except that it stores the single-precision floating point numbers in little-endian order. This conversion only produces meaningful output when used on machines which use the IEEE floating point representation (very common, but not universal.) -.VE 8.5 .IP \fBR\fR 5 -.VS 8.5 This form is the same as \fBr\fR except that it stores the single-precision floating point numbers in big-endian order. -.VE 8.5 .IP \fBd\fR 5 This form is the same as \fBf\fR except that it stores one or more one or more double-precision floating point numbers in the machine's native @@ -327,18 +410,14 @@ will return a string equivalent to \fB\ex9a\ex99\ex99\ex99\ex99\ex99\exf9\ex3f\fR. .RE .IP \fBq\fR 5 -.VS 8.5 This form (mnemonically the mirror of \fBd\fR) is the same as \fBd\fR except that it stores the double-precision floating point numbers in little-endian order. This conversion only produces meaningful output when used on machines which use the IEEE floating point representation (very common, but not universal.) -.VE 8.5 .IP \fBQ\fR 5 -.VS 8.5 This form is the same as \fBq\fR except that it stores the double-precision floating point numbers in big-endian order. -.VE 8.5 .IP \fBx\fR 5 Stores \fIcount\fR null bytes in the output string. If \fIcount\fR is not specified, stores one null byte. If \fIcount\fR is \fB*\fR, @@ -543,9 +622,10 @@ reverse (low-to-high) order within each byte. For example, .CE will return \fB2\fR with \fB706\fR stored in \fIvar1\fR and \fB502143\fR stored in \fIvar2\fR. -.RE +.PP Note that most code that wishes to parse the hexadecimal digits from multiple bytes in order should use the \fBH\fR format. +.RE .IP \fBc\fR 5 The data is turned into \fIcount\fR 8-bit signed integers and stored in the corresponding variable as a list. If \fIcount\fR is \fB*\fR, @@ -595,13 +675,11 @@ will return \fB2\fR with \fB5 7\fR stored in \fIvar1\fR and \fB\-16\fR stored in \fIvar2\fR. .RE .IP \fBt\fR 5 -.VS 8.5 The data is interpreted as \fIcount\fR 16-bit signed integers represented in the native byte order of the machine running the Tcl script. It is otherwise identical to \fBs\fR and \fBS\fR. To determine what the native byte order of the machine is, refer to the \fBbyteOrder\fR element of the \fBtcl_platform\fR array. -.VE 8.5 .IP \fBi\fR 5 The data is interpreted as \fIcount\fR 32-bit signed integers represented in little-endian byte order. The integers are stored in @@ -635,13 +713,11 @@ will return \fB2\fR with \fB5 7\fR stored in \fIvar1\fR and \fB\-16\fR stored in \fIvar2\fR. .RE .IP \fBn\fR 5 -.VS 8.5 The data is interpreted as \fIcount\fR 32-bit signed integers represented in the native byte order of the machine running the Tcl script. It is otherwise identical to \fBi\fR and \fBI\fR. To determine what the native byte order of the machine is, refer to the \fBbyteOrder\fR element of the \fBtcl_platform\fR array. -.VE 8.5 .IP \fBw\fR 5 The data is interpreted as \fIcount\fR 64-bit signed integers represented in little-endian byte order. The integers are stored in @@ -671,13 +747,11 @@ will return \fB2\fR with \fB21474836487\fR stored in \fIvar1\fR and \fB\-16\fR stored in \fIvar2\fR. .RE .IP \fBm\fR 5 -.VS 8.5 The data is interpreted as \fIcount\fR 64-bit signed integers represented in the native byte order of the machine running the Tcl script. It is otherwise identical to \fBw\fR and \fBW\fR. To determine what the native byte order of the machine is, refer to the \fBbyteOrder\fR element of the \fBtcl_platform\fR array. -.VE 8.5 .IP \fBf\fR 5 The data is interpreted as \fIcount\fR single-precision floating point numbers in the machine's native representation. The floating point @@ -698,19 +772,15 @@ will return \fB1\fR with \fB1.6000000238418579\fR stored in \fIvar1\fR. .RE .IP \fBr\fR 5 -.VS 8.5 This form is the same as \fBf\fR except that the data is interpreted as \fIcount\fR single-precision floating point number in little-endian order. This conversion is not portable to the minority of systems not using IEEE floating point representations. -.VE 8.5 .IP \fBR\fR 5 -.VS 8.5 This form is the same as \fBf\fR except that the data is interpreted as \fIcount\fR single-precision floating point number in big-endian order. This conversion is not portable to the minority of systems not using IEEE floating point representations. -.VE 8.5 .IP \fBd\fR 5 This form is the same as \fBf\fR except that the data is interpreted as \fIcount\fR double-precision floating point numbers in the @@ -724,19 +794,15 @@ will return \fB1\fR with \fB1.6000000000000001\fR stored in \fIvar1\fR. .RE .IP \fBq\fR 5 -.VS 8.5 This form is the same as \fBd\fR except that the data is interpreted as \fIcount\fR double-precision floating point number in little-endian order. This conversion is not portable to the minority of systems not using IEEE floating point representations. -.VE 8.5 .IP \fBQ\fR 5 -.VS 8.5 This form is the same as \fBd\fR except that the data is interpreted as \fIcount\fR double-precision floating point number in big-endian order. This conversion is not portable to the minority of systems not using IEEE floating point representations. -.VE 8.5 .IP \fBx\fR 5 Moves the cursor forward \fIcount\fR bytes in \fIstring\fR. If \fIcount\fR is \fB*\fR or is larger than the number of bytes after the @@ -778,6 +844,7 @@ will return \fB2\fR with \fB1 2\fR stored in \fIvar1\fR and \fB020304\fR stored in \fIvar2\fR. .RE .SH "PORTABILITY ISSUES" +.PP The \fBr\fR, \fBR\fR, \fBq\fR and \fBQ\fR conversions will only work reliably for transferring data between computers which are all using IEEE floating point representations. This is very common, but not @@ -785,6 +852,7 @@ universal. To transfer floating-point numbers portably between all architectures, use their textual representation (as produced by \fBformat\fR) instead. .SH EXAMPLES +.PP This is a procedure to write a Tcl string to a binary-encoded channel as UTF-8 data preceded by a length word: .CS @@ -806,7 +874,19 @@ proc \fIreadString\fR {channel} { return [encoding convertfrom utf-8 $data] } .CE +.PP +This converts the contents of a file (named in the variable \fIfilename\fR) to +base64 and prints them: +.CS +set f [open $filename rb] +set data [read $f] +close $f +puts [\fBbinary encode\fR base64 \-maxlen 64 $data] +.CE .SH "SEE ALSO" format(n), scan(n), tclvars(n) .SH KEYWORDS binary, format, scan +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/break.n b/doc/break.n index ed09c03..cef37c6 100644 --- a/doc/break.n +++ b/doc/break.n @@ -14,12 +14,11 @@ break \- Abort looping command .SH SYNOPSIS \fBbreak\fR .BE - .SH DESCRIPTION .PP This command is typically invoked inside the body of a looping command such as \fBfor\fR or \fBforeach\fR or \fBwhile\fR. -It returns a \fBTCL_BREAK\fR code, which causes a break exception +It returns a 3 (\fBTCL_BREAK\fR) result code, which causes a break exception to occur. The exception causes the current script to be aborted out to the innermost containing loop command, which then @@ -28,18 +27,21 @@ Break exceptions are also handled in a few other situations, such as the \fBcatch\fR command, Tk event bindings, and the outermost scripts of procedure bodies. .SH EXAMPLE +.PP Print a line for each of the integers from 0 to 5: +.PP .CS for {set x 0} {$x<10} {incr x} { - if {$x > 5} { - \fBbreak\fR - } - puts "x is $x" + if {$x > 5} { + \fBbreak\fR + } + puts "x is $x" } .CE - .SH "SEE ALSO" catch(n), continue(n), for(n), foreach(n), return(n), while(n) - .SH KEYWORDS abort, break, loop +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/catch.n b/doc/catch.n index 0e2ec04..1da163d 100644 --- a/doc/catch.n +++ b/doc/catch.n @@ -15,12 +15,11 @@ catch \- Evaluate script and trap exceptional returns .SH SYNOPSIS \fBcatch\fI script \fR?\fIresultVarName\fR? ?\fIoptionsVarName\fR? .BE - .SH DESCRIPTION .PP The \fBcatch\fR command may be used to prevent errors from aborting command -interpretation. The \fBcatch\fR command calls the Tcl interpreter recursively to -execute \fIscript\fR, and always returns without raising an error, +interpretation. The \fBcatch\fR command calls the Tcl interpreter recursively +to execute \fIscript\fR, and always returns without raising an error, regardless of any errors that might occur while executing \fIscript\fR. .PP If \fIscript\fR raises an error, \fBcatch\fR will return a non-zero integer @@ -33,16 +32,15 @@ by a return code of \fBTCL_ERROR\fR. The other exceptional return codes are returned by the \fBreturn\fR, \fBbreak\fR, and \fBcontinue\fR commands and in other special situations as documented. Tcl packages can define new commands that return other integer values as return codes as well, -and scripts that make use of the \fBreturn -code\fR command can also +and scripts that make use of the \fBreturn \-code\fR command can also have return codes other than the five defined by Tcl. .PP If the \fIresultVarName\fR argument is given, then the variable it names is -set to the result of the script evaluation. When the return code from -the script is 1 (\fBTCL_ERROR\fR), the value stored in \fIresultVarName\fR is an error -message. When the return code from the script is 0 (\fBTCL_OK\fR), the value -stored in \fIresultVarName\fR is the value returned from \fIscript\fR. +set to the result of the script evaluation. When the return code from the +script is 1 (\fBTCL_ERROR\fR), the value stored in \fIresultVarName\fR is an +error message. When the return code from the script is 0 (\fBTCL_OK\fR), the +value stored in \fIresultVarName\fR is the value returned from \fIscript\fR. .PP -.VS 8.5 If the \fIoptionsVarName\fR argument is given, then the variable it names is set to a dictionary of return options returned by evaluation of \fIscript\fR. Tcl specifies two entries that are always @@ -54,31 +52,59 @@ Only when the return code is \fBTCL_RETURN\fR will the values of the \fB\-level\fR and \fB\-code\fR entries be something else, as further described in the documentation for the \fBreturn\fR command. .PP -When the return code from evaluation of \fIscript\fR is \fBTCL_ERROR\fR, -three additional entries are defined in the dictionary of return options -stored in \fIoptionsVarName\fR: \fB\-errorinfo\fR, \fB\-errorcode\fR, -and \fB\-errorline\fR. The value of the \fB\-errorinfo\fR entry -is a formatted stack trace containing more information about -the context in which the error happened. The formatted stack -trace is meant to be read by a person. The value of -the \fB\-errorcode\fR entry is additional information about the -error stored as a list. The \fB\-errorcode\fR value is meant to -be further processed by programs, and may not be particularly -readable by people. The value of the \fB\-errorline\fR entry -is an integer indicating which line of \fIscript\fR was being -evaluated when the error occurred. The values of the \fB\-errorinfo\fR -and \fB\-errorcode\fR entries of the most recent error are also -available as values of the global variables \fB::errorInfo\fR -and \fB::errorCode\fR respectively. +When the return code from evaluation of \fIscript\fR is +\fBTCL_ERROR\fR, four additional entries are defined in the dictionary +of return options stored in \fIoptionsVarName\fR: \fB\-errorinfo\fR, +\fB\-errorcode\fR, \fB\-errorline\fR, and +.VS 8.6 +\fB\-errorstack\fR. +.VE 8.6 +The value of the \fB\-errorinfo\fR entry is a formatted stack trace containing +more information about the context in which the error happened. The formatted +stack trace is meant to be read by a person. The value of the +\fB\-errorcode\fR entry is additional information about the error stored as a +list. The \fB\-errorcode\fR value is meant to be further processed by +programs, and may not be particularly readable by people. The value of the +\fB\-errorline\fR entry is an integer indicating which line of \fIscript\fR +was being evaluated when the error occurred. +.VS 8.6 +The value of the \fB\-errorstack\fR entry is an +even-sized list made of token-parameter pairs accumulated while +unwinding the stack. The token may be +.QW \fBCALL\fR , +in which case the parameter is a list made of the proc name and arguments at +the corresponding level; or it may be +.QW \fBUP\fR , +in which case the parameter is +the relative level (as in \fBuplevel\fR) of the previous \fBCALL\fR. The +salient differences wrt \fB\-errorinfo\fR are that: +.IP [1] +it is a machine-readable form that is amenable to processing with +[\fBforeach\fR {tok prm} ...], +.IP [2] +it contains the true (substituted) values passed to the functions, instead of +the static text of the calling sites, and +.IP [3] +it is coarser-grained, with only one element per stack frame (like procs; no +separate elements for \fBforeach\fR constructs for example). +.VE 8.6 +.PP +The values of the \fB\-errorinfo\fR and \fB\-errorcode\fR entries of +the most recent error are also available as values of the global +variables \fB::errorInfo\fR and \fB::errorCode\fR respectively. +.VS 8.6 +The value of the \fB\-errorstack\fR entry surfaces as \fBinfo errorstack\fR. +.VE 8.6 .PP Tcl packages may provide commands that set other entries in the dictionary of return options, and the \fBreturn\fR command may be used by scripts to set return options in addition to those defined above. -.VE 8.5 .SH EXAMPLES +.PP The \fBcatch\fR command may be used in an \fBif\fR to branch based on the success of a script. +.PP .CS if { [\fBcatch\fR {open $someFile w} fid] } { puts stderr "Could not open $someFile for writing\en$fid" @@ -88,9 +114,11 @@ if { [\fBcatch\fR {open $someFile w} fid] } { .PP There are more complex examples of \fBcatch\fR usage in the documentation for the \fBreturn\fR command. - .SH "SEE ALSO" -break(n), continue(n), dict(n), error(n), return(n), tclvars(n) - +break(n), continue(n), dict(n), error(n), info(n), return(n), tclvars(n) .SH KEYWORDS -catch, error +catch, error, exception +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: @@ -14,7 +14,6 @@ cd \- Change working directory .SH SYNOPSIS \fBcd \fR?\fIdirName\fR? .BE - .SH DESCRIPTION .PP Change the current working directory to \fIdirName\fR, or to the @@ -25,19 +24,20 @@ Note that the current working directory is a per-process resource; the \fBcd\fR command changes the working directory for all interpreters and (in a threaded environment) all threads. .SH EXAMPLES +.PP Change to the home directory of the user \fBfred\fR: +.PP .CS \fBcd\fR ~fred .CE .PP Change to the directory \fBlib\fR that is a sibling directory of the current one: +.PP .CS \fBcd\fR ../lib .CE - .SH "SEE ALSO" filename(n), glob(n), pwd(n) - .SH KEYWORDS working directory @@ -31,22 +31,35 @@ otherwise. Note that this only ever returns 1 when the channel has been configured to be non-blocking; all Tcl channels have blocking turned on by default. .TP -\fBchan close \fIchannelId\fR +\fBchan close \fIchannelId\fR ?\fIdirection\fR? . Close and destroy the channel called \fIchannelId\fR. Note that this deletes all existing file-events registered on the channel. +.VS 8.6 +If the \fIdirection\fR argument (which must be \fBread\fR or \fBwrite\fR or +any unique abbreviation of them) is present, the channel will only be +half-closed, so that it can go from being read-write to write-only or +read-only respectively. If a read-only channel is closed for reading, it is +the same as if the channel is fully closed, and respectively similar for +write-only channels. Without the \fIdirection\fR argument, the channel is +closed for both reading and writing (but only if those directions are +currently open). It is an error to close a read-only channel for writing, or a +write-only channel for reading. +.VE 8.6 .RS .PP As part of closing the channel, all buffered output is flushed to the -channel's output device, any buffered input is discarded, the -underlying operating system resource is closed and \fIchannelId\fR -becomes unavailable for future use. -.PP -If the channel is blocking, the command does not return until all -output is flushed. If the channel is nonblocking and there is -unflushed output, the channel remains open and the command returns -immediately; output will be flushed in the background and the channel -will be closed when all the flushing is complete. +channel's output device (only if the channel is ceasing to be writable), any +buffered input is discarded (only if the channel is ceasing to be readable), +the underlying operating system resource is closed and \fIchannelId\fR becomes +unavailable for future use (both only if the channel is being completely +closed). +.PP +If the channel is blocking and the channel is ceasing to be writable, the +command does not return until all output is flushed. If the channel is +nonblocking and there is unflushed output, the channel remains open and the +command returns immediately; output will be flushed in the background and the +channel will be closed when all the flushing is complete. .PP If \fIchannelId\fR is a blocking channel for a command pipeline then \fBchan close\fR waits for the child processes to complete. @@ -56,10 +69,12 @@ makes \fIchannelId\fR unavailable in the invoking interpreter but has no other effect until all of the sharing interpreters have closed the channel. When the last interpreter in which the channel is registered invokes \fBchan close\fR (or \fBclose\fR), the cleanup actions -described above occur. See the \fBinterp\fR command for a description -of channel sharing. +described above occur. With half-closing, the half-close of the channel only +applies to the current interpreter's view of the channel until all channels +have closed it in that direction (or completely). +See the \fBinterp\fR command for a description of channel sharing. .PP -Channels are automatically closed when an interpreter is destroyed and +Channels are automatically fully closed when an interpreter is destroyed and when the process exits. Channels are switched to blocking mode, to ensure that all output is correctly flushed before the process exits. .PP @@ -67,6 +82,13 @@ The command returns an empty string, and may generate an error if an error occurs while flushing output. If a command in a command pipeline created with \fBopen\fR returns an error, \fBchan close\fR generates an error (similar to the \fBexec\fR command.) +.PP +.VS 8.6 +Note that half-closes of sockets and command pipelines can have important side +effects because they result in a shutdown() or close() of the underlying +system resource, which can change how other processes or systems respond to +the Tcl program. +.VE 8.6 .RE .TP \fBchan configure \fIchannelId\fR ?\fIoptionName\fR? ?\fIvalue\fR? ?\fIoptionName value\fR?... @@ -87,8 +109,9 @@ The options described below are supported for all channels. In addition, each channel type may add options that only it supports. See the manual entry for the command that creates each type of channels for the options that that specific type of channel supports. For -example, see the manual entry for the \fBsocket\fR command for its -additional options. +example, see the manual entry for the \fBsocket\fR command for additional +options for sockets, and the \fBopen\fR command for additional options for +serial devices. .TP \fB\-blocking\fR \fIboolean\fR . @@ -328,7 +351,7 @@ This subcommand creates a new script level channel using the command prefix \fIcmdPrefix\fR as its handler. Any such channel is called a \fBreflected\fR channel. The specified command prefix, \fBcmdPrefix\fR, must be a non-empty list, and should provide the API described in the -\fBreflectedchan\fR manual page. The handle of the new channel is +\fBrefchan\fR manual page. The handle of the new channel is returned as the result of the \fBchan create\fR command, and the channel is open. Use either \fBclose\fR or \fBchan close\fR to remove the channel. @@ -347,7 +370,7 @@ mode, or an error is thrown. .PP The command prefix is executed in the global namespace, at the top of call stack, following the appending of arguments as described in the -\fBreflectedchan\fR manual page. Command resolution happens at the +\fBrefchan\fR manual page. Command resolution happens at the time of the call. Renaming the command, or destroying it means that the next call of a handler method may fail, causing the channel command invoking the handler to fail as well. Depending on the @@ -514,6 +537,27 @@ a potential denial-of-service attack where a hostile user crafts an extremely long line that exceeds the available memory to buffer it). Returns -1 if the channel was not opened for the mode in question. .TP +\fBchan pipe\fR +.VS 8.6 +Creates a standalone pipe whose read- and write-side channels are +returned as a 2-element list, the first element being the read side and +the second the write side. Can be useful e.g. to redirect +separately \fBstderr\fR and \fBstdout\fR from a subprocess. To do +this, spawn with "2>@" or +">@" redirection operators onto the write side of a pipe, and then +immediately close it in the parent. This is necessary to get an EOF on +the read side once the child has exited or otherwise closed its output. +.VE 8.6 +.TP +\fBchan pop \fIchannelId\fR +.VS 8.6 +Removes the topmost transformation from the channel \fIchannelId\fR, if there +is any. If there are no transformations added to \fIchannelId\fR, this is +equivalent to \fBchan close\fR of that channel. The result is normally the +empty string, but can be an error in some situations (i.e. where the +underlying system stream is closed and that results in an error). +.VE 8.6 +.TP \fBchan postevent \fIchannelId eventSpec\fR . This subcommand is used by command handlers specified with \fBchan @@ -539,7 +583,7 @@ other interpreter will cause this subcommand to report an error. Another restriction is that it is not possible to post events that the I/O core has not registered an interest in. Trying to do so will cause the method to throw an error. See the command handler method -\fBwatch\fR described in \fBreflectedchan\fR, the document specifying +\fBwatch\fR described in \fBrefchan\fR, the document specifying the API of command handlers for reflected channels. .PP This command is \fBsafe\fR and made accessible to safe interpreters. @@ -550,6 +594,18 @@ a trusted interpreter. \fBChan event\fR handlers are \fIalways\fR executed in the interpreter that set them up. .RE .TP +\fBchan push \fIchannelId cmdPrefix\fR +.VS 8.6 +Adds a new transformation on top of the channel \fIchannelId\fR. The +\fIcmdPrefix\fR argument describes a list of one or more words which represent +a handler that will be used to implement the transformation. The command +prefix must provide the API described in the \fBtranschan\fR manual page. +The result of this subcommand is a handle to the transformation. Note that it +is important to make sure that the transformation is capable of supporting the +channel mode that it is used with or this can make the channel neither +readable nor writable. +.VE 8.6 +.TP \fBchan puts\fR ?\fB\-nonewline\fR? ?\fIchannelId\fR? \fIstring\fR . Writes \fIstring\fR to the channel named \fIchannelId\fR followed by a @@ -620,9 +676,11 @@ in which \fBchan configure\fR will alter input). .PP When reading from a serial port, most applications should configure the serial port channel to be nonblocking, like this: +.PP .CS \fBchan configure \fIchannelId \fB\-blocking \fI0\fR. .CE +.PP Then \fBchan read\fR behaves much like described above. Note that most serial ports are comparatively slow; it is entirely possible to get a \fBreadable\fR event for each character read from them. Care @@ -695,7 +753,9 @@ Sets the byte length of the underlying data stream for the channel named \fIchannelId\fR to be \fIlength\fR (or to the current byte offset within the underlying data stream if \fIlength\fR is omitted). The channel is flushed before truncation. -.SH EXAMPLE +. +.SH EXAMPLES +.PP This opens a file using a known encoding (CP1252, a very common encoding on Windows), searches for a string, rewrites that part, and truncates the file after a further two lines. @@ -707,30 +767,70 @@ set offset 0 \fI# Search for string "FOOBAR" in the file\fR while {[\fBchan gets\fR $f line] >= 0} { - set idx [string first FOOBAR $line] - if {$idx > -1} { - \fI# Found it; rewrite line\fR + set idx [string first FOOBAR $line] + if {$idx > -1} { + \fI# Found it; rewrite line\fR - \fBchan seek\fR $f [expr {$offset + $idx}] - \fBchan puts\fR -nonewline $f BARFOO + \fBchan seek\fR $f [expr {$offset + $idx}] + \fBchan puts\fR -nonewline $f BARFOO - \fI# Skip to end of following line, and truncate\fR - \fBchan gets\fR $f - \fBchan gets\fR $f - \fBchan truncate\fR $f + \fI# Skip to end of following line, and truncate\fR + \fBchan gets\fR $f + \fBchan gets\fR $f + \fBchan truncate\fR $f - \fI# Stop searching the file now\fR - break - } + \fI# Stop searching the file now\fR + break + } - \fI# Save offset of start of next line for later\fR - set offset [\fBchan tell\fR $f] + \fI# Save offset of start of next line for later\fR + set offset [\fBchan tell\fR $f] } \fBchan close\fR $f .CE +.PP +A network server that does echoing of its input line-by-line without +preventing servicing of other connections at the same time. +.PP +.CS +# This is a very simple logger... +proc log {message} { + \fBchan puts\fR stdout $message +} + +# This is called whenever a new client connects to the server +proc connect {chan host port} { + set clientName [format <%s:%d> $host $port] + log "connection from $clientName" + \fBchan configure\fR $chan -blocking 0 -buffering line + \fBchan event\fR $chan readable [list echoLine $chan $clientName] +} + +# This is called whenever either at least one byte of input +# data is available, or the channel was closed by the client. +proc echoLine {chan clientName} { + \fBchan gets\fR $chan line + if {[\fBchan eof\fR $chan]} { + log "finishing connection from $clientName" + \fBchan close\fR $chan + } elseif {![\fBchan blocked\fR $chan]} { + # Didn't block waiting for end-of-line + log "$clientName - $line" + \fBchan puts\fR $chan $line + } +} + +# Create the server socket and enter the event-loop to wait +# for incoming connections... +socket -server connect 12345 +vwait forever +.CE .SH "SEE ALSO" close(n), eof(n), fblocked(n), fconfigure(n), fcopy(n), file(n), fileevent(n), flush(n), gets(n), open(n), puts(n), read(n), seek(n), -socket(n), tell(n), refchan(n) +socket(n), tell(n), refchan(n), transchan(n) .SH KEYWORDS channel, input, output, events, offset +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/class.n b/doc/class.n new file mode 100644 index 0000000..88d1b44 --- /dev/null +++ b/doc/class.n @@ -0,0 +1,136 @@ +'\" +'\" Copyright (c) 2007 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH class n 0.1 TclOO "TclOO Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +oo::class \- class of all classes +.SH SYNOPSIS +.nf +package require TclOO + +\fBoo::class\fI method \fR?\fIarg ...\fR? +.fi +.SH "CLASS HIERARCHY" +.nf +\fBoo::object\fR + \(-> \fBoo::class\fR +.fi +.BE +.SH DESCRIPTION +.PP +Classes are objects that can manufacture other objects according to a pattern +stored in the factory object (the class). An instance of the class is created +by calling one of the class's factory methods, typically either \fBcreate\fR +if an explicit name is being given, or \fBnew\fR if an arbitrary unique name +is to be automatically selected. +.PP +The \fBoo::class\fR class is the class of all classes; every class is an +instance of this class, which is consequently an instance of itself. This +class is a subclass of \fBoo::object\fR, so every class is also an object. +Additional metaclasses (i.e., classes of classes) can be defined if necessary +by subclassing \fBoo::class\fR. Note that the \fBoo::class\fR object hides the +\fBnew\fR method on itself, so new classes should always be made using the +\fBcreate\fR method. +.SS CONSTRUCTOR +.PP +The constructor of the \fBoo::class\fR class takes an optional argument which, +if present, is sent to the \fBoo::define\fR command (along with the name of +the newly-created class) to allow the class to be conveniently configured at +creation time. +.SS DESTRUCTOR +The \fBoo::class\fR class does not define an explicit destructor. However, +when a class is destroyed, all its subclasses and instances are also +destroyed, along with all objects that it has been mixed into. +.SS "EXPORTED METHODS" +.TP +\fIcls \fBcreate \fIname \fR?\fIarg ...\fR? +. +This creates a new instance of the class \fIcls\fR called \fIname\fR (which is +resolved within the calling context's namespace if not fully qualified), +passing the arguments, \fIarg ...\fR, to the constructor, and (if that returns +a successful result) returning the fully qualified name of the created object +(the result of the constructor is ignored). If the constructor fails (i.e. +returns a non-OK result) then the object is destroyed and the error message is +the result of this method call. +.TP +\fIcls \fBnew \fR?\fIarg ...\fR? +. +This creates a new instance of the class \fIcls\fR with a new unique name, +passing the arguments, \fIarg ...\fR, to the constructor, and (if that returns +a successful result) returning the fully qualified name of the created object +(the result of the constructor is ignored). If the constructor fails (i.e., +returns a non-OK result) then the object is destroyed and the error message is +the result of this method call. +.RS +.PP +Note that this method is not exported by the \fBoo::class\fR object itself, so +classes should not be created using this method. +.RE +.SS "NON-EXPORTED METHODS" +.PP +The \fBoo::class\fR class supports the following non-exported methods: +.TP +\fIcls \fBcreateWithNamespace\fI name nsName\fR ?\fIarg ...\fR? +. +This creates a new instance of the class \fIcls\fR called \fIname\fR (which is +resolved within the calling context's namespace if not fully qualified), +passing the arguments, \fIarg ...\fR, to the constructor, and (if that returns +a successful result) returning the fully qualified name of the created object +(the result of the constructor is ignored). The name of the instance's +internal namespace will be \fInsName\fR unless that namespace already exists +(when an arbitrary name will be chosen instead). If the constructor fails +(i.e., returns a non-OK result) then the object is destroyed and the error +message is the result of this method call. +.SH EXAMPLES +.PP +This example defines a simple class hierarchy and creates a new instance of +it. It then invokes a method of the object before destroying the hierarchy and +showing that the destruction is transitive. +.PP +.CS +\fBoo::class create\fR fruit { + method eat {} { + puts "yummy!" + } +} +\fBoo::class create\fR banana { + superclass fruit + constructor {} { + my variable peeled + set peeled 0 + } + method peel {} { + my variable peeled + set peeled 1 + puts "skin now off" + } + method edible? {} { + my variable peeled + return $peeled + } + method eat {} { + if {![my edible?]} { + my peel + } + next + } +} +set b [banana \fBnew\fR] +$b eat \fI\(-> prints "skin now off" and "yummy!"\fR +fruit destroy +$b eat \fI\(-> error "unknown command"\fR +.CE +.SH "SEE ALSO" +oo::define(n), oo::object(n) +.SH KEYWORDS +class, metaclass, object +.\" Local variables: +.\" mode: nroff +.\" fill-column: 78 +.\" End: diff --git a/doc/clock.n b/doc/clock.n index 600722b..8708029 100644 --- a/doc/clock.n +++ b/doc/clock.n @@ -42,12 +42,12 @@ is system-dependent but should be the highest resolution clock available on the system such as a CPU cycle counter. See \fBHIGH RESOLUTION TIMERS\fR for a full description. .RS .PP -If the \fI\-option\fR argument is \fI\-milliseconds\fR, then the command +If the \fI\-option\fR argument is \fB\-milliseconds\fR, then the command is synonymous with \fBclock milliseconds\fR (see below). This usage is obsolete, and \fBclock milliseconds\fR is to be considered the preferred way of obtaining a count of milliseconds. .PP -If the \fI\-option\fR argument is \fI\-microseconds\fR, then the command +If the \fI\-option\fR argument is \fB\-microseconds\fR, then the command is synonymous with \fBclock microseconds\fR (see below). This usage is obsolete, and \fBclock microseconds\fR is to be considered the preferred way of obtaining a count of microseconds. @@ -111,11 +111,12 @@ and their interpretation, are described under \fBFORMAT GROUPS\fR. .RS .PP On \fBclock format\fR, the default format is +.PP .CS %a %b %d %H:%M:%S %z %Y .CE .PP -On \fBclock scan\fR, the lack of a \fI\-format\fR option indicates that a +On \fBclock scan\fR, the lack of a \fB\-format\fR option indicates that a .QW "free format scan" is requested; see \fBFREE FORM SCAN\fR for a description of what happens. .RE @@ -160,12 +161,14 @@ the environment variable \fBTZ\fR. .IP [3] on Windows systems, the time zone settings from the Control Panel. .RE +.PP If none of these is present, the C \fBlocaltime\fR and \fBmktime\fR functions are used to attempt to convert times between local and Greenwich. On 32-bit systems, this approach is likely to have bugs, particularly for times that lie outside the window (approximately the years 1902 to 2037) that can be represented in a 32-bit integer. .SH "CLOCK ARITHMETIC" +.PP The \fBclock add\fR command performs clock arithmetic on a value (expressed as nominal seconds from the epoch time of 1 January 1970, 00:00 UTC) given as its first argument. The remaining arguments (other than the @@ -195,6 +198,7 @@ absolute time means that it will add fixed amounts of time in time zones that observe summer time (Daylight Saving Time). For example, the following code sets the value of \fBx\fR to \fB04:00:00\fR because the clock has changed in the interval in question. +.PP .CS set s [\fBclock scan\fR {2004-10-30 05:00:00} \e -format {%Y-%m-%d %H:%M:%S} \e @@ -215,6 +219,7 @@ Adding and subtracting a given number of days across the point that the time changes at the start or end of summer time (Daylight Saving Time) results in the \fIsame local time\fR on the day in question. For instance, the following code sets the value of \fBx\fR to \fB05:00:00\fR. +.PP .CS set s [\fBclock scan\fR {2004-10-30 05:00:00} \e -format {%Y-%m-%d %H:%M:%S} \e @@ -230,6 +235,7 @@ yields an impossible time (for instance, 02:30 during the Spring Daylight Saving Time change using US rules), the time is converted as if the clock had not changed. Thus, the following code will set the value of \fBx\fR to \fB03:30:00\fR. +.PP .CS set s [\fBclock scan\fR {2004-04-03 02:30:00} \e -format {%Y-%m-%d %H:%M:%S} \e @@ -242,6 +248,7 @@ set x [\fBclock format\fR $a \e Adding a given number of days or weeks works correctly across the conversion between the Julian and Gregorian calendars; the omitted days are skipped. The following code sets \fBz\fR to \fB1752-09-14\fR. +.PP .CS set x [\fBclock scan\fR 1752-09-02 -format %Y-%m-%d -locale en_US] set y [\fBclock add\fR $x 1 day -locale en_US] @@ -270,6 +277,7 @@ years as they are when adding/subtracting days and weeks. If multiple \fIcount unit\fR pairs are present on the command, they are evaluated consecutively, from left to right. .SH "HIGH RESOLUTION TIMERS" +.PP Most of the subcommands supported by the \fBclock\fR command deal with times represented as a count of seconds from the epoch time, and this is the representation that \fBclock seconds\fR returns. There are three exceptions, @@ -284,6 +292,7 @@ epoch; it is simply intended to be the most precise interval timer available, and is intended only for relative timing studies such as benchmarks. .SH "FORMATTING TIMES" +.PP The \fBclock format\fR command produces times for display to a user or writing to an external medium. The command accepts times that are expressed in seconds from the epoch time of 1 January 1970, 00:00 UTC, @@ -322,6 +331,7 @@ platforms that do not define a user selection of date and time formats separate from \fBLC_TIME\fR, \fB\-locale\fR \fBsystem\fR is synonymous with \fB\-locale\fR \fBcurrent\fR. .SH "SCANNING TIMES" +.PP The \fBclock scan\fR command accepts times that are formatted as strings and converts them to counts of seconds from the epoch time of 1 January 1970, 00:00 UTC. It normally takes a \fB\-format\fR @@ -444,6 +454,7 @@ If this situation occurs, the first occurrence of the time is chosen. time zone when converting local times. This caveat does not apply to UTC times.) .SH "FORMAT GROUPS" +.PP The following format groups are recognized by the \fBclock scan\fR and \fBclock format\fR commands. .TP @@ -733,6 +744,7 @@ character. Synonymous with .QW "\fB%a %b %e %H:%M:%S %Z %Y\fR" . .SH "TIME ZONES" +.PP When the \fBclock\fR command is processing a local time, it has several possible sources for the time zone to use. In order of preference, they are: @@ -754,6 +766,7 @@ The C library's idea of the local time zone, as defined by the .PP In case [1] \fIonly,\fR the string is tested to see if it is one of the strings: +.PP .CS gmt ut utc bst wet wat at nft nst ndt ast adt est edt @@ -765,6 +778,7 @@ of the strings: cadt east eadt gst nzt nzst nzdt idle .CE +.PP If it is a string in the above list, it designates a known time zone, and is interpreted as such. .PP @@ -798,13 +812,32 @@ environment variable will be recognized. The specification may be found at \fIhttp://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html\fR. .PP +If the Posix time zone string contains a DST (Daylight Savings Time) +part, but doesn't contain a rule stating when DST starts or ends, +then default rules are used. For Timezones with an offset between 0 +and +12, the current European/Russian rules are used, otherwise the +current US rules are used. In Europe (offset +0 to +2) the switch +to summertime is done each last Sunday in March at 1:00 GMT, and +the switch back is each last Sunday in October at 2:00 GMT. In +Russia (offset +3 to +12), the switch dates are the same, only +the switch to summertime is at 2:00 local time, and the switch +back is at 3:00 local time in all time zones. The US switch to +summertime takes place each second Sunday in March at 2:00 local +time, and the switch back is each first Sunday in November at +3:00 local time. These default rules mean that in all European, +Russian and US (or compatible) time zones, DST calculations will +be correct for dates in 2007 and later, unless in the future the +rules change again. +.PP Any other time zone string is processed by prefixing a colon and attempting to use it as a location name, as above. .SH "LOCALIZATION" +.PP Developers wishing to localize the date and time formatting and parsing are referred to \fIhttp://tip.tcl.tk/173\fR for a specification. .SH "FREE FORM SCAN" +.PP If the \fBclock scan\fR command is invoked without a \fB\-format\fR option, then it requests a \fIfree-form scan.\fR \fI This form of scan is deprecated.\fR The reason for the deprecation @@ -871,7 +904,7 @@ or Note that only these three formats are accepted. The command does \fInot\fR accept the full range of point-in-time specifications specified in ISO8601. Other formats can be recognized by -giving an explicit \fI\-format\fR option to the \fBclock scan\fR command. +giving an explicit \fB\-format\fR option to the \fBclock scan\fR command. .TP \fIrelative time\fR A specification relative to the current time. The format is \fBnumber @@ -899,3 +932,6 @@ msgcat(n) clock, date, time .SH "COPYRIGHT" Copyright (c) 2004 Kevin B. Kenny <kennykb@acm.org>. All rights reserved. +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/close.n b/doc/close.n index 4ef3c7d..2577cc5 100644 --- a/doc/close.n +++ b/doc/close.n @@ -12,19 +12,19 @@ .SH NAME close \- Close an open channel .SH SYNOPSIS -\fBclose \fIchannelId\fR +\fBclose \fIchannelId\fR ?r(ead)|w(rite)? .BE - .SH DESCRIPTION .PP -Closes the channel given by \fIchannelId\fR. +Closes or half-closes the channel given by \fIchannelId\fR. .PP \fIChannelId\fR must be an identifier for an open channel such as a Tcl standard channel (\fBstdin\fR, \fBstdout\fR, or \fBstderr\fR), the return value from an invocation of \fBopen\fR or \fBsocket\fR, or the result of a channel creation command provided by a Tcl extension. .PP -All buffered output is flushed to the channel's output device, +The single-argument form is a simple "full-close": +all buffered output is flushed to the channel's output device, any buffered input is discarded, the underlying file or device is closed, and \fIchannelId\fR becomes unavailable for use. .PP @@ -54,10 +54,32 @@ The command returns an empty string, and may generate an error if an error occurs while flushing output. If a command in a command pipeline created with \fBopen\fR returns an error, \fBclose\fR generates an error (similar to the \fBexec\fR command.) +.PP +.VS 8.6 +The two-argument form is a "half-close": given a bidirectional channel like a +socket or command pipeline and a (possibly abbreviated) direction, it closes +only the substream going in that direction. This means a shutdown() on a +socket, and a close() of one end of a pipe for a command pipeline. Then, the +Tcl-level channel data structure is either kept or freed depending on whether +the other direction is still open. +.PP +A single-argument close on an already half-closed bi-channel is defined to +just "finish the job. A half-close on an already closed half, or on a +wrong-sided unidirectional channel, raises an error. +.PP +In the case of a command pipeline, the child-reaping duty falls upon the +shoulders of the last close or half-close, which is thus allowed to report an +abnormal exit error. +.PP +Currently only sockets and command pipelines support half-close. A future +extension will allow reflected and stacked channels to do so. +.VE 8.6 .SH EXAMPLE +.PP This illustrates how you can use Tcl to ensure that files get closed even when errors happen by combining \fBcatch\fR, \fBclose\fR and \fBreturn\fR: +.PP .CS proc withOpenFile {filename channelVar script} { upvar 1 $channelVar chan @@ -69,9 +91,11 @@ proc withOpenFile {filename channelVar script} { return -options $options $result } .CE - .SH "SEE ALSO" file(n), open(n), socket(n), eof(n), Tcl_StandardChannels(3) - .SH KEYWORDS -blocking, channel, close, nonblocking +blocking, channel, close, nonblocking, half-close +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: diff --git a/doc/concat.n b/doc/concat.n index f7317c4..b079b30 100644 --- a/doc/concat.n +++ b/doc/concat.n @@ -14,11 +14,10 @@ concat \- Join lists together .SH SYNOPSIS \fBconcat\fI \fR?\fIarg arg ...\fR? .BE - .SH DESCRIPTION .PP This command joins each of its arguments together with spaces after -trimming leading and trailing white-space from each of them. If all the +trimming leading and trailing white-space from each of them. If all of the arguments are lists, this has the same effect as concatenating them into a single list. It permits any number of arguments; @@ -53,4 +52,7 @@ values, as can be seen here: .SH "SEE ALSO" append(n), eval(n), join(n) .SH KEYWORDS -concatenate, join, lists +concatenate, join, list +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/continue.n b/doc/continue.n index 221b7e2..de2f07c 100644 --- a/doc/continue.n +++ b/doc/continue.n @@ -14,13 +14,12 @@ continue \- Skip to the next iteration of a loop .SH SYNOPSIS \fBcontinue\fR .BE - .SH DESCRIPTION .PP This command is typically invoked inside the body of a looping command such as \fBfor\fR or \fBforeach\fR or \fBwhile\fR. -It returns a \fBTCL_CONTINUE\fR code, which causes a continue exception -to occur. +It returns a 4 (\fBTCL_CONTINUE\fR) result code, which causes a continue +exception to occur. The exception causes the current script to be aborted out to the innermost containing loop command, which then continues with the next iteration of the loop. @@ -28,18 +27,21 @@ Catch exceptions are also handled in a few other situations, such as the \fBcatch\fR command and the outermost scripts of procedure bodies. .SH EXAMPLE +.PP Print a line for each of the integers from 0 to 10 \fIexcept\fR 5: +.PP .CS for {set x 0} {$x<10} {incr x} { - if {$x == 5} { - \fBcontinue\fR - } - puts "x is $x" + if {$x == 5} { + \fBcontinue\fR + } + puts "x is $x" } .CE - .SH "SEE ALSO" break(n), for(n), foreach(n), return(n), while(n) - .SH KEYWORDS continue, iteration, loop +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/copy.n b/doc/copy.n new file mode 100644 index 0000000..51ec844 --- /dev/null +++ b/doc/copy.n @@ -0,0 +1,53 @@ +'\" +'\" Copyright (c) 2007 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH copy n 0.1 TclOO "TclOO Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +oo::copy \- create copies of objects and classes +.SH SYNOPSIS +.nf +package require TclOO + +\fBoo::copy\fI sourceObject \fR?\fItargetObject\fR? +.fi +.BE +.SH DESCRIPTION +.PP +The \fBoo::copy\fR command creates a copy of an object or class. It takes the +name of the object or class to be copied, \fIsourceObject\fR, and optionally +the name of the object or class to create, \fItargetObject\fR, which will be +resolved relative to the current namespace if not an absolute qualified name. +If \fItargetObject\fR is omitted, a new name is chosen. The copied object will +be of the same class as the source object, and will have all its per-object +methods copied. If it is a class, it will also have all the class methods in +the class copied, but it will not have any of its instances copied. The +contents of the source object's private namespace \fIwill not\fR be copied; it +is up to the caller to do this. The result of this command will be the +fully-qualified name of the new object or class. +.SH EXAMPLES +.PP +This example creates an object, copies it, modifies the source object, and +then demonstrates that the copied object is indeed a copy. +.PP +.CS +oo::object create src +oo::objdefine src method msg {} {puts foo} +\fBoo::copy\fR src dst +oo::objdefine src method msg {} {puts bar} +src msg \fI\(-> prints "bar"\fR +dst msg \fI\(-> prints "foo"\fR +.CE +.SH "SEE ALSO" +oo::class(n), oo::define(n), oo::object(n) +.SH KEYWORDS +clone, copy, duplication, object +.\" Local variables: +.\" mode: nroff +.\" fill-column: 78 +.\" End: diff --git a/doc/coroutine.n b/doc/coroutine.n new file mode 100644 index 0000000..f4b5d5b --- /dev/null +++ b/doc/coroutine.n @@ -0,0 +1,155 @@ +'\" +'\" Copyright (c) 2009 Donal K. Fellows. +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH coroutine n 8.6 Tcl "Tcl Built-In Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +coroutine, yield \- Create and produce values from coroutines +.SH SYNOPSIS +.nf +\fBcoroutine \fIname command\fR ?\fIarg...\fR? +\fByield\fR ?\fIvalue\fR? +\fIname\fR ?\fIvalue\fR? +.fi +.BE +.SH DESCRIPTION +.PP +The \fBcoroutine\fR command creates a new coroutine context (with associated +command) named \fIname\fR and executes that context by calling \fIcommand\fR, +passing in the other remaining arguments without further interpretation. Once +\fIcommand\fR returns normally or with an exception (e.g., an error) the +coroutine context \fIname\fR is deleted. +.PP +Within the context, values may be generated as results by using the +\fByield\fR command; if no \fIvalue\fR is supplied, the empty string is used. +When that is called, the context will suspend execution and the +\fBcoroutine\fR command will return the argument to \fByield\fR. The execution +of the context can then be resumed by calling the context command, optionally +passing in the value to use as the result of the \fByield\fR call that caused +the context to be suspended. If the coroutine context never yields and instead +returns conventionally, the result of the \fBcoroutine\fR command will be the +result of the evaluation of the context. +.PP +The coroutine can also be deleted by destroying the command \fIname\fR, and +the name of the current coroutine can be retrieved by using +\fBinfo coroutine\fR. +If there are deletion traces on variables in the coroutine's +implementation, they will fire at the point when the coroutine is explicitly +deleted (or, naturally, if the command returns conventionally). +.PP +At the point when \fIcommand\fR is called, the current namespace will be the +global namespace and there will be no stack frames above it (in the sense of +\fBupvar\fR and \fBuplevel\fR). However, which command to call will be +determined in the namespace that the \fBcoroutine\fR command was called from. +.SH EXAMPLES +.PP +This example shows a coroutine that will produce an infinite sequence of +even values, and a loop that consumes the first ten of them. +.PP +.CS +proc allNumbers {} { + \fByield\fR + set i 0 + while 1 { + \fByield\fR $i + incr i 2 + } +} +\fBcoroutine\fR nextNumber allNumbers +for {set i 0} {$i < 10} {incr i} { + puts "received [\fInextNumber\fR]" +} +rename nextNumber {} +.CE +.PP +In this example, the coroutine acts to add up the arguments passed to it. +.PP +.CS +\fBcoroutine\fR accumulator apply {{} { + set x 0 + while 1 { + incr x [\fByield\fR $x] + } +}} +for {set i 0} {$i < 10} {incr i} { + puts "$i -> [\fIaccumulator\fR $i]" +} +.CE +.PP +This example demonstrates the use of coroutines to implement the classic Sieve +of Eratosthenes algorithm for finding prime numbers. Note the creation of +coroutines inside a coroutine. +.PP +.CS +proc filterByFactor {source n} { + \fByield\fR [info coroutine] + while 1 { + set x [\fI$source\fR] + if {$x % $n} { + \fByield\fR $x + } + } +} +\fBcoroutine\fR allNumbers apply {{} {while 1 {\fByield\fR [incr x]}}} +\fBcoroutine\fR eratosthenes apply {c { + \fByield\fR + while 1 { + set n [\fI$c\fR] + \fByield\fR $n + set c [\fBcoroutine\fR prime$n filterByFactor $c $n] + } +}} allNumbers +for {set i 1} {$i <= 20} {incr i} { + puts "prime#$i = [\fIeratosthenes\fR]" +} +.CE +.SS "DETAILED SEMANTICS" +.PP +This example demonstrates that coroutines start from the global namespace, and +that \fIcommand\fR resolution happens before the coroutine stack is created. +.PP +.CS +proc report {where level} { + # Where was the caller called from? + set ns [uplevel 2 {namespace current}] + \fByield\fR "made $where $level context=$ns name=[info coroutine]" +} +proc example {} { + report outer [info level] +} +namespace eval demo { + proc example {} { + report inner [info level] + } + proc makeExample {} { + puts "making from [info level]" + puts [\fBcoroutine\fR coroEg example] + } + makeExample +} +.CE +.PP +Which produces the output below. In particular, we can see that stack +manipulation has occurred (comparing the levels from the first and second +line) and that the parent level in the coroutine is the global namespace. We +can also see that coroutine names are local to the current namespace if not +qualified, and that coroutines may yield at depth (e.g., in called +procedures). +.PP +.CS +making from 2 +made inner 1 context=:: name=::demo::coroEg +.CE +.SH "SEE ALSO" +apply(n), info(n), proc(n), return(n) +.SH KEYWORDS +coroutine, generator +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: @@ -123,6 +123,7 @@ command returns an error message if the script did not run, unless the \fB\-async\fR flag was used, in which case the command returns immediately with no error. This command can be used to replace send on Windows. .SH "DDE AND TCL" +.PP A Tcl interpreter always has a service name of \fBTclEval\fR. Each different interpreter of all running Tcl applications must be given a unique @@ -155,8 +156,10 @@ If for any reason the event queue is not flushed, DDE commands may hang until the event queue is flushed. This can create a deadlock situation. .SH EXAMPLE +.PP This asks Internet Explorer (which must already be running) to go to a particularly important website: +.PP .CS package require dde \fBdde execute\fR iexplore WWW_OpenURL http://www.tcl.tk/ diff --git a/doc/define.n b/doc/define.n new file mode 100644 index 0000000..58bc4cd --- /dev/null +++ b/doc/define.n @@ -0,0 +1,297 @@ +'\" +'\" Copyright (c) 2007 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH define n 0.3 TclOO "TclOO Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +oo::define, oo::objdefine \- define and configure classes and objects +.SH SYNOPSIS +.nf +package require TclOO + +\fBoo::define\fI class defScript\fR +\fBoo::define\fI class subcommand arg\fR ?\fIarg ...\fR? +\fBoo::objdefine\fI object defScript\fR +\fBoo::objdefine\fI object subcommand arg\fR ?\fIarg ...\fR? +.fi +.BE + +.SH DESCRIPTION +The \fBoo::define\fR command is used to control the configuration of classes, +and the \fBoo::objdefine\fR command is used to control the configuration of +objects (including classes as instance objects), with the configuration being +applied to the entity named in the \fIclass\fR or the \fIobject\fR argument. +Configuring a class also updates the +configuration of all subclasses of the class and all objects that are +instances of that class or which mix it in (as modified by any per-instance +configuration). The way in which the configuration is done is controlled by +either the \fIdefScript\fR argument or by the \fIsubcommand\fR and following +\fIarg\fR arguments; when the second is present, it is exactly as if all the +arguments from \fIsubcommand\fR onwards are made into a list and that list is +used as the \fIdefScript\fR argument. +.SS "CONFIGURING CLASSES" +.PP +The following commands are supported in the \fIdefScript\fR for +\fBoo::define\fR, each of which may also be used in the \fIsubcommand\fR form: +.TP +\fBconstructor\fI argList bodyScript\fR +. +This creates or updates the constructor for a class. The formal arguments to +the constructor (defined using the same format as for the Tcl \fBproc\fR +command) will be \fIargList\fR, and the body of the constructor will be +\fIbodyScript\fR. When the body of the constructor is evaluated, the current +namespace of the constructor will be a namespace that is unique to the object +being constructed. Within the constructor, the \fBnext\fR command should be +used to call the superclasses' constructors. If \fIbodyScript\fR is the empty +string, the constructor will be deleted. +.TP +\fBdeletemethod\fI name\fR ?\fIname ...\fR +. +This deletes each of the methods called \fIname\fR from a class. The methods +must have previously existed in that class. Does not affect the superclasses +of the class, nor does it affect the subclasses or instances of the class +(except when they have a call chain through the class being modified). +.TP +\fBdestructor\fI bodyScript\fR +. +This creates or updates the destructor for a class. Destructors take no +arguments, and the body of the destructor will be \fIbodyScript\fR. The +destructor is called when objects of the class are deleted, and when called +will have the object's unique namespace as the current namespace. Destructors +should use the \fBnext\fR command to call the superclasses' destructors. Note +that destructors are not called in all situations (e.g. if the interpreter is +destroyed). If \fIbodyScript\fR is the empty string, the destructor will be +deleted. +.RS +Note that errors during the evaluation of a destructor \fIare not returned\fR +to the code that causes the destruction of an object. Instead, they are passed +to the currently-defined \fBbgerror\fR handler. +.RE +.TP +\fBexport\fI name \fR?\fIname ...\fR? +. +This arranges for each of the named methods, \fIname\fR, to be exported +(i.e. usable outside an instance through the instance object's command) by the +class being defined. Note that the methods themselves may be actually defined +by a superclass; subclass exports override superclass visibility, and may in +turn be overridden by instances. +.TP +\fBfilter\fR ?\fImethodName ...\fR? +. +This sets or updates the list of method names that are used to guard whether a +method call to instances of the class may be called and what the method's +results are. Each \fImethodName\fR names a single filtering method (which may +be exposed or not exposed); it is not an error for a non-existent method to be +named since they may be defined by subclasses. If no \fImethodName\fR +arguments are present, the list of filter names is set to empty. +.TP +\fBforward\fI name cmdName \fR?\fIarg ...\fR? +. +This creates or updates a forwarded method called \fIname\fR. The method is +defined be forwarded to the command called \fIcmdName\fR, with additional +arguments, \fIarg\fR etc., added before those arguments specified by the +caller of the method. The \fIcmdName\fR will always be resolved using the +rules of the invoking objects' namespaces, i.e., when \fIcmdName\fR is not +fully-qualified, the command will be searched for in each object's namespace, +using the instances' namespace's path, or by looking in the global namespace. +The method will be exported if \fIname\fR starts with a lower-case letter, and +non-exported otherwise. +.TP +\fBmethod\fI name argList bodyScript\fR +. +This creates or updates a method that is implemented as a procedure-like +script. The name of the method is \fIname\fR, the formal arguments to the +method (defined using the same format as for the Tcl \fBproc\fR command) will +be \fIargList\fR, and the body of the method will be \fIbodyScript\fR. When +the body of the method is evaluated, the current namespace of the method will +be a namespace that is unique to the current object. The method will be +exported if \fIname\fR starts with a lower-case letter, and non-exported +otherwise; this behavior can be overridden via \fBexport\fR and +\fBunexport\fR. +.TP +\fBmixin\fR ?\fIclassName ...\fR? +. +This sets or updates the list of additional classes that are to be mixed into +all the instances of the class being defined. Each \fIclassName\fR argument +names a single class that is to be mixed in; if no classes are present, the +list of mixed-in classes is set to be empty. +.TP +\fBrenamemethod\fI fromName toName\fR +. +This renames the method called \fIfromName\fR in a class to \fItoName\fR. The +method must have previously existed in the class, and \fItoName\fR must not +previously refer to a method in that class. Does not affect the superclasses +of the class, nor does it affect the subclasses or instances of the class +(except when they have a call chain through the class being modified). Does +not change the export status of the method; if it was exported before, it will +be afterwards. +.TP +\fBself\fI subcommand arg ...\fR +.TP +\fBself\fI script\fR +. +This command is equivalent to calling \fBoo::objdefine\fR on the class being +defined (see \fBCONFIGURING OBJECTS\fR below for a description of the +supported values of \fIsubcommand\fR). It follows the same general pattern of +argument handling as the \fBoo::define\fR and \fBoo::objdefine\fR commands, +and +.QW "\fBoo::define \fIcls \fBself \fIsubcommand ...\fR" +operates identically to +.QW "\fBoo::objdefine \fIcls subcommand ...\fR" . +.TP +\fBsuperclass\fI className \fR?\fIclassName ...\fR? +. +This allows the alteration of the superclasses of the class being defined. +Each \fIclassName\fR argument names one class that is to be a superclass of +the defined class. Note that objects must not be changed from being classes to +being non-classes or vice-versa. +.TP +\fBunexport\fI name \fR?\fIname ...\fR? +. +This arranges for each of the named methods, \fIname\fR, to be not exported +(i.e. not usable outside the instance through the instance object's command, +but instead just through the \fBmy\fR command visible in each object's +context) by the class being defined. Note that the methods themselves may be +actually defined by a superclass; subclass unexports override superclass +visibility, and may be overridden by instance unexports. +.TP +\fBvariable\fR ?\fIname ...\fR? +.VS +This arranges for each of the named variables to be automatically made +available in the methods, constructor and destructor declared by the class +being defined. Note that the list of variable names is the whole list of +variable names for the class. Each variable name must not have any namespace +separators and must not look like an array access. All variables will be +actually present in the instance object on which the method is executed. Note +that the variable lists declared by a superclass or subclass are completely +disjoint, as are variable lists declared by instances; the list of variable +names is just for methods (and constructors and destructors) declared by this +class. +.VE +.SS "CONFIGURING OBJECTS" +.PP +The following commands are supported in the \fIdefScript\fR for +\fBoo::objdefine\fR, each of which may also be used in the \fIsubcommand\fR +form: +.TP +\fBclass\fI className\fR +. +This allows the class of an object to be changed after creation. Note that the +class's constructors are not called when this is done, and so the object may +well be in an inconsistent state unless additional configuration work is done. +.TP +\fBdeletemethod\fI name\fR ?\fIname ...\fR +. +This deletes each of the methods called \fIname\fR from an object. The methods +must have previously existed in that object. Does not affect the classes that +the object is an instance of. +.TP +\fBexport\fI name \fR?\fIname ...\fR? +. +This arranges for each of the named methods, \fIname\fR, to be exported +(i.e. usable outside the object through the object's command) by the object +being defined. Note that the methods themselves may be actually defined by a +class or superclass; object exports override class visibility. +.TP +\fBfilter\fR ?\fImethodName ...\fR? +. +This sets or updates the list of method names that are used to guard whether a +method call to the object may be called and what the method's results are. +Each \fImethodName\fR names a single filtering method (which may be exposed or +not exposed); it is not an error for a non-existent method to be named. If no +\fImethodName\fR arguments are present, the list of filter names is set to +empty. Note that the actual list of filters also depends on the filters set +upon any classes that the object is an instance of. +.TP +\fBforward\fI name cmdName \fR?\fIarg ...\fR? +. +This creates or updates a forwarded object method called \fIname\fR. The +method is defined be forwarded to the command called \fIcmdName\fR, with +additional arguments, \fIarg\fR etc., added before those arguments specified +by the caller of the method. Forwarded methods should be deleted using the +\fBmethod\fR subcommand. The method will be exported if \fIname\fR starts with +a lower-case letter, and non-exported otherwise. +.TP +\fBmethod\fI name argList bodyScript\fR +. +This creates, updates or deletes an object method. The name of the method is +\fIname\fR, the formal arguments to the method (defined using the same format +as for the Tcl \fBproc\fR command) will be \fIargList\fR, and the body of the +method will be \fIbodyScript\fR. When the body of the method is evaluated, the +current namespace of the method will be a namespace that is unique to the +object. The method will be exported if \fIname\fR starts with a lower-case +letter, and non-exported otherwise. +.TP +\fBmixin\fR ?\fIclassName ...\fR? +. +This sets or updates a per-object list of additional classes that are to be +mixed into the object. Each argument, \fIclassName\fR, names a single class +that is to be mixed in; if no classes are present, the list of mixed-in +classes is set to be empty. +.TP +\fBrenamemethod\fI fromName toName\fR +. +This renames the method called \fIfromName\fR in an object to \fItoName\fR. +The method must have previously existed in the object, and \fItoName\fR must +not previously refer to a method in that object. Does not affect the classes +that the object is an instance of. Does not change the export status of the +method; if it was exported before, it will be afterwards. +.TP +\fBunexport\fI name \fR?\fIname ...\fR? +. +This arranges for each of the named methods, \fIname\fR, to be not exported +(i.e. not usable outside the object through the object's command, but instead +just through the \fBmy\fR command visible in the object's context) by the +object being defined. Note that the methods themselves may be actually defined +by a class; instance unexports override class visibility. +.TP +\fBvariable\fR ?\fIname ...\fR? +.VS +This arranges for each of the named variables to be automatically made +available in the methods declared by the object being defined. Note that the +list of variable names is the whole list of variable names for the object. +Each variable name must not have any namespace separators and must not look +like an array access. All variables will be actually present in the object on +which the method is executed. Note that the variable lists declared by the +classes and mixins of which the object is an instance are completely disjoint; +the list of variable names is just for methods declared by this object. +.VE +.SH EXAMPLES +This example demonstrates how to use both forms of the \fBoo::define\fR and +\fBoo::objdefine\fR commands (they work in the same way), as well as +illustrating four of the subcommands of them. +.PP +.CS +oo::class create c +c create o +\fBoo::define\fR c \fBmethod\fR foo {} { + puts "world" +} +\fBoo::objdefine\fR o { + \fBmethod\fR bar {} { + my Foo "hello " + my foo + } + \fBforward\fR Foo ::puts -nonewline + \fBunexport\fR foo +} +o bar \fI\(-> prints "hello world"\fR +o foo \fI\(-> error "unknown method foo"\fR +o Foo Bar \fI\(-> error "unknown method Foo"\fR +\fBoo::objdefine\fR o \fBrenamemethod\fR bar lollipop +o lollipop \fI\(-> prints "hello world"\fR +.CE +.SH "SEE ALSO" +next(n), oo::class(n), oo::object(n) +.SH KEYWORDS +class, definition, method, object + +.\" Local variables: +.\" mode: nroff +.\" fill-column: 78 +.\" End: @@ -21,33 +21,40 @@ below for a description), depending on \fIoption\fR. The legal \fIoption\fRs (which may be abbreviated) are: .TP \fBdict append \fIdictionaryVariable key \fR?\fIstring ...\fR? +. This appends the given string (or strings) to the value that the given key maps to in the dictionary value contained in the given variable, writing the resulting dictionary value back to that variable. Non-existent keys are treated as if they map to an empty string. .TP \fBdict create \fR?\fIkey value ...\fR? +. Create a new dictionary that contains each of the key/value mappings listed as arguments (keys and values alternating, with each key being followed by its associated value.) .TP \fBdict exists \fIdictionaryValue key \fR?\fIkey ...\fR? +. This returns a boolean value indicating whether the given key (or path of keys through a set of nested dictionaries) exists in the given dictionary value. This returns a true value exactly when \fBdict get\fR on that path will succeed. .TP \fBdict filter \fIdictionaryValue filterType arg \fR?\fIarg ...\fR? +. This takes a dictionary value and returns a new dictionary that contains just those key/value pairs that match the specified filter type (which may be abbreviated.) Supported filter types are: .RS .TP -\fBdict filter \fIdictionaryValue \fBkey \fIglobPattern\fR -The key rule only matches those key/value pairs whose keys match the -given pattern (in the style of \fBstring match\fR.) +\fBdict filter \fIdictionaryValue \fBkey\fR ?\fIglobPattern ...\fR? +.VS 8.6 +The key rule only matches those key/value pairs whose keys match any +of the given patterns (in the style of \fBstring match\fR.) +.VE 8.6 .TP \fBdict filter \fIdictionaryValue \fBscript {\fIkeyVar valueVar\fB} \fIscript\fR +. The script rule tests for matching by assigning the key to the \fIkeyVar\fR and the value to the \fIvalueVar\fR, and then evaluating the given script which should return a boolean value (with the @@ -60,12 +67,15 @@ dictionary, and a condition of \fBTCL_CONTINUE\fR is equivalent to a false result. The key/value pairs are tested in the order in which the keys were inserted into the dictionary. .TP -\fBdict filter \fIdictionaryValue \fBvalue \fIglobPattern\fR -The value rule only matches those key/value pairs whose values match -the given pattern (in the style of \fBstring match\fR.) +\fBdict filter \fIdictionaryValue \fBvalue \fR?\fIglobPattern ...\fR? +.VS 8.6 +The value rule only matches those key/value pairs whose values match any +of the given patterns (in the style of \fBstring match\fR.) +.VE 8.6 .RE .TP \fBdict for {\fIkeyVar valueVar\fB} \fIdictionaryValue body\fR +. This command takes three arguments, the first a two-element list of variable names (for the key and value respectively of each mapping in the dictionary), the second the dictionary value to iterate across, @@ -80,6 +90,7 @@ normal \fBTCL_OK\fR result. The order of iteration is the order in which the keys were inserted into the dictionary. .TP \fBdict get \fIdictionaryValue \fR?\fIkey ...\fR? +. Given a dictionary value (first argument) and a key (second argument), this will retrieve the value for that key. Where several keys are supplied, the behaviour of the command shall be as if the result of @@ -104,6 +115,7 @@ present in the dictionary. .RE .TP \fBdict incr \fIdictionaryVariable key \fR?\fIincrement\fR? +. This adds the given increment value (an integer that defaults to 1 if not specified) to the value that the given key maps to in the dictionary value contained in the given variable, writing the @@ -112,6 +124,7 @@ are treated as if they map to 0. It is an error to increment a value for an existing key if that value is not an integer. .TP \fBdict info \fIdictionaryValue\fR +. This returns information (intended for display to people) about the given dictionary though the format of this data is dependent on the implementation of the dictionary. For dictionaries that are @@ -119,12 +132,14 @@ implemented by hash tables, it is expected that this will return the string produced by \fBTcl_HashStats\fR, similar to \fBarray statistics\fR. .TP \fBdict keys \fIdictionaryValue \fR?\fIglobPattern\fR? +. Return a list of all keys in the given dictionary value. If a pattern is supplied, only those keys that match it (according to the rules of \fBstring match\fR) will be returned. The returned keys will be in the order that they were inserted into the dictionary. .TP \fBdict lappend \fIdictionaryVariable key \fR?\fIvalue ...\fR? +. This appends the given items to the list value that the given key maps to in the dictionary value contained in the given variable, writing the resulting dictionary value back to that variable. Non-existent @@ -133,6 +148,7 @@ there to be no items to append to the list. It is an error for the value that the key maps to to not be representable as a list. .TP \fBdict merge \fR?\fIdictionaryValue ...\fR? +. Return a dictionary that contains the contents of each of the \fIdictionaryValue\fR arguments. Where two (or more) dictionaries contain a mapping for the same key, the resulting dictionary maps that @@ -140,6 +156,7 @@ key to the value according to the last dictionary on the command line containing a mapping for that key. .TP \fBdict remove \fIdictionaryValue \fR?\fIkey ...\fR? +. Return a new dictionary that is a copy of an old one passed in as first argument except without mappings for each of the keys listed. It is legal for there to be no keys to remove, and it also legal for @@ -147,6 +164,7 @@ any of the keys to be removed to not be present in the input dictionary in the first place. .TP \fBdict replace \fIdictionaryValue \fR?\fIkey value ...\fR? +. Return a new dictionary that is a copy of an old one passed in as first argument except with some values different or some extra key/value pairs added. It is legal for this command to be called with @@ -154,6 +172,7 @@ no key/value pairs, but illegal for this command to be called with a key but no value. .TP \fBdict set \fIdictionaryVariable key \fR?\fIkey ...\fR? \fIvalue\fR +. This operation takes the name of a variable containing a dictionary value and places an updated dictionary value in that variable containing a mapping from the given key to the given value. When @@ -161,9 +180,11 @@ multiple keys are present, this operation creates or updates a chain of nested dictionaries. .TP \fBdict size \fIdictionaryValue\fR +. Return the number of key/value mappings in the given dictionary value. .TP \fBdict unset \fIdictionaryVariable key \fR?\fIkey ...\fR? +. This operation (the companion to \fBdict set\fR) takes the name of a variable containing a dictionary value and places an updated dictionary value in that variable that does not contain a mapping for @@ -173,6 +194,7 @@ must be specified, but the last key on the key-path need not exist. All other components on the path must exist. .TP \fBdict update \fIdictionaryVariable key varName \fR?\fIkey varName ...\fR? \fIbody\fR +. Execute the Tcl script in \fIbody\fR with the value for each \fIkey\fR (as found by reading the dictionary value in \fIdictionaryVariable\fR) mapped to the variable \fIvarName\fR. There may be multiple @@ -189,7 +211,7 @@ evaluation of \fIbody\fR. .PP Each \fIvarName\fR is mapped in the scope enclosing the \fBdict update\fR; it is recommended that this command only be used in a local scope -(\fBproc\fRedure or lambda term for \fBapply\fR). Because of +(\fBproc\fRedure, lambda term for \fBapply\fR, or method). Because of this, the variables set by \fBdict update\fR will continue to exist after the command finishes (unless explicitly \fBunset\fR). Note that the mapping of values to variables @@ -198,6 +220,7 @@ contents only happen when \fIbody\fR terminates. .RE .TP \fBdict values \fIdictionaryValue \fR?\fIglobPattern\fR? +. Return a list of all values in the given dictionary value. If a pattern is supplied, only those values that match it (according to the rules of \fBstring match\fR) will be returned. The returned values @@ -205,6 +228,7 @@ will be in the order of that the keys associated with those values were inserted into the dictionary. .TP \fBdict with \fIdictionaryVariable \fR?\fIkey ...\fR? \fIbody\fR +. Execute the Tcl script in \fIbody\fR with the value for each key in \fIdictionaryVariable\fR mapped (in a manner similarly to \fBdict update\fR) to a variable with the same name. Where one or more @@ -221,7 +245,7 @@ dictionaries no longer exists. The result of \fBdict with\fR is .PP The variables are mapped in the scope enclosing the \fBdict with\fR; it is recommended that this command only be used in a local scope -(\fBproc\fRedure or lambda term for \fBapply\fR). Because of +(\fBproc\fRedure, lambda term for \fBapply\fR, or method). Because of this, the variables set by \fBdict with\fR will continue to exist after the command finishes (unless explicitly \fBunset\fR). Note that the mapping of values to variables does not use @@ -311,16 +335,16 @@ Constructing and using nested dictionaries: set i 0 puts "There are [\fBdict size\fR $employeeInfo] employees" \fBdict for\fR {id info} $employeeInfo { - puts "Employee #[incr i]: $id" - \fBdict with\fR info { - puts " Name: $forenames $surname" - puts " Address: $street, $city" - puts " Telephone: $phone" - } + puts "Employee #[incr i]: $id" + \fBdict with\fR info { + puts " Name: $forenames $surname" + puts " Address: $street, $city" + puts " Telephone: $phone" + } } # Another way to iterate and pick out names... foreach id [\fBdict keys\fR $employeeInfo] { - puts "Hello, [\fBdict get\fR $employeeInfo $id forenames]!" + puts "Hello, [\fBdict get\fR $employeeInfo $id forenames]!" } .CE .PP @@ -330,7 +354,7 @@ A localizable version of \fBstring toupper\fR: # Set up the basic C locale set capital [\fBdict create\fR C [\fBdict create\fR]] foreach c [split {abcdefghijklmnopqrstuvwxyz} ""] { - \fBdict set\fR capital C $c [string toupper $c] + \fBdict set\fR capital C $c [string toupper $c] } # English locales can luckily share the "C" locale @@ -349,22 +373,22 @@ Showing the detail of \fBdict with\fR: .PP .CS proc sumDictionary {varName} { - upvar 1 $varName vbl - foreach key [\fBdict keys\fR $vbl] { - # Manufacture an entry in the subdictionary - \fBdict set\fR vbl $key total 0 - # Add the values and remove the old - \fBdict with\fR vbl $key { - set total [expr {$x + $y + $z}] - unset x y z - } - } - puts "last total was $total, for key $key" + upvar 1 $varName vbl + foreach key [\fBdict keys\fR $vbl] { + # Manufacture an entry in the subdictionary + \fBdict set\fR vbl $key total 0 + # Add the values and remove the old + \fBdict with\fR vbl $key { + set total [expr {$x + $y + $z}] + unset x y z + } + } + puts "last total was $total, for key $key" } set myDict { - a {x 1 y 2 z 3} - b {x 6 y 5 z 4} + a {x 1 y 2 z 3} + b {x 6 y 5 z 4} } sumDictionary myDict @@ -387,3 +411,6 @@ puts $foo append(n), array(n), foreach(n), incr(n), list(n), lappend(n), set(n) .SH KEYWORDS dictionary, create, update, lookup, iterate, filter +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/encoding.n b/doc/encoding.n index f8f3d54..5269a18 100644 --- a/doc/encoding.n +++ b/doc/encoding.n @@ -12,7 +12,6 @@ encoding \- Manipulate encodings .SH SYNOPSIS \fBencoding \fIoption\fR ?\fIarg arg ...\fR? .BE - .SH INTRODUCTION .PP Strings in Tcl are encoded using 16-bit Unicode characters. Different @@ -25,6 +24,7 @@ Performs one of several encoding related operations, depending on \fIoption\fR. The legal \fIoption\fRs are: .TP \fBencoding convertfrom\fR ?\fIencoding\fR? \fIdata\fR +. Convert \fIdata\fR to Unicode from the specified \fIencoding\fR. The characters in \fIdata\fR are treated as binary data where the lower 8-bits of each character is taken as a single byte. The resulting @@ -33,6 +33,7 @@ sequence of bytes is treated as a string in the specified system encoding is used. .TP \fBencoding convertto\fR ?\fIencoding\fR? \fIstring\fR +. Convert \fIstring\fR from Unicode to the specified \fIencoding\fR. The result is a sequence of bytes that represents the converted string. Each byte is stored in the lower 8-bits of a Unicode @@ -40,7 +41,7 @@ character. If \fIencoding\fR is not specified, the current system encoding is used. .TP \fBencoding dirs\fR ?\fIdirectoryList\fR? -.VS 8.5 +. Tcl can load encoding data files from the file system that describe additional encodings for it to work with. This command sets the search path for \fB*.enc\fR encoding data files to the list of directories @@ -50,13 +51,14 @@ search path. It is an error for \fIdirectoryList\fR to not be a valid list. If, when a search for an encoding data file is happening, an element in \fIdirectoryList\fR does not refer to a readable, searchable directory, that element is ignored. -.VE 8.5 .TP \fBencoding names\fR +. Returns a list containing the names of all of the encodings that are currently available. .TP \fBencoding system\fR ?\fIencoding\fR? +. Set the system encoding to \fIencoding\fR. If \fIencoding\fR is omitted then the command returns the current system encoding. The system encoding is used whenever Tcl passes strings to system calls. @@ -79,15 +81,15 @@ contain a sequence of Latin-1 characters that correspond to the bytes of the original string. The \fBencoding\fR command can be used to convert this string to the expected Japanese Unicode characters. For example, +.PP .CS set s [\fBencoding convertfrom\fR euc-jp "\exA4\exCF"] .CE +.PP would return the Unicode string .QW "\eu306F" , which is the Hiragana letter HA. - .SH "SEE ALSO" Tcl_GetEncoding(3) - .SH KEYWORDS -encoding +encoding, unicode @@ -14,7 +14,6 @@ eof \- Check for end of file condition on channel .SH SYNOPSIS \fBeof \fIchannelId\fR .BE - .SH DESCRIPTION .PP Returns 1 if an end of file condition occurred during the most @@ -26,7 +25,9 @@ Tcl standard channel (\fBstdin\fR, \fBstdout\fR, or \fBstderr\fR), the return value from an invocation of \fBopen\fR or \fBsocket\fR, or the result of a channel creation command provided by a Tcl extension. .SH EXAMPLES +.PP Read and print out the contents of a file line-by-line: +.PP .CS set f [open somefile.txt] while {1} { @@ -40,6 +41,7 @@ while {1} { .CE .PP Read and print out the contents of a file by fixed-size records: +.PP .CS set f [open somefile.dat] fconfigure $f -translation binary @@ -53,9 +55,7 @@ while {1} { puts "Read record: $record" } .CE - .SH "SEE ALSO" file(n), open(n), close(n), fblocked(n), Tcl_StandardChannels(3) - .SH KEYWORDS channel, end of file diff --git a/doc/error.n b/doc/error.n index 77391e5..d61bd7b 100644 --- a/doc/error.n +++ b/doc/error.n @@ -37,18 +37,21 @@ with the \fBcatch\fR command: if a caught error cannot be handled successfully, \fIinfo\fR can be used to return a stack trace reflecting the original point of occurrence of the error: +.PP .CS -\fBcatch {...} errMsg +catch {...} errMsg set savedInfo $::errorInfo \&... -error $errMsg $savedInfo\fR +\fBerror\fR $errMsg $savedInfo .CE +.PP When working with Tcl 8.5 or later, the following code should be used instead: +.PP .CS -\fBcatch {...} errMsg options +catch {...} errMsg options \&... -return -options $options $errMsg\fR +return -options $options $errMsg .CE .PP If the \fIcode\fR argument is present, then its value is stored @@ -58,15 +61,18 @@ of the error in cases where such information is available; see the \fBreturn\fR manual page for information on the proper format for this option's value. .SH EXAMPLE +.PP Generate an error if a basic mathematical operation fails: +.PP .CS if {1+2 != 3} { \fBerror\fR "something is very wrong with addition" } .CE - .SH "SEE ALSO" catch(n), return(n) - .SH KEYWORDS -error +error, exception +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -14,7 +14,6 @@ eval \- Evaluate a Tcl script .SH SYNOPSIS \fBeval \fIarg \fR?\fIarg ...\fR? .BE - .SH DESCRIPTION .PP \fBEval\fR takes one or more arguments, which together comprise a Tcl @@ -26,11 +25,13 @@ evaluation (or any error generated by it). Note that the \fBlist\fR command quotes sequences of words in such a way that they are not further expanded by the \fBeval\fR command. .SH EXAMPLES +.PP Often, it is useful to store a fragment of a script in a variable and execute it later on with extra values appended. This technique is used in a number of places throughout the Tcl core (e.g. in \fBfcopy\fR, \fBlsort\fR and \fBtrace\fR command callbacks). This example shows how to do this using core Tcl commands: +.PP .CS set script { puts "logging now" @@ -48,35 +49,35 @@ for {set i 0} {$i<10} {incr i} { } .CE .PP -.VS 8.5 Note that in the most common case (where the script fragment is actually just a list of words forming a command prefix), it is better to use \fB{*}$script\fR when doing this sort of invocation pattern. It is less general than the \fBeval\fR command, and hence easier to make robust in practice. -.VE 8.5 The following procedure acts in a way that is analogous to the \fBlappend\fR command, except it inserts the argument values at the start of the list in the variable: +.PP .CS proc lprepend {varName args} { - upvar 1 $varName var - # Ensure that the variable exists and contains a list - lappend var - # Now we insert all the arguments in one go - set var [\fBeval\fR [list linsert $var 0] $args] + upvar 1 $varName var + # Ensure that the variable exists and contains a list + lappend var + # Now we insert all the arguments in one go + set var [\fBeval\fR [list linsert $var 0] $args] } .CE -.VS 8.5 +.PP However, the last line would now normally be written without \fBeval\fR, like this: +.PP .CS set var [linsert $var 0 {*}$args] .CE -.VE 8.5 - .SH "SEE ALSO" catch(n), concat(n), error(n), interp(n), list(n), namespace(n), subst(n), tclvars(n), uplevel(n) - .SH KEYWORDS concatenate, evaluate, script +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -13,9 +13,8 @@ .SH NAME exec \- Invoke subprocesses .SH SYNOPSIS -\fBexec \fR?\fIswitches\fR? \fIarg \fR?\fIarg ...\fR? +\fBexec \fR?\fIswitches\fR? \fIarg \fR?\fIarg ...\fR? ?\fB&\fR? .BE - .SH DESCRIPTION .PP This command treats its arguments as the specification @@ -30,16 +29,17 @@ of the pipeline specification. The following switches are currently supported: .TP 13 \fB\-ignorestderr\fR -.VS 8.5 +. Stops the \fBexec\fR command from treating the output of messages to the pipeline's standard error channel as an error case. -.VE 8.5 .TP 13 \fB\-keepnewline\fR +. Retains a trailing newline in the pipeline's output. Normally a trailing newline will be deleted. .TP 13 \fB\-\|\-\fR +. Marks the end of switches. The argument following this one will be treated as the first \fIarg\fR even if it starts with a \fB\-\fR. .PP @@ -55,64 +55,77 @@ or in the same argument with no intervening space (i.e. .QW \fB<\fIfileName\fR ). .TP 15 \fB|\fR +. Separates distinct commands in the pipeline. The standard output of the preceding command will be piped into the standard input of the next command. .TP 15 \fB|&\fR +. Separates distinct commands in the pipeline. Both standard output and standard error of the preceding command will be piped into the standard input of the next command. This form of redirection overrides forms such as 2> and >&. .TP 15 \fB<\0\fIfileName\fR +. The file named by \fIfileName\fR is opened and used as the standard input for the first command in the pipeline. .TP 15 \fB<@\0\fIfileId\fR +. \fIFileId\fR must be the identifier for an open file, such as the return value from a previous call to \fBopen\fR. It is used as the standard input for the first command in the pipeline. \fIFileId\fR must have been opened for reading. .TP 15 \fB<<\0\fIvalue\fR +. \fIValue\fR is passed to the first command as its standard input. .TP 15 \fB>\0\fIfileName\fR +. Standard output from the last command is redirected to the file named \fIfileName\fR, overwriting its previous contents. .TP 15 \fB2>\0\fIfileName\fR +. Standard error from all commands in the pipeline is redirected to the file named \fIfileName\fR, overwriting its previous contents. .TP 15 \fB>&\0\fIfileName\fR +. Both standard output from the last command and standard error from all commands are redirected to the file named \fIfileName\fR, overwriting its previous contents. .TP 15 \fB>>\0\fIfileName\fR +. Standard output from the last command is redirected to the file named \fIfileName\fR, appending to it rather than overwriting it. .TP 15 \fB2>>\0\fIfileName\fR +. Standard error from all commands in the pipeline is redirected to the file named \fIfileName\fR, appending to it rather than overwriting it. .TP 15 \fB>>&\0\fIfileName\fR +. Both standard output from the last command and standard error from all commands are redirected to the file named \fIfileName\fR, appending to it rather than overwriting it. .TP 15 \fB>@\0\fIfileId\fR +. \fIFileId\fR must be the identifier for an open file, such as the return value from a previous call to \fBopen\fR. Standard output from the last command is redirected to \fIfileId\fR's file, which must have been opened for writing. .TP 15 \fB2>@\0\fIfileId\fR +. \fIFileId\fR must be the identifier for an open file, such as the return value from a previous call to \fBopen\fR. Standard error from all commands in the pipeline is @@ -120,11 +133,13 @@ redirected to \fIfileId\fR's file. The file must have been opened for writing. .TP 15 \fB2>@1\0\fR +. Standard error from all commands in the pipeline is redirected to the command result. This operator is only valid at the end of the command pipeline. .TP 15 \fB>&@\0\fIfileId\fR +. \fIFileId\fR must be the identifier for an open file, such as the return value from a previous call to \fBopen\fR. Both standard output from the last command and standard error from @@ -133,12 +148,9 @@ The file must have been opened for writing. .PP If standard output has not been redirected then the \fBexec\fR command returns the standard output from the last command -in the pipeline, -.VS 8.5 -unless +in the pipeline, unless .QW 2>@1 was specified, in which case standard error is included as well. -.VE 8.5 If any of the commands in the pipeline exit abnormally or are killed or suspended, then \fBexec\fR will return an error and the error message will include the pipeline's output followed by @@ -147,9 +159,7 @@ error messages describing the abnormal terminations; the about the last abnormal termination encountered. If any of the commands writes to its standard error file and that standard error is not redirected -.VS 8.5 and \fB\-ignorestderr\fR is not specified, -.VE 8.5 then \fBexec\fR will return an error; the error message will include the pipeline's standard output, followed by messages about abnormal terminations (if any), followed by the standard error @@ -229,7 +239,7 @@ names must use the short, cryptic, path format (e.g., using instead of .QW applbakery.default ), which can be obtained with the -.QW "\fBfile attributes \fIfileName \fB\-shortname\fR" +.QW "\fBfile attributes\fI fileName \fB\-shortname\fR" command. .PP Two or more forward or backward slashes in a row in a path refer to a @@ -270,17 +280,17 @@ for the longer name. If a directory name was not specified as part of the application name, the following directories are automatically searched in order when attempting to locate the application: .RS -.IP \(bu +.IP \(bu 3 The directory from which the Tcl executable was loaded. -.IP \(bu +.IP \(bu 3 The current directory. -.IP \(bu +.IP \(bu 3 The Windows NT 32-bit system directory. -.IP \(bu +.IP \(bu 3 The Windows NT 16-bit system directory. -.IP \(bu +.IP \(bu 3 The Windows NT home directory. -.IP \(bu +.IP \(bu 3 The directories listed in the path. .PP In order to execute shell built-in commands like \fBdir\fR and \fBcopy\fR, @@ -298,15 +308,15 @@ for the longer name. If a directory name was not specified as part of the application name, the following directories are automatically searched in order when attempting to locate the application: .RS -.IP \(bu +.IP \(bu 3 The directory from which the Tcl executable was loaded. -.IP \(bu +.IP \(bu 3 The current directory. -.IP \(bu +.IP \(bu 3 The Windows 9x system directory. -.IP \(bu +.IP \(bu 3 The Windows 9x home directory. -.IP \(bu +.IP \(bu 3 The directories listed in the path. .RE .RS @@ -350,73 +360,122 @@ output may fail, hang Tcl, or even hang the system if their own private console window is not available to them. .RE .TP -\fBUnix\fR\0\0\0\0\0\0\0 +\fBUnix\fR (including Mac OS X) +. The \fBexec\fR command is fully functional and works as described. .SH "UNIX EXAMPLES" -Here are some examples of the use of the \fBexec\fR command on Unix. .PP +Here are some examples of the use of the \fBexec\fR command on Unix. To execute a simple program and get its result: +.PP .CS \fBexec\fR uname -a .CE +.SS "WORKING WITH NON-ZERO RESULTS" .PP To execute a program that can return a non-zero result, you should wrap the call to \fBexec\fR in \fBcatch\fR and check the contents of the \fB\-errorcode\fR return option if you have an error: +.PP .CS set status 0 if {[catch {\fBexec\fR grep foo bar.txt} results options]} { - set details [dict get $options -errorcode] - if {[lindex $details 0] eq "CHILDSTATUS"} { - set status [lindex $details 2] - } else { - # Some kind of unexpected failure - } + set details [dict get $options -errorcode] + if {[lindex $details 0] eq "CHILDSTATUS"} { + set status [lindex $details 2] + } else { + # Some other error; regenerate it to let caller handle + return -options $options -level 0 $results + } +} +.CE +.VS 8.6 +.PP +This is more easily written using the \fBtry\fR command, as that makes +it simpler to trap specific types of errors. This is +done using code like this: +.PP +.CS +try { + set results [\fBexec\fR grep foo bar.txt] + set status 0 +} trap CHILDSTATUS {results options} { + set status [lindex [dict get $options -errorcode] 2] } .CE +.VE 8.6 +.SS "WORKING WITH QUOTED ARGUMENTS" .PP When translating a command from a Unix shell invocation, care should be taken over the fact that single quote characters have no special significance to Tcl. Thus: +.PP .CS awk '{sum += $1} END {print sum}' numbers.list .CE +.PP would be translated into something like: +.PP .CS \fBexec\fR awk {{sum += $1} END {print sum}} numbers.list .CE +.SS "WORKING WITH GLOBBING" .PP If you are converting invocations involving shell globbing, you should remember that Tcl does not handle globbing or expand things into multiple arguments by default. Instead you should write things like this: +.PP .CS \fBexec\fR ls -l {*}[glob *.tcl] .CE +.SS "WORKING WITH USER-SUPPLIED SHELL SCRIPT FRAGMENTS" +.PP +One useful technique can be to expose to users of a script the ability +to specify a fragment of shell script to execute that will have some +data passed in on standard input that was produced by the Tcl program. +This is a common technique for using the \fIlpr\fR program for +printing. By far the simplest way of doing this is to pass the user's +script to the user's shell for processing, as this avoids a lot of +complexity with parsing other languages. +.PP +.CS +set lprScript [\fIget from user...\fR] +set postscriptData [\fIgenerate somehow...\fR] + +\fBexec\fR $env(SHELL) -c $lprScript << $postscriptData +.CE .SH "WINDOWS EXAMPLES" -Here are some examples of the use of the \fBexec\fR command on Windows. .PP +Here are some examples of the use of the \fBexec\fR command on Windows. To start an instance of \fInotepad\fR editing a file without waiting for the user to finish editing the file: +.PP .CS \fBexec\fR notepad myfile.txt & .CE .PP To print a text file using \fInotepad\fR: +.PP .CS \fBexec\fR notepad /p myfile.txt .CE +.SS "WORKING WITH CONSOLE PROGRAMS" .PP If a program calls other programs, such as is common with compilers, then you may need to resort to batch files to hide the console windows that sometimes pop up: +.PP .CS \fBexec\fR cmp.bat somefile.c -o somefile .CE +.PP With the file \fIcmp.bat\fR looking something like: +.PP .CS @gcc %1 %2 %3 %4 %5 %6 %7 %8 %9 .CE +.SS "WORKING WITH COMMAND BUILT-INS" .PP Sometimes you need to be careful, as different programs may have the same name and be in the path. It can then happen that typing a command @@ -431,10 +490,27 @@ applies especially when you want to run commands like \fIdir\fR from a Tcl script (if you just want to list filenames, use the \fBglob\fR command.) To do that, use this: +.PP .CS \fBexec\fR {*}[auto_execok dir] *.tcl .CE +.SS "WORKING WITH NATIVE FILENAMES" +.PP +Many programs on Windows require filename arguments to be passed in with +backslashes as pathname separators. This is done with the help of the +\fBfile nativename\fR command. For example, to make a directory (on NTFS) +encrypted so that only the current user can access it requires use of +the \fICIPHER\fR command, like this: +.PP +.CS +set secureDir "~/Desktop/Secure Directory" +file mkdir $secureDir +\fBexec\fR CIPHER /e /s:[file nativename $secureDir] +.CE .SH "SEE ALSO" -error(n), open(n) +error(n), file(n), open(n) .SH KEYWORDS execute, pipeline, redirection, subprocess +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -22,10 +22,12 @@ system as the exit status. If \fIreturnCode\fR is not specified then it defaults to 0. .SH EXAMPLE +.PP Since non-zero exit codes are usually interpreted as error cases by the calling process, the \fBexit\fR command is an important part of signaling that something fatal has gone wrong. This code fragment is useful in scripts to act as a general problem trap: +.PP .CS proc main {} { # ... put the real main code in here ... @@ -43,9 +45,7 @@ if {[catch {main} msg options]} { \fBexit\fR 2 } .CE - .SH "SEE ALSO" exec(n) - .SH KEYWORDS -exit, process +abort, exit, process @@ -26,9 +26,11 @@ as the corresponding C operators. Expressions almost always yield numeric results (integer or floating-point values). For example, the expression +.PP .CS -\fBexpr 8.2 + 6\fR +\fBexpr\fR 8.2 + 6 .CE +.PP evaluates to 14.2. Tcl expressions differ from C expressions in the way that operands are specified. Also, Tcl expressions support @@ -41,7 +43,6 @@ and parentheses. White space may be used between the operands and operators and parentheses; it is ignored by the expression's instructions. Where possible, operands are interpreted as integer values. -.VS 8.5 Integer values may be specified in decimal (the normal case), in binary (if the first two characters of the operand are \fB0b\fR), in octal (if the first two characters of the operand are \fB0o\fR), or in hexadecimal @@ -58,7 +59,6 @@ the sign characters \fB+\fR or \fB\-\fR. For example, all of the following are valid floating-point numbers: 2.1, 3., 6e4, 7.91e+16. Also recognized as floating point values are the strings \fBInf\fR and \fBNaN\fR making use of any case for each character. -.VE 8.5 If no numeric interpretation is possible (note that all literal operands that are not numeric or boolean must be quoted with either braces or with double quotes), then an operand is left as a string @@ -68,7 +68,8 @@ Operands may be specified in any of the following ways: .IP [1] As a numeric value, either integer or floating-point. .IP [2] -As a boolean value, using any form understood by \fBstring is boolean\fR. +As a boolean value, using any form understood by \fBstring is\fR +\fBboolean\fR. .IP [3] As a Tcl variable, using standard \fB$\fR notation. The variable's value will be used as the operand. @@ -89,7 +90,7 @@ the operand. As a mathematical function whose arguments have any of the above forms for operands, such as \fBsin($x)\fR. See \fBMATH FUNCTIONS\fR below for a discussion of how mathematical functions are handled. -.LP +.PP Where the above substitutions occur (e.g. inside quoted strings), they are performed by the expression's instructions. However, the command parser may already have performed one round of @@ -103,6 +104,7 @@ For some examples of simple expressions, suppose the variable the variable \fBb\fR has the value 6. Then the command on the left side of each of the lines below will produce the value on the right side of the line: +.PP .CS .ta 6c \fBexpr\fR 3.1 + $a \fI6.1\fR @@ -117,16 +119,17 @@ the \fBtcl::mathop\fR namespace; see the \fBmathop\fR(n) manual page for details) are listed below, grouped in decreasing order of precedence: .TP 20 \fB\-\0\0+\0\0~\0\0!\fR +. Unary minus, unary plus, bit-wise NOT, logical NOT. None of these operators may be applied to string operands, and bit-wise NOT may be applied only to integers. .TP 20 \fB**\fR -.VS 8.5 +. Exponentiation. Valid for any numeric operands. -.VE 8.5 .TP 20 \fB*\0\0/\0\0%\fR +. Multiply, divide, remainder. None of these operators may be applied to string operands, and remainder may be applied only to integers. @@ -134,80 +137,98 @@ The remainder will always have the same sign as the divisor and an absolute value smaller than the divisor. .TP 20 \fB+\0\0\-\fR +. Add and subtract. Valid for any numeric operands. .TP 20 \fB<<\0\0>>\fR +. Left and right shift. Valid for integer operands only. A right shift always propagates the sign bit. .TP 20 \fB<\0\0>\0\0<=\0\0>=\fR +. Boolean less, greater, less than or equal, and greater than or equal. Each operator produces 1 if the condition is true, 0 otherwise. These operators may be applied to strings as well as numeric operands, in which case string comparison is used. .TP 20 \fB==\0\0!=\fR +. Boolean equal and not equal. Each operator produces a zero/one result. Valid for all operand types. .TP 20 \fBeq\0\0ne\fR +. Boolean string equal and string not equal. Each operator produces a zero/one result. The operand types are interpreted only as strings. .TP 20 \fBin\0\0ni\fR -.VS 8.5 +. List containment and negated list containment. Each operator produces a zero/one result and treats its first argument as a string and its second argument as a Tcl list. The \fBin\fR operator indicates whether the first argument is a member of the second argument list; the \fBni\fR operator inverts the sense of the result. -.VE 8.5 .TP 20 \fB&\fR +. Bit-wise AND. Valid for integer operands only. .TP 20 \fB^\fR +. Bit-wise exclusive OR. Valid for integer operands only. .TP 20 \fB|\fR +. Bit-wise OR. Valid for integer operands only. .TP 20 \fB&&\fR +. Logical AND. Produces a 1 result if both operands are non-zero, 0 otherwise. Valid for boolean and numeric (integers or floating-point) operands only. .TP 20 \fB||\fR +. Logical OR. Produces a 0 result if both operands are zero, 1 otherwise. Valid for boolean and numeric (integers or floating-point) operands only. .TP 20 \fIx\fB?\fIy\fB:\fIz\fR +. If-then-else, as in C. If \fIx\fR evaluates to non-zero, then the result is the value of \fIy\fR. Otherwise the result is the value of \fIz\fR. The \fIx\fR operand must have a boolean or numeric value. -.LP +.PP See the C manual for more details on the results produced by each operator. -.VS 8.5 The exponentiation operator promotes types like the multiply and divide operators, and produces a result that is the same as the output of the \fBpow\fR function (after any type conversions.) -.VE 8.5 -All of the binary operators group left-to-right within the same -precedence level. For example, the command +All of the binary operators but exponentiation group left-to-right +within the same precedence level; exponentiation groups right-to-left. For example, the command +.PP .CS \fBexpr\fR {4*2 < 7} .CE -returns 0. +.PP +returns 0, while +.PP +.CS +\fBexpr\fR {2**3**2} +.CE +.PP +returns 512. .PP The \fB&&\fR, \fB||\fR, and \fB?:\fR operators have .QW "lazy evaluation" , just as in C, which means that operands are not evaluated if they are not needed to determine the outcome. For example, in the command +.PP .CS -\fBexpr {$v ? [a] : [b]}\fR +\fBexpr\fR {$v ? [a] : [b]} .CE +.PP only one of .QW \fB[a]\fR or @@ -222,21 +243,25 @@ and before invoking the \fBexpr\fR command. .SS "MATH FUNCTIONS" .PP -.VS 8.5 When the expression parser encounters a mathematical function such as \fBsin($x)\fR, it replaces it with a call to an ordinary Tcl function in the \fBtcl::mathfunc\fR namespace. The processing of an expression such as: +.PP .CS -\fBexpr {sin($x+$y)}\fR +\fBexpr\fR {sin($x+$y)} .CE +.PP is the same in every way as the processing of: +.PP .CS -\fBexpr {[tcl::mathfunc::sin [expr {$x+$y}]]}\fR +\fBexpr\fR {[tcl::mathfunc::sin [\fBexpr\fR {$x+$y}]]} .CE +.PP which in turn is the same as the processing of: +.PP .CS -\fBtcl::mathfunc::sin [expr {$x+$y}]\fR +tcl::mathfunc::sin [\fBexpr\fR {$x+$y}] .CE .PP The executor will search for \fBtcl::mathfunc::sin\fR using the usual @@ -247,10 +272,8 @@ may as well (depending on the current \fBnamespace path\fR setting). .PP See the \fBmathfunc\fR(n) manual page for the math functions that are available by default. -.VE 8.5 .SS "TYPES, OVERFLOW, AND PRECISION" .PP -.VS 8.5 All internal computations involving integers are done calling on the LibTomMath multiple precision integer library as required so that all integer calculations are performed exactly. Note that in Tcl releases @@ -260,7 +283,6 @@ in those calculations where values overflowed the range of those types. Any code that relied on these implicit truncations will need to explicitly add \fBint()\fR or \fBwide()\fR function calls to expressions at the points where such truncation is required to take place. -.VE 8.5 .PP All internal computations involving floating-point are done with the C type \fIdouble\fR. @@ -275,23 +297,29 @@ and string operands is done automatically as needed. For arithmetic computations, integers are used until some floating-point number is introduced, after which floating-point is used. For example, +.PP .CS \fBexpr\fR {5 / 4} .CE +.PP returns 1, while +.PP .CS \fBexpr\fR {5 / 4.0} \fBexpr\fR {5 / ( [string length "abcd"] + 0.0 )} .CE +.PP both return 1.25. Floating-point values are always returned with a .QW \fB.\fR or an .QW \fBe\fR so that they will not look like integer values. For example, +.PP .CS \fBexpr\fR {20.0/5.0} .CE +.PP returns \fB4.0\fR, not \fB4\fR. .SS "STRING OPERATIONS" .PP @@ -306,10 +334,12 @@ Canonical string representation for integer values is a decimal string format. Canonical string representation for floating-point values is that produced by the \fB%g\fR format specifier of Tcl's \fBformat\fR command. For example, the commands +.PP .CS -\fBexpr {"0x03" > "2"}\fR -\fBexpr {"0y" < "0x12"}\fR +\fBexpr\fR {"0x03" > "2"} +\fBexpr\fR {"0y" < "0x12"} .CE +.PP both return 1. The first comparison is done using integer comparison, and the second is done using string comparison after the second operand is converted to the string \fB18\fR. @@ -327,11 +357,13 @@ This allows the Tcl bytecode compiler to generate the best code. As mentioned above, expressions are substituted twice: once by the Tcl parser and once by the \fBexpr\fR command. For example, the commands +.PP .CS -\fBset a 3\fR -\fBset b {$a + 2}\fR -\fBexpr $b*4\fR +set a 3 +set b {$a + 2} +\fBexpr\fR $b*4 .CE +.PP return 11, not a multiple of 4. This is because the Tcl parser will first substitute \fB$a + 2\fR for the variable \fBb\fR, @@ -349,15 +381,15 @@ The most expensive code is required for unbraced expressions that contain command substitutions. These expressions must be implemented by generating new code each time the expression is executed. -.VS 8.5 When the expression is unbraced to allow the substitution of a function or operator, consider using the commands documented in the \fBmathfunc\fR(n) or \fBmathop\fR(n) manual pages directly instead. -.VE 8.5 .SH EXAMPLES +.PP Define a procedure that computes an .QW interesting mathematical function: +.PP .CS proc tcl::mathfunc::calc {x y} { \fBexpr\fR { ($x**2 - $y**2) / exp($x**2 + $y**2) } @@ -365,6 +397,7 @@ proc tcl::mathfunc::calc {x y} { .CE .PP Convert polar coordinates into cartesian coordinates: +.PP .CS # convert from ($radius,$angle) set x [\fBexpr\fR { $radius * cos($angle) }] @@ -372,6 +405,7 @@ set y [\fBexpr\fR { $radius * sin($angle) }] .CE .PP Convert cartesian coordinates into polar coordinates: +.PP .CS # convert from ($x,$y) set radius [\fBexpr\fR { hypot($y, $x) }] @@ -380,12 +414,14 @@ set angle [\fBexpr\fR { atan2($y, $x) }] .PP Print a message describing the relationship of two string values to each other: +.PP .CS puts "a and b are [\fBexpr\fR {$a eq $b ? {equal} : {different}}]" .CE .PP Set a variable to whether an environment variable is both defined at all and also set to a true boolean value: +.PP .CS set isTrue [\fBexpr\fR { [info exists ::env(SOME_ENV_VAR)] && @@ -394,6 +430,7 @@ set isTrue [\fBexpr\fR { .CE .PP Generate a random integer in the range 0..99 inclusive: +.PP .CS set randNum [\fBexpr\fR { int(100 * rand()) }] .CE @@ -408,3 +445,6 @@ Copyright (c) 1993 The Regents of the University of California. Copyright (c) 1994-2000 Sun Microsystems Incorporated. Copyright (c) 2005 by Kevin B. Kenny <kennykb@acm.org>. All rights reserved. .fi +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/fblocked.n b/doc/fblocked.n index d8e8af7..2841aee 100644 --- a/doc/fblocked.n +++ b/doc/fblocked.n @@ -4,7 +4,6 @@ '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" -.so man.macros .TH fblocked n 7.5 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! @@ -62,9 +61,7 @@ proc echoLine {chan clientName} { socket -server connect 12345 vwait forever .CE - .SH "SEE ALSO" gets(n), open(n), read(n), socket(n), Tcl_StandardChannels(3) - .SH KEYWORDS blocking, nonblocking diff --git a/doc/fconfigure.n b/doc/fconfigure.n index 0763232..ac0366c 100644 --- a/doc/fconfigure.n +++ b/doc/fconfigure.n @@ -39,7 +39,8 @@ The options described below are supported for all channels. In addition, each channel type may add options that only it supports. See the manual entry for the command that creates each type of channels for the options that that specific type of channel supports. For example, see the manual -entry for the \fBsocket\fR command for its additional options. +entry for the \fBsocket\fR command for additional options for sockets, and +the \fBopen\fR command for additional options for serial devices. .TP \fB\-blocking\fR \fIboolean\fR The \fB\-blocking\fR option determines whether I/O operations on the @@ -213,34 +214,38 @@ If, for example, a Tcl application is started by the \fBinet\fR super-server common on Unix system its Tcl standard channels will be sockets and thus support the socket options. .SH EXAMPLES +.PP Instruct Tcl to always send output to \fBstdout\fR immediately, whether or not it is to a terminal: +.PP .CS \fBfconfigure\fR stdout -buffering none .CE .PP Open a socket and read lines from it without ever blocking the processing of other events: +.PP .CS set s [socket some.where.com 12345] \fBfconfigure\fR $s -blocking 0 fileevent $s readable "readMe $s" proc readMe chan { - if {[gets $chan line] < 0} { - if {[eof $chan]} { - close $chan - return - } - # Could not read a complete line this time; Tcl's - # internal buffering will hold the partial line for us - # until some more data is available over the socket. - } else { - puts stdout $line - } + if {[gets $chan line] < 0} { + if {[eof $chan]} { + close $chan + return + } + # Could not read a complete line this time; Tcl's + # internal buffering will hold the partial line for us + # until some more data is available over the socket. + } else { + puts stdout $line + } } .CE .PP Read a PPM-format image from a file: +.PP .CS # Open the file and put it into Unix ASCII mode set f [open teapot.ppm] @@ -248,16 +253,16 @@ set f [open teapot.ppm] # Get the header if {[gets $f] ne "P6"} { - error "not a raw\-bits PPM" + error "not a raw\-bits PPM" } # Read lines until we have got non-comment lines # that supply us with three decimal values. set words {} while {[llength $words] < 3} { - gets $f line - if {[string match "#*" $line]} continue - lappend words {*}[join [scan $line %d%d%d]] + gets $f line + if {[string match "#*" $line]} continue + lappend words {*}[join [scan $line %d%d%d]] } # Those words supply the size of the image and its @@ -272,12 +277,13 @@ set data [read $f $numDataBytes] close $f .CE - .SH "SEE ALSO" close(n), flush(n), gets(n), open(n), puts(n), read(n), socket(n), Tcl_StandardChannels(3) - .SH KEYWORDS blocking, buffering, carriage return, end of line, flushing, linemode, newline, nonblocking, platform, translation, encoding, filter, byte array, binary +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/fcopy.n b/doc/fcopy.n index d583cf0..6a4bf1a 100644 --- a/doc/fcopy.n +++ b/doc/fcopy.n @@ -90,13 +90,13 @@ the system will assume that the incoming bytes are valid UTF-8 characters and convert them according to the output encoding. The behaviour of the system for bytes which are not valid UTF-8 characters is undefined in this case. - .SH EXAMPLES .PP The first example transfers the contents of one channel exactly to another. Note that when copying one file to another, it is better to use \fBfile copy\fR which also copies file metadata (e.g. the file access permissions) where possible. +.PP .CS fconfigure $in -translation binary fconfigure $out -translation binary @@ -108,6 +108,7 @@ passed the number of bytes transferred. It also uses vwait to put the application into the event loop. Of course, this simplified example could be done without the command callback. +.PP .CS proc Cleanup {in out bytes {error {}}} { global total @@ -115,7 +116,7 @@ proc Cleanup {in out bytes {error {}}} { close $in close $out if {[string length $error] != 0} { - # error occurred during the copy + # error occurred during the copy } } set in [open $file1] @@ -125,17 +126,18 @@ vwait total .CE .PP The third example copies in chunks and tests for end of file -in the command callback +in the command callback. +.PP .CS proc CopyMore {in out chunk bytes {error {}}} { global total done incr total $bytes if {([string length $error] != 0) || [eof $in]} { - set done $total - close $in - close $out + set done $total + close $in + close $out } else { - \fBfcopy\fR $in $out -size $chunk \e + \fBfcopy\fR $in $out -size $chunk \e -command [list CopyMore $in $out $chunk] } } @@ -147,9 +149,7 @@ set total 0 -command [list CopyMore $in $out $chunk] vwait done .CE - .SH "SEE ALSO" eof(n), fblocked(n), fconfigure(n), file(n) - .SH KEYWORDS blocking, channel, end of line, end of file, nonblocking, read, translation @@ -104,12 +104,12 @@ within a single filesystem, \fIfile copy\fR will copy soft links (i.e. the links themselves are copied, not the things they point to). Trying to overwrite a non-empty directory, overwrite a directory with a file, or overwrite a file with a directory will all result in errors even if -\fI\-force\fR was specified. Arguments are processed in the order +\fB\-force\fR was specified. Arguments are processed in the order specified, halting at the first error, if any. A \fB\-\|\-\fR marks the end of switches; the argument following the \fB\-\|\-\fR will be treated as a \fIsource\fR even if it starts with a \fB\-\fR. .TP -\fBfile delete \fR?\fB\-force\fR? ?\fB\-\|\-\fR? \fIpathname\fR ?\fIpathname\fR ... ? +\fBfile delete \fR?\fB\-force\fR? ?\fB\-\|\-\fR? ?\fIpathname\fR ... ? . Removes the file or directory specified by each \fIpathname\fR argument. Non-empty directories will be removed only if the @@ -136,20 +136,26 @@ only contains one path element, then returns If \fIname\fR refers to a root directory, then the root directory is returned. For example, .RS +.PP .CS -\fBfile dirname c:/\fR +\fBfile dirname\fR c:/ .CE +.PP returns \fBc:/\fR. .PP Note that tilde substitution will only be performed if it is necessary to complete the command. For example, +.PP .CS -\fBfile dirname ~/src/foo.c\fR +\fBfile dirname\fR ~/src/foo.c .CE +.PP returns \fB~/src\fR, whereas +.PP .CS -\fBfile dirname ~\fR +\fBfile dirname\fR ~ .CE +.PP returns \fB/home\fR (or something similar). .RE .TP @@ -185,9 +191,11 @@ relative, then it will be joined to the previous file name argument. Otherwise, any earlier arguments will be discarded, and joining will proceed from the current argument. For example, .RS +.PP .CS -\fBfile join a b /foo bar\fR +\fBfile join\fR a b /foo bar .CE +.PP returns \fB/foo/bar\fR. .PP Note that any of the names can contain separators, and that the result @@ -219,9 +227,9 @@ If the user wishes to make a link of a specific type only, (and signal an error if for some reason that is not possible), then the optional \fI\-linktype\fR argument should be given. Accepted values for \fI\-linktype\fR are -.QW \-symbolic +.QW \fB\-symbolic\fR and -.QW \-hard . +.QW \fB\-hard\fR . .PP On Unix, symbolic links can be made to relative paths, and those paths must be relative to the actual \fIlinkName\fR's location (not to the @@ -249,7 +257,7 @@ is for the link rather than the file it refers to. On systems that do not support symbolic links this option behaves exactly the same as the \fBstat\fR option. .TP -\fBfile mkdir \fIdir\fR ?\fIdir\fR ...? +\fBfile mkdir ?\fIdir\fR ...? . Creates each directory specified. For each pathname \fIdir\fR specified, this command will create all non-existing parent directories as @@ -370,10 +378,14 @@ All other elements will be relative. Path separators will be discarded unless they are needed to ensure that an element is unambiguously relative. For example, under Unix .RS +.PP .CS -file split /foo/~bar/baz +\fBfile split\fR /foo/~bar/baz .CE -returns \fB/\0\0foo\0\0./~bar\0\0baz\fR to ensure that later commands +.PP +returns +.QW \fB/\0\0foo\0\0./~bar\0\0baz\fR +to ensure that later commands that use the third component do not attempt to perform tilde substitution. .RE @@ -421,6 +433,25 @@ If \fIname\fR contains no separators then returns \fIname\fR. So, \fBfile tail a/b\fR, \fBfile tail a/b/\fR and \fBfile tail b\fR all return \fBb\fR. .TP +\fBfile tempfile\fR ?\fInameVar\fR? ?\fItemplate\fR? +'\" TIP #210 +.VS 8.6 +Creates a temporary file and returns a read-write channel opened on that file. +If the \fInameVar\fR is given, it specifies a variable that the name of the +temporary file will be written into; if absent, Tcl will attempt to arrange +for the temporary file to be deleted once it is no longer required. If the +\fItemplate\fR is present, it specifies parts of the template of the filename +to use when creating it (such as the directory, base-name or extension) though +some platforms may ignore some or all of these parts and use a built-in +default instead. +.RS +.PP +Note that temporary files are \fIonly\fR ever created on the native +filesystem. As such, they can be relied upon to be used with operating-system +native APIs and external programs that require a filename. +.RE +.VE 8.6 +.TP \fBfile type \fIname\fR . Returns a string giving the type of file \fIname\fR, which will be one of @@ -451,38 +482,41 @@ Returns \fB1\fR if file \fIname\fR is writable by the current user, These commands always operate using the real user and group identifiers, not the effective ones. .SH EXAMPLES +.PP This procedure shows how to search for C files in a given directory that have a correspondingly-named object file in the current directory: +.PP .CS proc findMatchingCFiles {dir} { - set files {} - switch $::tcl_platform(platform) { - windows { - set ext .obj - } - unix { - set ext .o - } - } - foreach file [glob \-nocomplain \-directory $dir *.c] { - set objectFile [\fBfile tail\fR [\fBfile rootname\fR $file]]$ext - if {[\fBfile exists\fR $objectFile]} { - lappend files $file - } - } - return $files + set files {} + switch $::tcl_platform(platform) { + windows { + set ext .obj + } + unix { + set ext .o + } + } + foreach file [glob \-nocomplain \-directory $dir *.c] { + set objectFile [\fBfile tail\fR [\fBfile rootname\fR $file]]$ext + if {[\fBfile exists\fR $objectFile]} { + lappend files $file + } + } + return $files } .CE .PP Rename a file and leave a symbolic link pointing from the old location to the new place: +.PP .CS set oldName foobar.txt set newName foo/bar.txt # Make sure that where we're going to move to exists... if {![\fBfile isdirectory\fR [\fBfile dirname\fR $newName]]} { - \fBfile mkdir\fR [\fBfile dirname\fR $newName] + \fBfile mkdir\fR [\fBfile dirname\fR $newName] } \fBfile rename\fR $oldName $newName \fBfile link\fR \-symbolic $oldName $newName @@ -493,6 +527,7 @@ On Windows, a file can be easily enough (equivalent to double-clicking on it in the Explorer interface) but the name passed to the operating system must be in native format: +.PP .CS exec {*}[auto_execok start] {} [\fBfile nativename\fR ~/example.txt] .CE @@ -500,4 +535,9 @@ exec {*}[auto_execok start] {} [\fBfile nativename\fR ~/example.txt] filename(n), open(n), close(n), eof(n), gets(n), tell(n), seek(n), fblocked(n), flush(n) .SH KEYWORDS -attributes, copy files, delete files, directory, file, move files, name, rename files, stat +attributes, copy files, delete files, directory, file, move files, name, +rename files, stat, user +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: diff --git a/doc/fileevent.n b/doc/fileevent.n index eb555f5..df48d2a 100644 --- a/doc/fileevent.n +++ b/doc/fileevent.n @@ -1,6 +1,7 @@ '\" '\" Copyright (c) 1994 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. +'\" Copyright (c) 2008 Pat Thoyts '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. @@ -90,6 +91,11 @@ In nonblocking mode \fBputs\fR, \fBread\fR, and \fBgets\fR never block. See the documentation for the individual commands for information on how they handle blocking and nonblocking channels. .PP +Testing for the end of file condition should be done after any attempts +read the channel data. The eof flag is set once an attempt to read the +end of data has occurred and testing before this read will require an +additional event to be fired. +.PP The script for a file event is executed at global level (outside the context of any Tcl procedure) in the interpreter in which the \fBfileevent\fR command was invoked. @@ -99,26 +105,49 @@ In addition, the file event handler is deleted if it ever returns an error; this is done in order to prevent infinite loops due to buggy handlers. .SH EXAMPLE +.PP In this setup \fBGetData\fR will be called with the channel as an -argument whenever $chan becomes readable. +argument whenever $chan becomes readable. The \fBread\fR call will +read whatever binary data is currently available without blocking. +Here the channel has the fileevent removed when an end of file +occurs to avoid being continually called (see above). Alternatively +the channel may be closed on this condition. +.PP .CS proc GetData {chan} { - if {![eof $chan]} { - puts [gets $chan] + set data [read $chan] + puts "[string length $data] $data" + if {[eof $chan]} { + fileevent $chan readable {} } } +fconfigure $chan -blocking 0 -encoding binary \fBfileevent\fR $chan readable [list GetData $chan] .CE +.PP +The next example demonstrates use of \fBgets\fR to read line-oriented +data. +.PP +.CS +proc GetData {chan} { + if {[gets $chan line] >= 0} { + puts $line + } + if {[eof $chan]} { + close $chan + } +} +fconfigure $chan -blocking 0 -buffering line -translation crlf +\fBfileevent\fR $chan readable [list GetData $chan] +.CE .SH CREDITS .PP \fBfileevent\fR is based on the \fBaddinput\fR command created by Mark Diekhans. - .SH "SEE ALSO" fconfigure(n), gets(n), interp(n), puts(n), read(n), Tcl_StandardChannels(3) - .SH KEYWORDS asynchronous I/O, blocking, channel, event handler, nonblocking, readable, script, writable. diff --git a/doc/filename.n b/doc/filename.n index 1fe22f0..d481fc9 100644 --- a/doc/filename.n +++ b/doc/filename.n @@ -38,7 +38,7 @@ type of a given path. .SH "PATH SYNTAX" .PP The rules for native names depend on the value reported in the Tcl -array element \fBtcl_platform(platform)\fR: +\fBplatform\fR element of the \fBtcl_platform\fR array: .TP 10 \fBUnix\fR On Unix and Apple MacOS X platforms, Tcl uses path names where the diff --git a/doc/flush.n b/doc/flush.n index 1c79ea0..b8bf3e9 100644 --- a/doc/flush.n +++ b/doc/flush.n @@ -14,7 +14,6 @@ flush \- Flush buffered output for a channel .SH SYNOPSIS \fBflush \fIchannelId\fR .BE - .SH DESCRIPTION .PP Flushes any output that has been buffered for \fIchannelId\fR. @@ -31,16 +30,16 @@ nonblocking mode, the command may return before all buffered output has been flushed; the remainder will be flushed in the background as fast as the underlying file or device is able to absorb it. .SH EXAMPLE +.PP Prompt for the user to type some information in on the console: +.PP .CS puts -nonewline "Please type your name: " \fBflush\fR stdout gets stdin name puts "Hello there, $name!" .CE - .SH "SEE ALSO" file(n), open(n), socket(n), Tcl_StandardChannels(3) - .SH KEYWORDS blocking, buffer, channel, flush, nonblocking, output @@ -48,10 +48,12 @@ expression is evaluated (before each loop iteration), so changes in the variables will be visible. See below for an example: .SH EXAMPLES +.PP Print a line for each of the integers from 0 to 10: +.PP .CS -for {set x 0} {$x<10} {incr x} { - puts "x is $x" +\fBfor\fR {set x 0} {$x<10} {incr x} { + puts "x is $x" } .CE .PP @@ -62,21 +64,24 @@ before the \fBfor\fR command is run and whether its value is a value that is less than or greater than/equal to ten, and this is because the expression will be substituted before the \fBfor\fR command is executed. +.PP .CS -for {set x 0} $x<10 {incr x} { - puts "x is $x" +\fBfor\fR {set x 0} $x<10 {incr x} { + puts "x is $x" } .CE .PP Print out the powers of two from 1 to 1024: +.PP .CS -for {set x 1} {$x<=1024} {set x [expr {$x * 2}]} { - puts "x is $x" +\fBfor\fR {set x 1} {$x<=1024} {set x [expr {$x * 2}]} { + puts "x is $x" } .CE - .SH "SEE ALSO" -break, continue, foreach, while - +break(n), continue(n), foreach(n), while(n) .SH KEYWORDS -for, iteration, looping +boolean, for, iteration, loop +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/foreach.n b/doc/foreach.n index 654c0cf..fb075d3 100644 --- a/doc/foreach.n +++ b/doc/foreach.n @@ -49,8 +49,10 @@ The \fBbreak\fR and \fBcontinue\fR statements may be invoked inside \fIbody\fR, with the same effect as in the \fBfor\fR command. \fBForeach\fR returns an empty string. .SH EXAMPLES +.PP This loop prints every value in a list together with the square and cube of the value: +.PP .CS '\" Maintainers: notice the tab hacking below! .ta 3i @@ -63,6 +65,7 @@ puts "Value\etSquare\etCube" ;# Neat-looking header .PP The following loop uses i and j as loop variables to iterate over pairs of elements of a single list. +.PP .CS set x {} \fBforeach\fR {i j} {a b c d e f} { @@ -73,6 +76,7 @@ set x {} .CE .PP The next loop uses i and j to iterate over two lists in parallel. +.PP .CS set x {} \fBforeach\fR i {a b c} j {d e f g} { @@ -83,6 +87,7 @@ set x {} .CE .PP The two forms are combined in the following example. +.PP .CS set x {} \fBforeach\fR i {a b c} {j k} {d e f g} { @@ -96,4 +101,4 @@ set x {} for(n), while(n), break(n), continue(n) .SH KEYWORDS -foreach, iteration, list, looping +foreach, iteration, list, loop diff --git a/doc/format.n b/doc/format.n index f842f16..23dfe60 100644 --- a/doc/format.n +++ b/doc/format.n @@ -46,6 +46,7 @@ and a conversion character. Any of these fields may be omitted except for the conversion character. The fields that are present must appear in the order given above. The paragraphs below discuss each of these fields in turn. +.SS "OPTIONAL POSITIONAL SPECIFIER" .PP If the \fB%\fR is followed by a decimal number and a \fB$\fR, as in .QW \fB%2$d\fR , @@ -59,6 +60,7 @@ given by the number. This follows the XPG3 conventions for positional specifiers. If there are any positional specifiers in \fIformatString\fR then all of the specifiers must be positional. +.SS "OPTIONAL FLAGS" .PP The second portion of a conversion specifier may contain any of the following flag characters, in any order: @@ -85,11 +87,14 @@ Requests an alternate output form. For \fBo\fR and \fBO\fR conversions it guarantees that the first digit is always \fB0\fR. For \fBx\fR or \fBX\fR conversions, \fB0x\fR or \fB0X\fR (respectively) will be added to the beginning of the result unless it is zero. +For \fBb\fR conversions, \fB0b\fR +will be added to the beginning of the result unless it is zero. For all floating-point conversions (\fBe\fR, \fBE\fR, \fBf\fR, \fBg\fR, and \fBG\fR) it guarantees that the result always has a decimal point. For \fBg\fR and \fBG\fR conversions it specifies that trailing zeroes should not be removed. +.SS "OPTIONAL FIELD WIDTH" .PP The third portion of a conversion specifier is a decimal number giving a minimum field width for this conversion. @@ -104,6 +109,7 @@ spaces on the right, respectively. If the minimum field width is specified as \fB*\fR rather than a number, then the next argument to the \fBformat\fR command determines the minimum field width; it must be an integer value. +.SS "OPTIONAL PRECISION/BOUND" .PP The fourth portion of a conversion specifier is a precision, which consists of a period followed by a number. @@ -121,6 +127,7 @@ printed; if the string is longer than this then the trailing characters will be If the precision is specified with \fB*\fR rather than a number then the next argument to the \fBformat\fR command determines the precision; it must be a numeric string. +.SS "OPTIONAL SIZE MODIFIER" .PP The fifth part of a conversion specifier is a size modifier, which must be \fBll\fR, \fBh\fR, or \fBl\fR. @@ -134,7 +141,9 @@ function of the \fBexpr\fR command (at least a 64-bit range). If neither \fBh\fR nor \fBl\fR are present, the integer value is truncated to the same range as that produced by the \fBint()\fR function of the \fBexpr\fR command (at least a 32-bit range, but -determined by the value of \fBtcl_platform(wordSize)\fR). +determined by the value of the \fBwordSize\fR element of the +\fBtcl_platform\fR array). +.SS "MANDATORY CONVERSION TYPE" .PP The last thing in a conversion specifier is an alphabetic character that determines what kind of conversion to perform. @@ -159,6 +168,9 @@ for \fBx\fR and .QW 0123456789ABCDEF for \fBX\fR). .TP 10 +\fBb\fR +Convert integer to binary string, using digits 0 and 1. +.TP 10 \fBc\fR Convert integer to the Unicode character it represents. .TP 10 @@ -194,16 +206,21 @@ The behavior of the format command is the same as the ANSI C \fBsprintf\fR procedure except for the following differences: .IP [1] -\fB%p\fR and \fB%n\fR specifiers are not supported. +Tcl guarantees that it will be working with UNICODE characters. .IP [2] +\fB%p\fR and \fB%n\fR specifiers are not supported. +.IP [3] For \fB%c\fR conversions the argument must be an integer value, which will then be converted to the corresponding character value. -.IP [3] +.IP [4] The size modifiers are ignored when formatting floating-point values. The \fBll\fR modifier has no \fBsprintf\fR counterpart. +The \fBb\fR specifier has no \fBsprintf\fR counterpart. .SH EXAMPLES +.PP Convert the numeric value of a UNICODE character to the character itself: +.PP .CS set value 120 set char [\fBformat\fR %c $value] @@ -211,12 +228,14 @@ set char [\fBformat\fR %c $value] .PP Convert the output of \fBtime\fR into seconds to an accuracy of hundredths of a second: +.PP .CS set us [lindex [time $someTclCode] 0] puts [\fBformat\fR "%.2f seconds to execute" [expr {$us / 1e6}]] .CE .PP Create a packed X11 literal color specification: +.PP .CS # Each color-component should be in range (0..255) set color [\fBformat\fR "#%02x%02x%02x" $r $g $b] @@ -225,6 +244,7 @@ set color [\fBformat\fR "#%02x%02x%02x" $r $g $b] Use XPG3 format codes to allow reordering of fields (a technique that is often used in localized message catalogs; see \fBmsgcat\fR) without reordering the data values passed to \fBformat\fR: +.PP .CS set fmt1 "Today, %d shares in %s were bought at $%.2f each" puts [\fBformat\fR $fmt1 123 "Global BigCorp" 19.37] @@ -234,6 +254,7 @@ puts [\fBformat\fR $fmt2 123 "Global BigCorp" 19.37] .CE .PP Print a small table of powers of three: +.PP .CS # Set up the column widths set w1 5 @@ -248,8 +269,8 @@ puts $sep # Print the contents of the table set p 1 for {set i 0} {$i<=20} {incr i} { - puts [\fBformat\fR "| %*d | %*ld |" $w1 $i $w2 $p] - set p [expr {wide($p) * 3}] + puts [\fBformat\fR "| %*d | %*ld |" $w1 $i $w2 $p] + set p [expr {wide($p) * 3}] } # Finish off by printing the separator again @@ -259,3 +280,6 @@ puts $sep scan(n), sprintf(3), string(n) .SH KEYWORDS conversion specifier, format, sprintf, string, substitution +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -4,7 +4,6 @@ '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. -'\" .so man.macros .TH glob n 8.3 Tcl "Tcl Built-In Commands" .BS @@ -12,63 +11,74 @@ .SH NAME glob \- Return names of files that match patterns .SH SYNOPSIS -\fBglob \fR?\fIswitches\fR? \fIpattern \fR?\fIpattern ...\fR? +\fBglob \fR?\fIswitches\fR? ?\fIpattern ...\fR? .BE - .SH DESCRIPTION .PP This command performs file name .QW globbing in a fashion similar to -the csh shell. It returns a list of the files whose names match any -of the \fIpattern\fR arguments. No particular order is guaranteed -in the list, so if a sorted list is required the caller should use +the csh shell or bash shell. +It returns a list of the files whose names match any +of the \fIpattern\fR arguments. No particular order is guaranteed +in the list, so if a sorted list is required the caller should use \fBlsort\fR. -.LP +.SS OPTIONS +.PP If the initial arguments to \fBglob\fR start with \fB\-\fR then -they are treated as switches. The following switches are +they are treated as switches. The following switches are currently supported: .TP \fB\-directory\fR \fIdirectory\fR +. Search for files which match the given patterns starting in the given -\fIdirectory\fR. This allows searching of directories whose name +\fIdirectory\fR. This allows searching of directories whose name contains glob-sensitive characters without the need to quote such -characters explicitly. This option may not be used in conjunction with +characters explicitly. This option may not be used in conjunction with \fB\-path\fR, which is used to allow searching for complete file paths whose names may contain glob-sensitive characters. .TP \fB\-join\fR +. The remaining pattern arguments, after option processing, are treated as a single pattern obtained by joining the arguments with directory separators. .TP \fB\-nocomplain\fR -Allows an empty list to be returned without error; without this +. +Allows an empty list to be returned without error; without this switch an error is returned if the result list would be empty. .TP \fB\-path\fR \fIpathPrefix\fR +. Search for files with the given \fIpathPrefix\fR where the rest of the name -matches the given patterns. This allows searching for files with names -similar to a given file (as opposed to a directory) even when the names -contain glob-sensitive -characters. This option may not be used in conjunction with -\fB\-directory\fR. For example, to find all files with the same root name -as $path, but differing extensions, you should use \fBglob --path [file rootname $path] .*\fR which will work even if $path contains +matches the given patterns. This allows searching for files with names +similar to a given file (as opposed to a directory) even when the names +contain glob-sensitive +characters. This option may not be used in conjunction with +\fB\-directory\fR. For example, to find all files with the same root name +as $path, but differing extensions, you should use +.QW "\fBglob \-path [file rootname $path] .*\fR" +which will work even if \fB$path\fR contains numerous glob-sensitive characters. .TP \fB\-tails\fR +. Only return the part of each file found which follows the last directory -named in any \fB\-directory\fR or \fB\-path\fR path specification. -Thus \fBglob -tails -directory $dir *\fR is equivalent to -\fBset pwd [pwd] ; cd $dir ; glob *; cd $pwd\fR. For -\fB\-path\fR specifications, the returned names will include the last -path segment, so \fBglob -tails -path [file rootname ~/foo.tex] .*\fR +named in any \fB\-directory\fR or \fB\-path\fR path specification. +Thus +.QW "\fBglob \-tails \-directory $dir *\fR" +is equivalent to +.QW "\fBset pwd [pwd]; cd $dir; glob *; cd $pwd\fR" . +For \fB\-path\fR specifications, the returned names will include the last +path segment, so +.QW "\fBglob \-tails \-path [file rootname ~/foo.tex] .*\fR" will return paths like \fBfoo.aux foo.bib foo.tex\fR etc. .TP \fB\-types\fR \fItypeList\fR +. Only list files or directories which match \fItypeList\fR, where the items -in the list have two forms. The first form is like the \-type option of +in the list have two forms. The first form is like the \-type option of the Unix find command: \fIb\fR (block special file), \fIc\fR (character special file), @@ -78,75 +88,83 @@ the Unix find command: \fIp\fR (named pipe), or \fIs\fR (socket), where multiple types may be specified in the list. \fBGlob\fR will return all files which match at least one of the types given. -Note that symbolic links will be returned both if \fB\-types l\fR is given, -or if the target of a link matches the requested type. So, a link to +Note that symbolic links will be returned both if \fB\-types l\fR is given, +or if the target of a link matches the requested type. So, a link to a directory will be returned if \fB\-types d\fR was specified. .RS .PP The second form specifies types where all the types given must match. These are \fIr\fR, \fIw\fR, \fIx\fR as file permissions, and -\fIreadonly\fR, \fIhidden\fR as special permission cases. On the +\fIreadonly\fR, \fIhidden\fR as special permission cases. On the Macintosh, MacOS types and creators are also supported, where any item which is four characters long is assumed to be a MacOS type -(e.g. \fBTEXT\fR). Items which are of the form \fI{macintosh type XXXX}\fR +(e.g. \fBTEXT\fR). Items which are of the form \fI{macintosh type XXXX}\fR or \fI{macintosh creator XXXX}\fR will match types or creators -respectively. Unrecognized types, or specifications of multiple MacOS +respectively. Unrecognized types, or specifications of multiple MacOS types/creators will signal an error. .PP The two forms may be mixed, so \fB\-types {d f r w}\fR will find all regular files OR directories that have both read AND write permissions. The following are equivalent: -.RS +.PP .CS \fBglob \-type d *\fR \fBglob */\fR .CE -.RE +.PP except that the first case doesn't return the trailing .QW / and is more platform independent. .RE .TP \fB\-\|\-\fR -Marks the end of switches. The argument following this one will +. +Marks the end of switches. The argument following this one will be treated as a \fIpattern\fR even if it starts with a \fB\-\fR. +.SS "GLOBBING PATTERNS" .PP The \fIpattern\fR arguments may contain any of the following -special characters: +special characters, which are a superset of those supported by +\fBstring match\fR: .TP 10 \fB?\fR +. Matches any single character. .TP 10 \fB*\fR +. Matches any sequence of zero or more characters. .TP 10 \fB[\fIchars\fB]\fR -Matches any single character in \fIchars\fR. If \fIchars\fR +. +Matches any single character in \fIchars\fR. If \fIchars\fR contains a sequence of the form \fIa\fB\-\fIb\fR then any character between \fIa\fR and \fIb\fR (inclusive) will match. .TP 10 \fB\e\fIx\fR +. Matches the character \fIx\fR. .TP 10 \fB{\fIa\fB,\fIb\fB,\fI...\fR} -Matches any of the strings \fIa\fR, \fIb\fR, etc. -.LP +. +Matches any of the sub-patterns \fIa\fR, \fIb\fR, etc. +.PP On Unix, as with csh, a -.QW . +.QW . \| at the beginning of a file's name or just after a .QW / must be matched explicitly or with a {} construct, unless the \fB\-types hidden\fR flag is given (since -.QW . -at the beginning of a file's name indicates that it is hidden). On +.QW . \| +at the beginning of a file's name indicates that it is hidden). On other platforms, files beginning with a -.QW . +.QW . \| are handled no differently to any others, except the special directories -.QW . +.QW . \| and -.QW .. +.QW .. \| which must be matched explicitly (this is to avoid a recursive pattern like -.QW "glob -join * * * *" +.QW "glob \-join * * * *" from recursing up the directory hierarchy as well as down). In addition, all .QW / characters must be matched explicitly. @@ -160,63 +178,78 @@ If the is followed immediately by .QW / then the value of the HOME environment variable is used. -.LP +.PP The \fBglob\fR command differs from csh globbing in two ways. First, it does not sort its result list (use the \fBlsort\fR command if you want the list sorted). Second, \fBglob\fR only returns the names of files that actually -exist; in csh no check for existence is made unless a pattern +exist; in csh no check for existence is made unless a pattern contains a ?, *, or [] construct. .LP When the \fBglob\fR command returns relative paths whose filenames start with a tilde .QW ~ -(for example through \fBglob *\fR or \fBglob -tails\fR, the returned +(for example through \fBglob *\fR or \fBglob \-tails\fR, the returned list will not quote the tilde with .QW ./ . This means care must be taken if those names are later to be used with \fBfile join\fR, to avoid them being interpreted as absolute paths pointing to a given user's home directory. -.SH "PORTABILITY ISSUES" +.SH "WINDOWS PORTABILITY ISSUES" .PP -\fBWindows\fR -. For Windows UNC names, the servername and sharename components of the path -may not contain ?, *, or [] constructs. On Windows NT, if \fIpattern\fR is +may not contain ?, *, or [] constructs. On Windows NT, if \fIpattern\fR is of the form .QW \fB~\fIusername\fB@\fIdomain\fR , it refers to the home directory of the user whose account information resides on the specified NT -domain server. Otherwise, user account information is obtained from -the local computer. On Windows 95 and 98, \fBglob\fR accepts patterns +domain server. Otherwise, user account information is obtained from +the local computer. On Windows 95 and 98, \fBglob\fR accepted patterns like .QW .../ and .QW ..../ -for successively higher up parent directories. -.PP -Since the backslash character has a special meaning to the glob -command, glob patterns containing Windows style path separators need -special care. The pattern \fIC:\e\efoo\e\e*\fR is interpreted as -\fIC:\efoo\e*\fR where \fI\ef\fR will match the single character \fIf\fR -and \fI\e*\fR will match the single character \fI*\fR and will not be -interpreted as a wildcard character. One solution to this problem is -to use the Unix style forward slash as a path separator. Windows style -paths can be converted to Unix style paths with the command \fBfile -join $path\fR (or \fBfile normalize $path\fR in Tcl 8.4). +for successively higher up parent directories, but later versions of +Windows do not accept these forms. +.PP +Since the backslash character has a special meaning to the glob +command, glob patterns containing Windows style path separators need +special care. The pattern +.QW \fIC:\e\efoo\e\e*\fR +is interpreted as +.QW \fIC:\efoo\e*\fR +where +.QW \fI\ef\fR +will match the single character +.QW \fIf\fR +and +.QW \fI\e*\fR +will match the single character +.QW \fI*\fR +and will not be +interpreted as a wildcard character. One solution to this problem is +to use the Unix style forward slash as a path separator. Windows style +paths can be converted to Unix style paths with the command +.QW "\fBfile join\fR \fB$path\fR" +or +.QW "\fBfile normalize\fR \fB$path\fR" . .SH EXAMPLES +.PP Find all the Tcl files in the current directory: +.PP .CS \fBglob\fR *.tcl .CE .PP Find all the Tcl files in the user's home directory, irrespective of what the current directory is: +.PP .CS \fBglob\fR \-directory ~ *.tcl .CE .PP Find all subdirectories of the current directory: +.PP .CS \fBglob\fR \-type d * .CE @@ -227,12 +260,14 @@ a .QW b or the sequence .QW cde : +.PP .CS \fBglob\fR \-type f *{a,b,cde}* .CE - .SH "SEE ALSO" file(n) - .SH KEYWORDS exist, file, glob, pattern +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/global.n b/doc/global.n index c9d7a36..c17c370 100644 --- a/doc/global.n +++ b/doc/global.n @@ -12,9 +12,8 @@ .SH NAME global \- Access global variables .SH SYNOPSIS -\fBglobal \fIvarname \fR?\fIvarname ...\fR? +\fBglobal \fR?\fIvarname ...\fR? .BE - .SH DESCRIPTION .PP This command has no effect unless executed in the context of a proc body. @@ -31,7 +30,9 @@ the unqualified name of the global variable, as determined by the array element. An error is returned if the name looks like an array element, such as \fBa(b)\fR. .SH EXAMPLES +.PP This procedure sets the namespace variable \fI::a::x\fR +.PP .CS proc reset {} { \fBglobal\fR a::x @@ -44,15 +45,14 @@ buffer, separated by newlines. It is useful for situations when you want to build a message piece-by-piece (as if with \fBputs\fR) but send that full message in a single piece (e.g. over a connection opened with \fBsocket\fR or as part of a counted HTTP response). +.PP .CS proc accum {string} { \fBglobal\fR accumulator append accumulator $string \en } .CE - .SH "SEE ALSO" namespace(n), upvar(n), variable(n) - .SH KEYWORDS global, namespace, procedure, variable @@ -16,9 +16,9 @@ http \- Client-side implementation of the HTTP/1.1 protocol \fBpackage require http ?2.7?\fR .\" See Also -useragent option documentation in body! .sp -\fB::http::config \fI?options?\fR +\fB::http::config ?\fI\-option value\fR ...? .sp -\fB::http::geturl \fIurl ?options?\fR +\fB::http::geturl \fIurl\fR ?\fI\-option value\fR ...? .sp \fB::http::formatQuery\fR \fIkey value\fR ?\fIkey value\fR ...? .sp @@ -77,6 +77,7 @@ applications, the caller can use \fB::http::wait\fR after calling .SH COMMANDS .TP \fB::http::config\fR ?\fIoptions\fR? +. The \fB::http::config\fR command is used to set and query the name of the proxy server and port, and the User-Agent name used in the HTTP requests. If no options are specified, then the current configuration @@ -87,6 +88,7 @@ flags and values that define the configuration: .RS .TP \fB\-accept\fR \fImimetypes\fR +. The Accept header of the request. The default is */*, which means that all types of documents are accepted. Otherwise you can supply a comma-separated list of mime type patterns that you are @@ -94,13 +96,16 @@ willing to receive. For example, .QW "image/gif, image/jpeg, text/*" . .TP \fB\-proxyhost\fR \fIhostname\fR +. The name of the proxy host, if any. If this value is the empty string, the URL host is contacted directly. .TP \fB\-proxyport\fR \fInumber\fR +. The proxy port number. .TP \fB\-proxyfilter\fR \fIcommand\fR +. The command is a callback that is made during \fB::http::geturl\fR to determine if a proxy is required for a given host. One argument, a @@ -112,6 +117,7 @@ an empty list. The default filter returns the values of the non-empty. .TP \fB\-urlencoding\fR \fIencoding\fR +. The \fIencoding\fR used for creating the x-url-encoded URLs with \fB::http::formatQuery\fR. The default is \fButf-8\fR, as specified by RFC 2718. Prior to http 2.5 this was unspecified, and that behavior can be @@ -121,11 +127,13 @@ returned by specifying the empty string (\fB{}\fR), although characters. .TP \fB\-useragent\fR \fIstring\fR +. The value of the User-Agent header in the HTTP request. The default is .QW "\fBTcl http client package 2.7\fR" . .RE .TP \fB::http::geturl\fR \fIurl\fR ?\fIoptions\fR? +. The \fB::http::geturl\fR command is the main procedure in the package. The \fB\-query\fR option causes a POST operation and the \fB\-validate\fR option causes a HEAD operation; @@ -140,21 +148,25 @@ that is invoked when the HTTP transaction completes. .RS .TP \fB\-binary\fR \fIboolean\fR +. Specifies whether to force interpreting the URL data as binary. Normally this is auto-detected (anything not beginning with a \fBtext\fR content type or whose content encoding is \fBgzip\fR or \fBcompress\fR is considered binary data). .TP \fB\-blocksize\fR \fIsize\fR +. The block size used when reading the URL. At most \fIsize\fR bytes are read at once. After each block, a call to the \fB\-progress\fR callback is made (if that option is specified). .TP \fB\-channel\fR \fIname\fR +. Copy the URL contents to channel \fIname\fR instead of saving it in \fBstate(body)\fR. .TP \fB\-command\fR \fIcallback\fR +. Invoke \fIcallback\fR after the HTTP transaction completes. This option causes \fB::http::geturl\fR to return immediately. The \fIcallback\fR gets an additional argument that is the \fItoken\fR returned @@ -162,6 +174,7 @@ from \fB::http::geturl\fR. This token is the name of an array that is described in the \fBSTATE ARRAY\fR section. Here is a template for the callback: .RS +.PP .CS proc httpCallback {token} { upvar #0 $token state @@ -171,6 +184,7 @@ proc httpCallback {token} { .RE .TP \fB\-handler\fR \fIcallback\fR +. Invoke \fIcallback\fR whenever HTTP data is available; if present, nothing else will be done with the HTTP data. This procedure gets two additional arguments: the socket for the HTTP data and the \fItoken\fR returned from @@ -179,6 +193,7 @@ described in the \fBSTATE ARRAY\fR section. The procedure is expected to return the number of bytes read from the socket. Here is a template for the callback: .RS +.PP .CS proc httpHandlerCallback {socket token} { upvar #0 $token state @@ -194,6 +209,7 @@ proc httpHandlerCallback {socket token} { .RE .TP \fB\-headers\fR \fIkeyvaluelist\fR +. This option is used to add extra headers to the HTTP request. The \fIkeyvaluelist\fR argument must be a list with an even number of elements that alternate between keys and values. The keys become @@ -201,24 +217,31 @@ header field names. Newlines are stripped from the values so the header cannot be corrupted. For example, if \fIkeyvaluelist\fR is \fBPragma no-cache\fR then the following header is included in the HTTP request: +.RS +.PP .CS Pragma: no-cache .CE +.RE .TP \fB\-keepalive\fR \fIboolean\fR +. If true, attempt to keep the connection open for servicing multiple requests. Default is 0. .TP \fB\-method\fR \fItype\fR +. Force the HTTP request method to \fItype\fR. \fB::http::geturl\fR will auto-select GET, POST or HEAD based on other options, but this option enables choices like PUT and DELETE for webdav support. .TP \fB\-myaddr\fR \fIaddress\fR +. Pass an specific local address to the underlying \fBsocket\fR call in case multiple interfaces are available. .TP \fB\-progress\fR \fIcallback\fR +. The \fIcallback\fR is made after each transfer of data from the URL. The callback gets three additional arguments: the \fItoken\fR from \fB::http::geturl\fR, the expected total size of the contents from the @@ -227,6 +250,7 @@ transferred so far. The expected total size may be unknown, in which case zero is passed to the callback. Here is a template for the progress callback: .RS +.PP .CS proc httpProgress {token total current} { upvar #0 $token state @@ -235,17 +259,20 @@ proc httpProgress {token total current} { .RE .TP \fB\-protocol\fR \fIversion\fR +. Select the HTTP protocol version to use. This should be 1.0 or 1.1 (the default). Should only be necessary for servers that do not understand or otherwise complain about HTTP/1.1. .TP \fB\-query\fR \fIquery\fR +. This flag causes \fB::http::geturl\fR to do a POST request that passes the \fIquery\fR to the server. The \fIquery\fR must be an x-url-encoding formatted query. The \fB::http::formatQuery\fR procedure can be used to do the formatting. .TP \fB\-queryblocksize\fR \fIsize\fR +. The block size used when posting query data to the URL. At most \fIsize\fR @@ -254,6 +281,7 @@ bytes are written at once. After each block, a call to the callback is made (if that option is specified). .TP \fB\-querychannel\fR \fIchannelID\fR +. This flag causes \fB::http::geturl\fR to do a POST request that passes the data contained in \fIchannelID\fR to the server. The data contained in \fIchannelID\fR must be an x-url-encoding @@ -264,14 +292,17 @@ in order to create that header. If it is unable to determine the size, it returns an error. .TP \fB\-queryprogress\fR \fIcallback\fR +. The \fIcallback\fR is made after each transfer of data to the URL (i.e. POST) and acts exactly like the \fB\-progress\fR option (the callback format is the same). .TP \fB\-strict\fR \fIboolean\fR +. Whether to enforce RFC 3986 URL validation on the request. Default is 1. .TP \fB\-timeout\fR \fImilliseconds\fR +. If \fImilliseconds\fR is non-zero, then \fB::http::geturl\fR sets up a timeout to occur after the specified number of milliseconds. A timeout results in a call to \fB::http::reset\fR and to @@ -280,11 +311,13 @@ The return value of \fB::http::status\fR is \fBtimeout\fR after a timeout has occurred. .TP \fB\-type\fR \fImime-type\fR +. Use \fImime-type\fR as the \fBContent-Type\fR value, instead of the default value (\fBapplication/x-www-form-urlencoded\fR) during a POST operation. .TP \fB\-validate\fR \fIboolean\fR +. If \fIboolean\fR is non-zero, then \fB::http::geturl\fR does an HTTP HEAD request. This request returns meta information about the URL, but the contents are not returned. The meta information is available in the @@ -293,6 +326,7 @@ contents are not returned. The meta information is available in the .RE .TP \fB::http::formatQuery\fR \fIkey value\fR ?\fIkey value\fR ...? +. This procedure does x-url-encoding of query data. It takes an even number of arguments that are the keys and values of the query. It encodes the keys and values, and generates one string that has the @@ -300,10 +334,13 @@ proper & and = separators. The result is suitable for the \fB\-query\fR value passed to \fB::http::geturl\fR. .TP \fB::http::reset\fR \fItoken\fR ?\fIwhy\fR? -This command resets the HTTP transaction identified by \fItoken\fR, if -any. This sets the \fBstate(status)\fR value to \fIwhy\fR, which defaults to \fBreset\fR, and then calls the registered \fB\-command\fR callback. +. +This command resets the HTTP transaction identified by \fItoken\fR, if any. +This sets the \fBstate(status)\fR value to \fIwhy\fR, which defaults to +\fBreset\fR, and then calls the registered \fB\-command\fR callback. .TP \fB::http::wait\fR \fItoken\fR +. This is a convenience procedure that blocks and waits for the transaction to complete. This only works in trusted code because it uses \fBvwait\fR. Also, it is not useful for the case where @@ -313,36 +350,44 @@ until the HTTP transaction is complete, and thus there is nothing to wait for. .TP \fB::http::data\fR \fItoken\fR +. This is a convenience procedure that returns the \fBbody\fR element (i.e., the URL data) of the state array. .TP \fB::http::error\fR \fItoken\fR +. This is a convenience procedure that returns the \fBerror\fR element of the state array. .TP \fB::http::status\fR \fItoken\fR +. This is a convenience procedure that returns the \fBstatus\fR element of the state array. .TP \fB::http::code\fR \fItoken\fR +. This is a convenience procedure that returns the \fBhttp\fR element of the state array. .TP \fB::http::ncode\fR \fItoken\fR +. This is a convenience procedure that returns just the numeric return code (200, 404, etc.) from the \fBhttp\fR element of the state array. .TP \fB::http::size\fR \fItoken\fR +. This is a convenience procedure that returns the \fBcurrentsize\fR element of the state array, which represents the number of bytes received from the URL in the \fB::http::geturl\fR call. .TP \fB::http::meta\fR \fItoken\fR +. This is a convenience procedure that returns the \fBmeta\fR element of the state array which contains the HTTP response headers. See below for an explanation of this element. .TP \fB::http::cleanup\fR \fItoken\fR +. This procedure cleans up the state associated with the connection identified by \fItoken\fR. After this call, the procedures like \fB::http::data\fR cannot be used to get information @@ -353,10 +398,12 @@ so will result in memory not being freed, and if your app calls performance hit...or worse. .TP \fB::http::register\fR \fIproto port command\fR +. This procedure allows one to provide custom HTTP transport types such as HTTPS, by registering a prefix, the default port, and the command to execute to create the Tcl \fBchannel\fR. E.g.: .RS +.PP .CS package require http package require tls @@ -368,6 +415,7 @@ set token [::http::geturl https://my.secure.site/] .RE .TP \fB::http::unregister\fR \fIproto\fR +. This procedure unregisters a protocol handler that was previously registered via \fB::http::register\fR. .SH ERRORS @@ -408,7 +456,8 @@ There are other possible results of the HTTP transaction determined by examining the status from \fB::http::status\fR. These are described below. .TP -ok +\fBok\fR +. If the HTTP transaction completes entirely, then status will be \fBok\fR. However, you should still check the \fB::http::code\fR value to get the HTTP status. The \fB::http::ncode\fR procedure provides just @@ -416,11 +465,13 @@ the numeric error (e.g., 200, 404 or 500) while the \fB::http::code\fR procedure returns a value like .QW "HTTP 404 File not found" . .TP -eof +\fBeof\fR +. If the server closes the socket without replying, then no error is raised, but the status of the transaction will be \fBeof\fR. .TP -error +\fBerror\fR +. The error message will also be stored in the \fBerror\fR status array element, accessible via \fB::http::error\fR. .PP @@ -437,9 +488,11 @@ an \fBeof\fR status. The \fB::http::geturl\fR procedure returns a \fItoken\fR that can be used to get to the state of the HTTP transaction in the form of a Tcl array. Use this construct to create an easy-to-use array variable: +.PP .CS upvar #0 $token state .CE +.PP Once the data associated with the URL is no longer needed, the state array should be unset to free up storage. The \fB::http::cleanup\fR procedure is provided for that purpose. @@ -448,33 +501,41 @@ the array are supported: .RS .TP \fBbody\fR +. The contents of the URL. This will be empty if the \fB\-channel\fR option has been specified. This value is returned by the \fB::http::data\fR command. .TP \fBcharset\fR +. The value of the charset attribute from the \fBContent-Type\fR meta-data value. If none was specified, this defaults to the RFC standard \fBiso8859-1\fR, or the value of \fB$::http::defaultCharset\fR. Incoming text data will be automatically converted from this charset to utf-8. .TP \fBcoding\fR +. A copy of the \fBContent-Encoding\fR meta-data value. .TP \fBcurrentsize\fR +. The current number of bytes fetched from the URL. This value is returned by the \fB::http::size\fR command. .TP \fBerror\fR +. If defined, this is the error string seen when the HTTP transaction was aborted. .TP \fBhttp\fR +. The HTTP status reply from the server. This value is returned by the \fB::http::code\fR command. The format of this value is: .RS +.PP .CS \fIHTTP/1.1 code string\fR .CE +.PP The \fIcode\fR is a three-digit number defined in the HTTP standard. A code of 200 is OK. Codes beginning with 4 or 5 indicate errors. Codes beginning with 3 are redirection errors. In this case the @@ -483,86 +544,103 @@ requested information. .RE .TP \fBmeta\fR +. The HTTP protocol returns meta-data that describes the URL contents. The \fBmeta\fR element of the state array is a list of the keys and values of the meta-data. This is in a format useful for initializing an array that just contains the meta-data: .RS +.PP .CS array set meta $state(meta) .CE +.PP Some of the meta-data keys are listed below, but the HTTP standard defines more, and servers are free to add their own. .TP \fBContent-Type\fR +. The type of the URL contents. Examples include \fBtext/html\fR, \fBimage/gif,\fR \fBapplication/postscript\fR and \fBapplication/x-tcl\fR. .TP \fBContent-Length\fR +. The advertised size of the contents. The actual size obtained by -\fB::http::geturl\fR is available as \fBstate(size)\fR. +\fB::http::geturl\fR is available as \fBstate(currentsize)\fR. .TP \fBLocation\fR +. An alternate URL that contains the requested data. .RE .TP \fBposterror\fR +. The error, if any, that occurred while writing the post query data to the server. .TP \fBstatus\fR +. Either \fBok\fR, for successful completion, \fBreset\fR for user-reset, \fBtimeout\fR if a timeout occurred before the transaction could complete, or \fBerror\fR for an error condition. During the transaction this value is the empty string. .TP \fBtotalsize\fR +. A copy of the \fBContent-Length\fR meta-data value. .TP \fBtype\fR +. A copy of the \fBContent-Type\fR meta-data value. .TP \fBurl\fR +. The requested URL. .RE .SH EXAMPLE +.PP +This example creates a procedure to copy a URL to a file while printing a +progress meter, and prints the meta-data associated with the URL. +.PP .CS -# Copy a URL to a file and print meta-data proc httpcopy { url file {chunk 4096} } { - set out [open $file w] - set token [\fB::http::geturl\fR $url -channel $out \e - -progress httpCopyProgress -blocksize $chunk] - close $out + set out [open $file w] + set token [\fB::http::geturl\fR $url -channel $out \e + -progress httpCopyProgress -blocksize $chunk] + close $out - # This ends the line started by httpCopyProgress - puts stderr "" + # This ends the line started by httpCopyProgress + puts stderr "" - upvar #0 $token state - set max 0 - foreach {name value} $state(meta) { - if {[string length $name] > $max} { - set max [string length $name] - } - if {[regexp -nocase ^location$ $name]} { - # Handle URL redirects - puts stderr "Location:$value" - return [httpcopy [string trim $value] $file $chunk] - } - } - incr max - foreach {name value} $state(meta) { - puts [format "%-*s %s" $max $name: $value] - } + upvar #0 $token state + set max 0 + foreach {name value} $state(meta) { + if {[string length $name] > $max} { + set max [string length $name] + } + if {[regexp -nocase ^location$ $name]} { + # Handle URL redirects + puts stderr "Location:$value" + return [httpcopy [string trim $value] $file $chunk] + } + } + incr max + foreach {name value} $state(meta) { + puts [format "%-*s %s" $max $name: $value] + } - return $token + return $token } proc httpCopyProgress {args} { - puts -nonewline stderr . - flush stderr + puts -nonewline stderr . + flush stderr } .CE .SH "SEE ALSO" safe(n), socket(n), safesock(n) .SH KEYWORDS -security policy, socket +internet, security policy, socket, www +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -38,43 +38,51 @@ The return value from the command is the result of the body script that was executed, or an empty string if none of the expressions was non-zero and there was no \fIbodyN\fR. .SH EXAMPLES +.PP A simple conditional: +.PP .CS \fBif\fR {$vbl == 1} { puts "vbl is one" } .CE .PP With an \fBelse\fR-clause: +.PP .CS \fBif\fR {$vbl == 1} { - puts "vbl is one" + puts "vbl is one" } \fBelse\fR { - puts "vbl is not one" + puts "vbl is not one" } .CE .PP With an \fBelseif\fR-clause too: +.PP .CS \fBif\fR {$vbl == 1} { - puts "vbl is one" + puts "vbl is one" } \fBelseif\fR {$vbl == 2} { - puts "vbl is two" + puts "vbl is two" } \fBelse\fR { - puts "vbl is not one or two" + puts "vbl is not one or two" } .CE .PP Remember, expressions can be multi-line, but in that case it can be a good idea to use the optional \fBthen\fR keyword for clarity: +.PP .CS \fBif\fR { - $vbl == 1 || $vbl == 2 || $vbl == 3 + $vbl == 1 + || $vbl == 2 + || $vbl == 3 } \fBthen\fR { - puts "vbl is one, two or three" + puts "vbl is one, two or three" } .CE - .SH "SEE ALSO" expr(n), for(n), foreach(n) - .SH KEYWORDS boolean, conditional, else, false, if, true +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -14,7 +14,6 @@ incr \- Increment the value of a variable .SH SYNOPSIS \fBincr \fIvarName \fR?\fIincrement\fR? .BE - .SH DESCRIPTION .PP Increments the value stored in the variable whose name is \fIvarName\fR. @@ -25,24 +24,26 @@ integer) is added to the value of variable \fIvarName\fR; otherwise The new value is stored as a decimal string in variable \fIvarName\fR and also returned as result. .PP -.VS 8.5 Starting with the Tcl 8.5 release, the variable \fIvarName\fR passed to \fBincr\fR may be unset, and in that case, it will be set to the value \fIincrement\fR or to the default increment value of \fB1\fR. -.VE 8.5 .SH EXAMPLES +.PP Add one to the contents of the variable \fIx\fR: +.PP .CS \fBincr\fR x .CE .PP Add 42 to the contents of the variable \fIx\fR: +.PP .CS \fBincr\fR x 42 .CE .PP Add the contents of the variable \fIy\fR to the contents of the variable \fIx\fR: +.PP .CS \fBincr\fR x $y .CE @@ -50,12 +51,11 @@ variable \fIx\fR: Add nothing at all to the variable \fIx\fR (often useful for checking whether an argument to a procedure is actually integral and generating an error if it is not): +.PP .CS \fBincr\fR x 0 .CE - .SH "SEE ALSO" -expr(n) - +expr(n), set(n) .SH KEYWORDS add, increment, variable, value @@ -3,6 +3,7 @@ '\" Copyright (c) 1994-1997 Sun Microsystems, Inc. '\" Copyright (c) 1993-1997 Bell Labs Innovations for Lucent Technologies '\" Copyright (c) 1998-2000 Ajuba Solutions +'\" Copyright (c) 2007-2008 Donal K. Fellows '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. @@ -16,7 +17,6 @@ info \- Return information about the state of the Tcl interpreter .SH SYNOPSIS \fBinfo \fIoption \fR?\fIarg arg ...\fR? .BE - .SH DESCRIPTION .PP This command provides information about various internals of the Tcl @@ -24,22 +24,30 @@ interpreter. The legal \fIoption\fRs (which may be abbreviated) are: .TP \fBinfo args \fIprocname\fR +. Returns a list containing the names of the arguments to procedure \fIprocname\fR, in order. \fIProcname\fR must be the name of a Tcl command procedure. .TP \fBinfo body \fIprocname\fR +. Returns the body of procedure \fIprocname\fR. \fIProcname\fR must be the name of a Tcl command procedure. .TP +\fBinfo class\fI subcommand class\fR ?\fIarg ...\fR +.VS 8.6 +Returns information about the class, \fIclass\fR. The \fIsubcommand\fRs are +described in \fBCLASS INTROSPECTION\fR below. +.VE 8.6 +.TP \fBinfo cmdcount\fR +. Returns a count of the total number of commands that have been invoked in this interpreter. .TP \fBinfo commands \fR?\fIpattern\fR? +. If \fIpattern\fR is not specified, -.\" Do not move this .VS above the .TP -.VS 8.5 returns a list of names of all the Tcl commands visible (i.e. executable without using a qualified name) to the current namespace, including both the built-in commands written in C and @@ -58,9 +66,9 @@ of the specified namespace, and only the commands defined in the named namespace are returned. .\" Technically, most of this hasn't changed; that's mostly just the .\" way it always worked. Hardly anyone knew that though. -.VE 8.5 .TP \fBinfo complete \fIcommand\fR +. Returns 1 if \fIcommand\fR is a complete Tcl command in the sense of having no unclosed quotes, braces, brackets or array element names. If the command does not appear to be complete then 0 is returned. @@ -69,19 +77,53 @@ to allow users to type in commands that span multiple lines; if the command is not complete, the script can delay evaluating it until additional lines have been typed to complete the command. .TP +\fBinfo coroutine\fR +.VS 8.6 +Returns the name of the currently executing coroutine, or the empty string if +either no coroutine is currently executing, or the current coroutine has been +deleted (but has not yet returned or yielded since deletion). +.VE 8.6 +.TP \fBinfo default \fIprocname arg varname\fR +. \fIProcname\fR must be the name of a Tcl command procedure and \fIarg\fR must be the name of an argument to that procedure. If \fIarg\fR does not have a default value then the command returns \fB0\fR. Otherwise it returns \fB1\fR and places the default value of \fIarg\fR into variable \fIvarname\fR. .TP +\fBinfo errorstack \fR?\fIinterp\fR? +.VS 8.6 +Returns, in a form that is programmatically easy to parse, the function names +and arguments at each level from the call stack of the last error in the given +\fIinterp\fR, or in the current one if not specified. + +This form is an even-sized list alternating tokens and parameters. Tokens are +currently either \fBCALL\fR, \fBUP\fR, or \fBINNER\fR, but other values may be +introduced in the future. \fBCALL\fR indicates a procedure call, and its +parameter is the corresponding [info level 0]. \fBUP\fR indicates a shift in +variable frames generated by uplevel or similar, and applies to the previous +CALL item. Its parameter is the level offset. \fBINNER\fR identifies the +"inner context", which is the innermost atomic command or bytecode instruction +that raised the error, along with its arguments when available. While +\fBCALL\fR and \fBUP\fR allow to follow complex call paths, \fBINNER\fR homes +in on the offending operation in the innermost proc call, even going to +sub-expr granularity. + +This information is also present in the +\fB\-errorstack\fR entry of the options dictionary returned by 3-argument +\fBcatch\fR; \fBinfo errorstack\fR is a convenient way of retrieving it for +uncaught errors at toplevel in an interactive tclsh. +.VE 8.6 +.TP \fBinfo exists \fIvarName\fR +. Returns \fB1\fR if the variable named \fIvarName\fR exists in the current context (either as a global or local variable) and has been defined by being given a value, returns \fB0\fR otherwise. .TP \fBinfo frame\fR ?\fInumber\fR? +. This command provides access to all frames on the stack, even those hidden from \fBinfo level\fR. If \fInumber\fR is not specified, this command returns a number giving the frame level of the command. This @@ -91,10 +133,11 @@ information for the command at the \fInumber\fRed level on the stack. .RS .PP If \fInumber\fR is positive (> 0) then it selects a particular stack -level (1 refers to the top-most active command, i.e., \fBinfo frame\fR -itself, 2 to the command it was called from, and so on); otherwise it -gives a level relative to the current command (0 refers to the current -command, i.e., \fBinfo frame\fR itself, -1 to its caller, and so on). +level (1 refers to the outer-most active command, 2 to the command it +called, and so on, up to the current frame level which refers to +\fBinfo frame\fR itself); otherwise it gives a level relative to the +current command (0 refers to the current command, i.e., \fBinfo +frame\fR itself, -1 to its caller, and so on). .PP This is similar to how \fBinfo level\fR works, except that this subcommand reports all frames, like \fBsource\fRd scripts, @@ -112,28 +155,34 @@ The result dictionary may contain the keys listed below, with the specified meanings for their values: .TP \fBtype\fR +. This entry is always present and describes the nature of the location for the command. The recognized values are \fBsource\fR, \fBproc\fR, \fBeval\fR, and \fBprecompiled\fR. .RS .TP \fBsource\fR\0\0\0\0\0\0\0\0 +. means that the command is found in a script loaded by the \fBsource\fR command. .TP \fBproc\fR\0\0\0\0\0\0\0\0 +. means that the command is found in dynamically created procedure body. .TP \fBeval\fR\0\0\0\0\0\0\0\0 +. means that the command is executed by \fBeval\fR or \fBuplevel\fR. .TP \fBprecompiled\fR\0\0\0\0\0\0\0\0 +. means that the command is found in a precompiled script (loadable by the package \fBtbcload\fR), and no further information will be available. .RE .TP \fBline\fR +. This entry provides the number of the line the command is at inside of the script it is a part of. This information is not present for type \fBprecompiled\fR. For type \fBsource\fR this information is counted @@ -141,10 +190,12 @@ relative to the beginning of the file, whereas for the last two types the line is counted relative to the start of the script. .TP \fBfile\fR +. This entry is present only for type \fBsource\fR. It provides the normalized path of the file the command is in. .TP \fBcmd\fR +. This entry provides the string representation of the command. This is usually the unsubstituted form, however for commands which are a pure list executed by eval it is the substituted form as they have no other @@ -152,15 +203,18 @@ string representation. Care is taken that the pure-List property of the latter is not spoiled. .TP \fBproc\fR +. This entry is present only if the command is found in the body of a regular Tcl procedure. It then provides the name of that procedure. .TP \fBlambda\fR +. This entry is present only if the command is found in the body of an anonymous Tcl procedure, i.e. a lambda. It then provides the entire definition of the lambda in question. .TP \fBlevel\fR +. This entry is present only if the queried frame has a corresponding frame returned by \fBinfo level\fR. It provides the index of this frame, relative to the current level (0 and negative numbers). @@ -191,6 +245,7 @@ counted relative to the start of each word (smallest scope) .RE .TP \fBinfo functions \fR?\fIpattern\fR? +. If \fIpattern\fR is not specified, returns a list of all the math functions currently defined. If \fIpattern\fR is specified, only those functions whose name matches @@ -198,6 +253,7 @@ If \fIpattern\fR is specified, only those functions whose name matches rules as for \fBstring match\fR. .TP \fBinfo globals \fR?\fIpattern\fR? +. If \fIpattern\fR is not specified, returns a list of all the names of currently-defined global variables. Global variables are variables in the global namespace. @@ -206,6 +262,7 @@ are returned. Matching is determined using the same rules as for \fBstring match\fR. .TP \fBinfo hostname\fR +. Returns the name of the computer on which this invocation is being executed. Note that this name is not guaranteed to be the fully qualified domain @@ -215,6 +272,7 @@ installed,) it is the name that is suitable for TCP/IP networking that is returned. .TP \fBinfo level\fR ?\fInumber\fR? +. If \fInumber\fR is not specified, this command returns a number giving the stack level of the invoking procedure, or 0 if the command is invoked at top-level. If \fInumber\fR is specified, @@ -228,6 +286,7 @@ See the \fBuplevel\fR command for more information on what stack levels mean. .TP \fBinfo library\fR +. Returns the name of the library directory in which standard Tcl scripts are stored. This is actually the value of the \fBtcl_library\fR @@ -235,6 +294,7 @@ variable and may be changed by setting \fBtcl_library\fR. See the \fBtclvars\fR manual entry for more information. .TP \fBinfo loaded \fR?\fIinterp\fR? +. Returns a list describing all of the packages that have been loaded into \fIinterp\fR with the \fBload\fR command. Each list element is a sub-list with two elements consisting of the @@ -247,6 +307,7 @@ To get a list of just the packages in the current interpreter, specify an empty string for the \fIinterp\fR argument. .TP \fBinfo locals \fR?\fIpattern\fR? +. If \fIpattern\fR is not specified, returns a list of all the names of currently-defined local variables, including arguments to the current procedure, if any. @@ -257,15 +318,24 @@ are returned. Matching is determined using the same rules as for \fBstring match\fR. .TP \fBinfo nameofexecutable\fR +. Returns the full path name of the binary file from which the application was invoked. If Tcl was unable to identify the file, then an empty string is returned. .TP +\fBinfo object\fI subcommand object\fR ?\fIarg ...\fR +.VS 8.6 +Returns information about the object, \fIobject\fR. The \fIsubcommand\fRs are +described in \fBOBJECT INTROSPECTION\fR below. +.VE 8.6 +.TP \fBinfo patchlevel\fR +. Returns the value of the global variable \fBtcl_patchLevel\fR; see the \fBtclvars\fR manual entry for more information. .TP \fBinfo procs \fR?\fIpattern\fR? +. If \fIpattern\fR is not specified, returns a list of all the names of Tcl command procedures in the current namespace. If \fIpattern\fR is specified, @@ -280,6 +350,7 @@ within; the matching pattern is taken to be the part after the last namespace separator. .TP \fBinfo script\fR ?\fIfilename\fR? +. If a Tcl script file is currently being evaluated (i.e. there is a call to \fBTcl_EvalFile\fR active or there is an active invocation of the \fBsource\fR command), then this command returns the name @@ -290,16 +361,19 @@ useful in virtual file system applications. Otherwise the command returns an empty string. .TP \fBinfo sharedlibextension\fR +. Returns the extension used on this platform for the names of files containing shared libraries (for example, \fB.so\fR under Solaris). If shared libraries are not supported on this platform then an empty string is returned. .TP \fBinfo tclversion\fR +. Returns the value of the global variable \fBtcl_version\fR; see the \fBtclvars\fR manual entry for more information. .TP \fBinfo vars\fR ?\fIpattern\fR? +. If \fIpattern\fR is not specified, returns a list of all the names of currently-visible variables. This includes locals and currently-visible globals. @@ -319,7 +393,291 @@ Note that a currently-visible variable may not yet .QW exist if it has not been set (e.g. a variable declared but not set by \fBvariable\fR). -.SH EXAMPLE +.SS "CLASS INTROSPECTION" +.VS 8.6 +.PP +The following \fIsubcommand\fR values are supported by \fBinfo class\fR: +.VE 8.6 +.TP +\fBinfo class call\fI class method\fR +.VS +Returns a description of the method implementations that are used to provide a +stereotypical instance of \fIclass\fR's implementation of \fImethod\fR +(stereotypical instances being objects instantiated by a class without having +any object-specific definitions added). This consists of a list of lists of +four elements, where each sublist consists of a word that describes the +general type of method implementation (being one of \fBmethod\fR for an +ordinary method, \fBfilter\fR for an applied filter, and \fBunknown\fR for a +method that is invoked as part of unknown method handling), a word giving the +name of the particular method invoked (which is always the same as +\fImethod\fR for the \fBmethod\fR type, and +.QW \fBunknown\fR +for the \fBunknown\fR type), a word giving the fully qualified name of the +class that defined the method, and a word describing the type of method +implementation (see \fBinfo class methodtype\fR). +.RS +.PP +Note that there is no inspection of whether the method implementations +actually use \fBnext\fR to transfer control along the call chain. +.RE +.VE 8.6 +.TP +\fBinfo class constructor\fI class\fR +.VS 8.6 +This subcommand returns a description of the definition of the constructor of +class \fIclass\fR. The defintion is described as a two element list; the first +element is the list of arguments to the constructor in a form suitable for +passing to another call to \fBproc\fR or a method defintion, and the second +element is the body of the constructor. If no constructor is present, this +returns the empty list. +.VE 8.6 +.TP +\fBinfo class definition\fI class method\fR +.VS 8.6 +This subcommand returns a description of the definition of the method named +\fImethod\fR of class \fIclass\fR. The defintion is described as a two element +list; the first element is the list of arguments to the method in a form +suitable for passing to another call to \fBproc\fR or a method defintion, and +the second element is the body of the method. +.VE 8.6 +.TP +\fBinfo class destructor\fI class\fR +.VS 8.6 +This subcommand returns the body of the destructor of class \fIclass\fR. If no +destructor is present, this returns the empty string. +.VE 8.6 +.TP +\fBinfo class filters\fI class\fR +.VS 8.6 +This subcommand returns the list of filter methods set on the class. +.VE 8.6 +.TP +\fBinfo class forward\fI class method\fR +.VS 8.6 +This subcommand returns the argument list for the method forwarding called +\fImethod\fR that is set on the class called \fIclass\fR. +.VE 8.6 +.TP +\fBinfo class instances\fI class\fR ?\fIpattern\fR? +.VS 8.6 +This subcommand returns a list of instances of class \fIclass\fR. If the +optional \fIpattern\fR argument is present, it constrains the list of returned +instances to those that match it according to the rules of \fBstring match\fR. +.VE 8.6 +.TP +\fBinfo class methods\fI class\fR ?\fIoptions...\fR? +.VS 8.6 +This subcommand returns a list of all public (i.e. exported) methods of the +class called \fIclass\fR. Any of the following \fIoption\fRs may be +specified, controlling exactly which method names are returned: +.RS +.VE 8.6 +.TP +\fB\-all\fR +.VS 8.6 +If the \fB\-all\fR flag is given, the list of methods will include those +methods defined not just by the class, but also by the class's superclasses +and mixins. +.VE 8.6 +.TP +\fB\-private\fR +.VS 8.6 +If the \fB\-private\fR flag is given, the list of methods will also include +the private (i.e. non-exported) methods of the class (and superclasses and +mixins, if \fB\-all\fR is also given). +.RE +.VE 8.6 +.TP +\fBinfo class methodtype\fI class method\fR +.VS 8.6 +This subcommand returns a description of the type of implementation used for +the method named \fImethod\fR of class \fIclass\fR. When the result is +\fBmethod\fR, further information can be discovered with \fBinfo class +definition\fR, and when the result is \fBforward\fR, further information can +be discovered with \fBinfo class forward\fR. +.VE 8.6 +.TP +\fBinfo class mixins\fI class\fR +.VS 8.6 +This subcommand returns a list of all classes that have been mixed into the +class named \fIclass\fR. +.VE 8.6 +.TP +\fBinfo class subclasses\fI class\fR ?\fIpattern\fR? +.VS 8.6 +This subcommand returns a list of direct subclasses of class \fIclass\fR. If +the optional \fIpattern\fR argument is present, it constrains the list of +returned classes to those that match it according to the rules of +\fBstring match\fR. +.VE 8.6 +.TP +\fBinfo class superclasses\fI class\fR +.VS 8.6 +This subcommand returns a list of direct superclasses of class \fIclass\fR in +inheritance precedence order. +.VE 8.6 +.TP +\fBinfo class variables\fI class\fR +.VS 8.6 +This subcommand returns a list of all variables that have been declared for +the class named \fIclass\fR (i.e. that are automatically present in the +class's methods, constructor and destructor). +.SS "OBJECT INTROSPECTION" +.PP +The following \fIsubcommand\fR values are supported by \fBinfo object\fR: +.VE 8.6 +.TP +\fBinfo object call\fI object method\fR +.VS 8.6 +Returns a description of the method implementations that are used to provide +\fIobject\fR's implementation of \fImethod\fR. This consists of a list of +lists of four elements, where each sublist consists of a word that describes +the general type of method implementation (being one of \fBmethod\fR for an +ordinary method, \fBfilter\fR for an applied filter, and \fBunknown\fR for a +method that is invoked as part of unknown method handling), a word giving the +name of the particular method invoked (which is always the same as +\fImethod\fR for the \fBmethod\fR type, and +.QW \fBunknown\fR +for the \fBunknown\fR type), a word giving what defined the method (the fully +qualified name of the class, or the literal string \fBobject\fR if the method +implementation is on an instance), and a word describing the type of method +implementation (see \fBinfo object methodtype\fR). +.RS +.PP +Note that there is no inspection of whether the method implementations +actually use \fBnext\fR to transfer control along the call chain. +.RE +.VE 8.6 +.TP +\fBinfo object class\fI object\fR ?\fIclassName\fR? +.VS 8.6 +If \fIclassName\fR is unspecified, this subcommand returns class of the +\fIobject\fR object. If \fIclassName\fR is present, this subcommand returns a +boolean value indicating whether the \fIobject\fR is of that class. +.VE 8.6 +.TP +\fBinfo object definition\fI object method\fR +.VS 8.6 +This subcommand returns a description of the definition of the method named +\fImethod\fR of object \fIobject\fR. The defintion is described as a two +element list; the first element is the list of arguments to the method in a +form suitable for passing to another call to \fBproc\fR or a method defintion, +and the second element is the body of the method. +.VE 8.6 +.TP +\fBinfo object filters\fI object\fR +.VS 8.6 +This subcommand returns the list of filter methods set on the object. +.VE 8.6 +.TP +\fBinfo object forward\fI object method\fR +.VS 8.6 +This subcommand returns the argument list for the method forwarding called +\fImethod\fR that is set on the object called \fIobject\fR. +.VE 8.6 +.TP +\fBinfo object isa\fI category object\fR ?\fIarg\fR? +.VS 8.6 +This subcommand tests whether an object belongs to a particular category, +returning a boolean value that indicates whether the \fIobject\fR argument +meets the criteria for the category. The supported categories are: +.VE 8.6 +.RS +.TP +\fBinfo object isa class\fI object\fR +.VS 8.6 +This returns whether \fIobject\fR is a class (i.e. an instance of +\fBoo::class\fR or one of its subclasses). +.VE 8.6 +.TP +\fBinfo object isa metaclass\fI object\fR +.VS 8.6 +This returns whether \fIobject\fR is a class that can manufacture classes +(i.e. is \fBoo::class\fR or a subclass of it). +.VE 8.6 +.TP +\fBinfo object isa mixin\fI object class\fR +.VS 8.6 +This returns whether \fIclass\fR is directly mixed into \fIobject\fR. +.VE 8.6 +.TP +\fBinfo object isa object\fI object\fR +.VS 8.6 +This returns whether \fIobject\fR really is an object. +.VE 8.6 +.TP +\fBinfo object isa typeof\fI object class\fR +.VS 8.6 +This returns whether \fIclass\fR is the type of \fIobject\fR (i.e. whether +\fIobject\fR is an instance of \fIclass\fR or one of its subclasses, whether +direct or indirect). +.RE +.VE 8.6 +.TP +\fBinfo object methods\fI object\fR ?\fIoption...\fR? +.VS 8.6 +This subcommand returns a list of all public (i.e. exported) methods of the +object called \fIobject\fR. Any of the following \fIoption\fRs may be +specified, controlling exactly which method names are returned: +.RS +.VE 8.6 +.TP +\fB\-all\fR +.VS 8.6 +If the \fB\-all\fR flag is given, the list of methods will include those +methods defined not just by the object, but also by the object's class and +mixins, plus the superclasses of those classes. +.VE 8.6 +.TP +\fB\-private\fR +.VS 8.6 +If the \fB\-private\fR flag is given, the list of methods will also include +the private (i.e. non-exported) methods of the object (and classes, if +\fB\-all\fR is also given). +.RE +.VE 8.6 +.TP +\fBinfo object methodtype\fI object method\fR +.VS 8.6 +This subcommand returns a description of the type of implementation used for +the method named \fImethod\fR of object \fIobject\fR. When the result is +\fBmethod\fR, further information can be discovered with \fBinfo object +definition\fR, and when the result is \fBforward\fR, further information can +be discovered with \fBinfo object forward\fR. +.VE 8.6 +.TP +\fBinfo object mixins\fI object\fR +.VS 8.6 +This subcommand returns a list of all classes that have been mixed into the +object named \fIobject\fR. +.VE 8.6 +.TP +\fBinfo object namespace\fI object\fR +.VS 8.6 +This subcommand returns the name of the internal namespace of the object named +\fIobject\fR. +.VE 8.6 +.TP +\fBinfo object variables\fI object\fR +.VS 8.6 +This subcommand returns a list of all variables that have been declared for +the object named \fIobject\fR (i.e. that are automatically present in the +object's methods). +.VE 8.6 +.TP +\fBinfo object vars\fI object\fR ?\fIpattern\fR? +.VS 8.6 +This subcommand returns a list of all variables in the private namespace of +the object named \fIobject\fR. If the optional \fIpattern\fR argument is +given, it is a filter (in the syntax of a \fBstring match\fR glob pattern) +that constrains the list of variables returned. Note that this is different +from the lit returned by \fBinfo object variables\fR; that can include +variables that are currently unset, whereas this can include variables that +are not automatically included by any of \fIobject\fR's methods (or those of +its class, superclasses or mixins). +.VE 8.6 +.SH EXAMPLES +.PP This command prints out a procedure suitable for saving in a Tcl script: .PP @@ -339,10 +697,75 @@ proc printProc {procName} { puts [lappend result $formals [\fBinfo body\fR $procName]] } .CE +.SS "EXAMPLES WITH OBJECTS" +.VS 8.6 +.PP +Every object necessarily knows what its class is; this information is +trivially extractable through introspection: +.PP +.CS +oo::class create c +c create o +puts [\fBinfo object class\fR o] + \fI\(-> prints "::c"\fR +puts [\fBinfo object class\fR c] + \fI\(-> prints "::oo::class"\fR +.CE +.PP +The introspection capabilities can be used to discover what class implements a +method and get how it is defined. This procedure illustrates how: +.PP +.CS +proc getDef {obj method} { + foreach inf [\fBinfo object call\fR $obj $method] { + lassign $inf calltype name locus methodtype + # Assume no forwards or filters, and hence no $calltype + # or $methodtype checks... + if {$locus eq "object"} { + return [\fBinfo object definition\fR $obj $name] + } else { + return [\fBinfo class definition\fR $locus $name] + } + } + error "no definition for $method" +} +.CE +.PP +This is an alternate way of implementing the definition lookup is by manually +scanning the list of methods up the inheritance tree. This code assumes that +only single inheritance is in use, and that there is no complex use of +mixed-in classes: +.PP +.CS +proc getDef {obj method} { + if {$method in [\fBinfo object methods\fR $obj]} { + # Assume no forwards + return [\fBinfo object definition\fR $obj $method] + } + set cls [\fBinfo object class\fR $obj] + while {$method ni [\fBinfo class methods\fR $cls]} { + # Assume the simple case + set cls [lindex [\fBinfo class superclass\fR $cls] 0] + if {$cls eq {}} { + error "no definition for $method" + } + } + # Assume no forwards + return [\fBinfo class definition\fR $cls $method] +} +.CE +.VE 8.6 .SH "SEE ALSO" -global(n), proc(n) +.VS 8.6 +global(n), oo::class(n), oo::define(n), oo::object(n), proc(n), self(n) +.VE 8.6 .SH KEYWORDS -command, information, interpreter, level, namespace, procedure, variable -.\" Local Variables: -.\" mode: nroff -.\" End: +command, information, interpreter, introspection, level, namespace, +.VS 8.6 +object, +.VE 8.6 +procedure, variable +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: diff --git a/doc/interp.n b/doc/interp.n index c753ee9..6ce10ee 100644 --- a/doc/interp.n +++ b/doc/interp.n @@ -1,12 +1,13 @@ '\" '\" Copyright (c) 1995-1996 Sun Microsystems, Inc. '\" Copyright (c) 2004 Donal K. Fellows +'\" Copyright (c) 2006-2008 Joe Mistachkin. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" .so man.macros -.TH interp n 7.6 Tcl "Tcl Built-In Commands" +.TH interp n 8.6 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME @@ -33,10 +34,7 @@ command to be invoked in its master interpreter or in another slave interpreter. The only other connections between interpreters are through environment variables (the \fBenv\fR variable), which are normally shared among all interpreters in the application, -.VS 8.5 -and by resource limit exceeded callbacks. -.VE 8.5 -Note that the +and by resource limit exceeded callbacks. Note that the name space for files (such as the names returned by the \fBopen\fR command) is no longer shared between interpreters. Explicit commands are provided to share files and to transfer references to open files from one interpreter @@ -63,10 +61,18 @@ on how the alias mechanism works. A qualified interpreter name is a proper Tcl lists containing a subset of its ancestors in the interpreter hierarchy, terminated by the string naming the interpreter in its immediate master. Interpreter names are relative to the -interpreter in which they are used. For example, if \fBa\fR is a slave of -the current interpreter and it has a slave \fBa1\fR, which in turn has a -slave \fBa11\fR, the qualified name of \fBa11\fR in \fBa\fR is the list -\fBa1 a11\fR. +interpreter in which they are used. For example, if +.QW \fBa\fR +is a slave of the current interpreter and it has a slave +.QW \fBa1\fR , +which in turn has a slave +.QW \fBa11\fR , +the qualified name of +.QW \fBa11\fR +in +.QW \fBa\fR +is the list +.QW "\fBa1 a11\fR" . .PP The \fBinterp\fR command, described below, accepts qualified interpreter names as arguments; the interpreter in which the command is being evaluated @@ -83,6 +89,7 @@ channels between interpreters. It can have any of several forms, depending on the \fIsubcommand\fR argument: .TP \fBinterp\fR \fBalias\fR \fIsrcPath\fR \fIsrcToken\fR +. Returns a Tcl list whose elements are the \fItargetCmd\fR and \fIarg\fRs associated with the alias represented by \fIsrcToken\fR (this is the value returned when the alias was @@ -90,6 +97,7 @@ created; it is possible that the name of the source command in the slave is different from \fIsrcToken\fR). .TP \fBinterp\fR \fBalias\fR \fIsrcPath\fR \fIsrcToken\fR \fB{}\fR +. Deletes the alias for \fIsrcToken\fR in the slave interpreter identified by \fIsrcPath\fR. \fIsrcToken\fR refers to the value returned when the alias @@ -97,6 +105,7 @@ was created; if the source command has been renamed, the renamed command will be deleted. .TP \fBinterp\fR \fBalias\fR \fIsrcPath\fR \fIsrcCmd\fR \fItargetPath\fR \fItargetCmd \fR?\fIarg arg ...\fR? +. This command creates an alias between one slave and another (see the \fBalias\fR slave command below for creating aliases between a slave and its master). In this command, either of the slave interpreters @@ -107,10 +116,12 @@ invoking the command. interpreter. For example, .QW "\fBa b\fR" identifies an interpreter -\fBb\fR, which is a slave of interpreter \fBa\fR, which is a slave -of the invoking interpreter. An empty list specifies the interpreter -invoking the command. \fIsrcCmd\fR gives the name of a new -command, which will be created in the source interpreter. +.QW \fBb\fR , +which is a slave of interpreter +.QW \fBa\fR , +which is a slave of the invoking interpreter. An empty list specifies +the interpreter invoking the command. \fIsrcCmd\fR gives the name of +a new command, which will be created in the source interpreter. \fITargetPath\fR and \fItargetCmd\fR specify a target interpreter and command, and the \fIarg\fR arguments, if any, specify additional arguments to \fItargetCmd\fR which are prepended to any arguments specified @@ -126,6 +137,7 @@ The command returns a token that uniquely identifies the command created does not have to be equal to \fIsrcCmd\fR. .TP \fBinterp\fR \fBaliases \fR?\fIpath\fR? +. This command returns a Tcl list of the tokens of all the source commands for aliases defined in the interpreter identified by \fIpath\fR. The tokens correspond to the values returned when @@ -133,16 +145,32 @@ the aliases were created (which may not be the same as the current names of the commands). .TP \fBinterp bgerror \fIpath\fR ?\fIcmdPrefix\fR? -.VS 8.5 -This command either gets or sets the current background error handler +. +This command either gets or sets the current background exception handler for the interpreter identified by \fIpath\fR. If \fIcmdPrefix\fR is -absent, the current background error handler is returned, and if it is +absent, the current background exception handler is returned, and if it is present, it is a list of words (of minimum length one) that describes -what to set the interpreter's background error to. See the -\fBBACKGROUND ERROR HANDLING\fR section for more details. -.VE 8.5 +what to set the interpreter's background exception handler to. See the +\fBBACKGROUND EXCEPTION HANDLING\fR section for more details. +.TP +\fBinterp\fR \fBcancel \fR?\fB\-unwind\fR? ?\fB\-\|\-\fR? ?\fIpath\fR? ?\fIresult\fR? +.VS 8.6 +Cancels the script being evaluated in the interpreter identified by +\fIpath\fR. Without the \fB\-unwind\fR switch the evaluation stack for +the interpreter is unwound until an enclosing catch command is found or +there are no further invocations of the interpreter left on the call +stack. With the \fB\-unwind\fR switch the evaluation stack for the +interpreter is unwound without regard to any intervening catch command +until there are no further invocations of the interpreter left on the +call stack. The \fB\-\|\-\fR switch can be used to mark the end of +switches; it may be needed if \fIpath\fR is an unusual value such +as \fB\-safe\fR. If \fIresult\fR is present, it will be used as the +error message string; otherwise, a default error message string will be +used. +.VE 8.6 .TP \fBinterp\fR \fBcreate \fR?\fB\-safe\fR? ?\fB\-\|\-\fR? ?\fIpath\fR? +. Creates a slave interpreter identified by \fIpath\fR and a new command, called a \fIslave command\fR. The name of the slave command is the last component of \fIpath\fR. The new slave interpreter and the slave command @@ -166,18 +194,18 @@ given name already exists in this master. The initial recursion limit of the slave interpreter is set to the current recursion limit of its parent interpreter. .TP -\fBinterp\fR \fBdebug \fIpath\fR ?\fI\-frame\fR ?\fIbool\fR?? +\fBinterp\fR \fBdebug \fIpath\fR ?\fB\-frame\fR ?\fIbool\fR?? . Controls whether frame-level stack information is captured in the slave interpreter identified by \fIpath\fR. If no arguments are -given, option and current setting are returned. If \fI\-frame\fR +given, option and current setting are returned. If \fB\-frame\fR is given, the debug setting is set to the given boolean if provided and the current setting is returned. This only effects the output of \fBinfo frame\fR, in that exact frame-level information for command invocation at the bytecode level is only captured with this setting on. -.PP .RS +.PP For example, with code like .PP .CS @@ -202,9 +230,14 @@ extends so far that the system will be able to determine the file and absolute line number of this command, and return a frame of type \fBsource\fR. This more exact information is paid for with slower execution of all commands. +.PP +Note that once it is on, this flag cannot be switched back off: such +attempts are silently ignored. This is needed to maintain the +consistency of the underlying interpreter's state. .RE .TP \fBinterp\fR \fBdelete \fR?\fIpath ...?\fR +. Deletes zero or more interpreters given by the optional \fIpath\fR arguments, and for each interpreter, it also deletes its slaves. The command also deletes the slave command for each interpreter deleted. @@ -212,6 +245,7 @@ For each \fIpath\fR argument, if no interpreter by that name exists, the command raises an error. .TP \fBinterp\fR \fBeval\fR \fIpath arg \fR?\fIarg ...\fR? +. This command concatenates all of the \fIarg\fR arguments in the same fashion as the \fBconcat\fR command, then evaluates the resulting string as a Tcl script in the slave interpreter identified by \fIpath\fR. The result @@ -225,11 +259,13 @@ the slave that find out information about the slave's current state and stack frame. .TP \fBinterp exists \fIpath\fR +. Returns \fB1\fR if a slave interpreter by the specified \fIpath\fR exists in this master, \fB0\fR otherwise. If \fIpath\fR is omitted, the invoking interpreter is used. .TP \fBinterp expose \fIpath\fR \fIhiddenName\fR ?\fIexposedCmdName\fR? +. Makes the hidden command \fIhiddenName\fR exposed, eventually bringing it back under a new \fIexposedCmdName\fR name (this name is currently accepted only if it is a valid global name space name without any ::), @@ -240,6 +276,7 @@ fails. Hidden commands are explained in more detail in \fBHIDDEN COMMANDS\fR, below. .TP \fBinterp\fR \fBhide\fR \fIpath\fR \fIexposedCmdName\fR ?\fIhiddenCmdName\fR? +. Makes the exposed command \fIexposedCmdName\fR hidden, renaming it to the hidden command \fIhiddenCmdName\fR, or keeping the same name if \fIhiddenCmdName\fR is not given, in the interpreter denoted @@ -255,10 +292,12 @@ command, by making the current namespace be different from the global one. Hidden commands are explained in more detail in \fBHIDDEN COMMANDS\fR, below. .TP \fBinterp\fR \fBhidden\fR \fIpath\fR +. Returns a list of the names of all hidden commands in the interpreter identified by \fIpath\fR. .TP \fBinterp\fR \fBinvokehidden\fR \fIpath\fR ?\fI\-option ...\fR? \fIhiddenCmdName\fR ?\fIarg ...\fR? +. Invokes the hidden command \fIhiddenCmdName\fR with the arguments supplied in the interpreter denoted by \fIpath\fR. No substitutions or evaluation are applied to the arguments. Three \fI\-option\fRs are supported, all @@ -279,8 +318,13 @@ Note that the hidden command will be executed (by default) in the current context stack frame of the \fIpath\fR interpreter. Hidden commands are explained in more detail in \fBHIDDEN COMMANDS\fR, below. .TP +\fBinterp issafe\fR ?\fIpath\fR? +. +Returns \fB1\fR if the interpreter identified by the specified \fIpath\fR +is safe, \fB0\fR otherwise. +.TP \fBinterp\fR \fBlimit\fR \fIpath\fR \fIlimitType\fR ?\fI\-option\fR? ?\fIvalue\fR \fI...\fR? -.VS 8.5 +. Sets up, manipulates and queries the configuration of the resource limit \fIlimitType\fR for the interpreter denoted by \fIpath\fR. If no \fI\-option\fR is specified, return the current configuration of the @@ -288,13 +332,9 @@ limit. If \fI\-option\fR is the sole argument, return the value of that option. Otherwise, a list of \fI\-option\fR/\fIvalue\fR argument pairs must supplied. See \fBRESOURCE LIMITS\fR below for a more detailed explanation of what limits and options are supported. -.VE 8.5 -.TP -\fBinterp issafe\fR ?\fIpath\fR? -Returns \fB1\fR if the interpreter identified by the specified \fIpath\fR -is safe, \fB0\fR otherwise. .TP \fBinterp marktrusted\fR \fIpath\fR +. Marks the interpreter identified by \fIpath\fR as trusted. Does not expose the hidden commands. This command can only be invoked from a trusted interpreter. @@ -302,10 +342,11 @@ The command has no effect if the interpreter identified by \fIpath\fR is already trusted. .TP \fBinterp\fR \fBrecursionlimit\fR \fIpath\fR ?\fInewlimit\fR? +. Returns the maximum allowable nesting depth for the interpreter specified by \fIpath\fR. If \fInewlimit\fR is specified, the interpreter recursion limit will be set so that nesting -of more than \fInewlimit\fR calls to \fBTcl_Eval()\fR +of more than \fInewlimit\fR calls to \fBTcl_Eval\fR and related procedures in that interpreter will return an error. The \fInewlimit\fR value is also returned. The \fInewlimit\fR value must be a positive integer between 1 and the @@ -321,6 +362,7 @@ the maximum size of the C stack. .RE .TP \fBinterp\fR \fBshare\fR \fIsrcPath channelId destPath\fR +. Causes the IO channel identified by \fIchannelId\fR to become shared between the interpreter identified by \fIsrcPath\fR and the interpreter identified by \fIdestPath\fR. Both interpreters have the same permissions @@ -330,11 +372,13 @@ channels accessible in an interpreter are automatically closed when an interpreter is destroyed. .TP \fBinterp\fR \fBslaves\fR ?\fIpath\fR? +. Returns a Tcl list of the names of all the slave interpreters associated with the interpreter identified by \fIpath\fR. If \fIpath\fR is omitted, the invoking interpreter is used. .TP \fBinterp\fR \fBtarget\fR \fIpath alias\fR +. Returns a Tcl list describing the target interpreter for an alias. The alias is specified with an interpreter path and source command name, just as in \fBinterp alias\fR above. The name of the target interpreter is @@ -345,6 +389,7 @@ invoking interpreter or one of its descendants then an error is generated. The target command does not have to be defined at the time of this invocation. .TP \fBinterp\fR \fBtransfer\fR \fIsrcPath channelId destPath\fR +. Causes the IO channel identified by \fIchannelId\fR to become available in the interpreter identified by \fIdestPath\fR and unavailable in the interpreter identified by \fIsrcPath\fR. @@ -355,20 +400,24 @@ new Tcl command is created in the master interpreter with the same name as the new interpreter. This command may be used to invoke various operations on the interpreter. It has the following general form: +.PP .CS \fIslave command \fR?\fIarg arg ...\fR? .CE +.PP \fISlave\fR is the name of the interpreter, and \fIcommand\fR and the \fIarg\fRs determine the exact behavior of the command. The valid forms of this command are: .TP \fIslave \fBaliases\fR +. Returns a Tcl list whose elements are the tokens of all the aliases in \fIslave\fR. The tokens correspond to the values returned when the aliases were created (which may not be the same as the current names of the commands). .TP \fIslave \fBalias \fIsrcToken\fR +. Returns a Tcl list whose elements are the \fItargetCmd\fR and \fIarg\fRs associated with the alias represented by \fIsrcToken\fR (this is the value returned when the alias was @@ -376,12 +425,14 @@ created; it is possible that the actual source command in the slave is different from \fIsrcToken\fR). .TP \fIslave \fBalias \fIsrcToken \fB{}\fR +. Deletes the alias for \fIsrcToken\fR in the slave interpreter. \fIsrcToken\fR refers to the value returned when the alias was created; if the source command has been renamed, the renamed command will be deleted. .TP \fIslave \fBalias \fIsrcCmd targetCmd \fR?\fIarg ..\fR? +. Creates an alias such that whenever \fIsrcCmd\fR is invoked in \fIslave\fR, \fItargetCmd\fR is invoked in the master. The \fIarg\fR arguments will be passed to \fItargetCmd\fR as additional @@ -393,16 +444,16 @@ The command returns a token that uniquely identifies the command created does not have to be equal to \fIsrcCmd\fR. .TP \fIslave \fBbgerror\fR ?\fIcmdPrefix\fR? -.VS 8.5 -This command either gets or sets the current background error handler +. +This command either gets or sets the current background exception handler for the \fIslave\fR interpreter. If \fIcmdPrefix\fR is -absent, the current background error handler is returned, and if it is +absent, the current background exception handler is returned, and if it is present, it is a list of words (of minimum length one) that describes -what to set the interpreter's background error to. See the -\fBBACKGROUND ERROR HANDLING\fR section for more details. -.VE 8.5 +what to set the interpreter's background exception handler to. See the +\fBBACKGROUND EXCEPTION HANDLING\fR section for more details. .TP \fIslave \fBeval \fIarg \fR?\fIarg ..\fR? +. This command concatenates all of the \fIarg\fR arguments in the same fashion as the \fBconcat\fR command, then evaluates the resulting string as a Tcl script in \fIslave\fR. @@ -416,6 +467,7 @@ the slave that find out information about the slave's current state and stack frame. .TP \fIslave \fBexpose \fIhiddenName \fR?\fIexposedCmdName\fR? +. This command exposes the hidden command \fIhiddenName\fR, eventually bringing it back under a new \fIexposedCmdName\fR name (this name is currently accepted only if it is a valid global name space name without any ::), @@ -425,6 +477,7 @@ fails. For more details on hidden commands, see \fBHIDDEN COMMANDS\fR, below. .TP \fIslave \fBhide \fIexposedCmdName\fR ?\fIhiddenCmdName\fR? +. This command hides the exposed command \fIexposedCmdName\fR, renaming it to the hidden command \fIhiddenCmdName\fR, or keeping the same name if the argument is not given, in the \fIslave\fR interpreter. @@ -439,9 +492,11 @@ command, by making the current namespace be different from the global one. For more details on hidden commands, see \fBHIDDEN COMMANDS\fR, below. .TP \fIslave \fBhidden\fR +. Returns a list of the names of all hidden commands in \fIslave\fR. .TP \fIslave \fBinvokehidden\fR ?\fI\-option ...\fR? \fIhiddenName \fR?\fIarg ..\fR? +. This command invokes the hidden command \fIhiddenName\fR with the supplied arguments, in \fIslave\fR. No substitutions or evaluations are applied to the arguments. Three \fI\-option\fRs are supported, all @@ -463,10 +518,11 @@ For more details on hidden commands, see \fBHIDDEN COMMANDS\fR, below. .TP \fIslave \fBissafe\fR +. Returns \fB1\fR if the slave interpreter is safe, \fB0\fR otherwise. .TP \fIslave \fBlimit\fR \fIlimitType\fR ?\fI\-option\fR? ?\fIvalue\fR \fI...\fR? -.VS 8.5 +. Sets up, manipulates and queries the configuration of the resource limit \fIlimitType\fR for the slave interpreter. If no \fI\-option\fR is specified, return the current configuration of the limit. If @@ -474,15 +530,16 @@ is specified, return the current configuration of the limit. If Otherwise, a list of \fI\-option\fR/\fIvalue\fR argument pairs must supplied. See \fBRESOURCE LIMITS\fR below for a more detailed explanation of what limits and options are supported. -.VE 8.5 .TP \fIslave \fBmarktrusted\fR +. Marks the slave interpreter as trusted. Can only be invoked by a trusted interpreter. This command does not expose any hidden commands in the slave interpreter. The command has no effect if the slave is already trusted. .TP \fIslave\fR \fBrecursionlimit\fR ?\fInewlimit\fR? +. Returns the maximum allowable nesting depth for the \fIslave\fR interpreter. If \fInewlimit\fR is specified, the recursion limit in \fIslave\fR will be set so that nesting of more than \fInewlimit\fR calls to \fBTcl_Eval()\fR @@ -710,7 +767,6 @@ namespace even if the current namespace is not the global one. This prevents slaves from fooling a master interpreter into hiding the wrong command, by making the current namespace be different from the global one. .SH "RESOURCE LIMITS" -.VS 8.5 .PP Every interpreter has two kinds of resource limits that may be imposed by any master interpreter upon its slaves. Command limits (of type \fBcommand\fR) @@ -735,50 +791,46 @@ catch and handle. Every limit has a number of options associated with it, some of which are common across all kinds of limits, and others of which are particular to the kind of limit. -.VE 8.5 .TP \fB\-command\fR -.VS 8.5 +. This option (common for all limit types) specifies (if non-empty) a Tcl script to be executed in the global namespace of the interpreter reading and writing the option when the particular limit in the limited interpreter is exceeded. The callback may modify the limit on the interpreter if it wishes the limited -interpreter to continue executing. If the callback generates an error, it is -reported through the background error mechanism (see \fBBACKGROUND ERROR -HANDLING\fR). Note that the callbacks defined by one interpreter are +interpreter to continue executing. If the callback generates an exception, it +is reported through the background exception mechanism (see +\fBBACKGROUND EXCEPTION HANDLING\fR). +Note that the callbacks defined by one interpreter are completely isolated from the callbacks defined by another, and that the order in which those callbacks are called is undefined. -.VE 8.5 .TP \fB\-granularity\fR -.VS 8.5 +. This option (common for all limit types) specifies how frequently (out of the points when the Tcl interpreter is in a consistent state where limit checking is possible) that the limit is actually checked. This allows the tuning of how frequently a limit is checked, and hence how often the limit-checking overhead (which may be substantial in the case of time limits) is incurred. -.VE 8.5 .TP \fB\-milliseconds\fR -.VS 8.5 +. This option specifies the number of milliseconds after the moment defined in the \fB\-seconds\fR option that the time limit will fire. It should only ever be specified in conjunction with the \fB\-seconds\fR option (whether it was set previously or is being set this invocation.) -.VE 8.5 .TP \fB\-seconds\fR -.VS 8.5 +. This option specifies the number of seconds after the epoch (see \fBclock seconds\fR) that the time limit for the interpreter will be triggered. The limit will be triggered at the start of the second unless specified at a sub-second level using the \fB\-milliseconds\fR option. This option may be the empty string, which indicates that a time limit is not set for the interpreter. -.VE 8.5 .TP \fB\-value\fR -.VS 8.5 +. This option specifies the number of commands that the interpreter may execute before triggering the command limit. This option may be the empty string, which indicates that a command limit is not set for the interpreter. @@ -791,29 +843,32 @@ these conditions, it should hide the \fBinterp\fR command in the child and then use aliases and the \fBinterp invokehidden\fR subcommand to provide such access as it chooses to the \fBinterp\fR command to the limited master as necessary. -.SH "BACKGROUND ERROR HANDLING" +.SH "BACKGROUND EXCEPTION HANDLING" .PP -When an error happens in a situation where it cannot be reported directly up +When an exception happens in a situation where it cannot be reported directly up the stack (e.g. when processing events in an \fBupdate\fR or \fBvwait\fR call) -the error is instead reported through the background error handling mechanism. -Every interpreter has a background error handler registered; the default error +the exception is instead reported through the background exception handling mechanism. +Every interpreter has a background exception handler registered; the default exception handler arranges for the \fBbgerror\fR command in the interpreter's global -namespace to be called, but other error handlers may be installed and process -background errors in substantially different ways. +namespace to be called, but other exception handlers may be installed and process +background exceptions in substantially different ways. .PP -A background error handler consists of a non-empty list of words to which will +A background exception handler consists of a non-empty list of words to which will be appended two further words at invocation time. The first word will be the -error message string, and the second will a dictionary of return options (this -is also the sort of information that can be obtained by trapping a normal -error using \fBcatch\fR of course.) The resulting list will then be executed +interpreter result at time of the exception, typically an error message, +and the second will be the dictionary of return options at the time of +the exception. These are the same values that \fBcatch\fR can capture +when it controls script evaluation in a non-background situation. +The resulting list will then be executed in the interpreter's global namespace without further substitutions being performed. -.VE 8.5 .SH CREDITS The safe interpreter mechanism is based on the Safe-Tcl prototype implemented by Nathaniel Borenstein and Marshall Rose. .SH EXAMPLES +.PP Creating and using an alias for a command in the current interpreter: +.PP .CS \fBinterp alias\fR {} getIndex {} lsearch {alpha beta gamma delta} set idx [getIndex delta] @@ -821,32 +876,35 @@ set idx [getIndex delta] .PP Executing an arbitrary command in a safe interpreter where every invocation of \fBlappend\fR is logged: +.PP .CS set i [\fBinterp create\fR -safe] \fBinterp hide\fR $i lappend \fBinterp alias\fR $i lappend {} loggedLappend $i proc loggedLappend {i args} { - puts "logged invocation of lappend $args" - \fBinterp invokehidden\fR $i lappend {*}$args + puts "logged invocation of lappend $args" + \fBinterp invokehidden\fR $i lappend {*}$args } \fBinterp eval\fR $i $someUntrustedScript .CE .PP -.VS 8.5 Setting a resource limit on an interpreter so that an infinite loop terminates. +.PP .CS set i [\fBinterp create\fR] \fBinterp limit\fR $i command -value 1000 \fBinterp eval\fR $i { - set x 0 - while {1} { - puts "Counting up... [incr x]" - } + set x 0 + while {1} { + puts "Counting up... [incr x]" + } } .CE -.VE 8.5 .SH "SEE ALSO" -bgerror(n), load(n), safe(n), Tcl_CreateSlave(3) +bgerror(n), load(n), safe(n), Tcl_CreateSlave(3), Tcl_Eval(3), Tcl_BackgroundException(3) .SH KEYWORDS alias, master interpreter, safe interpreter, slave interpreter +'\"Local Variables: +'\"mode: nroff +'\"End: @@ -14,7 +14,6 @@ join \- Create a string by joining together list elements .SH SYNOPSIS \fBjoin \fIlist \fR?\fIjoinString\fR? .BE - .SH DESCRIPTION .PP The \fIlist\fR argument must be a valid Tcl list. @@ -23,7 +22,9 @@ formed by joining all of the elements of \fIlist\fR together with \fIjoinString\fR separating each adjacent pair of elements. The \fIjoinString\fR argument defaults to a space character. .SH EXAMPLES +.PP Making a comma-separated list: +.PP .CS set data {1 2 3 4 5} \fBjoin\fR $data ", " @@ -31,14 +32,13 @@ set data {1 2 3 4 5} .CE .PP Using \fBjoin\fR to flatten a list by a single level: +.PP .CS set data {1 {2 3} 4 {5 {6 7} 8}} \fBjoin\fR $data \fB\(-> 1 2 3 4 5 {6 7} 8\fR .CE - .SH "SEE ALSO" list(n), lappend(n), split(n) - .SH KEYWORDS element, join, list, separator diff --git a/doc/lappend.n b/doc/lappend.n index dbed3bb..9bfab72 100644 --- a/doc/lappend.n +++ b/doc/lappend.n @@ -15,7 +15,6 @@ lappend \- Append list elements onto a variable .SH SYNOPSIS \fBlappend \fIvarName \fR?\fIvalue value value ...\fR? .BE - .SH DESCRIPTION .PP This command treats the variable given by \fIvarName\fR as a list @@ -32,7 +31,9 @@ is much more efficient than .QW "\fBset a [concat $a [list $b]]\fR" when \fB$a\fR is long. .SH EXAMPLE +.PP Using \fBlappend\fR to build up a list of numbers. +.PP .CS % set var 1 1 @@ -41,10 +42,8 @@ Using \fBlappend\fR to build up a list of numbers. % \fBlappend\fR var 3 4 5 1 2 3 4 5 .CE - .SH "SEE ALSO" list(n), lindex(n), linsert(n), llength(n), lset(n), lsort(n), lrange(n) - .SH KEYWORDS append, element, list, variable diff --git a/doc/lassign.n b/doc/lassign.n index b791feb..6f5042b 100644 --- a/doc/lassign.n +++ b/doc/lassign.n @@ -12,9 +12,8 @@ .SH NAME lassign \- Assign list elements to variables .SH SYNOPSIS -\fBlassign \fIlist varName \fR?\fIvarName ...\fR? +\fBlassign \fIlist \fR?\fIvarName ...\fR? .BE - .SH DESCRIPTION .PP This command treats the value \fIlist\fR as a list and assigns @@ -24,32 +23,38 @@ than list elements, the remaining variables are set to the empty string. If there are more list elements than variables, a list of unassigned elements is returned. .SH EXAMPLES +.PP An illustration of how multiple assignment works, and what happens when there are either too few or too many elements. +.PP .CS -lassign {a b c} x y z ;# Empty return +\fBlassign\fR {a b c} x y z ;# Empty return puts $x ;# Prints "a" puts $y ;# Prints "b" puts $z ;# Prints "c" -lassign {d e} x y z ;# Empty return +\fBlassign\fR {d e} x y z ;# Empty return puts $x ;# Prints "d" puts $y ;# Prints "e" puts $z ;# Prints "" -lassign {f g h i} x y ;# Returns "h i" +\fBlassign\fR {f g h i} x y ;# Returns "h i" puts $x ;# Prints "f" puts $y ;# Prints "g" .CE +.PP The \fBlassign\fR command has other uses. It can be used to create the analogue of the .QW shift command in many shell languages like this: +.PP .CS -set ::argv [lassign $::argv argumentToReadOff] +set ::argv [\fBlassign\fR $::argv argumentToReadOff] .CE .SH "SEE ALSO" -lindex(n), list(n), lset(n), set(n) - +lindex(n), list(n), lrange(n), lset(n), set(n) .SH KEYWORDS assign, element, list, multiple, set, variable +'\"Local Variables: +'\"mode: nroff +'\"End: diff --git a/doc/library.n b/doc/library.n index f29af8b..2413692 100644 --- a/doc/library.n +++ b/doc/library.n @@ -9,14 +9,13 @@ .TH library n "8.0" Tcl "Tcl Built-In Commands" .BS .SH NAME -auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore \- standard library of Tcl procedures +auto_execok, auto_import, auto_load, auto_mkindex, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore \- standard library of Tcl procedures .SH SYNOPSIS .nf \fBauto_execok \fIcmd\fR \fBauto_import \fIpattern\fR \fBauto_load \fIcmd\fR \fBauto_mkindex \fIdir pattern pattern ...\fR -\fBauto_mkindex_old \fIdir pattern pattern ...\fR \fBauto_qualify \fIcommand namespace\fR \fBauto_reset\fR \fBtcl_findLibrary \fIbasename version patch initScript enVarName varName\fR @@ -39,14 +38,16 @@ its own library of support procedures as well; the location of this library is normally given by the value of the \fB$\fIapp\fB_library\fR global variable, where \fIapp\fR is the name of the application. For example, the location of the Tk library is kept in the variable -\fB$tk_library\fR. +\fBtk_library\fR. .PP To access the procedures in the Tcl library, an application should source the file \fBinit.tcl\fR in the library, for example with the Tcl command +.PP .CS \fBsource [file join [info library] init.tcl]\fR .CE +.PP If the library procedure \fBTcl_Init\fR is invoked from an application's \fBTcl_AppInit\fR procedure, this happens automatically. The code in \fBinit.tcl\fR will define the \fBunknown\fR procedure @@ -83,8 +84,8 @@ matching rules of \fBnamespace import\fR. This command attempts to load the definition for a Tcl command named \fIcmd\fR. To do this, it searches an \fIauto-load path\fR, which is a list of one or more directories. The auto-load path is given by the -global variable \fB$auto_path\fR if it exists. If there is no -\fB$auto_path\fR variable, then the TCLLIBPATH environment variable is +global variable \fBauto_path\fR if it exists. If there is no +\fBauto_path\fR variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file \fBtclIndex\fR that describes one or more @@ -105,6 +106,7 @@ cached index information may be deleted with the command reload the index database from disk. .TP \fBauto_mkindex \fIdir pattern pattern ...\fR +. Generates an index suitable for use by \fBauto_load\fR. The command searches \fIdir\fR for all files whose names match any of the \fIpattern\fR arguments (matching is done with the \fBglob\fR @@ -113,10 +115,11 @@ in all the matching files, and stores the index information in a file named \fBtclIndex\fR in \fIdir\fR. If no pattern is given a pattern of \fB*.tcl\fR will be assumed. For example, the command .RS +.PP .CS \fBauto_mkindex foo *.tcl\fR .CE -.LP +.PP will read all the \fB.tcl\fR files in subdirectory \fBfoo\fR and generate a new index file \fBfoo/tclIndex\fR. .PP @@ -127,21 +130,25 @@ auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. .PP -\fBAuto_mkindex_old\fR parses the Tcl scripts in a relatively -unsophisticated way: if any line contains the word \fBproc\fR +\fBAuto_mkindex_old\fR +(which has the same syntax as \fBauto_mkindex\fR) +parses the Tcl scripts in a relatively +unsophisticated way: if any line contains the word +.QW \fBproc\fR as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure's name. -Procedure definitions that do not appear in this way (e.g. they +Procedure definitions that do not appear in this way (e.g.\ they have spaces before the \fBproc\fR) will not be indexed. If your script contains .QW dangerous code, such as global initialization code or procedure names with special characters like \fB$\fR, -\fB*\fR, \fB[\fR or \fB]\fR, you are safer using auto_mkindex_old. +\fB*\fR, \fB[\fR or \fB]\fR, you are safer using \fBauto_mkindex_old\fR. .RE .TP \fBauto_reset\fR +. Destroys all the information cached by \fBauto_execok\fR and \fBauto_load\fR. This information will be re-read from disk the next time it is needed. \fBAuto_reset\fR also deletes any procedures @@ -192,7 +199,7 @@ relative to the executable file in a parallel build tree. \fBparray \fIarrayName\fR Prints on standard output the names and values of all the elements in the array \fIarrayName\fR. -\fBArrayName\fR must be an array accessible to the caller of \fBparray\fR. +\fIArrayName\fR must be an array accessible to the caller of \fBparray\fR. It may be either local or global. .TP \fBtcl_endOfWord \fIstr start\fR @@ -234,7 +241,9 @@ boundary. .SH "VARIABLES" .PP The following global variables are defined or used by the procedures in -the Tcl library: +the Tcl library. They fall into two broad classes, handling unknown +commands and packages, and determining what are words. +.SS "AUTOLOADING AND PACKAGE MANAGEMENT VARIABLES" .TP \fBauto_execs\fR Used by \fBauto_execok\fR to record information about whether @@ -256,10 +265,10 @@ any commands. If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: -the directories listed in the TCLLIBPATH environment variable, -the directory named by the $tcl_library variable, -the parent directory of $tcl_library, -the directories listed in the $tcl_pkgPath variable. +the directories listed in the \fBTCLLIBPATH\fR environment variable, +the directory named by the \fBtcl_library\fR variable, +the parent directory of \fBtcl_library\fR, +the directories listed in the \fBtcl_pkgPath\fR variable. .TP \fBenv(TCL_LIBRARY)\fR If set, then it specifies the location of the directory containing @@ -275,6 +284,10 @@ Tcl format, using .QW / as the path separator, regardless of platform. This variable is only used when initializing the \fBauto_path\fR variable. +.SS "WORD BOUNDARY DETERMINATION VARIABLES" +These variables are only used in the \fBtcl_endOfWord\fR, +\fBtcl_startOfNextWord\fR, \fBtcl_startOfPreviousWord\fR, +\fBtcl_wordBreakAfter\fR, and \fBtcl_wordBreakBefore\fR commands. .TP \fBtcl_nonwordchars\fR This variable contains a regular expression that is used by routines @@ -293,6 +306,9 @@ considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. .SH "SEE ALSO" -info(n), re_syntax(n) +info(n), re_syntax(n), tclvars(n) .SH KEYWORDS auto-exec, auto-load, library, unknown, word, whitespace +'\"Local Variables: +'\"mode: nroff +'\"End: diff --git a/doc/lindex.n b/doc/lindex.n index f0417ac..bb272a6 100644 --- a/doc/lindex.n +++ b/doc/lindex.n @@ -13,7 +13,7 @@ .SH NAME lindex \- Retrieve an element from a list .SH SYNOPSIS -\fBlindex \fIlist ?index...?\fR +\fBlindex \fIlist ?index ...?\fR .BE .SH DESCRIPTION .PP @@ -24,13 +24,17 @@ command line, or grouped in a Tcl list and presented as a single argument. .PP If no indices are presented, the command takes the form: +.PP .CS -lindex list +\fBlindex \fIlist\fR .CE +.PP or +.PP .CS -lindex list {} +\fBlindex \fIlist\fR {} .CE +.PP In this case, the return value of \fBlindex\fR is simply the value of the \fIlist\fR parameter. .PP @@ -44,32 +48,34 @@ substitution and command substitution do not occur. If \fIindex\fR is negative or greater than or equal to the number of elements in \fIvalue\fR, then an empty string is returned. -.VS 8.5 The interpretation of each simple \fIindex\fR value is the same as for the command \fBstring index\fR, supporting simple index arithmetic and indices relative to the end of the list. -.VE 8.5 .PP If additional \fIindex\fR arguments are supplied, then each argument is used in turn to select an element from the previous indexing operation, allowing the script to select elements from sublists. The command, +.PP .CS -lindex $a 1 2 3 +\fBlindex\fR $a 1 2 3 .CE +.PP or +.PP .CS -lindex $a {1 2 3} +\fBlindex\fR $a {1 2 3} .CE +.PP is synonymous with +.PP .CS -lindex [lindex [lindex $a 1] 2] 3 +\fBlindex\fR [\fBlindex\fR [\fBlindex\fR $a 1] 2] 3 .CE .SH EXAMPLES +.PP +Lists can be indexed into from either end: +.PP .CS -\fBlindex\fR {a b c} - \fI\(-> a b c\fR -\fBlindex\fR {a b c} {} - \fI\(-> a b c\fR \fBlindex\fR {a b c} 0 \fI\(-> a\fR \fBlindex\fR {a b c} 2 @@ -78,6 +84,15 @@ lindex [lindex [lindex $a 1] 2] 3 \fI\(-> c\fR \fBlindex\fR {a b c} end-1 \fI\(-> b\fR +.CE +.PP +Lists or sequences of indices allow selection into lists of lists: +.PP +.CS +\fBlindex\fR {a b c} + \fI\(-> a b c\fR +\fBlindex\fR {a b c} {} + \fI\(-> a b c\fR \fBlindex\fR {{a b c} {d e f} {g h i}} 2 1 \fI\(-> h\fR \fBlindex\fR {{a b c} {d e f} {g h i}} {2 1} @@ -87,12 +102,24 @@ lindex [lindex [lindex $a 1] 2] 3 \fBlindex\fR {{{a b} {c d}} {{e f} {g h}}} {1 1 0} \fI\(-> g\fR .CE +.PP +List indices may also perform limited computation, adding or subtracting fixed +amounts from other indices: +.PP +.CS +set idx 1 +\fBlindex\fR {a b c d e f} $idx+2 + \fI\(-> d\fR +set idx 3 +\fBlindex\fR {a b c d e f} $idx+2 + \fI\(-> f\fR +.CE .SH "SEE ALSO" list(n), lappend(n), linsert(n), llength(n), lsearch(n), lset(n), lsort(n), lrange(n), lreplace(n), -.VS 8.5 string(n) -.VE - .SH KEYWORDS element, index, list +'\"Local Variables: +'\"mode: nroff +'\"End: diff --git a/doc/linsert.n b/doc/linsert.n index 9f37fcd..c722e4f 100644 --- a/doc/linsert.n +++ b/doc/linsert.n @@ -13,24 +13,30 @@ .SH NAME linsert \- Insert elements into a list .SH SYNOPSIS -\fBlinsert \fIlist index element \fR?\fIelement element ...\fR? +\fBlinsert \fIlist index \fR?\fIelement element ...\fR? .BE - .SH DESCRIPTION .PP This command produces a new list from \fIlist\fR by inserting all of the \fIelement\fR arguments just before the \fIindex\fR'th element of \fIlist\fR. Each \fIelement\fR argument will become a separate element of the new list. If \fIindex\fR is less than or equal to zero, then the new -elements are inserted at the beginning of the list. -.VS 8.5 -The interpretation of the \fIindex\fR value is the same as -for the command \fBstring index\fR, supporting simple index -arithmetic and indices relative to the end of the list. -.VE +elements are inserted at the beginning of the list, and if \fIindex\fR is +greater or equal to the length of \fIlist\fR, it is as if it was \fBend\fR. +As with \fBstring index\fR, the \fIindex\fR value supports both simple index +arithmetic and end-relative indexing. +.PP +Subject to the restrictions that indices must refer to locations inside the +list and that the \fIelement\fRs will always be inserted in order, insertions +are done so that when \fIindex\fR is start-relative, the first \fIelement\fR +will be at that index in the resulting list, and when \fIindex\fR is +end-relative, the last \fIelement\fR will be at that index in the resulting +list. .SH EXAMPLE +.PP Putting some values into a list, first indexing from the start and then indexing from the end, and then chaining them together: +.PP .CS set oldList {the fox jumps over the dog} set midList [\fBlinsert\fR $oldList 1 quick] @@ -38,13 +44,12 @@ set newList [\fBlinsert\fR $midList end-1 lazy] # The old lists still exist though... set newerList [\fBlinsert\fR [\fBlinsert\fR $oldList end-1 quick] 1 lazy] .CE - .SH "SEE ALSO" list(n), lappend(n), lindex(n), llength(n), lsearch(n), lset(n), lsort(n), lrange(n), lreplace(n), -.VS 8.5 string(n) -.VE - .SH KEYWORDS element, insert, list +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -15,7 +15,6 @@ list \- Create a list .SH SYNOPSIS \fBlist \fR?\fIarg arg ...\fR? .BE - .SH DESCRIPTION .PP This command returns a list comprised of all the \fIarg\fRs, @@ -28,25 +27,30 @@ its arguments. \fBList\fR produces slightly different results than \fBconcat\fR: \fBconcat\fR removes one level of grouping before forming the list, while \fBlist\fR works directly from the original arguments. .SH EXAMPLE +.PP The command +.PP .CS \fBlist\fR a b "c d e " " f {g h}" .CE +.PP will return +.PP .CS \fBa b {c d e } { f {g h}}\fR .CE +.PP while \fBconcat\fR with the same arguments will return +.PP .CS \fBa b c d e f {g h}\fR .CE - .SH "SEE ALSO" lappend(n), lindex(n), linsert(n), llength(n), lrange(n), -.VS 8.5 lrepeat(n), -.VE 8.5 lreplace(n), lsearch(n), lset(n), lsort(n) - .SH KEYWORDS -element, list +element, list, quoting +'\"Local Variables: +'\"mode: nroff +'\"End: diff --git a/doc/llength.n b/doc/llength.n index 627800f..b0ee4d9 100644 --- a/doc/llength.n +++ b/doc/llength.n @@ -15,14 +15,14 @@ llength \- Count the number of elements in a list .SH SYNOPSIS \fBllength \fIlist\fR .BE - .SH DESCRIPTION .PP Treats \fIlist\fR as a list and returns a decimal string giving the number of elements in it. - .SH EXAMPLES +.PP The result is the number of elements: +.PP .CS % \fBllength\fR {a b c d e} 5 @@ -34,6 +34,7 @@ The result is the number of elements: .PP Elements are not guaranteed to be exactly words in a dictionary sense of course, especially when quoting is used: +.PP .CS % \fBllength\fR {a b {c d} e} 4 @@ -42,14 +43,13 @@ of course, especially when quoting is used: .CE .PP An empty list is not necessarily an empty string: +.PP .CS % set var { }; puts "[string length $var],[\fBllength\fR $var]" 1,0 .CE - .SH "SEE ALSO" list(n), lappend(n), lindex(n), linsert(n), lsearch(n), lset(n), lsort(n), lrange(n), lreplace(n) - .SH KEYWORDS element, list, length @@ -17,7 +17,6 @@ load \- Load machine code and initialize new commands .br \fBload \fIfileName packageName interp\fR .BE - .SH DESCRIPTION .PP This command loads binary code from a file into the @@ -56,9 +55,12 @@ by the package that is safe for use by untrusted code. For more information on Safe\-Tcl, see the \fBsafe\fR manual entry. .PP The initialization procedure must match the following prototype: +.PP .CS -typedef int Tcl_PackageInitProc(Tcl_Interp *\fIinterp\fR); +typedef int \fBTcl_PackageInitProc\fR( + Tcl_Interp *\fIinterp\fR); .CE +.PP The \fIinterp\fR argument identifies the interpreter in which the package is to be loaded. The initialization procedure must return \fBTCL_OK\fR or \fBTCL_ERROR\fR to indicate whether or not it completed @@ -71,12 +73,10 @@ in an application. If a given \fIfileName\fR is loaded into multiple interpreters, then the first \fBload\fR will load the code and call the initialization procedure; subsequent \fBload\fRs will call the initialization procedure without loading the code again. -.VS 8.5 For Tcl versions lower than 8.5, it is not possible to unload or reload a package. From version 8.5 however, the \fBunload\fR command allows the unloading of libraries loaded with \fBload\fR, for libraries that are aware of the Tcl's unloading mechanism. -.VE 8.5 .PP The \fBload\fR command also supports packages that are statically linked with the application, if those packages have been registered @@ -119,9 +119,12 @@ When loading a DLL in the current directory, Windows will ignore .QW ./ as a path specifier and use a search heuristic to find the DLL instead. To avoid this, load the DLL with: +.RS +.PP .CS \fBload\fR [file join [pwd] mylib.DLL] .CE +.RE .SH BUGS .PP If the same file is \fBload\fRed by different \fIfileName\fRs, it will @@ -129,6 +132,7 @@ be loaded into the process's address space multiple times. The behavior of this varies from system to system (some systems may detect the redundant loads, others may not). .SH EXAMPLE +.PP The following is a minimal extension: .PP .CS @@ -156,20 +160,21 @@ it can then be loaded into Tcl with the following: .CS # Load the extension switch $tcl_platform(platform) { - windows { - \fBload\fR [file join [pwd] foo.dll] - } - unix { - \fBload\fR [file join [pwd] libfoo[info sharedlibextension]] - } + windows { + \fBload\fR [file join [pwd] foo.dll] + } + unix { + \fBload\fR [file join [pwd] libfoo[info sharedlibextension]] + } } # Now execute the command defined by the extension foo .CE - .SH "SEE ALSO" -info sharedlibextension, Tcl_StaticPackage(3), safe(n) - +info sharedlibextension, package(n), Tcl_StaticPackage(3), safe(n) .SH KEYWORDS -binary code, loading, safe interpreter, shared library +binary code, dynamic library, load, safe interpreter, shared library +'\"Local Variables: +'\"mode: nroff +'\"End: diff --git a/doc/lrange.n b/doc/lrange.n index 34f0150..4f4816a 100644 --- a/doc/lrange.n +++ b/doc/lrange.n @@ -15,18 +15,15 @@ lrange \- Return one or more adjacent elements from a list .SH SYNOPSIS \fBlrange \fIlist first last\fR .BE - .SH DESCRIPTION .PP \fIList\fR must be a valid Tcl list. This command will return a new list consisting of elements \fIfirst\fR through \fIlast\fR, inclusive. -.VS 8.5 The index values \fIfirst\fR and \fIlast\fR are interpreted the same as index values for the command \fBstring index\fR, supporting simple index arithmetic and indices relative to the end of the list. -.VE If \fIfirst\fR is less than zero, it is treated as if it were zero. If \fIlast\fR is greater than or equal to the number of elements in the list, then it is treated as if it were \fBend\fR. @@ -40,19 +37,23 @@ does not always produce the same result as braces); it does, however, produce exactly the same results as .QW "\fBlist [lindex \fIlist first\fB]\fR" .SH EXAMPLES +.PP Selecting the first two elements: +.PP .CS % \fBlrange\fR {a b c d e} 0 1 a b .CE .PP Selecting the last three elements: +.PP .CS % \fBlrange\fR {a b c d e} end-2 end c d e .CE .PP Selecting everything except the first and last element: +.PP .CS % \fBlrange\fR {a b c d e} 1 end-1 b c d @@ -60,6 +61,7 @@ b c d .PP Selecting a single element with \fBlrange\fR is not the same as doing so with \fBlindex\fR: +.PP .CS % set var {some {elements to} select} some {elements to} select @@ -68,13 +70,9 @@ elements to % \fBlrange\fR $var 1 1 {elements to} .CE - .SH "SEE ALSO" list(n), lappend(n), lindex(n), linsert(n), llength(n), lsearch(n), lset(n), lreplace(n), lsort(n), -.VS 8.5 string(n) -.VE - .SH KEYWORDS element, list, range, sublist diff --git a/doc/lrepeat.n b/doc/lrepeat.n index ac78690..59a1edf 100644 --- a/doc/lrepeat.n +++ b/doc/lrepeat.n @@ -11,16 +11,15 @@ .SH NAME lrepeat \- Build a list by repeating elements .SH SYNOPSIS -\fBlrepeat \fInumber element1 \fR?\fIelement2 element3 ...\fR? +\fBlrepeat \fIcount \fR?\fIelement ...\fR? .BE .SH DESCRIPTION .PP -The \fBlrepeat\fR command creates a list of size \fInumber * number of -elements\fR by repeating \fInumber\fR times the sequence of elements -\fIelement1 element2 ...\fR. \fInumber\fR must be a positive integer, -\fIelementn\fR can be any Tcl value. Note that \fBlrepeat 1 arg ...\fR -is identical to \fBlist arg ...\fR, though the \fIarg\fR is required -with \fBlrepeat\fR. +The \fBlrepeat\fR command creates a list of size \fIcount * number of +elements\fR by repeating \fIcount\fR times the sequence of elements +\fIelement ...\fR. \fIcount\fR must be a non-negative integer, +\fIelement\fR can be any Tcl value. Note that \fBlrepeat 1 element ...\fR +is identical to \fBlist element ...\fR. .SH EXAMPLES .CS \fBlrepeat\fR 3 a diff --git a/doc/lreplace.n b/doc/lreplace.n index 2cd79d8..6e6c3ea 100644 --- a/doc/lreplace.n +++ b/doc/lreplace.n @@ -19,7 +19,6 @@ lreplace \- Replace elements in a list with new elements .PP \fBlreplace\fR returns a new list formed by replacing one or more elements of \fIlist\fR with the \fIelement\fR arguments. -.VS 8.5 \fIfirst\fR and \fIlast\fR are index values specifying the first and last elements of the range to replace. The index values \fIfirst\fR and \fIlast\fR are interpreted @@ -29,7 +28,6 @@ end of the list. 0 refers to the first element of the list, and \fBend\fR refers to the last element of the list. If \fIlist\fR is empty, then \fIfirst\fR and \fIlast\fR are ignored. -.VE .PP If \fIfirst\fR is less than zero, it is considered to refer to before the first element of the list. For non-empty lists, the element indicated @@ -47,19 +45,23 @@ the list. If no \fIelement\fR arguments are specified, then the elements between \fIfirst\fR and \fIlast\fR are simply deleted. If \fIlist\fR is empty, any \fIelement\fR arguments are added to the end of the list. .SH EXAMPLES +.PP Replacing an element of a list with another: +.PP .CS % \fBlreplace\fR {a b c d e} 1 1 foo a foo c d e .CE .PP Replacing two elements of a list with three: +.PP .CS % \fBlreplace\fR {a b c d e} 1 2 three more elements a three more elements d e .CE .PP Deleting the last element from a list in a variable: +.PP .CS % set var {a b c d e} a b c d e @@ -68,6 +70,7 @@ a b c d .CE .PP A procedure to delete a given element from a list: +.PP .CS proc lremove {listVariable value} { upvar 1 $listVariable var @@ -78,8 +81,6 @@ proc lremove {listVariable value} { .SH "SEE ALSO" list(n), lappend(n), lindex(n), linsert(n), llength(n), lsearch(n), lset(n), lrange(n), lsort(n), -.VS 8.5 string(n) -.VE .SH KEYWORDS element, list, replace diff --git a/doc/lreverse.n b/doc/lreverse.n index da5e489..f52db9b 100644 --- a/doc/lreverse.n +++ b/doc/lreverse.n @@ -1,4 +1,4 @@ -'\" -*- nroff -*- +'\" '\" Copyright (c) 2006 by Donal K. Fellows. All rights reserved. '\" '\" See the file "license.terms" for information on usage and redistribution @@ -29,3 +29,6 @@ list(n), lsearch(n), lsort(n) .SH KEYWORDS element, list, reverse +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/lsearch.n b/doc/lsearch.n index b046ba2..7835352 100644 --- a/doc/lsearch.n +++ b/doc/lsearch.n @@ -8,7 +8,7 @@ '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" .so man.macros -.TH lsearch n 8.5 Tcl "Tcl Built-In Commands" +.TH lsearch n 8.6 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME @@ -16,7 +16,6 @@ lsearch \- See if a list contains a particular element .SH SYNOPSIS \fBlsearch \fR?\fIoptions\fR? \fIlist pattern\fR .BE - .SH DESCRIPTION .PP This command searches the elements of \fIlist\fR to see if one @@ -27,24 +26,29 @@ If not, the command returns \fB\-1\fR. The \fIoption\fR arguments indicates how the elements of the list are to be matched against \fIpattern\fR and must have one of the values below: .SS "MATCHING STYLE OPTIONS" +.PP If all matching style options are omitted, the default matching style is \fB\-glob\fR. If more than one matching style is specified, the last matching style given takes precedence. .TP \fB\-exact\fR +. \fIPattern\fR is a literal string that is compared for exact equality against each list element. .TP \fB\-glob\fR +. \fIPattern\fR is a glob-style pattern which is matched against each list element using the same rules as the \fBstring match\fR command. .TP \fB\-regexp\fR +. \fIPattern\fR is treated as a regular expression and matched against each list element using the rules described in the \fBre_syntax\fR reference page. .TP \fB\-sorted\fR +. The list elements are in sorted order. If this option is specified, \fBlsearch\fR will use a more efficient searching algorithm to search \fIlist\fR. If no other options are specified, \fIlist\fR is assumed @@ -53,6 +57,7 @@ option is mutually exclusive with \fB\-glob\fR and \fB\-regexp\fR, and is treated exactly like \fB\-exact\fR when either \fB\-all\fR or \fB\-not\fR are specified. .SS "GENERAL MODIFIER OPTIONS" +.PP These options may be given with all matching styles. .TP \fB\-all\fR @@ -63,32 +68,36 @@ indices will be in numeric order. If values are returned, the order of the values will be the order of those values within the input \fIlist\fR. .TP \fB\-inline\fR +. The matching value is returned instead of its index (or an empty string if no value matches.) If \fB\-all\fR is also specified, then the result of the command is the list of all values that matched. .TP \fB\-not\fR +. This negates the sense of the match, returning the index of the first non-matching value in the list. .TP \fB\-start\fR\0\fIindex\fR +. The list is searched starting at position \fIindex\fR. -.VS 8.5 The interpretation of the \fIindex\fR value is the same as for the command \fBstring index\fR, supporting simple index arithmetic and indices relative to the end of the list. -.VE 8.5 .SS "CONTENTS DESCRIPTION OPTIONS" +.PP These options describe how to interpret the items in the list being searched. They are only meaningful when used with the \fB\-exact\fR and \fB\-sorted\fR options. If more than one is specified, the last one takes precedence. The default is \fB\-ascii\fR. .TP \fB\-ascii\fR +. The list elements are to be examined as Unicode strings (the name is for backward-compatibility reasons.) .TP \fB\-dictionary\fR +. The list elements are to be compared using dictionary-style comparisons (see \fBlsort\fR for a fuller description). Note that this only makes a meaningful difference from the \fB\-ascii\fR option when @@ -96,49 +105,67 @@ the \fB\-sorted\fR option is given, because values are only dictionary-equal when exactly equal. .TP \fB\-integer\fR +. The list elements are to be compared as integers. -.VS 8.5 .TP \fB\-nocase\fR +. Causes comparisons to be handled in a case-insensitive manner. Has no effect if combined with the \fB\-dictionary\fR, \fB\-integer\fR, or \fB\-real\fR options. -.VE 8.5 .TP \fB\-real\fR +. The list elements are to be compared as floating-point values. .SS "SORTED LIST OPTIONS" +.PP These options (only meaningful with the \fB\-sorted\fR option) specify how the list is sorted. If more than one is given, the last one takes precedence. The default option is \fB\-increasing\fR. .TP \fB\-decreasing\fR +. The list elements are sorted in decreasing order. This option is only meaningful when used with \fB\-sorted\fR. .TP \fB\-increasing\fR +. The list elements are sorted in increasing order. This option is only meaningful when used with \fB\-sorted\fR. +.TP +\fB\-bisect\fR +.VS 8.6 +Inexact search when the list elements are in sorted order. For an increasing +list the last index where the element is less than or equal to the pattern +is returned. For a decreasing list the last index where the element is greater +than or equal to the pattern is returned. If the pattern is before the first +element or the list is empty, -1 is returned. +This option implies \fB\-sorted\fR and cannot be used with either \fB\-all\fR +or \fB\-not\fR. +.VE 8.6 .SS "NESTED LIST OPTIONS" -.VS 8.5 +.PP These options are used to search lists of lists. They may be used with any other options. .TP \fB\-index\fR\0\fIindexList\fR +. This option is designed for use when searching within nested lists. The \fIindexList\fR argument gives a path of indices (much as might be used with the \fBlindex\fR or \fBlset\fR commands) within each element to allow the location of the term being matched against. .TP \fB\-subindices\fR +. If this option is given, the index result from this command (or every index result when \fB\-all\fR is also specified) will be a complete path (suitable for use with \fBlindex\fR or \fBlset\fR) within the overall list to the term found. This option has no effect unless the -\fI\-index\fR is also specified, and is just a convenience short-cut. -.VE 8.5 +\fB\-index\fR is also specified, and is just a convenience short-cut. .SH EXAMPLES +.PP Basic searching: +.PP .CS \fBlsearch\fR {a b c d e} c \fI\(-> 2\fR @@ -147,6 +174,7 @@ Basic searching: .CE .PP Using \fBlsearch\fR to filter lists: +.PP .CS \fBlsearch\fR -inline {a20 b35 c47} b* \fI\(-> b35\fR @@ -161,18 +189,21 @@ Using \fBlsearch\fR to filter lists: This can even do a .QW set-like removal operation: +.PP .CS \fBlsearch\fR -all -inline -not -exact {a b c a d e a f g a} a \fI\(-> b c d e f g\fR .CE .PP Searching may start part-way through the list: +.PP .CS \fBlsearch\fR -start 3 {a b c a b c} c \fI\(-> 5\fR .CE .PP It is also possible to search inside elements: +.PP .CS \fBlsearch\fR -index 1 -all -inline {{a abc} {b bcd} {c cde}} *bc* \fI\(-> {a abc} {b bcd}\fR @@ -180,10 +211,9 @@ It is also possible to search inside elements: .SH "SEE ALSO" foreach(n), list(n), lappend(n), lindex(n), linsert(n), llength(n), lset(n), lsort(n), lrange(n), lreplace(n), -.VS 8.5 string(n) -.VE .SH KEYWORDS +binary search, linear search, list, match, pattern, regular expression, search, string '\" Local Variables: '\" mode: nroff diff --git a/doc/lset.n b/doc/lset.n index 5efcbae..805de16 100644..100755 --- a/doc/lset.n +++ b/doc/lset.n @@ -11,7 +11,7 @@ .SH NAME lset \- Change an element in a list .SH SYNOPSIS -\fBlset \fIvarName ?index...? newValue\fR +\fBlset \fIvarName ?index ...? newValue\fR .BE .SH DESCRIPTION .PP @@ -24,13 +24,17 @@ Tcl list and presented as a single argument. Finally, it accepts a new value for an element of \fIvarName\fR. .PP If no indices are presented, the command takes the form: +.PP .CS -lset varName newValue +\fBlset\fR varName newValue .CE +.PP or +.PP .CS -lset varName {} newValue +\fBlset\fR varName {} newValue .CE +.PP In this case, \fInewValue\fR replaces the old value of the variable \fIvarName\fR. .PP @@ -47,42 +51,53 @@ replaced with \fInewValue\fR. This new list is stored in the variable \fIvarName\fR, and is also the return value from the \fBlset\fR command. .PP -If \fIindex\fR is negative or greater than or equal to the number +If \fIindex\fR is negative or greater than the number of elements in \fI$varName\fR, then an error occurs. .PP -.VS 8.5 +If \fIindex\fR is equal to the number of elements in \fI$varName\fR, +then the given element is appended to the list. +.PP The interpretation of each simple \fIindex\fR value is the same as for the command \fBstring index\fR, supporting simple index arithmetic and indices relative to the end of the list. -.VE 8.5 .PP If additional \fIindex\fR arguments are supplied, then each argument is used in turn to address an element within a sublist designated by the previous indexing operation, -allowing the script to alter elements in sublists. The command, +allowing the script to alter elements in sublists (or append elements +to sublists). The command, +.PP .CS -lset a 1 2 newValue +\fBlset\fR a 1 2 newValue .CE +.PP or +.PP .CS -lset a {1 2} newValue +\fBlset\fR a {1 2} newValue .CE +.PP replaces element 2 of sublist 1 with \fInewValue\fR. .PP The integer appearing in each \fIindex\fR argument must be greater than or equal to zero. The integer appearing in each \fIindex\fR -argument must be strictly less than the length of the corresponding -list. In other words, the \fBlset\fR command cannot change the size -of a list. If an index is outside the permitted range, an error is reported. +argument must be less than or equal to the length of the corresponding +list. In other words, the \fBlset\fR command can change the size +of a list only by appending an element (setting the one after the current +end). If an index is outside the permitted range, an error is reported. .SH EXAMPLES +.PP In each of these examples, the initial value of \fIx\fR is: +.PP .CS set x [list [list a b c] [list d e f] [list g h i]] \fI\(-> {a b c} {d e f} {g h i}\fR .CE +.PP The indicated return value also becomes the new value of \fIx\fR (except in the last case, which is an error which leaves the value of \fIx\fR unchanged.) +.PP .CS \fBlset\fR x {j k l} \fI\(-> j k l\fR @@ -103,13 +118,17 @@ The indicated return value also becomes the new value of \fIx\fR \fBlset\fR x {2 3} j \fI\(-> list index out of range\fR .CE +.PP In the following examples, the initial value of \fIx\fR is: +.PP .CS set x [list [list [list a b] [list c d]] \e [list [list e f] [list g h]]] \fI\(-> {{a b} {c d}} {{e f} {g h}}\fR .CE +.PP The indicated return value also becomes the new value of \fIx\fR. +.PP .CS \fBlset\fR x 1 1 0 j \fI\(-> {{a b} {c d}} {{e f} {j h}}\fR @@ -119,10 +138,9 @@ The indicated return value also becomes the new value of \fIx\fR. .SH "SEE ALSO" list(n), lappend(n), lindex(n), linsert(n), llength(n), lsearch(n), lsort(n), lrange(n), lreplace(n), -.VS 8.5 string(n) -.VE - - .SH KEYWORDS element, index, list, replace, set +'\"Local Variables: +'\"mode: nroff +'\"End: diff --git a/doc/lsort.n b/doc/lsort.n index 1726e92..312048e 100644 --- a/doc/lsort.n +++ b/doc/lsort.n @@ -16,7 +16,6 @@ lsort \- Sort the elements of a list .SH SYNOPSIS \fBlsort \fR?\fIoptions\fR? \fIlist\fR .BE - .SH DESCRIPTION .PP This command sorts the elements of \fIlist\fR, returning a new @@ -28,26 +27,31 @@ By default ASCII sorting is used with the result returned in increasing order. However, any of the following options may be specified before \fIlist\fR to control the sorting process (unique abbreviations are accepted): -.TP 20 +.TP \fB\-ascii\fR +. Use string comparison with Unicode code-point collation order (the name is for backward-compatibility reasons.) This is the default. -.TP 20 +.TP \fB\-dictionary\fR +. Use dictionary-style comparison. This is the same as \fB\-ascii\fR except (a) case is ignored except as a tie-breaker and (b) if two strings contain embedded numbers, the numbers compare as integers, not characters. For example, in \fB\-dictionary\fR mode, \fBbigBoy\fR sorts between \fBbigbang\fR and \fBbigboy\fR, and \fBx10y\fR sorts between \fBx9y\fR and \fBx11y\fR. -.TP 20 +.TP \fB\-integer\fR +. Convert list elements to integers and use integer comparison. -.TP 20 +.TP \fB\-real\fR +. Convert list elements to floating-point values and use floating comparison. -.TP 20 +.TP \fB\-command\0\fIcommand\fR +. Use \fIcommand\fR as a comparison command. To compare two elements, evaluate a Tcl script consisting of \fIcommand\fR with the two elements appended as additional @@ -55,74 +59,109 @@ arguments. The script should return an integer less than, equal to, or greater than zero if the first element is to be considered less than, equal to, or greater than the second, respectively. -.TP 20 +.TP \fB\-increasing\fR +. Sort the list in increasing order .PQ smallest "items first" . This is the default. -.TP 20 +.TP \fB\-decreasing\fR +. Sort the list in decreasing order .PQ largest "items first" . -.TP 20 +.TP \fB\-indices\fR -.VS "8.5 (TIP#217)" +. Return a list of indices into \fIlist\fR in sorted order instead of the values themselves. -.VE "8.5 (TIP#217)" -.TP 20 +.TP \fB\-index\0\fIindexList\fR +. If this option is specified, each of the elements of \fIlist\fR must -itself be a proper Tcl sublist. Instead of sorting based on whole -sublists, \fBlsort\fR will extract the \fIindexList\fR'th element from -each sublist -.VS 8.5 -(as if the overall element and the \fIindexList\fR were passed to -\fBlindex\fR) and sort based on the given element. -.VE 8.5 +itself be a proper Tcl sublist (unless \fB\-stride\fR is used). +Instead of sorting based on whole sublists, \fBlsort\fR will extract +the \fIindexList\fR'th element from each sublist (as if the overall +element and the \fIindexList\fR were passed to \fBlindex\fR) and sort +based on the given element. For example, .RS +.PP .CS -lsort -integer -index 1 \e +\fBlsort\fR -integer -index 1 \e {{First 24} {Second 18} {Third 30}} .CE -returns \fB{Second 18} {First 24} {Third 30}\fR, and +.PP +returns \fB{Second 18} {First 24} {Third 30}\fR, +.PP '\" '\" This example is from the test suite! '\" .CS -lsort -index end-1 \e - {{a 1 e i} {b 2 3 f g} {c 4 5 6 d h}} +\fBlsort\fR -index end-1 \e + {{a 1 e i} {b 2 3 f g} {c 4 5 6 d h}} .CE +.PP returns \fB{c 4 5 6 d h} {a 1 e i} {b 2 3 f g}\fR, -.VS 8.5 and +.PP .CS -lsort -index {0 1} { - {{b i g} 12345} - {{d e m o} 34512} - {{c o d e} 54321} +\fBlsort\fR -index {0 1} { + {{b i g} 12345} + {{d e m o} 34512} + {{c o d e} 54321} } .CE +.PP returns \fB{{d e m o} 34512} {{b i g} 12345} {{c o d e} 54321}\fR (because \fBe\fR sorts before \fBi\fR which sorts before \fBo\fR.) -.VE 8.5 This option is much more efficient than using \fB\-command\fR to achieve the same effect. .RE -.VS 8.5 -.TP 20 +.TP +\fB\-stride\0\fIstrideLength\fR +. +If this option is specified, the list is treated as consisting of +groups of \fIstrideLength\fR elements and the groups are sorted by +either their first element or, if the \fB\-index\fR option is used, +by the element within each group given by the first index passed to +\fB\-index\fR (which is then ignored by \fB\-index\fR). Elements +always remain in the same position within their group. +.RS +.PP +The list length must be an integer multiple of \fIstrideLength\fR, which +in turn must be at least 2. +.PP +For example, +.PP +.CS +\fBlsort\fR \-stride 2 {carrot 10 apple 50 banana 25} +.CE +.PP +returns +.QW "apple 50 banana 25 carrot 10" , +and +.PP +.CS +\fBlsort\fR \-stride 2 \-index 1 \-integer {carrot 10 apple 50 banana 25} +.CE +.PP +returns +.QW "carrot 10 banana 25 apple 50" . +.RE +.TP \fB\-nocase\fR +. Causes comparisons to be handled in a case-insensitive manner. Has no effect if combined with the \fB\-dictionary\fR, \fB\-integer\fR, or \fB\-real\fR options. -.VE 8.5 -.TP 20 +.TP \fB\-unique\fR +. If this option is specified, then only the last set of duplicate elements found in the list will be retained. Note that duplicates are determined relative to the comparison used in the sort. Thus if -\fI\-index 0\fR is used, \fB{1 a}\fR and \fB{1 b}\fR would be +\fB\-index 0\fR is used, \fB{1 a}\fR and \fB{1 b}\fR would be considered duplicates and only the second element, \fB{1 b}\fR, would be retained. .SH "NOTES" @@ -138,53 +177,80 @@ option. .SH "EXAMPLES" .PP Sorting a list using ASCII sorting: +.PP .CS -% \fBlsort\fR {a10 B2 b1 a1 a2} +\fI%\fR \fBlsort\fR {a10 B2 b1 a1 a2} B2 a1 a10 a2 b1 .CE .PP Sorting a list using Dictionary sorting: +.PP .CS -% \fBlsort\fR -dictionary {a10 B2 b1 a1 a2} +\fI%\fR \fBlsort\fR -dictionary {a10 B2 b1 a1 a2} a1 a2 a10 b1 B2 .CE .PP Sorting lists of integers: +.PP .CS -% \fBlsort\fR -integer {5 3 1 2 11 4} +\fI%\fR \fBlsort\fR -integer {5 3 1 2 11 4} 1 2 3 4 5 11 -% \fBlsort\fR -integer {1 2 0x5 7 0 4 -1} +\fI%\fR \fBlsort\fR -integer {1 2 0x5 7 0 4 -1} -1 0 1 2 4 0x5 7 .CE .PP Sorting lists of floating-point numbers: +.PP .CS -% \fBlsort\fR -real {5 3 1 2 11 4} +\fI%\fR \fBlsort\fR -real {5 3 1 2 11 4} 1 2 3 4 5 11 -% \fBlsort\fR -real {.5 0.07e1 0.4 6e-1} +\fI%\fR \fBlsort\fR -real {.5 0.07e1 0.4 6e-1} 0.4 .5 6e-1 0.07e1 .CE .PP Sorting using indices: +.PP .CS -% # Note the space character before the c -% \fBlsort\fR {{a 5} { c 3} {b 4} {e 1} {d 2}} +\fI%\fR # Note the space character before the c +\fI%\fR \fBlsort\fR {{a 5} { c 3} {b 4} {e 1} {d 2}} { c 3} {a 5} {b 4} {d 2} {e 1} -% \fBlsort\fR -index 0 {{a 5} { c 3} {b 4} {e 1} {d 2}} +\fI%\fR \fBlsort\fR -index 0 {{a 5} { c 3} {b 4} {e 1} {d 2}} {a 5} {b 4} { c 3} {d 2} {e 1} -% \fBlsort\fR -index 1 {{a 5} { c 3} {b 4} {e 1} {d 2}} +\fI%\fR \fBlsort\fR -index 1 {{a 5} { c 3} {b 4} {e 1} {d 2}} {e 1} {d 2} { c 3} {b 4} {a 5} .CE .PP +.VS 8.6 +Sorting a dictionary: +.PP +.CS +\fI%\fR set d [dict create c d a b h i f g c e] +c e a b h i f g +\fI%\fR \fBlsort\fR -stride 2 $d +a b c e f g h i +.CE +.PP +Sorting using striding and multiple indices: +.PP +.CS +\fI%\fR # Note the first index value is relative to the group +\fI%\fR \fBlsort\fR \-stride 3 \-index {0 1} \e + {{Bob Smith} 25 Audi {Jane Doe} 40 Ford} +{{Jane Doe} 40 Ford {Bob Smith} 25 Audi} +.CE +.VE 8.6 +.PP Stripping duplicate values using sorting: +.PP .CS -% \fBlsort\fR -unique {a b c a b c a b c} +\fI%\fR \fBlsort\fR -unique {a b c a b c a b c} a b c .CE .PP More complex sorting using a comparison function: +.PP .CS -% proc compare {a b} { +\fI%\fR proc compare {a b} { set a0 [lindex $a 0] set b0 [lindex $b 0] if {$a0 < $b0} { @@ -194,14 +260,15 @@ More complex sorting using a comparison function: } return [string compare [lindex $a 1] [lindex $b 1]] } -% \fBlsort\fR -command compare \e +\fI%\fR \fBlsort\fR -command compare \e {{3 apple} {0x2 carrot} {1 dingo} {2 banana}} {1 dingo} {2 banana} {0x2 carrot} {3 apple} .CE - .SH "SEE ALSO" list(n), lappend(n), lindex(n), linsert(n), llength(n), lsearch(n), lset(n), lrange(n), lreplace(n) - .SH KEYWORDS element, list, order, sort +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/mathfunc.n b/doc/mathfunc.n index 4ba25e4..3da6d5a 100644 --- a/doc/mathfunc.n +++ b/doc/mathfunc.n @@ -35,10 +35,8 @@ package require \fBTcl 8.5\fR .br \fB::tcl::mathfunc::double\fR \fIarg\fR .br -.VS 8.5 \fB::tcl::mathfunc::entier\fR \fIarg\fR .br -.VE 8.5 \fB::tcl::mathfunc::exp\fR \fIarg\fR .br \fB::tcl::mathfunc::floor\fR \fIarg\fR @@ -115,28 +113,34 @@ for new implementations. .SS "DETAILED DEFINITIONS" .TP \fBabs \fIarg\fR +. Returns the absolute value of \fIarg\fR. \fIArg\fR may be either integer or floating-point, and the result is returned in the same form. .TP \fBacos \fIarg\fR +. Returns the arc cosine of \fIarg\fR, in the range [\fI0\fR,\fIpi\fR] radians. \fIArg\fR should be in the range [\fI\-1\fR,\fI1\fR]. .TP \fBasin \fIarg\fR +. Returns the arc sine of \fIarg\fR, in the range [\fI\-pi/2\fR,\fIpi/2\fR] radians. \fIArg\fR should be in the range [\fI\-1\fR,\fI1\fR]. .TP \fBatan \fIarg\fR +. Returns the arc tangent of \fIarg\fR, in the range [\fI\-pi/2\fR,\fIpi/2\fR] radians. .TP \fBatan2 \fIy x\fR +. Returns the arc tangent of \fIy\fR/\fIx\fR, in the range [\fI\-pi\fR,\fIpi\fR] radians. \fIx\fR and \fIy\fR cannot both be 0. If \fIx\fR is greater than \fI0\fR, this is equivalent to .QW "\fBatan \fR[\fBexpr\fR {\fIy\fB/\fIx\fR}]" . .TP \fBbool \fIarg\fR +. Accepts any numeric value, or any string acceptable to \fBstring is boolean\fR, and returns the corresponding boolean value \fB0\fR or \fB1\fR. Non-zero numbers are true. @@ -144,18 +148,22 @@ Other numbers are false. Non-numeric strings produce boolean value in agreement with \fBstring is true\fR and \fBstring is false\fR. .TP \fBceil \fIarg\fR +. Returns the smallest integral floating-point value (i.e. with a zero fractional part) not less than \fIarg\fR. The argument may be any numeric value. .TP \fBcos \fIarg\fR +. Returns the cosine of \fIarg\fR, measured in radians. .TP \fBcosh \fIarg\fR +. Returns the hyperbolic cosine of \fIarg\fR. If the result would cause an overflow, an error is returned. .TP \fBdouble \fIarg\fR +. The argument may be any numeric value, If \fIarg\fR is a floating-point value, returns \fIarg\fR, otherwise converts \fIarg\fR to floating-point and returns the converted value. May return @@ -163,64 +171,78 @@ If \fIarg\fR is a floating-point value, returns \fIarg\fR, otherwise converts the floating-point range. .TP \fBentier \fIarg\fR -.VS 8.5 +. The argument may be any numeric value. The integer part of \fIarg\fR is determined and returned. The integer range returned by this function is unlimited, unlike \fBint\fR and \fBwide\fR which truncate their range to fit in particular storage widths. -.VE 8.5 .TP \fBexp \fIarg\fR +. Returns the exponential of \fIarg\fR, defined as \fIe\fR**\fIarg\fR. If the result would cause an overflow, an error is returned. .TP \fBfloor \fIarg\fR +. Returns the largest integral floating-point value (i.e. with a zero fractional part) not greater than \fIarg\fR. The argument may be any numeric value. .TP \fBfmod \fIx y\fR +. Returns the floating-point remainder of the division of \fIx\fR by \fIy\fR. If \fIy\fR is 0, an error is returned. .TP \fBhypot \fIx y\fR -Computes the length of the hypotenuse of a right-angled triangle -.QW "\fBsqrt\fR [\fBexpr\fR {\fIx\fB*\fIx\fB+\fIy\fB*\fIy\fR}]". +. +Computes the length of the hypotenuse of a right-angled triangle, +approximately +.QW "\fBsqrt\fR [\fBexpr\fR {\fIx\fB*\fIx\fB+\fIy\fB*\fIy\fR}]" +except for being more numerically stable when the two arguments have +substantially different magnitudes. .TP \fBint \fIarg\fR +. The argument may be any numeric value. The integer part of \fIarg\fR is determined, and then the low order bits of that integer value up to the machine word size are returned as an integer value. For reference, -the number of bytes in the machine word are stored in -\fBtcl_platform(wordSize)\fR. +the number of bytes in the machine word are stored in the \fBwordSize\fR +element of the \fBtcl_platform\fR array. .TP \fBisqrt \fIarg\fR +. Computes the integer part of the square root of \fIarg\fR. \fIArg\fR must be a positive value, either an integer or a floating point number. Unlike \fBsqrt\fR, which is limited to the precision of a floating point number, \fIisqrt\fR will return a result of arbitrary precision. .TP \fBlog \fIarg\fR +. Returns the natural logarithm of \fIarg\fR. \fIArg\fR must be a positive value. .TP \fBlog10 \fIarg\fR +. Returns the base 10 logarithm of \fIarg\fR. \fIArg\fR must be a positive value. .TP \fBmax \fIarg\fB \fI...\fR +. Accepts one or more numeric arguments. Returns the one argument with the greatest value. .TP \fBmin \fIarg\fB \fI...\fR +. Accepts one or more numeric arguments. Returns the one argument with the least value. .TP \fBpow \fIx y\fR +. Computes the value of \fIx\fR raised to the power \fIy\fR. If \fIx\fR is negative, \fIy\fR must be an integer value. .TP \fBrand\fR +. Returns a pseudo-random floating-point value in the range (\fI0\fR,\fI1\fR). The generator algorithm is a simple linear congruential generator that is not cryptographically secure. Each result from \fBrand\fR completely @@ -230,34 +252,42 @@ one-time passwords. The seed of the generator is initialized from the internal clock of the machine or may be set with the \fBsrand\fR function. .TP \fBround \fIarg\fR +. If \fIarg\fR is an integer value, returns \fIarg\fR, otherwise converts \fIarg\fR to integer by rounding and returns the converted value. .TP \fBsin \fIarg\fR +. Returns the sine of \fIarg\fR, measured in radians. .TP \fBsinh \fIarg\fR +. Returns the hyperbolic sine of \fIarg\fR. If the result would cause an overflow, an error is returned. .TP \fBsqrt \fIarg\fR +. The argument may be any non-negative numeric value. Returns a floating-point value that is the square root of \fIarg\fR. May return \fBInf\fR when the argument is a numeric value that exceeds the square of the maximum value of the floating-point range. .TP \fBsrand \fIarg\fR +. The \fIarg\fR, which must be an integer, is used to reset the seed for the random number generator of \fBrand\fR. Returns the first random number (see \fBrand\fR) from that seed. Each interpreter has its own seed. .TP \fBtan \fIarg\fR +. Returns the tangent of \fIarg\fR, measured in radians. .TP \fBtanh \fIarg\fR +. Returns the hyperbolic tangent of \fIarg\fR. .TP \fBwide \fIarg\fR +. The argument may be any numeric value. The integer part of \fIarg\fR is determined, and then the low order 64 bits of that integer value are returned as an integer value. diff --git a/doc/mathop.n b/doc/mathop.n index 5a6ba4e..e359276 100644 --- a/doc/mathop.n +++ b/doc/mathop.n @@ -1,4 +1,4 @@ -.\" -*- nroff -*- +.\" .\" Copyright (c) 2006-2007 Donal K. Fellows. .\" .\" See the file "license.terms" for information on usage and redistribution @@ -131,8 +131,9 @@ Each \fInumber\fR must have an integral value. Note that Tcl defines this operation exactly even for negative numbers, so that the following equality holds true: .RS +.PP .CS -(\fIx \fB/ \fIy\fR) \fB* \fIy \fB== \fIx \fB-\fR (\fIx \fB% \fIy\fR) +(\fIx \fB/ \fIy\fR) \fB* \fIy \fB== \fIx \fB\-\fR (\fIx \fB% \fIy\fR) .CE .RE .TP @@ -271,9 +272,11 @@ Returns whether the value \fIarg\fR is present in the list \fIlist\fR Returns whether the value \fIarg\fR is not present in the list \fIlist\fR (according to exact string comparison of elements). .SH EXAMPLES +.PP The simplest way to use the operators is often by using \fBnamespace path\fR to make the commands available. This has the advantage of not affecting the set of commands defined by the current namespace. +.PP .CS namespace path {\fB::tcl::mathop\fR ::tcl::mathfunc} @@ -297,3 +300,6 @@ set sorted [\fB<=\fR {*}$list] expr(n), mathfunc(n), namespace(n) .SH KEYWORDS command, expression, operator +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/memory.n b/doc/memory.n index 4ff681d..f82c5b4 100644 --- a/doc/memory.n +++ b/doc/memory.n @@ -110,3 +110,6 @@ occur long after the overwrite occurred. ckalloc, ckfree, Tcl_ValidateAllMemory, Tcl_DumpActiveMemory, TCL_MEM_DEBUG .SH KEYWORDS memory, debug +'\"Local Variables: +'\"mode: nroff +'\"End: diff --git a/doc/msgcat.n b/doc/msgcat.n index 00141ad..d389757 100644 --- a/doc/msgcat.n +++ b/doc/msgcat.n @@ -49,6 +49,7 @@ wishes to be enabled for multi-lingual applications. .SH COMMANDS .TP \fB::msgcat::mc \fIsrc-string\fR ?\fIarg arg ...\fR? +. Returns a translation of \fIsrc-string\fR according to the user's current locale. If additional arguments past \fIsrc-string\fR are given, the \fBformat\fR command is used to substitute the @@ -71,12 +72,14 @@ later simply by defining new message catalog entries. .RE .TP \fB::msgcat::mcmax ?\fIsrc-string src-string ...\fR? +. Given several source strings, \fB::msgcat::mcmax\fR returns the length of the longest translated string. This is useful when designing localized GUIs, which may require that all buttons, for example, be a fixed width (which will be the width of the widest button). .TP -\fB::msgcat::mclocale \fR?\fInewLocale\fR? +\fB::msgcat::mclocale \fR?\fInewLocale\fR? +. This function sets the locale to \fInewLocale\fR. If \fInewLocale\fR is omitted, the current locale is returned, otherwise the current locale is set to \fInewLocale\fR. msgcat stores and compares the locale in a @@ -86,6 +89,7 @@ the user's environment. See \fBLOCALE SPECIFICATION\fR below for a description of the locale string format. .TP \fB::msgcat::mcpreferences\fR +. Returns an ordered list of the locales preferred by the user, based on the user's language specification. The list is ordered from most specific to least @@ -93,11 +97,10 @@ preference. The list is derived from the current locale set in msgcat by \fB::msgcat::mclocale\fR, and cannot be set independently. For example, if the current locale is en_US_funky, then \fB::msgcat::mcpreferences\fR -.VS 1.4 returns \fB{en_US_funky en_US en {}}\fR. -.VE 1.4 .TP \fB::msgcat::mcload \fIdirname\fR +. Searches the specified directory for files that match the language specifications returned by \fB::msgcat::mcpreferences\fR (note that these are all lowercase), extended by the file extension @@ -111,12 +114,14 @@ evaluation. The number of message files which matched the specification and were loaded is returned. .TP \fB::msgcat::mcset \fIlocale src-string \fR?\fItranslate-string\fR? +. Sets the translation for \fIsrc-string\fR to \fItranslate-string\fR in the specified \fIlocale\fR and the current namespace. If \fItranslate-string\fR is not specified, \fIsrc-string\fR is used for both. The function returns \fItranslate-string\fR. .TP \fB::msgcat::mcmset \fIlocale src-trans-list\fR +. Sets the translation for multiple source strings in \fIsrc-trans-list\fR in the specified \fIlocale\fR and the current namespace. @@ -127,6 +132,7 @@ faster than multiple invocations of \fB::msgcat::mcset\fR. The function returns the number of translations set. .TP \fB::msgcat::mcunknown \fIlocale src-string\fR +. This routine is called by \fB::msgcat::mc\fR in the case when a translation for \fIsrc-string\fR is not defined in the current locale. The default action is to return @@ -157,14 +163,18 @@ according to the user's environment. The variables \fBenv(LC_ALL)\fR, \fBenv(LC_MESSAGES)\fR, and \fBenv(LANG)\fR are examined in order. The first of them to have a non-empty value is used to determine the initial locale. The value is parsed according to the XPG4 pattern +.PP .CS language[_country][.codeset][@modifier] .CE +.PP to extract its parts. The initial locale is then set by calling \fB::msgcat::mclocale\fR with the argument +.PP .CS language[_country][_modifier] .CE +.PP On Windows, if none of those environment variables is set, msgcat will attempt to extract locale information from the registry. If all these attempts to discover an initial locale @@ -176,7 +186,6 @@ When a locale is specified by the user, a .QW "best match" search is performed during string translation. For example, if a user specifies -.VS 1.4 en_GB_Funky, the locales .QW en_GB_Funky , .QW en_GB , @@ -184,7 +193,6 @@ en_GB_Funky, the locales and .MT (the empty string) -.VE 1.4 are searched in order until a matching translation string is found. If no translation string is available, then \fB::msgcat::mcunknown\fR is called. @@ -198,15 +206,18 @@ source string to be shorter and less prone to typographical error. .PP For example, executing the code +.PP .CS \fB::msgcat::mcset\fR en hello "hello from ::" namespace eval foo { - \fB::msgcat::mcset\fR en hello "hello from ::foo" + \fB::msgcat::mcset\fR en hello "hello from ::foo" } puts [\fB::msgcat::mc\fR hello] namespace eval foo {puts [\fB::msgcat::mc\fR hello]} .CE +.PP will print +.PP .CS hello from :: hello from ::foo @@ -222,23 +233,26 @@ messages from their parent namespace. For example, executing (in the .QW en locale) the code +.PP .CS \fB::msgcat::mcset\fR en m1 ":: message1" \fB::msgcat::mcset\fR en m2 ":: message2" \fB::msgcat::mcset\fR en m3 ":: message3" namespace eval ::foo { - \fB::msgcat::mcset\fR en m2 "::foo message2" - \fB::msgcat::mcset\fR en m3 "::foo message3" + \fB::msgcat::mcset\fR en m2 "::foo message2" + \fB::msgcat::mcset\fR en m3 "::foo message3" } namespace eval ::foo::bar { - \fB::msgcat::mcset\fR en m3 "::foo::bar message3" + \fB::msgcat::mcset\fR en m3 "::foo::bar message3" } namespace import \fB::msgcat::mc\fR puts "[\fBmc\fR m1]; [\fBmc\fR m2]; [\fBmc\fR m3]" namespace eval ::foo {puts "[\fBmc\fR m1]; [\fBmc\fR m2]; [\fBmc\fR m3]"} namespace eval ::foo::bar {puts "[\fBmc\fR m1]; [\fBmc\fR m2]; [\fBmc\fR m3]"} .CE +.PP will print +.PP .CS :: message1; :: message2; :: message3 :: message1; ::foo message2; ::foo message3 @@ -254,11 +268,12 @@ All message files for a package are in the same directory. The message file name is a msgcat locale specifier (all lowercase) followed by .QW .msg . For example: +.PP .CS es.msg \(em spanish en_gb.msg \(em United Kingdom English .CE -.VS 1.4 +.PP \fIException:\fR The message file for the root locale .MT is called @@ -267,16 +282,16 @@ This exception is made so as not to cause peculiar behavior, such as marking the message file as .QW hidden on Unix file systems. -.VE 1.4 .IP [3] The file contains a series of calls to \fBmcset\fR and \fBmcmset\fR, setting the necessary translation strings for the language, likely enclosed in a \fBnamespace eval\fR so that all source strings are tied to the namespace of the package. For example, a short \fBes.msg\fR might contain: +.PP .CS namespace eval ::mypackage { - \fB::msgcat::mcset\fR es "Free Beer!" "Cerveza Gracias!" + \fB::msgcat::mcset\fR es "Free Beer!" "Cerveza Gracias!" } .CE .SH "RECOMMENDED MESSAGE SETUP FOR PACKAGES" @@ -290,8 +305,8 @@ During package installation, create a subdirectory .IP [2] Copy your *.msg files into that directory. .IP [3] - Add the following command to your package -initialization script: +Add the following command to your package initialization script: +.PP .CS # load language files, stored in msgs subdirectory \fB::msgcat::mcload\fR [file join [file dirname [info script]] msgs] @@ -303,6 +318,7 @@ to \fBformat\fR might have positionally dependent parameters that might need to be repositioned. For example, it might be syntactically desirable to rearrange the sentence structure while translating. +.PP .CS format "We produced %d units in location %s" $num $city format "In location %s we produced %d units" $city $num @@ -310,13 +326,23 @@ format "In location %s we produced %d units" $city $num .PP This can be handled by using the positional parameters: +.PP .CS format "We produced %1\e$d units in location %2\e$s" $num $city format "In location %2\e$s we produced %1\e$d units" $num $city .CE .PP Similarly, positional parameters can be used with \fBscan\fR to -extract values from internationalized strings. +extract values from internationalized strings. Note that it is not +necessary to pass the output of \fB::msgcat::mc\fR to \fBformat\fR +directly; by passing the values to substitute in as arguments, the +formatting substitution is done directly. +.PP +.CS +\fBmsgcat::mc\fR {Produced %1$d at %2$s} $num $city +# ... where that key is mapped to one of the +# human-oriented versions by \fBmsgcat::mcset\fR +.CE .SH CREDITS .PP The message catalog code was developed by Mark Harrison. @@ -324,3 +350,6 @@ The message catalog code was developed by Mark Harrison. format(n), scan(n), namespace(n), package(n) .SH KEYWORDS internationalization, i18n, localization, l10n, message, text, translation +.\" Local Variables: +.\" mode: nroff +.\" End: diff --git a/doc/my.n b/doc/my.n new file mode 100644 index 0000000..b6a3a29 --- /dev/null +++ b/doc/my.n @@ -0,0 +1,56 @@ +'\" +'\" Copyright (c) 2007 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH my n 0.1 TclOO "TclOO Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +my \- invoke any method of current object +.SH SYNOPSIS +.nf +package require TclOO + +\fBmy\fI methodName\fR ?\fIarg ...\fR? +.fi +.BE +.SH DESCRIPTION +.PP +The \fBmy\fR command is used to allow methods of objects to invoke any method +of the object (or its class). In particular, the set of valid values for +\fImethodName\fR is the set of all methods supported by an object and its +superclasses, including those that are not exported. The object upon which the +method is invoked is always the one that is the current context of the method +(i.e. the object that is returned by \fBself object\fR) from which the +\fBmy\fR command is invoked. +.PP +Each object has its own \fBmy\fR command, contained in its instance namespace. +.SH EXAMPLES +.PP +This example shows basic use of \fBmy\fR to use the \fBvariables\fR method of +the \fBoo::object\fR class, which is not publically visible by default: +.PP +.CS +oo::class create c { + method count {} { + \fBmy\fR variable counter + print [incr counter] + } +} +c create o +o count \fI\(-> prints "1"\fR +o count \fI\(-> prints "2"\fR +o count \fI\(-> prints "3"\fR +.CE +.SH "SEE ALSO" +next(n), oo::object(n), self(n) +.SH KEYWORDS +method, method visibility, object, private method, public method + +.\" Local variables: +.\" mode: nroff +.\" fill-column: 78 +.\" End: diff --git a/doc/namespace.n b/doc/namespace.n index ddf7b51..a32c2f3 100644 --- a/doc/namespace.n +++ b/doc/namespace.n @@ -26,6 +26,7 @@ The legal values of \fIsubcommand\fR are listed below. Note that you can abbreviate the \fIsubcommand\fRs. .TP \fBnamespace children \fR?\fInamespace\fR? ?\fIpattern\fR? +. Returns a list of all child namespaces that belong to the namespace \fInamespace\fR. If \fInamespace\fR is not specified, @@ -41,6 +42,7 @@ otherwise the namespace \fInamespace\fR is prepended onto the pattern. .TP \fBnamespace code \fIscript\fR +. Captures the current namespace context for later execution of the script \fIscript\fR. It returns a new script in which \fIscript\fR has been wrapped @@ -68,6 +70,7 @@ See the section \fBSCOPED SCRIPTS\fR for some examples of how this is used to create callback scripts. .TP \fBnamespace current\fR +. Returns the fully-qualified name for the current namespace. The actual name of the global namespace is .MT @@ -76,6 +79,7 @@ but this command returns \fB::\fR for the global namespace as a convenience to programmers. .TP \fBnamespace delete \fR?\fInamespace namespace ...\fR? +. Each namespace \fInamespace\fR is deleted and all variables, procedures, and child namespaces contained in the namespace are deleted. @@ -87,13 +91,13 @@ If a namespace does not exist, this command returns an error. If no namespace names are given, this command does nothing. .TP \fBnamespace ensemble\fR \fIsubcommand\fR ?\fIarg ...\fR? -.VS 8.5 +. Creates and manipulates a command that is formed out of an ensemble of subcommands. See the section \fBENSEMBLES\fR below for further details. -.VE 8.5 .TP \fBnamespace eval\fR \fInamespace arg\fR ?\fIarg ...\fR? +. Activates a namespace called \fInamespace\fR and evaluates some code in that context. If the namespace does not already exist, it is created. @@ -109,10 +113,12 @@ they are automatically created. .RE .TP \fBnamespace exists\fR \fInamespace\fR +. Returns \fB1\fR if \fInamespace\fR is a valid namespace in the current context, returns \fB0\fR otherwise. .TP -\fBnamespace export \fR?\-\fBclear\fR? ?\fIpattern pattern ...\fR? +\fBnamespace export \fR?\fB\-clear\fR? ?\fIpattern pattern ...\fR? +. Specifies which commands are exported from a namespace. The exported commands are those that can be later imported into another namespace using a \fBnamespace import\fR command. @@ -133,6 +139,7 @@ If no \fIpattern\fRs are given and the \fB\-clear\fR flag is not given, this command returns the namespace's current export list. .TP \fBnamespace forget \fR?\fIpattern pattern ...\fR? +. Removes previously imported commands from a namespace. Each \fIpattern\fR is a simple or qualified name such as \fBx\fR, \fBfoo::x\fR or \fBa::b::p*\fR. @@ -157,7 +164,7 @@ If so, this command deletes the corresponding imported commands. In effect, this un-does the action of a \fBnamespace import\fR command. .TP \fBnamespace import \fR?\fB\-force\fR? ?\fIpattern\fR \fIpattern ...\fR? -.VS 8.5 +. Imports commands into a namespace, or queries the set of imported commands in a namespace. When no arguments are present, \fBnamespace import\fR returns the list of commands in @@ -166,7 +173,8 @@ namespaces. The commands in the returned list are in the format of simple names, with no namespace qualifiers at all. This format is suitable for composition with \fBnamespace forget\fR (see \fBEXAMPLES\fR below). -.VE 8.5 +.RS +.PP When \fIpattern\fR arguments are present, each \fIpattern\fR is a qualified name like \fBfoo::x\fR or \fBa::p*\fR. @@ -174,6 +182,11 @@ That is, it includes the name of an exporting namespace and may have glob-style special characters in the command name at the end of the qualified name. Glob characters may not appear in a namespace name. +When the namespace name is not fully qualified (i.e., does not start +with a namespace separator) it is resolved as a namespace name in the +way described in the \fBNAME RESOLUTION\fR section; it is an error if +no namespace with that name can be found. +.PP All the commands that match a \fIpattern\fR string and which are currently exported from their namespace are added to the current namespace. @@ -182,7 +195,7 @@ that points to the exported command in its original namespace; when the new imported command is called, it invokes the exported command. This command normally returns an error if an imported command conflicts with an existing command. -However, if the \-\fBforce\fR option is given, +However, if the \fB\-force\fR option is given, imported commands will silently replace existing commands. The \fBnamespace import\fR command has snapshot semantics: that is, only requested commands that are currently defined @@ -191,8 +204,10 @@ In other words, you can import only the commands that are in a namespace at the time when the \fBnamespace import\fR command is executed. If another command is defined and exported in this namespace later on, it will not be imported. +.RE .TP \fBnamespace inscope\fR \fInamespace\fR \fIscript\fR ?\fIarg ...\fR? +. Executes a script in the context of the specified \fInamespace\fR. This command is not expected to be used directly by programmers; calls to it are generated implicitly when applications @@ -207,15 +222,19 @@ as proper list elements. .CS \fBnamespace inscope ::foo $script $x $y $z\fR .CE +.PP is equivalent to +.PP .CS \fBnamespace eval ::foo [concat $script [list $x $y $z]]\fR .CE +.PP thus additional arguments will not undergo a second round of substitution, as is the case with \fBnamespace eval\fR. .RE .TP \fBnamespace origin \fIcommand\fR +. Returns the fully-qualified name of the original command to which the imported command \fIcommand\fR refers. When a command is imported into a namespace, @@ -230,23 +249,23 @@ If \fIcommand\fR does not refer to an imported command, the command's own fully-qualified name is returned. .TP \fBnamespace parent\fR ?\fInamespace\fR? +. Returns the fully-qualified name of the parent namespace for namespace \fInamespace\fR. If \fInamespace\fR is not specified, the fully-qualified name of the current namespace's parent is returned. .TP \fBnamespace path\fR ?\fInamespaceList\fR? -.\" Should really have the .TP inside the .VS, but that triggers a groff bug -.VS 8.5 +. Returns the command resolution path of the current namespace. If \fInamespaceList\fR is specified as a list of named namespaces, the current namespace's command resolution path is set to those namespaces and returns the empty list. The default command resolution path is always empty. See the section \fBNAME RESOLUTION\fR below for an explanation of the rules regarding name resolution. -.VE 8.5 .TP \fBnamespace qualifiers\fR \fIstring\fR +. Returns any leading namespace qualifiers for \fIstring\fR. Qualifiers are namespace names separated by double colons (\fB::\fR). For the \fIstring\fR \fB::foo::bar::x\fR, @@ -258,6 +277,7 @@ namespace names are, in fact, the names of currently defined namespaces. .TP \fBnamespace tail\fR \fIstring\fR +. Returns the simple name at the end of a qualified string. Qualifiers are namespace names separated by double colons (\fB::\fR). For the \fIstring\fR \fB::foo::bar::x\fR, @@ -267,8 +287,9 @@ This command is the complement of the \fBnamespace qualifiers\fR command. It does not check whether the namespace names are, in fact, the names of currently defined namespaces. .TP -\fBnamespace upvar\fR \fInamespace\fR \fIotherVar myVar \fR?\fIotherVar myVar \fR... -This command arranges for one or more local variables in the current +\fBnamespace upvar\fR \fInamespace\fR ?\fIotherVar myVar \fR... +. +This command arranges for zero or more local variables in the current procedure to refer to variables in \fInamespace\fR. The namespace name is resolved as described in section \fBNAME RESOLUTION\fR. The command @@ -278,9 +299,11 @@ used for qualified namespace or variable names. \fBnamespace upvar\fR returns an empty string. .TP \fBnamespace unknown\fR ?\fIscript\fR? +. Sets or returns the unknown command handler for the current namespace. The handler is invoked when a command called from within the namespace -cannot be found (in either the current namespace or the global namespace). +cannot be found in the current namespace, the namespace's path nor in +the global namespace. The \fIscript\fR argument, if given, should be a well formed list representing a command name and optional arguments. When the handler is invoked, the full invocation line will be appended to the @@ -288,7 +311,8 @@ script and the result evaluated in the context of the namespace. The default handler for all namespaces is \fB::unknown\fR. If no argument is given, it returns the handler for the current namespace. .TP -\fBnamespace which\fR ?\-\fBcommand\fR? ?\-\fBvariable\fR? \fIname\fR +\fBnamespace which\fR ?\fB\-command\fR? ?\fB\-variable\fR? \fIname\fR +. Looks up \fIname\fR as either a command or variable and returns its fully-qualified name. For example, if \fIname\fR does not exist in the current namespace @@ -312,17 +336,19 @@ which we refer to as the \fIglobal namespace\fR. The global namespace holds all global variables and commands. The \fBnamespace eval\fR command lets you create new namespaces. For example, +.PP .CS \fBnamespace eval\fR Counter { - \fBnamespace export\fR bump - variable num 0 + \fBnamespace export\fR bump + variable num 0 - proc bump {} { - variable num - incr num - } + proc bump {} { + variable num + incr num + } } .CE +.PP creates a new namespace containing the variable \fBnum\fR and the procedure \fBbump\fR. The commands and variables in this namespace are separate from @@ -342,23 +368,25 @@ so you can build up the contents of a namespace over time using a series of \fBnamespace eval\fR commands. For example, the following series of commands has the same effect as the namespace definition shown above: +.PP .CS \fBnamespace eval\fR Counter { - variable num 0 - proc bump {} { - variable num - return [incr num] - } + variable num 0 + proc bump {} { + variable num + return [incr num] + } } \fBnamespace eval\fR Counter { - proc test {args} { - return $args - } + proc test {args} { + return $args + } } \fBnamespace eval\fR Counter { - rename test "" + rename test "" } .CE +.PP Note that the \fBtest\fR procedure is added to the \fBCounter\fR namespace, and later removed via the \fBrename\fR command. .PP @@ -390,19 +418,24 @@ you must use some extra syntax. Names must be qualified by the namespace that contains them. From the global namespace, we might access the \fBCounter\fR procedures like this: +.PP .CS Counter::bump 5 Counter::Reset .CE +.PP We could access the current count like this: +.PP .CS puts "count = $Counter::num" .CE +.PP When one namespace contains another, you may need more than one qualifier to reach its elements. If we had a namespace \fBFoo\fR that contained the namespace \fBCounter\fR, you could invoke its \fBbump\fR procedure from the global namespace like this: +.PP .CS Foo::Counter::bump 3 .CE @@ -410,10 +443,13 @@ Foo::Counter::bump 3 You can also use qualified names when you create and rename commands. For example, you could add a procedure to the \fBFoo\fR namespace like this: +.PP .CS proc Foo::Test {args} {return $args} .CE +.PP And you could move the same procedure to another namespace like this: +.PP .CS rename Foo::Test Bar::Test .CE @@ -440,43 +476,46 @@ you mean. However, if the name does not start with a \fB::\fR (i.e., is \fIrelative\fR), Tcl follows basic rules for looking it up: -Variable names are always resolved -by looking first in the current namespace, -and then in the global namespace. -.VS 8.5 -Command names are also always resolved by looking in the current -namespace first. If not found there, they are searched for in every -namespace on the current namespace's command path (which is empty by -default). If not found there, command names are looked up in the -global namespace (or, failing that, are processed by the \fBunknown\fR -command.) -.VE 8.5 -Namespace names, on the other hand, are always resolved -by looking in only the current namespace. +.IP \(bu +\fBVariable names\fR are always resolved by looking first in the current +namespace, and then in the global namespace. +.IP \(bu +\fBCommand names\fR are always resolved by looking in the current namespace +first. If not found there, they are searched for in every namespace on the +current namespace's command path (which is empty by default). If not found +there, command names are looked up in the global namespace (or, failing that, +are processed by the appropriate \fBnamespace unknown\fR handler.) +.IP \(bu +\fBNamespace names\fR are always resolved by looking in only the current +namespace. .PP In the following example, +.PP .CS set traceLevel 0 \fBnamespace eval\fR Debug { - printTrace $traceLevel + printTrace $traceLevel } .CE +.PP Tcl looks for \fBtraceLevel\fR in the namespace \fBDebug\fR and then in the global namespace. It looks up the command \fBprintTrace\fR in the same way. If a variable or command name is not found in either context, the name is undefined. To make this point absolutely clear, consider the following example: +.PP .CS set traceLevel 0 \fBnamespace eval\fR Foo { - variable traceLevel 3 + variable traceLevel 3 - \fBnamespace eval\fR Debug { - printTrace $traceLevel - } + \fBnamespace eval\fR Debug { + printTrace $traceLevel + } } .CE +.PP Here Tcl looks for \fBtraceLevel\fR first in the namespace \fBFoo::Debug\fR. Since it is not found there, Tcl then looks for it in the global namespace. @@ -486,14 +525,18 @@ during the name resolution process. You can use the \fBnamespace which\fR command to clear up any question about name resolution. For example, the command: +.PP .CS \fBnamespace eval\fR Foo::Debug {\fBnamespace which\fR \-variable traceLevel} .CE +.PP returns \fB::traceLevel\fR. On the other hand, the command, +.PP .CS \fBnamespace eval\fR Foo {\fBnamespace which\fR \-variable traceLevel} .CE +.PP returns \fB::Foo::traceLevel\fR. .PP As mentioned above, @@ -531,23 +574,29 @@ that it is a nuisance to type their qualified names. For example, suppose that all of the commands in a package like BLT are contained in a namespace called \fBBlt\fR. Then you might access these commands like this: +.PP .CS Blt::graph .g \-background red Blt::table . .g 0,0 .CE +.PP If you use the \fBgraph\fR and \fBtable\fR commands frequently, you may want to access them without the \fBBlt::\fR prefix. You can do this by importing the commands into the current namespace, like this: +.PP .CS \fBnamespace import\fR Blt::* .CE +.PP This adds all exported commands from the \fBBlt\fR namespace into the current namespace context, so you can write code like this: +.PP .CS graph .g \-background red table . .g 0,0 .CE +.PP The \fBnamespace import\fR command only imports commands from a namespace that that namespace exported with a \fBnamespace export\fR command. @@ -556,9 +605,11 @@ Importing \fIevery\fR command from a namespace is generally a bad idea since you do not know what you will get. It is better to import just the specific commands you need. For example, the command +.PP .CS \fBnamespace import\fR Blt::graph Blt::table .CE +.PP imports only the \fBgraph\fR and \fBtable\fR commands into the current context. .PP @@ -569,57 +620,67 @@ you may want to get around this restriction. You may want to reissue the \fBnamespace import\fR command to pick up new commands that have appeared in a namespace. In that case, you can use the \fB\-force\fR option, and existing commands will be silently overwritten: +.PP .CS \fBnamespace import\fR \-force Blt::graph Blt::table .CE +.PP If for some reason, you want to stop using the imported commands, you can remove them with a \fBnamespace forget\fR command, like this: +.PP .CS \fBnamespace forget\fR Blt::* .CE +.PP This searches the current namespace for any commands imported from \fBBlt\fR. If it finds any, it removes them. Otherwise, it does nothing. After this, the \fBBlt\fR commands must be accessed with the \fBBlt::\fR prefix. .PP When you delete a command from the exporting namespace like this: +.PP .CS rename Blt::graph "" .CE +.PP the command is automatically removed from all namespaces that import it. .SH "EXPORTING COMMANDS" You can export commands from a namespace like this: +.PP .CS \fBnamespace eval\fR Counter { - \fBnamespace export\fR bump reset - variable Num 0 - variable Max 100 + \fBnamespace export\fR bump reset + variable Num 0 + variable Max 100 - proc bump {{by 1}} { - variable Num - incr Num $by - Check - return $Num - } - proc reset {} { - variable Num - set Num 0 - } - proc Check {} { - variable Num - variable Max - if {$Num > $Max} { - error "too high!" - } - } + proc bump {{by 1}} { + variable Num + incr Num $by + Check + return $Num + } + proc reset {} { + variable Num + set Num 0 + } + proc Check {} { + variable Num + variable Max + if {$Num > $Max} { + error "too high!" + } + } } .CE +.PP The procedures \fBbump\fR and \fBreset\fR are exported, so they are included when you import from the \fBCounter\fR namespace, like this: +.PP .CS \fBnamespace import\fR Counter::* .CE +.PP However, the \fBCheck\fR procedure is not exported, so it is ignored by the import operation. .PP @@ -640,13 +701,13 @@ namespace: .PP .CS \fBnamespace eval\fR a { - variable b - proc theTraceCallback { n1 n2 op } { - upvar 1 $n1 var - puts "the value of $n1 has changed to $var" - return - } - trace add variable b write [\fBnamespace code\fR theTraceCallback] + variable b + proc theTraceCallback { n1 n2 op } { + upvar 1 $n1 var + puts "the value of $n1 has changed to $var" + return + } + trace add variable b write [\fBnamespace code\fR theTraceCallback] } set a::b c .CE @@ -658,7 +719,6 @@ the value of a::b has changed to c .CE .SH ENSEMBLES .PP -.VS 8.5 The \fBnamespace ensemble\fR is used to create and manipulate ensemble commands, which are commands formed by grouping subcommands together. The commands typically come from the current namespace when the @@ -672,6 +732,7 @@ namespace is maintained however the ensemble is renamed. Three subcommands of the \fBnamespace ensemble\fR command are defined: .TP \fBnamespace ensemble create\fR ?\fIoption value ...\fR? +. Creates a new ensemble command linked to the current namespace, returning the fully qualified name of the command created. The arguments to \fBnamespace ensemble create\fR allow the configuration @@ -682,12 +743,14 @@ namespace. See the section \fBENSEMBLE OPTIONS\fR below for a full list of options supported and their effects. .TP \fBnamespace ensemble configure \fIcommand\fR ?\fIoption\fR? ?\fIvalue ...\fR? +. Retrieves the value of an option associated with the ensemble command named \fIcommand\fR, or updates some options associated with that ensemble command. See the section \fBENSEMBLE OPTIONS\fR below for a full list of options supported and their effects. .TP \fBnamespace ensemble exists\fR \fIcommand\fR +. Returns a boolean value that describes whether the command \fIcommand\fR exists and is an ensemble command. This command only ever returns an error if the number of arguments to the command is @@ -710,6 +773,7 @@ create\fR and \fBnamespace ensemble configure\fR commands, control how an ensemble command behaves: .TP \fB\-map\fR +. When non-empty, this option supplies a dictionary that provides a mapping from subcommand names to a list of prefix words to substitute in place of the ensemble command and subcommand words (in a manner @@ -720,13 +784,23 @@ name. Note that when this option is non-empty and the \fB\-subcommands\fR option is empty, the ensemble subcommand names will be exactly those words that have mappings in the dictionary. .TP +\fB\-parameters\fR +.VS 8.6 +This option gives a list of named arguments (the names being used during +generation of error messages) that are passed by the caller of the ensemble +between the name of the ensemble and the subcommand argument. By default, it +is the empty list. +.VE 8.6 +.TP \fB\-prefixes\fR +. This option (which is enabled by default) controls whether the ensemble command recognizes unambiguous prefixes of its subcommands. When turned off, the ensemble command requires exact matching of subcommand names. .TP \fB\-subcommands\fR +. When non-empty, this option lists exactly what subcommands are in the ensemble. The mapping for each of those commands will be either whatever is defined in the \fB\-map\fR option, or to the command with the same @@ -737,6 +811,7 @@ of the linked namespace at the time of the invocation of the ensemble command. .TP \fB\-unknown\fR +. When non-empty, this option provides a partial command (to which all the words that are arguments to the ensemble command, including the fully-qualified name of the ensemble, are appended) to handle the case @@ -750,6 +825,7 @@ The following extra option is allowed by \fBnamespace ensemble create\fR: .TP \fB\-command\fR +. This write-only option allows the name of the ensemble created by \fBnamespace ensemble create\fR to be anything in any existing namespace. The default value for this option is the fully-qualified @@ -760,6 +836,7 @@ The following extra option is allowed by \fBnamespace ensemble configure\fR: .TP \fB\-namespace\fR +. This read-only option allows the retrieval of the fully-qualified name of the namespace which the ensemble was created within. .SS "UNKNOWN HANDLER BEHAVIOUR" @@ -811,29 +888,30 @@ error message from \fBTcl_GetIndexFromObj\fR). This is the error that will be thrown when the subcommand is still not recognized during reparsing. It is also an error for an \fB\-unknown\fR handler to delete its namespace. -.VE 8.5 .SH EXAMPLES Create a namespace containing a variable and an exported command: +.PP .CS \fBnamespace eval\fR foo { - variable bar 0 - proc grill {} { - variable bar - puts "called [incr bar] times" - } - \fBnamespace export\fR grill + variable bar 0 + proc grill {} { + variable bar + puts "called [incr bar] times" + } + \fBnamespace export\fR grill } .CE .PP Call the command defined in the previous example in various ways. +.PP .CS # Direct call ::foo::grill # Use the command resolution path to find the name \fBnamespace eval\fR boo { - \fBnamespace path\fR ::foo - grill + \fBnamespace path\fR ::foo + grill } # Import into current namespace, then call local alias @@ -843,23 +921,46 @@ grill # Create two ensembles, one with the default name and one with a # specified name. Then call through the ensembles. \fBnamespace eval\fR foo { - \fBnamespace ensemble\fR create - \fBnamespace ensemble\fR create -command ::foobar + \fBnamespace ensemble\fR create + \fBnamespace ensemble\fR create -command ::foobar } foo grill foobar grill .CE .PP Look up where the command imported in the previous example came from: +.PP .CS puts "grill came from [\fBnamespace origin\fR grill]" .CE .PP Remove all imported commands from the current namespace: +.PP .CS namespace forget {*}[namespace import] .CE +.PP +.VS 8.6 +Create an ensemble for simple working with numbers, using the +\fB\-parameters\fR option to allow the operator to be put between the first +and second arguments. +.PP +.CS +\fBnamespace eval\fR do { + \fBnamespace export\fR * + \fBnamespace ensemble\fR create -parameters x + proc plus {x y} {expr { $x + $y }} + proc minus {x y} {expr { $x - $y }} +} + +# In use, the ensemble works like this: +puts [do 1 plus [do 9 minus 7]] +.CE +.VE 8.6 .SH "SEE ALSO" interp(n), upvar(n), variable(n) .SH KEYWORDS command, ensemble, exported, internal, variable +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/next.n b/doc/next.n new file mode 100644 index 0000000..8eb2ba6 --- /dev/null +++ b/doc/next.n @@ -0,0 +1,203 @@ +'\" +'\" Copyright (c) 2007 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH next n 0.1 TclOO "TclOO Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +next \- invoke superclass method implementations +.SH SYNOPSIS +.nf +package require TclOO + +\fBnext\fR ?\fIarg ...\fR? +\fBnextto\fI class\fR ?\fIarg ...\fR? +.fi +.BE + +.SH DESCRIPTION +.PP +The \fBnext\fR command is used to call implementations of a method by a class, +superclass or mixin that are overridden by the current method. It can only be +used from within a method. It is also used within filters to indicate the +point where a filter calls the actual implementation (the filter may decide to +not go along the chain, and may process the results of going along the chain +of methods as it chooses). The result of the \fBnext\fR command is the result +of the next method in the method chain; if there are no further methods in the +method chain, the result of \fBnext\fR will be an error. The arguments, +\fIarg\fR, to \fBnext\fR are the arguments to pass to the next method in the +chain. +.PP +The \fBnextto\fR command is the same as the \fBnext\fR command, except that it +takes an additional \fIclass\fR argument that identifies a class whose +implementation of the current method chain (see \fBinfo object\fR \fBcall\fR) should +be used; the method implementation selected will be the one provided by the +given class, and it must refer to an existing non-filter invocation that lies +further along the chain than the current implementation. +.SH "THE METHOD CHAIN" +.PP +When a method of an object is invoked, things happen in several stages: +.IP [1] +The structure of the object, its class, superclasses, filters, and mixins, are +examined to build a \fImethod chain\fR, which contains a list of method +implementations to invoke. +.IP [2] +The first method implementation on the chain is invoked. +.IP [3] +If that method implementation invokes the \fBnext\fR command, the next method +implementation is invoked (with its arguments being those that were passed to +\fBnext\fR). +.IP [4] +The result from the overall method call is the result from the outermost +method implementation; inner method implementations return their results +through \fBnext\fR. +.IP [5] +The method chain is cached for future use. +.SS "METHOD SEARCH ORDER" +.PP +When constructing the method chain, method implementations are searched for in +the following order: +.IP [1] +In the object. +.IP [2] +In the classes mixed into the object, in class traversal order. The list of +mixins is checked in natural order. +.IP [3] +In the classes mixed into the classes of the object, with sources of mixing in +being searched in class traversal order. Within each class, the list of mixins +is processed in natural order. +.IP [4] +In the object's class. +.IP [5] +In the superclasses of the class, following each superclass in a depth-first +fashion in the natural order of the superclass list. +.PP +Any particular method implementation always comes as \fIlate\fR in the +resulting list of implementations as possible. +.SS FILTERS +.PP +When an object has a list of filter names set upon it, or is an instance of a +class (or has mixed in a class) that has a list of filter names set upon it, +before every invokation of any method the filters are processed. Filter +implementations are found in class traversal order, as are the lists of filter +names (each of which is traversed in natural list order). Explicitly invoking +a method used as a filter will cause that method to be invoked twice, once as +a filter and once as a normal method. +.PP +Each filter should decide for itself whether to permit the execution to go +forward to the proper implementation of the method (which it does by invoking +the \fBnext\fR command as filters are inserted into the front of the method +call chain) and is responsible for returning the result of \fBnext\fR. +.PP +Filters are not invoked when processing an invokation of the \fBunknown\fR +method because of a failure to locate a method implementation, or when +invoking either constructors or destructors. +.SH EXAMPLES +.PP +This example demonstrates how to use the \fBnext\fR command to call the +(super)class's implementation of a method. The script: +.PP +.CS +oo::class create theSuperclass { + method example {args} { + puts "in the superclass, args = $args" + } +} +oo::class create theSubclass { + superclass theSuperclass + method example {args} { + puts "before chaining from subclass, args = $args" + \fBnext\fR a {*}$args b + \fBnext\fR pureSynthesis + puts "after chaining from subclass" + } +} +theSubclass create obj +oo::define obj method example args { + puts "per-object method, args = $args" + \fBnext\fR x {*}$args y + \fBnext\fR +} +obj example 1 2 3 +.CE +.PP +prints the following: +.PP +.CS +per-object method, args = 1 2 3 +before chaining from subclass, args = x 1 2 3 y +in the superclass, args = a x 1 2 3 y b +in the superclass, args = pureSynthesis +after chaining from subclass +before chaining from subclass, args = +in the superclass, args = a b +in the superclassm args = pureSynthesis +after chaining from subclass +.CE +.PP +This example demonstrates how to build a simple cache class that applies +memoization to all the method calls of the objects it is mixed into, and shows +how it can make a difference to computation times: +.PP +.CS +oo::class create cache { + filter Memoize + method Memoize args { + \fI# Do not filter the core method implementations\fR + if {[lindex [self target] 0] eq "::oo::object"} { + return [\fBnext\fR {*}$args] + } + + \fI# Check if the value is already in the cache\fR + my variable ValueCache + set key [self target],$args + if {[info exist ValueCache($key)]} { + return $ValueCache($key) + } + + \fI# Compute value, insert into cache, and return it\fR + return [set ValueCache($key) [\fBnext\fR {*}$args]] + } + method flushCache {} { + my variable ValueCache + unset ValueCache + \fI# Skip the cacheing\fR + return -level 2 "" + } +} + +oo::object create demo +oo::define demo { + mixin cache + method compute {a b c} { + after 3000 \fI;# Simulate deep thought\fR + return [expr {$a + $b * $c}] + } + method compute2 {a b c} { + after 3000 \fI;# Simulate deep thought\fR + return [expr {$a * $b + $c}] + } +} + +puts [demo compute 1 2 3] \fI\(-> prints "7" after delay\fR +puts [demo compute2 4 5 6] \fI\(-> prints "26" after delay\fR +puts [demo compute 1 2 3] \fI\(-> prints "7" instantly\fR +puts [demo compute2 4 5 6] \fI\(-> prints "26" instantly\fR +puts [demo compute 4 5 6] \fI\(-> prints "34" after delay\fR +puts [demo compute 4 5 6] \fI\(-> prints "34" instantly\fR +puts [demo compute 1 2 3] \fI\(-> prints "7" instantly\fR +demo flushCache +puts [demo compute 1 2 3] \fI\(-> prints "7" after delay\fR +.CE +.SH "SEE ALSO" +oo::class(n), oo::define(n), oo::object(n), self(n) +.SH KEYWORDS +call, method, method chain +.\" Local variables: +.\" mode: nroff +.\" fill-column: 78 +.\" End: diff --git a/doc/object.n b/doc/object.n new file mode 100644 index 0000000..0640580 --- /dev/null +++ b/doc/object.n @@ -0,0 +1,113 @@ +'\" +'\" Copyright (c) 2007-2008 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH object n 0.1 TclOO "TclOO Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +oo::object \- root class of the class hierarchy +.SH SYNOPSIS +.nf +package require TclOO + +\fBoo::object\fI method \fR?\fIarg ...\fR? +.fi +.SH "CLASS HIERARCHY" +.nf +\fBoo::object\fR +.fi +.BE +.SH DESCRIPTION +.PP +The \fBoo::object\fR class is the root class of the object hierarchy; every +object is an instance of this class. Since classes are themselves objects, +they are instances of this class too. Objects are always referred to by their +name, and may be \fBrename\fRd while maintaining their identity. +.PP +Instances of objects may be made with either the \fBcreate\fR or \fBnew\fR +methods of the \fBoo::object\fR object itself, or by invoking those methods on +any of the subclass objects; see \fBoo::class\fR for more details. The +configuration of individual objects (i.e., instance-specific methods, mixed-in +classes, etc.) may be controlled with the \fBoo::objdefine\fR command. +.PP +Each object has a unique namespace associated with it, the instance namespace. +This namespace holds all the instance variables of the object, and will be the +current namespace whenever a method of the object is invoked (including a +method of the class of the object). When the object is destroyed, its instance +namespace is deleted. The instance namespace contains the object's \fBmy\fR +command, which may be used to invoke non-exported methods of the object or to +create a reference to the object for the purpose of invokation which persists +across renamings of the object. +.SS CONSTRUCTOR +The \fBoo::object\fR class does not define an explicit constructor. +.SS DESTRUCTOR +The \fBoo::object\fR class does not define an explicit destructor. +.SS "EXPORTED METHODS" +The \fBoo::object\fR class supports the following exported methods: +.TP +\fIobj \fBdestroy\fR +. +This method destroys the object, \fIobj\fR, that it is invoked upon, invoking +any destructors on the object's class in the process. It is equivalent to +using \fBrename\fR to delete the object command. The result of this method is +always the empty string. +.SS "NON-EXPORTED METHODS" +.PP +The \fBoo::object\fR class supports the following non-exported methods: +.TP +\fIobj \fBeval\fR ?\fIarg ...\fR? +. +This method concatenates the arguments, \fIarg\fR, as if with \fBconcat\fR, +and then evaluates the resulting script in the namespace that is uniquely +associated with \fIobj\fR, returning the result of the evaluation. +.TP +\fIobj \fBunknown \fImethodName\fR ?\fIarg ...\fR? +. +This method is called when an attempt to invoke the method \fImethodName\fR on +object \fIobj\fR fails. The arguments that the user supplied to the method are +given as \fIarg\fR argments. The default implementation (i.e. the one defined +by the \fBoo::object\fR class) generates a suitable error, detailing what +methods the object supports given whether the object was invoked by its public +name or through the \fBmy\fR command. +.TP +\fIobj \fBvariable \fR?\fIvarName ...\fR? +. +This method arranges for each variable called \fIvarName\fR to be linked from +the object \fIobj\fR's unique namespace into the caller's context. Thus, if it +is invoked from inside a procedure then the namespace variable in the object +is linked to the local variable in the procedure. Each \fIvarName\fR argument +must not have any namespace separators in it. The result is the empty string. +.TP +\fIobj \fBvarname \fIvarName\fR +. +This method returns the globally qualified name of the variable \fIvarName\fR +in the unique namespace for the object \fIobj\fR. +.SH EXAMPLES +.PP +This example demonstrates basic use of an object. +.PP +.CS +set obj [\fBoo::object\fR new] +$obj foo \fI\(-> error "unknown method foo"\fR +oo::objdefine $obj method foo {} { + my \fBvariable\fR count + puts "bar[incr count]" +} +$obj foo \fI\(-> prints "bar1"\fR +$obj foo \fI\(-> prints "bar2"\fR +$obj variable count \fI\(-> error "unknown method variable"\fR +$obj \fBdestroy\fR +$obj foo \fI\(-> error "unknown command obj"\fR +.CE +.SH "SEE ALSO" +my(n), oo::class(n) +.SH KEYWORDS +base class, class, object, root class +.\" Local variables: +.\" mode: nroff +.\" fill-column: 78 +.\" End: @@ -34,73 +34,84 @@ The \fIaccess\fR argument, if present, indicates the way in which the file In the first form \fIaccess\fR may have any of the following values: .TP 15 \fBr\fR +. Open the file for reading only; the file must already exist. This is the default value if \fIaccess\fR is not specified. .TP 15 \fBr+\fR +. Open the file for both reading and writing; the file must already exist. .TP 15 \fBw\fR +. Open the file for writing only. Truncate it if it exists. If it does not exist, create a new file. .TP 15 \fBw+\fR +. Open the file for reading and writing. Truncate it if it exists. If it does not exist, create a new file. .TP 15 \fBa\fR +. Open the file for writing only. If the file does not exist, create a new empty file. Set the file pointer to the end of the file prior to each write. .TP 15 \fBa+\fR +. Open the file for reading and writing. If the file does not exist, create a new empty file. Set the initial access position to the end of the file. -.VS 8.5 .PP All of the legal \fIaccess\fR values above may have the character \fBb\fR added as the second or third character in the value to -indicate that the opened channel should be configured with the -\fB\-translation binary\fR option, making the channel suitable for +indicate that the opened channel should be configured as if with the +\fBfconfigure\fR \fB\-translation binary\fR option, making the channel suitable for reading or writing of binary data. -.VE 8.5 .PP In the second form, \fIaccess\fR consists of a list of any of the following flags, all of which have the standard POSIX meanings. One of the flags must be either \fBRDONLY\fR, \fBWRONLY\fR or \fBRDWR\fR. .TP 15 \fBRDONLY\fR +. Open the file for reading only. .TP 15 \fBWRONLY\fR +. Open the file for writing only. .TP 15 \fBRDWR\fR +. Open the file for both reading and writing. .TP 15 \fBAPPEND\fR +. Set the file pointer to the end of the file prior to each write. -.VS 8.5 .TP 15 \fBBINARY\fR +. Configure the opened channel with the \fB\-translation binary\fR option. -.VE 8.5 .TP 15 \fBCREAT\fR +. Create the file if it does not already exist (without this flag it is an error for the file not to exist). .TP 15 \fBEXCL\fR +. If \fBCREAT\fR is also specified, an error is returned if the file already exists. .TP 15 \fBNOCTTY\fR +. If the file is a terminal device, this flag prevents the file from becoming the controlling terminal of the process. .TP 15 \fBNONBLOCK\fR +. Prevents the process from blocking while opening the file, and possibly in subsequent I/O operations. The exact behavior of this flag is system- and device-dependent; its use is discouraged @@ -110,6 +121,7 @@ For details refer to your system documentation on the \fBopen\fR system call's \fBO_NONBLOCK\fR flag. .TP 15 \fBTRUNC\fR +. If the file exists it is truncated to zero length. .PP If a new file is created as part of opening it, \fIpermissions\fR @@ -119,7 +131,7 @@ conjunction with the process's file mode creation mask. .SH "COMMAND PIPELINES" .PP If the first character of \fIfileName\fR is -.QW | +.QW \fB|\fR then the remaining characters of \fIfileName\fR are treated as a list of arguments that describe a command pipeline to invoke, in the same style as the @@ -127,10 +139,12 @@ arguments for \fBexec\fR. In this case, the channel identifier returned by \fBopen\fR may be used to write to the command's input pipe or read from its output pipe, depending on the value of \fIaccess\fR. -If write-only access is used (e.g. \fIaccess\fR is \fBw\fR), then -standard output for the pipeline is directed to the current standard +If write-only access is used (e.g. \fIaccess\fR is +.QW \fBw\fR ), +then standard output for the pipeline is directed to the current standard output unless overridden by the command. -If read-only access is used (e.g. \fIaccess\fR is \fBr\fR), +If read-only access is used (e.g. \fIaccess\fR is +.QW \fBr\fR ), standard input for the pipeline is taken from the current standard input unless overridden by the command. The id of the spawned process is accessible through the \fBpid\fR @@ -156,6 +170,7 @@ The \fBfconfigure\fR command can be used to query and set additional configuration options specific to serial ports (where supported): .TP \fB\-mode\fR \fIbaud\fB,\fIparity\fB,\fIdata\fB,\fIstop\fR +. This option is a set of 4 comma-separated values: the baud rate, parity, number of data bits, and number of stop bits for this serial port. The \fIbaud\fR rate is a simple integer that specifies the connection speed. @@ -172,6 +187,7 @@ data bits and should be an integer from 5 to 8, while \fIstop\fR is the number of stop bits and should be the integer 1 or 2. .TP \fB\-handshake\fR \fItype\fR +. (Windows and Unix). This option is used to setup automatic handshake control. Note that not all handshake types maybe supported by your operating system. The \fItype\fR parameter is case-independent. @@ -189,11 +205,13 @@ The \fB\-handshake\fR option cannot be queried. .RE .TP \fB\-queue\fR +. (Windows and Unix). The \fB\-queue\fR option can only be queried. It returns a list of two integers representing the current number of bytes in the input and output queue respectively. .TP \fB\-timeout\fR \fImsec\fR +. (Windows and Unix). This option is used to set the timeout for blocking read operations. It specifies the maximum interval between the reception of two bytes in milliseconds. @@ -203,6 +221,7 @@ nonblocking reads. This option cannot be queried. .TP \fB\-ttycontrol\fR \fI{signal boolean signal boolean ...}\fR +. (Windows and Unix). This option is used to setup the handshake output lines (see below) permanently or to send a BREAK over the serial line. The \fIsignal\fR names are case-independent. @@ -215,6 +234,7 @@ The result is unpredictable. The \fB\-ttycontrol\fR option cannot be queried. .TP \fB\-ttystatus\fR +. (Windows and Unix). The \fB\-ttystatus\fR option can only be queried. It returns the current modem status and handshake input signals (see below). @@ -223,12 +243,14 @@ e.g. \fB{CTS 1 DSR 0 RING 1 DCD 0}\fR. The \fIsignal\fR names are returned upper case. .TP \fB\-xchar\fR \fI{xonChar xoffChar}\fR +. (Windows and Unix). This option is used to query or change the software handshake characters. Normally the operating system default should be DC1 (0x11) and DC3 (0x13) representing the ASCII standard XON and XOFF characters. .TP \fB\-pollinterval\fR \fImsec\fR +. (Windows only). This option is used to set the maximum time between polling for fileevents. This affects the time interval between checking for events throughout the Tcl @@ -239,6 +261,7 @@ you want to poll the serial port more or less often than 10 msec \fB\-sysbuffer\fR \fIinSize\fR .TP \fB\-sysbuffer\fR \fI{inSize outSize}\fR +. (Windows only). This option is used to change the size of Windows system buffers for a serial channel. Especially at higher communication rates the default input buffer size of 4096 bytes can overrun @@ -246,10 +269,11 @@ for latent systems. The first form specifies the input buffer size, in the second form both input and output buffers are defined. .TP \fB\-lasterror\fR +. (Windows only). This option is query only. In case of a serial communication error, \fBread\fR or \fBputs\fR returns a general Tcl file I/O error. -\fBfconfigure -lasterror\fR can be called to get a list of error details. +\fBfconfigure\fR \fB\-lasterror\fR can be called to get a list of error details. See below for an explanation of the various error codes. .SH "SERIAL PORT SIGNALS" .PP @@ -261,29 +285,29 @@ lines and handshaking. Here we are using the terms \fIworkstation\fR for your computer and \fImodem\fR for the external device, because some signal names (DCD, RI) come from modems. Of course your external device may use these signal lines for other purposes. -.IP \fBTXD(output)\fR +.IP \fBTXD\fR(output) \fBTransmitted Data:\fR Outgoing serial data. -.IP \fBRXD(input)\fR +.IP \fBRXD\fR(input) \fBReceived Data:\fRIncoming serial data. -.IP \fBRTS(output)\fR +.IP \fBRTS\fR(output) \fBRequest To Send:\fR This hardware handshake line informs the modem that your workstation is ready to receive data. Your workstation may automatically reset this signal to indicate that the input buffer is full. -.IP \fBCTS(input)\fR +.IP \fBCTS\fR(input) \fBClear To Send:\fR The complement to RTS. Indicates that the modem is ready to receive data. -.IP \fBDTR(output)\fR +.IP \fBDTR\fR(output) \fBData Terminal Ready:\fR This signal tells the modem that the workstation is ready to establish a link. DTR is often enabled automatically whenever a serial port is opened. -.IP \fBDSR(input)\fR +.IP \fBDSR\fR(input) \fBData Set Ready:\fR The complement to DTR. Tells the workstation that the modem is ready to establish a link. -.IP \fBDCD(input)\fR +.IP \fBDCD\fR(input) \fBData Carrier Detect:\fR This line becomes active when a modem detects a .QW Carrier signal. -.IP \fBRI(input)\fR +.IP \fBRI\fR(input) \fBRing Indicator:\fR Goes active when the modem detects an incoming call. .IP \fBBREAK\fR A BREAK condition is not a hardware signal line, but a logical zero on the @@ -299,39 +323,46 @@ event polling in background. The external device may have been switched off, the data lines may be noisy, system buffers may overrun or your mode settings may be wrong. That is why a reliable software should always \fBcatch\fR serial read operations. In cases of an error Tcl returns a -general file I/O error. Then \fBfconfigure -lasterror\fR may help to +general file I/O error. Then \fBfconfigure\fR \fB\-lasterror\fR may help to locate the problem. The following error codes may be returned. .TP 10 \fBRXOVER\fR +. Windows input buffer overrun. The data comes faster than your scripts reads -it or your system is overloaded. Use \fBfconfigure -sysbuffer\fR to avoid a +it or your system is overloaded. Use \fBfconfigure\fR \fB\-sysbuffer\fR to avoid a temporary bottleneck and/or make your script faster. .TP 10 \fBTXFULL\fR +. Windows output buffer overrun. Complement to RXOVER. This error should practically not happen, because Tcl cares about the output buffer status. .TP 10 \fBOVERRUN\fR +. UART buffer overrun (hardware) with data lost. The data comes faster than the system driver receives it. Check your advanced serial port settings to enable the FIFO (16550) buffer and/or setup a lower(1) interrupt threshold value. .TP 10 \fBRXPARITY\fR +. A parity error has been detected by your UART. -Wrong parity settings with \fBfconfigure -mode\fR or a noisy data line (RXD) +Wrong parity settings with \fBfconfigure\fR \fB\-mode\fR or a noisy data line (RXD) may cause this error. .TP 10 \fBFRAME\fR +. A stop-bit error has been detected by your UART. -Wrong mode settings with \fBfconfigure -mode\fR or a noisy data line (RXD) +Wrong mode settings with \fBfconfigure\fR \fB\-mode\fR or a noisy data line (RXD) may cause this error. .TP 10 \fBBREAK\fR +. A BREAK condition has been detected by your UART (see above). .SH "PORTABILITY ISSUES" .TP \fBWindows \fR(all versions) +. Valid values for \fIfileName\fR to open a serial port are of the form \fBcom\fIX\fB:\fR, where \fIX\fR is a number, generally from 1 to 4. This notation only works for serial ports from 1 to 9, if the system @@ -342,6 +373,7 @@ where X is any number that corresponds to a serial port; please note that this method is considerably slower on Windows 95 and Windows 98. .TP \fBWindows NT\fR +. When running Tcl interactively, there may be some strange interactions between the real console, if one is present, and a command pipeline that uses standard input or output. If a command pipeline is opened for reading, some @@ -357,6 +389,7 @@ standard input or output, but is redirected from or to a file, then the above problems do not occur. .TP \fBWindows 95\fR +. A command pipeline that executes a 16-bit DOS application cannot be opened for both reading and writing, since 16-bit DOS applications that receive standard input from a pipe and send standard output to a pipe run @@ -388,6 +421,7 @@ applications are run synchronously, as described above. .RE .TP \fBUnix\fR\0\0\0\0\0\0\0 +. Valid values for \fIfileName\fR to open a serial port are generally of the form \fB/dev/tty\fIX\fR, where \fIX\fR is \fBa\fR or \fBb\fR, but the name of any pseudo-file that maps to a serial port may be used. @@ -410,7 +444,9 @@ See the \fBPORTABILITY ISSUES\fR section of the \fBexec\fR command for additional information not specific to command pipelines about executing applications on the various platforms .SH "EXAMPLE" +.PP Open a command pipeline and catch any errors: +.PP .CS set fl [\fBopen\fR "| ls this_file_does_not_exist"] set data [read $fl] @@ -424,3 +460,6 @@ puts(n), exec(n), pid(n), fopen(3) .SH KEYWORDS access mode, append, create, file, non-blocking, open, permissions, pipeline, process, serial +'\"Local Variables: +'\"mode: nroff +'\"End: diff --git a/doc/package.n b/doc/package.n index d4fe657..6cf8991 100644 --- a/doc/package.n +++ b/doc/package.n @@ -12,7 +12,7 @@ package \- Facilities for package loading and version control .SH SYNOPSIS .nf -\fBpackage forget ?\fIpackage package ...\fR? +\fBpackage forget\fR ?\fIpackage package ...\fR? \fBpackage ifneeded \fIpackage version\fR ?\fIscript\fR? \fBpackage names\fR \fBpackage present \fIpackage \fR?\fIrequirement...\fR? @@ -27,7 +27,6 @@ package \- Facilities for package loading and version control \fBpackage prefer \fR?\fBlatest\fR|\fBstable\fR? .fi .BE - .SH DESCRIPTION .PP This command keeps a simple database of the packages available for @@ -44,12 +43,14 @@ primarily by system scripts that maintain the package database. The behavior of the \fBpackage\fR command is determined by its first argument. The following forms are permitted: .TP -\fBpackage forget ?\fIpackage package ...\fR? +\fBpackage forget\fR ?\fIpackage package ...\fR? +. Removes all information about each specified package from this interpreter, including information provided by both \fBpackage ifneeded\fR and \fBpackage provide\fR. .TP \fBpackage ifneeded \fIpackage version\fR ?\fIscript\fR? +. This command typically appears only in system configuration scripts to set up the package database. It indicates that a particular version of @@ -71,6 +72,7 @@ or an empty string if no \fBpackage ifneeded\fR command has been invoked for this \fIpackage\fR and \fIversion\fR. .TP \fBpackage names\fR +. Returns a list of the names of all packages in the interpreter for which a version has been provided (via \fBpackage provide\fR) or for which a \fBpackage ifneeded\fR @@ -83,6 +85,7 @@ This command is equivalent to \fBpackage require\fR except that it does not try and load the package if it is not already loaded. .TP \fBpackage provide \fIpackage \fR?\fIversion\fR? +. This command is invoked to indicate that version \fIversion\fR of package \fIpackage\fR is now present in the interpreter. It is typically invoked once as part of an \fBifneeded\fR script, @@ -94,7 +97,8 @@ returns the version number that is currently provided, or an empty string if no \fBpackage provide\fR command has been invoked for \fIpackage\fR in this interpreter. .TP -\fBpackage require\fR \fIpackage \fR?\fIrequirement...\fR? +\fBpackage require \fR\fIpackage \fR?\fIrequirement...\fR? +. This command is typically invoked by Tcl code that wishes to use a particular version of a particular package. The arguments indicate which package is wanted, and the command ensures that @@ -140,11 +144,13 @@ package, then the command returns an error. .RE .TP \fBpackage require \-exact \fIpackage version\fR +. This form of the command is used when only the given \fIversion\fR of \fIpackage\fR is acceptable to the caller. This command is equivalent to \fBpackage require \fIpackage version\fR-\fIversion\fR. .TP \fBpackage unknown \fR?\fIcommand\fR? +. This command supplies a .QW "last resort" command to invoke during @@ -166,30 +172,36 @@ If \fIcommand\fR is specified as an empty string, then the current \fBpackage unknown\fR script is removed, if there is one. .TP \fBpackage vcompare \fIversion1 version2\fR +. Compares the two version numbers given by \fIversion1\fR and \fIversion2\fR. Returns -1 if \fIversion1\fR is an earlier version than \fIversion2\fR, -0 if they are equal, and 1 if \fIversion1\fR is later than \fBversion2\fR. +0 if they are equal, and 1 if \fIversion1\fR is later than \fIversion2\fR. .TP \fBpackage versions \fIpackage\fR +. Returns a list of all the version numbers of \fIpackage\fR for which information has been provided by \fBpackage ifneeded\fR commands. .TP \fBpackage vsatisfies \fIversion requirement...\fR +. Returns 1 if the \fIversion\fR satisfies at least one of the given requirements, and 0 otherwise. Each \fIrequirement\fR is allowed to have any of the forms: .RS .TP min +. This form is called .QW min-bounded . .TP min- +. This form is called .QW min-unbound . .TP min-max +. This form is called .QW bounded . .RE @@ -328,8 +340,10 @@ Once you have done this, packages will be loaded automatically in response to \fBpackage require\fR commands. See the documentation for \fBpkg_mkIndex\fR for details. .SH EXAMPLES +.PP To state that a Tcl script requires the Tk and http packages, put this at the top of the script: +.PP .CS \fBpackage require\fR Tk \fBpackage require\fR http @@ -338,15 +352,19 @@ at the top of the script: To test to see if the Snack package is available and load if it is (often useful for optional enhancements to programs where the loss of the functionality is not critical) do this: +.PP .CS if {[catch {\fBpackage require\fR Snack}]} { - # Error thrown - package not found. - # Set up a dummy interface to work around the absence + # Error thrown - package not found. + # Set up a dummy interface to work around the absence } else { - # We have the package, configure the app to use it + # We have the package, configure the app to use it } .CE .SH "SEE ALSO" msgcat(n), packagens(n), pkgMkIndex(n) .SH KEYWORDS package, version +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/packagens.n b/doc/packagens.n index 1220b20..30617a3 100644 --- a/doc/packagens.n +++ b/doc/packagens.n @@ -9,7 +9,7 @@ .SH NAME pkg::create \- Construct an appropriate 'package ifneeded' command for a given package specification .SH SYNOPSIS -\fB::pkg::create \fI\-name packageName\fR \fI\-version packageVersion\fR ?\fI\-load filespec\fR? ... ?\fI\-source filespec\fR? ... +\fB::pkg::create\fR \fB\-name \fIpackageName \fB\-version \fIpackageVersion\fR ?\fB\-load \fIfilespec\fR? ... ?\fB\-source \fIfilespec\fR? ... .BE .SH DESCRIPTION @@ -22,13 +22,13 @@ command for a given package specification. It can be used to construct a .SH OPTIONS The parameters supported are: .TP -\fB\-name\fR\0\fIpackageName\fR +\fB\-name \fIpackageName\fR This parameter specifies the name of the package. It is required. .TP -\fB\-version\fR\0\fIpackageVersion\fR +\fB\-version \fIpackageVersion\fR This parameter specifies the version of the package. It is required. .TP -\fB\-load\fR\0\fIfilespec\fR +\fB\-load \fIfilespec\fR This parameter specifies a binary library that must be loaded with the \fBload\fR command. \fIfilespec\fR is a list with two elements. The first element is the name of the file to load. The second, optional @@ -37,7 +37,7 @@ list of procedures is empty or omitted, \fB::pkg::create\fR will set up the library for direct loading (see \fBpkg_mkIndex\fR). Any number of \fB\-load\fR parameters may be specified. .TP -\fB\-source\fR\0\fIfilespec\fR +\fB\-source \fIfilespec\fR This parameter is similar to the \fB\-load\fR parameter, except that it specifies a Tcl library that must be loaded with the \fBsource\fR command. Any number of \fB\-source\fR parameters may be diff --git a/doc/pkgMkIndex.n b/doc/pkgMkIndex.n index 5895407..2753208 100644 --- a/doc/pkgMkIndex.n +++ b/doc/pkgMkIndex.n @@ -12,7 +12,7 @@ pkg_mkIndex \- Build an index for automatic loading of packages .SH SYNOPSIS .nf -\fBpkg_mkIndex ?\fI\-direct\fR? ?\fI\-lazy\fR? ?\fI\-load pkgPat\fR? ?\fI\-verbose\fR? \fIdir\fR ?\fIpattern pattern ...\fR? +\fBpkg_mkIndex\fR ?\fIoptions...\fR? \fIdir\fR ?\fIpattern pattern ...\fR? .fi .BE .SH DESCRIPTION @@ -112,7 +112,7 @@ The index process will pre-load any packages that exist in the current interpreter and match \fIpkgPat\fR into the slave interpreter used to generate the index. The pattern match uses string match rules, but without making case distinctions. -See COMPLEX CASES below. +See \fBCOMPLEX CASES\fR below. .TP 15 \fB\-verbose\fR Generate output during the indexing process. Output is via @@ -153,7 +153,7 @@ commands for each version of each available package; these commands invoke \fBpackage provide\fR commands to announce the availability of the package, and they setup auto-loader information to load the files of the package. -If the \fI\-lazy\fR flag was provided when the \fBpkgIndex.tcl\fR +If the \fB\-lazy\fR flag was provided when the \fBpkgIndex.tcl\fR was generated, a given file of a given version of a given package is not actually loaded until the first time one of its commands @@ -168,7 +168,7 @@ commands or those which require special initialization, might select that their package files be loaded immediately upon \fBpackage require\fR instead of delaying the actual loading to the first use of one of the package's command. This is the default mode when generating the package -index. It can be overridden by specifying the \fI\-lazy\fR argument. +index. It can be overridden by specifying the \fB\-lazy\fR argument. .SH "COMPLEX CASES" Most complex cases of dependencies among scripts and binary files, and packages being split among scripts and @@ -228,3 +228,6 @@ the binary file may mask the package defined by the scripts. package(n) .SH KEYWORDS auto-load, index, package, version +'\"Local Variables: +'\"mode: nroff +'\"End: diff --git a/doc/prefix.n b/doc/prefix.n new file mode 100644 index 0000000..eb79996 --- /dev/null +++ b/doc/prefix.n @@ -0,0 +1,116 @@ +'\" +'\" Copyright (c) 2008 Peter Spjuth <pspjuth@users.sourceforge.net> +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH prefix n 8.6 Tcl "Tcl Built-In Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +tcl::prefix \- facilities for prefix matching +.SH SYNOPSIS +.nf +\fB::tcl::prefix all\fR \fItable\fR \fIstring\fR +\fB::tcl::prefix longest\fR \fItable\fR \fIstring\fR +\fB::tcl::prefix match\fR \fI?option ...?\fR \fItable\fR \fIstring\fR +.fi +.BE +.SH DESCRIPTION +.PP +This document describes commands looking up a prefix in a list of strings. +The following commands are supported: +.TP +\fB::tcl::prefix all\fR \fItable\fR \fIstring\fR +. +Returns a list of all elements in \fItable\fR that begin with the prefix +\fIstring\fR. +.TP +\fB::tcl::prefix longest\fR \fItable\fR \fIstring\fR +. +Returns the longest common prefix of all elements in \fItable\fR that +begin with the prefix \fIstring\fR. +.TP +\fB::tcl::prefix match\fR ?\fIoptions\fR? \fItable\fR \fIstring\fR +. +If \fIstring\fR equals one element in \fItable\fR or is a prefix to exactly +one element, the matched element is returned. If not, the result depends +on the \fB\-error\fR option. (It is recommended that the \fItable\fR be sorted +before use with this subcommand, so that the list of matches presented in the +error message also becomes sorted, though this is not strictly necessary for +the operation of this subcommand itself.) +.RS +.TP +\fB\-exact\fR\0 +. +Accept only exact matches. +.TP +\fB\-message\0\fIstring\fR +. +Use \fIstring\fR in the error message at a mismatch. Default is +.QW option . +.TP +\fB\-error\0\fIoptions\fR +. +The \fIoptions\fR are used when no match is found. If \fIoptions\fR is empty, +no error is generated and an empty string is returned. Otherwise the +\fIoptions\fR are used as \fBreturn\fR options when generating the error +message. The default corresponds to setting +.QW "\-level 0" . +Example: If +.QW "\fB\-error\fR {\-errorcode MyError \-level 1}" +is used, an error would be generated as: +.RS +.PP +.CS +return \-errorcode MyError \-level 1 \-code error \e + "ambiguous option ..." +.CE +.RE +.RE +.SH "EXAMPLES" +.PP +Basic use: +.PP +.CS +namespace import ::tcl::prefix +\fBprefix match\fR {apa bepa cepa} apa + \fI\(-> apa\fR +\fBprefix match\fR {apa bepa cepa} a + \fI\(-> apa\fR +\fBprefix match\fR \-exact {apa bepa cepa} a + \fI\(-> bad option "a": must be apa, bepa, or cepa\fR +\fBprefix match\fR \-message "switch" {apa ada bepa cepa} a + \fI\(-> ambiguous switch "a": must be apa, ada, bepa, or cepa\fR +\fBprefix longest\fR {fblocked fconfigure fcopy file fileevent flush} fc + \fI\(-> fco\fR +\fBprefix all\fR {fblocked fconfigure fcopy file fileevent flush} fc + \fI\(-> fconfigure fcopy\fR +.CE +.PP +Simplifying option matching: +.PP +.CS +array set opts {\-apa 1 \-bepa "" \-cepa 0} +foreach {arg val} $args { + set opts([\fBprefix match\fR {\-apa \-bepa \-cepa} $arg]) $val +} +.CE +.PP +Creating a \fBswitch\fR that supports prefixes: +.PP +.CS +switch [\fBprefix match\fR {apa bepa cepa} $arg] { + apa { } + bepa { } + cepa { } +} +.CE +.SH "SEE ALSO" +lsearch(n), namespace(n), string(n), Tcl_GetIndexFromObj(3) +.SH "KEYWORDS" +prefix, table lookup +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -14,7 +14,6 @@ proc \- Create a Tcl procedure .SH SYNOPSIS \fBproc \fIname args body\fR .BE - .SH DESCRIPTION .PP The \fBproc\fR command creates a new Tcl procedure named @@ -65,6 +64,12 @@ deleted when the procedure returns. One local variable is automatically created for each of the procedure's arguments. Other variables can only be accessed by invoking one of the \fBglobal\fR, \fBvariable\fR, \fBupvar\fR or \fBnamespace upvar\fR commands. +The current namespace when \fIbody\fR is executed will be the +namespace that the procedure's name exists in, which will be the +namespace that itwas created in unless it has been changed with +\fBrename\fR. +'\" We may change this! It makes [variable] unstable when renamed and is +'\" frankly pretty crazy, but doing it right is harder than it looks. .PP The \fBproc\fR command returns an empty string. When a procedure is invoked, the procedure's return value is the value specified in a @@ -74,28 +79,32 @@ executed in the procedure's body. If an error occurs while executing the procedure body, then the procedure-as-a-whole will return that same error. .SH EXAMPLES +.PP This is a procedure that accepts arbitrarily many arguments and prints them out, one by one. +.PP .CS \fBproc\fR printArguments args { - foreach arg $args { - puts $arg - } + foreach arg $args { + puts $arg + } } .CE .PP This procedure is a bit like the \fBincr\fR command, except it multiplies the contents of the named variable by the value, which defaults to \fB2\fR: +.PP .CS \fBproc\fR mult {varName {multiplier 2}} { - upvar 1 $varName var - set var [expr {$var * $multiplier}] + upvar 1 $varName var + set var [expr {$var * $multiplier}] } .CE - .SH "SEE ALSO" info(n), unknown(n) - .SH KEYWORDS argument, procedure +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -14,7 +14,6 @@ puts \- Write to a channel .SH SYNOPSIS \fBputs \fR?\fB\-nonewline\fR? ?\fIchannelId\fR? \fIstring\fR .BE - .SH DESCRIPTION .PP Writes the characters given by \fIstring\fR to the channel given @@ -64,33 +63,36 @@ be used in an event-driven fashion with the \fBfileevent\fR command (do not invoke \fBputs\fR unless you have recently been notified via a file event that the channel is ready for more output data). .SH EXAMPLES +.PP Write a short message to the console (or wherever \fBstdout\fR is directed): +.PP .CS \fBputs\fR "Hello, World!" .CE .PP Print a message in several parts: +.PP .CS \fBputs\fR -nonewline "Hello, " \fBputs\fR "World!" .CE .PP Print a message to the standard error channel: +.PP .CS \fBputs\fR stderr "Hello, World!" .CE .PP Append a log message to a file: +.PP .CS set chan [open my.log a] set timestamp [clock format [clock seconds]] \fBputs\fR $chan "$timestamp - Hello, World!" close $chan .CE - .SH "SEE ALSO" file(n), fileevent(n), Tcl_StandardChannels(3) - .SH KEYWORDS channel, newline, output, write @@ -14,17 +14,18 @@ pwd \- Return the absolute path of the current working directory .SH SYNOPSIS \fBpwd\fR .BE - .SH DESCRIPTION .PP Returns the absolute path name of the current working directory. .SH EXAMPLE +.PP Sometimes it is useful to change to a known directory when running some external command using \fBexec\fR, but it is important to keep the application usually running in the directory that it was started in (unless the user specifies otherwise) since that minimizes user confusion. The way to do this is to save the current directory while the external command is being run: +.PP .CS set tarFile [file normalize somefile.tar] set savedDir [\fBpwd\fR] @@ -34,6 +35,5 @@ cd $savedDir .CE .SH "SEE ALSO" file(n), cd(n), glob(n), filename(n) - .SH KEYWORDS working directory diff --git a/doc/re_syntax.n b/doc/re_syntax.n index 8701641..dacc41f 100644 --- a/doc/re_syntax.n +++ b/doc/re_syntax.n @@ -6,6 +6,8 @@ '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" .so man.macros +.ie '\w'o''\w'\C'^o''' .ds qo \C'^o' +.el .ds qo u .TH re_syntax n "8.1" Tcl "Tcl Built-In Commands" .BS .SH NAME @@ -290,12 +292,12 @@ treatment is as if the enclosing delimiters were .QW \fB[.\fR \& and .QW \fB.]\fR .) -For example, if \fBo\fR and \fB\N'244'\fR are the members of an +For example, if \fBo\fR and \fB\*(qo\fR are the members of an equivalence class, then .QW \fB[[=o=]]\fR , -.QW \fB[[=\N'244'=]]\fR , +.QW \fB[[=\*(qo=]]\fR , and -.QW \fB[o\N'244']\fR \& +.QW \fB[o\*(qo]\fR \& are all synonymous. An equivalence class may not be an endpoint of a range. .RS .PP @@ -359,39 +361,42 @@ horizontal tab, as in C .TP \fB\eu\fIwxyz\fR . -(where \fIwxyz\fR is exactly four hexadecimal digits) the Unicode +(where \fIwxyz\fR is one up to four hexadecimal digits) the Unicode character \fBU+\fIwxyz\fR in the local byte ordering .TP \fB\eU\fIstuvwxyz\fR . -(where \fIstuvwxyz\fR is exactly eight hexadecimal digits) reserved -for a somewhat-hypothetical Unicode extension to 32 bits +(where \fIstuvwxyz\fR is one up to eight hexadecimal digits) reserved +for a Unicode extension up to 21 bits. The digits are parsed until the +first non-hexadecimal character is encountered, the maximun of eight +hexadecimal digits are reached, or an overflow would occur in the maximum +value of \fBU+\fI10ffff\fR. .TP \fB\ev\fR . vertical tab, as in C are all available. .TP -\fB\ex\fIhhh\fR +\fB\ex\fIhh\fR . -(where \fIhhh\fR is any sequence of hexadecimal digits) the character -whose hexadecimal value is \fB0x\fIhhh\fR (a single character no -matter how many hexadecimal digits are used). +(where \fIhh\fR is one or two hexadecimal digits) the character +whose hexadecimal value is \fB0x\fIhh\fR. .TP \fB\e0\fR . the character whose value is \fB0\fR .TP +\fB\e\fIxyz\fR +. +(where \fIxyz\fR is exactly three octal digits, and is not a \fIback +reference\fR (see below)) the character whose octal value is +\fB0\fIxyz\fR. The first digit must be in the range 0-3, otherwise +the two-digit form is assumed. +.TP \fB\e\fIxy\fR . (where \fIxy\fR is exactly two octal digits, and is not a \fIback reference\fR (see below)) the character whose octal value is \fB0\fIxy\fR -.TP -\fB\e\fIxyz\fR -. -(where \fIxyz\fR is exactly three octal digits, and is not a back -reference (see below)) the character whose octal value is -\fB0\fIxyz\fR .RE .PP Hexadecimal digits are @@ -16,7 +16,6 @@ read \- Read from a channel .sp \fBread \fIchannelId numChars\fR .BE - .SH DESCRIPTION .PP In the first form, the \fBread\fR command reads all of the data from @@ -51,36 +50,40 @@ newline characters according to the \fB\-translation\fR option for the channel. See the \fBfconfigure\fR manual entry for a discussion on ways in which \fBfconfigure\fR will alter input. - .SH "USE WITH SERIAL PORTS" '\" Note: this advice actually applies to many versions of Tcl - +.PP For most applications a channel connected to a serial port should be -configured to be nonblocking: \fBfconfigure \fIchannelId \fB\-blocking +configured to be nonblocking: \fBfconfigure\fI channelId \fB\-blocking \fI0\fR. Then \fBread\fR behaves much like described above. Care must be taken when using \fBread\fR on blocking serial ports: .TP \fBread \fIchannelId numChars\fR +. In this form \fBread\fR blocks until \fInumChars\fR have been received from the serial port. .TP \fBread \fIchannelId\fR +. In this form \fBread\fR blocks until the reception of the end-of-file -character, see \fBfconfigure -eofchar\fR. If there no end-of-file +character, see \fBfconfigure\fR \fB\-eofchar\fR. If there no end-of-file character has been configured for the channel, then \fBread\fR will block forever. .SH "EXAMPLE" +.PP This example code reads a file all at once, and splits it into a list, with each line in the file corresponding to an element in the list: +.PP .CS set fl [open /proc/meminfo] set data [\fBread\fR $fl] close $fl set lines [split $data \en] .CE - .SH "SEE ALSO" file(n), eof(n), fblocked(n), fconfigure(n), Tcl_StandardChannels(3) - .SH KEYWORDS blocking, channel, end of line, end of file, nonblocking, read, translation, encoding +'\"Local Variables: +'\"mode: nroff +'\"End: diff --git a/doc/refchan.n b/doc/refchan.n index 577c78a..a51c3d7 100644 --- a/doc/refchan.n +++ b/doc/refchan.n @@ -9,7 +9,7 @@ .BS .\" Note: do not modify the .SH NAME line immediately below! .SH NAME -refchan \- Command handler API of reflected channels, version 1 +refchan \- command handler API of reflected channels .SH SYNOPSIS \fBcmdPrefix \fIoption\fR ?\fIarg arg ...\fR? .BE @@ -17,9 +17,10 @@ refchan \- Command handler API of reflected channels, version 1 .PP The Tcl-level handler for a reflected channel has to be a command with subcommands (termed an \fIensemble\fR, as it is a command such as that -created by \fBnamespace ensemble create\fR, though the implementation +created by \fBnamespace ensemble\fR \fBcreate\fR, though the implementation of handlers for reflected channel \fIis not\fR tied to \fBnamespace -ensemble\fRs in any way). Note that \fIcmdPrefix\fR is whatever was +ensemble\fRs in any way; see \fBEXAMPLE\fR below for how to build an +\fBoo::class\fR that supports the API). Note that \fIcmdPrefix\fR is whatever was specified in the call to \fBchan create\fR, and may consist of multiple arguments; this will be expanded to multiple words in place of the prefix. @@ -45,7 +46,7 @@ this command handler. Any error thrown by the method will abort the creation of the channel and no channel will be created. The thrown error will appear as error thrown by \fBchan create\fR. Any exception other than an \fBerror\fR -(e.g. \fBbreak\fR, etc.) is treated as (and converted to) an error. +(e.g.,\ \fBbreak\fR, etc.) is treated as (and converted to) an error. .PP \fBNote:\fR If the creation of the channel was aborted due to failures here, then the \fBfinalize\fR subcommand will not be called. @@ -73,8 +74,8 @@ cleaned up. The return value of this subcommand is ignored. .PP If the subcommand throws an error the command which caused its -invocation (usually \fBclose\fR) will appear to have thrown this -error. Any exception beyond \fIerror\fR (e.g. \fIbreak\fR, etc.) is +invocation (usually \fBchan close\fR) will appear to have thrown this +error. Any exception beyond \fBerror\fR (e.g.,\ \fBbreak\fR, etc.) is treated as (and converted to) an error. .PP This subcommand is not invoked if the creation of the channel was @@ -92,7 +93,7 @@ the handler should disable event generation completely. .RS .PP \fBWarning:\fR Any return value of the subcommand is ignored. This -includes all errors thrown by the subcommand, break, continue, and +includes all errors thrown by the subcommand, \fBbreak\fR, \fBcontinue\fR, and custom return codes. .PP This subcommand interacts with \fBchan postevent\fR. Trying to post an @@ -104,7 +105,7 @@ event which was not listed in the last call to \fBwatch\fR will cause \fIcmdPrefix \fBread \fIchannelId count\fR . This \fIoptional\fR subcommand is called when the user requests data from the -channel \fIchannelId\fR. \fIcount\fR specifies how many \fBbytes\fR have been +channel \fIchannelId\fR. \fIcount\fR specifies how many \fIbytes\fR have been requested. If the subcommand is not supported then it is not possible to read from the channel handled by the command. .RS @@ -130,8 +131,11 @@ error EAGAIN .PP For extensibility any error whose value is a negative integer number will cause the higher layers to set the C-level variable "\fBerrno\fR" -to the absolute value of this number, signaling a system error. This -means that both +to the absolute value of this number, signaling a system error. +However, note that the exact mapping between these error numbers and +their meanings is operating system dependent. +.PP +For example, while on Linux both .PP .CS return -code error -11 @@ -141,13 +145,17 @@ and error -11 .CE .PP -are equivalent to the examples above, using the more readable string "EAGAIN". -No other error value has such a mapping to a symbolic string. +are equivalent to the examples above, using the more readable string "EAGAIN", +this is not true for BSD, where the equivalent number is -35. +.PP +The symbolic string however is the same across systems, and internally +translated to the correct number. No other error value has such a mapping +to a symbolic string. .PP If the subcommand throws any other error, the command which caused its invocation (usually \fBgets\fR, or \fBread\fR) will appear to have -thrown this error. Any exception beyond \fIerror\fR, (e.g. -\fIbreak\fR, etc.) is treated as and converted to an error. +thrown this error. Any exception beyond \fBerror\fR, (e.g.,\ \fBbreak\fR, +etc.) is treated as and converted to an error. .RE .TP \fIcmdPrefix \fBwrite \fIchannelId data\fR @@ -203,18 +211,20 @@ to a symbolic string. .PP If the subcommand throws any other error the command which caused its invocation (usually \fBputs\fR) will appear to have thrown this error. -Any exception beyond \fIerror\fR (e.g.\ \fIbreak\fR, etc.) is treated +Any exception beyond \fBerror\fR (e.g.,\ \fBbreak\fR, etc.) is treated as and converted to an error. .RE .TP \fIcmdPrefix \fBseek \fIchannelId offset base\fR . This \fIoptional\fR subcommand is responsible for the handling of -\fBseek\fR and \fBtell\fR requests on the channel \fIchannelId\fR. If it is not -supported then seeking will not be possible for the channel. +\fBchan seek\fR and \fBchan tell\fR requests on the channel +\fIchannelId\fR. If it is not supported then seeking will not be possible for +the channel. .RS .PP -The \fIbase\fR argument is one of +The \fIbase\fR argument is the same as the equivalent argument of the +builtin \fBchan seek\fR, namely: .TP 10 \fBstart\fR . @@ -228,27 +238,22 @@ Seeking is relative to the current seek position. . Seeking is relative to the end of the channel. .PP -The \fIbase\fR argument of the builtin \fBchan seek\fR command takes -the same names. -.PP The \fIoffset\fR is an integer number specifying the amount of \fBbytes\fR to seek forward or backward. A positive number should seek forward, and a negative number should seek backward. -.PP A channel may provide only limited seeking. For example sockets can seek forward, but not backward. .PP The return value of the subcommand is taken as the (new) location of the channel, counted from the start. This has to be an integer number greater than or equal to zero. -.PP If the subcommand throws an error the command which caused its -invocation (usually \fBseek\fR, or \fBtell\fR) will appear to have -thrown this error. Any exception beyond \fIerror\fR (e.g. \fIbreak\fR, +invocation (usually \fBchan seek\fR, or \fBchan tell\fR) will appear to have +thrown this error. Any exception beyond \fBerror\fR (e.g.,\ \fBbreak\fR, etc.) is treated as and converted to an error. .PP -The offset/base combination of 0/\fBcurrent\fR signals a \fBtell\fR -request, i.e. seek nothing relative to the current location, making +The offset/base combination of 0/\fBcurrent\fR signals a \fBchan tell\fR +request, i.e.,\ seek nothing relative to the current location, making the new location identical to the current one, which is then returned. .RE .TP @@ -265,9 +270,9 @@ time; that is behavior implemented in the Tcl channel core. The return value of the subcommand is ignored. .PP If the subcommand throws an error the command which performed the -(re)configuration or query (usually \fBfconfigure\fR or \fBchan -configure\fR) will appear to have thrown this error. Any exception -beyond \fIerror\fR (e.g. \fIbreak\fR, etc.) is treated as and +(re)configuration or query (usually \fBfconfigure\fR or +\fBchan configure\fR) will appear to have thrown this error. Any exception +beyond \fBerror\fR (e.g.,\ \fBbreak\fR, etc.) is treated as and converted to an error. .RE .TP @@ -281,9 +286,9 @@ subcommand \fBcgetall\fR must be supported as well. The subcommand should return the value of the specified \fIoption\fR. .PP If the subcommand throws an error, the command which performed the -(re)configuration or query (usually \fBfconfigure\fR) will appear to -have thrown this error. Any exception beyond \fIerror\fR (e.g. -\fIbreak\fR, etc.) is treated as and converted to an error. +(re)configuration or query (usually \fBfconfigure\fR or \fBchan configure\fR) +will appear to have thrown this error. Any exception beyond \fIerror\fR +(e.g.,\ \fBbreak\fR, etc.) is treated as and converted to an error. .RE .TP \fIcmdPrefix \fBcgetall \fIchannelId\fR @@ -297,9 +302,9 @@ The subcommand should return a list of all options and their values. This list must have an even number of elements. .PP If the subcommand throws an error the command which performed the -(re)configuration or query (usually \fBfconfigure\fR) will appear to -have thrown this error. Any exception beyond \fIerror\fR (e.g. -\fIbreak\fR, etc.) is treated as and converted to an error. +(re)configuration or query (usually \fBfconfigure\fR or \fBchan configure\fR) +will appear to have thrown this error. Any exception beyond \fBerror\fR +(e.g.,\ \fBbreak\fR, etc.) is treated as and converted to an error. .RE .TP \fIcmdPrefix \fBblocking \fIchannelId mode\fR @@ -313,19 +318,19 @@ channel should be non-blocking. The return value of the subcommand is ignored. .PP If the subcommand throws an error the command which caused its -invocation (usually \fBfconfigure\fR) will appear to have thrown this -error. Any exception beyond \fIerror\fR (e.g. \fIbreak\fR, etc.) is -treated as and converted to an error. +invocation (usually \fBfconfigure\fR or \fBchan configure\fR) will appear to +have thrown this error. Any exception beyond \fBerror\fR (e.g.,\ \fBbreak\fR, +etc.) is treated as and converted to an error. .RE .SH NOTES Some of the functions supported in channels defined in Tcl's C interface are not available to channels reflected to the Tcl level. .PP -The function \fBTcl_DriverGetHandleProc\fR is not supported; i.e. -reflected channels do not have OS specific handles. +The function \fBTcl_DriverGetHandleProc\fR is not supported; +i.e.,\ reflected channels do not have OS specific handles. .PP The function \fBTcl_DriverHandlerProc\fR is not supported. This driver -function is relevant only for stacked channels, i.e. transformations. +function is relevant only for stacked channels, i.e.,\ transformations. Reflected channels are always base channels, not transformations. .PP The function \fBTcl_DriverFlushProc\fR is not supported. This is @@ -334,7 +339,73 @@ function anywhere at all. Therefore support at the Tcl level makes no sense either. This may be altered in the future (through extending the API defined here and changing its version number) should the function be used at some time in the future. +.SH EXAMPLE +.PP +This demonstrates how to make a channel that reads from a string. +.PP +.CS +oo::class create stringchan { + variable data pos + constructor {string {encoding {}}} { + if {$encoding eq ""} {set encoding [encoding system]} + set data [encoding convertto $encoding $string] + set pos 0 + } + + method \fBinitialize\fR {ch mode} { + return "initialize finalize watch read seek" + } + method \fBfinalize\fR {ch} { + my destroy + } + method \fBwatch\fR {ch events} { + # Must be present but we ignore it because we do not + # post any events + } + + # Must be present on a readable channel + method \fBread\fR {ch count} { + set d [string range $data $pos [expr {$pos+$count-1}]] + incr pos [string length $d] + return $d + } + + # This method is optional, but useful for the example below + method \fBseek\fR {ch offset base} { + switch $base { + start { + set pos $offset + } + current { + incr pos $offset + } + end { + set pos [string length $data] + incr pos $offset + } + } + if {$pos < 0} { + set pos 0 + } elseif {$pos > [string length $data]} { + set pos [string length $data] + } + return $pos + } +} + +# Now we create an instance... +set string "The quick brown fox jumps over the lazy dog.\\n" +set ch [\fBchan create\fR read [stringchan new $string]] + +puts [gets $ch]; # Prints the whole string + +seek $ch -5 end; +puts [read $ch]; # Prints just the last word +.CE .SH "SEE ALSO" -chan(n) +chan(n), transchan(n) .SH KEYWORDS -channel, reflection +API, channel, ensemble, prefix, reflection +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/regexp.n b/doc/regexp.n index 100f0d8..5e857f8 100644 --- a/doc/regexp.n +++ b/doc/regexp.n @@ -10,11 +10,9 @@ '\" Note: do not modify the .SH NAME line immediately below! .SH NAME regexp \- Match a regular expression against a string - .SH SYNOPSIS \fBregexp \fR?\fIswitches\fR? \fIexp string \fR?\fImatchVar\fR? ?\fIsubMatchVar subMatchVar ...\fR? .BE - .SH DESCRIPTION .PP Determines whether the regular expression \fIexp\fR matches part or @@ -22,7 +20,7 @@ all of \fIstring\fR and returns 1 if it does, 0 if it does not, unless \fB\-inline\fR is specified (see below). (Regular expression matching is described in the \fBre_syntax\fR reference page.) -.LP +.PP If additional arguments are specified after \fIstring\fR then they are treated as the names of variables in which to return information about which part(s) of \fIstring\fR matched \fIexp\fR. @@ -38,6 +36,7 @@ they are treated as switches. The following switches are currently supported: .TP 15 \fB\-about\fR +. Instead of attempting to match the regular expression, returns a list containing information about the regular expression. The first element of the list is a subexpression count. The second element is a @@ -45,11 +44,13 @@ list of property names that describe various attributes of the regular expression. This switch is primarily intended for debugging purposes. .TP 15 \fB\-expanded\fR +. Enables use of the expanded regular expression syntax where whitespace and comments are ignored. This is the same as specifying the \fB(?x)\fR embedded option (see the \fBre_syntax\fR manual page). .TP 15 \fB\-indices\fR +. Changes what is stored in the \fIsubMatchVar\fRs. Instead of storing the matching characters from \fIstring\fR, each variable @@ -58,6 +59,7 @@ in \fIstring\fR of the first and last characters in the matching range of characters. .TP 15 \fB\-line\fR +. Enables newline-sensitive matching. By default, newline is a completely ordinary character with no special meaning. With this flag, @@ -75,6 +77,7 @@ specifying both \fB\-linestop\fR and \fB\-lineanchor\fR, or the \fB(?n)\fR embedded option (see the \fBre_syntax\fR manual page). .TP 15 \fB\-linestop\fR +. Changes the behavior of .QW [^ bracket expressions and @@ -84,6 +87,7 @@ stop at newlines. This is the same as specifying the \fB(?p)\fR embedded option (see the \fBre_syntax\fR manual page). .TP 15 \fB\-lineanchor\fR +. Changes the behavior of .QW ^ and @@ -96,16 +100,19 @@ specifying the \fB(?w)\fR embedded option (see the \fBre_syntax\fR manual page). .TP 15 \fB\-nocase\fR +. Causes upper-case characters in \fIstring\fR to be treated as lower case during the matching process. .TP 15 \fB\-all\fR +. Causes the regular expression to be matched as many times as possible in the string, returning the total number of matches found. If this is specified with match variables, they will contain information for the last match only. .TP 15 \fB\-inline\fR +. Causes the command to return, as a list, the data that would otherwise be placed in match variables. When using \fB\-inline\fR, match variables may not be specified. If used with \fB\-all\fR, the @@ -113,20 +120,22 @@ list will be concatenated at each iteration, such that a flat list is always returned. For each match iteration, the command will append the overall match data, plus one element for each subexpression in the regular expression. Examples are: +.RS +.PP .CS \fBregexp\fR -inline -- {\ew(\ew)} " inlined " \fI\(-> in n\fR \fBregexp\fR -all -inline -- {\ew(\ew)} " inlined " \fI\(-> in n li i ne e\fR .CE +.RE .TP 15 \fB\-start\fR \fIindex\fR +. Specifies a character index offset into the string to start matching the regular expression at. -.VS 8.5 The \fIindex\fR value is interpreted in the same manner as the \fIindex\fR argument to \fBstring index\fR. -.VE 8.5 When using this switch, .QW ^ will not match the beginning of the line, and \eA will still @@ -136,6 +145,7 @@ absolute beginning of the input string. \fIindex\fR will be constrained to the bounds of the input string. .TP 15 \fB\-\|\-\fR +. Marks the end of switches. The argument following this one will be treated as \fIexp\fR even if it starts with a \fB\-\fR. .PP @@ -151,9 +161,11 @@ if \fB\-indices\fR has been specified or to an empty string otherwise. Find the first occurrence of a word starting with \fBfoo\fR in a string that is not actually an instance of \fBfoobar\fR, and get the letters following it up to the end of the word into a variable: +.PP .CS \fBregexp\fR {\emfoo(?!bar\eM)(\ew*)} $string \-> restOfWord .CE +.PP Note that the whole matched substring has been placed in the variable .QW \fB\->\fR , which is a name chosen to look nice given that we are not @@ -161,17 +173,21 @@ actually interested in its contents. .PP Find the index of the word \fBbadger\fR (in any case) within a string and store that in the variable \fBlocation\fR: +.PP .CS \fBregexp\fR \-indices {(?i)\embadger\eM} $string location .CE +.PP This could also be written as a \fIbasic\fR regular expression (as opposed to using the default syntax of \fIadvanced\fR regular expressions) match by prefixing the expression with a suitable flag: +.PP .CS \fBregexp\fR \-indices {(?ib)\e<badger\e>} $string location .CE .PP This counts the number of octal digits in a string: +.PP .CS \fBregexp\fR \-all {[0\-7]} $string .CE @@ -179,13 +195,14 @@ This counts the number of octal digits in a string: This lists all words (consisting of all sequences of non-whitespace characters) in a string, and is useful as a more powerful version of the \fBsplit\fR command: +.PP .CS \fBregexp\fR \-all \-inline {\eS+} $string .CE .SH "SEE ALSO" -re_syntax(n), regsub(n), -.VS 8.5 -string(n) -.VE +re_syntax(n), regsub(n), string(n) .SH KEYWORDS match, parsing, pattern, regular expression, splitting, string +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/registry.n b/doc/registry.n index e4371e6..2e69b1e 100644 --- a/doc/registry.n +++ b/doc/registry.n @@ -13,9 +13,9 @@ registry \- Manipulate the Windows registry .SH SYNOPSIS .sp -\fBpackage require registry 1.1\fR +\fBpackage require registry 1.3\fR .sp -\fBregistry \fIoption\fR \fIkeyName\fR ?\fIarg arg ...\fR? +\fBregistry \fR?\fI\-mode\fR? \fIoption\fR \fIkeyName\fR ?\fIarg arg ...\fR? .BE .SH DESCRIPTION .PP @@ -44,6 +44,14 @@ one of \fBHKEY_LOCAL_MACHINE\fR, \fBHKEY_USERS\fR, \fBHKEY_DYN_DATA\fR. The \fIkeypath\fR can be one or more registry key names separated by backslash (\fB\e\fR) characters. .PP +.VS 8.6 +The optional \fI\-mode\fR argument indicates which registry to work +with; when it is \fB\-32bit\fR the 32-bit registry will be used, and +when it is \fB\-64bit\fR the 64-bit registry will be used. If this +argument is omitted, the system's default registry will be the subject +of the requested operation. +.VE 8.6 +.PP \fIOption\fR indicates what to do with the registry key name. Any unique abbreviation for \fIoption\fR is acceptable. The valid options are: @@ -95,7 +103,7 @@ data, see \fBSUPPORTED TYPES\fR, below. If \fIpattern\fR is not specified, returns a list of names of all the subkeys of \fIkeyName\fR. If \fIpattern\fR is specified, only those names matching \fIpattern\fR are returned. Matching is determined -using the same rules as for \fBstring\fR \fBmatch\fR. If the +using the same rules as for \fBstring match\fR. If the specified \fIkeyName\fR does not exist, then an error is generated. .TP \fBregistry set \fIkeyName\fR ?\fIvalueName data \fR?\fItype\fR?? @@ -119,7 +127,7 @@ Returns the type of the value \fIvalueName\fR in the key If \fIpattern\fR is not specified, returns a list of names of all the values of \fIkeyName\fR. If \fIpattern\fR is specified, only those names matching \fIpattern\fR are returned. Matching is determined -using the same rules as for \fBstring\fR \fBmatch\fR. +using the same rules as for \fBstring match\fR. .SH "SUPPORTED TYPES" Each value under a key in the registry contains some data of a particular type in a type-specific representation. The \fBregistry\fR @@ -205,3 +213,6 @@ puts "$ext opens with $command" .CE .SH KEYWORDS registry +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/regsub.n b/doc/regsub.n index 5adfd61..fe473d9 100644 --- a/doc/regsub.n +++ b/doc/regsub.n @@ -54,8 +54,9 @@ backslashes. If the initial arguments to \fBregsub\fR start with \fB\-\fR then they are treated as switches. The following switches are currently supported: -.TP 10 +.TP \fB\-all\fR +. All ranges in \fIstring\fR that match \fIexp\fR are found and substitution is performed for each of these ranges. Without this switch only the first @@ -66,13 +67,15 @@ and .QW \e\fIn\fR sequences are handled for each substitution using the information from the corresponding match. -.TP 15 +.TP \fB\-expanded\fR +. Enables use of the expanded regular expression syntax where whitespace and comments are ignored. This is the same as specifying the \fB(?x)\fR embedded option (see the \fBre_syntax\fR manual page). -.TP 15 +.TP \fB\-line\fR +. Enables newline-sensitive matching. By default, newline is a completely ordinary character with no special meaning. With this flag, .QW [^ @@ -87,8 +90,9 @@ matches an empty string before any newline in addition to its normal function. This flag is equivalent to specifying both \fB\-linestop\fR and \fB\-lineanchor\fR, or the \fB(?n)\fR embedded option (see the \fBre_syntax\fR manual page). -.TP 15 +.TP \fB\-linestop\fR +. Changes the behavior of .QW [^ bracket expressions and @@ -96,8 +100,9 @@ bracket expressions and so that they stop at newlines. This is the same as specifying the \fB(?p)\fR embedded option (see the \fBre_syntax\fR manual page). -.TP 15 +.TP \fB\-lineanchor\fR +. Changes the behavior of .QW ^ and @@ -108,26 +113,27 @@ so they match the beginning and end of a line respectively. This is the same as specifying the \fB(?w)\fR embedded option (see the \fBre_syntax\fR manual page). -.TP 10 +.TP \fB\-nocase\fR +. Upper-case characters in \fIstring\fR will be converted to lower-case before matching against \fIexp\fR; however, substitutions specified by \fIsubSpec\fR use the original unconverted form of \fIstring\fR. -.TP 10 +.TP \fB\-start\fR \fIindex\fR +. Specifies a character index offset into the string to start matching the regular expression at. -.VS 8.5 The \fIindex\fR value is interpreted in the same manner as the \fIindex\fR argument to \fBstring index\fR. -.VE 8.5 When using this switch, .QW ^ will not match the beginning of the line, and \eA will still match the start of the string at \fIindex\fR. \fIindex\fR will be constrained to the bounds of the input string. -.TP 10 +.TP \fB\-\|\-\fR +. Marks the end of switches. The argument following this one will be treated as \fIexp\fR even if it starts with a \fB\-\fR. .PP @@ -140,24 +146,29 @@ of regular expressions. .PP Replace (in the string in variable \fIstring\fR) every instance of \fBfoo\fR which is a word by itself with \fBbar\fR: +.PP .CS \fBregsub\fR -all {\emfoo\eM} $string bar string .CE +.PP or (using the .QW "basic regular expression" syntax): +.PP .CS \fBregsub\fR -all {(?b)\e<foo\e>} $string bar string .CE .PP Insert double-quotes around the first instance of the word \fBinteresting\fR, however it is capitalized. +.PP .CS \fBregsub\fR -nocase {\eyinteresting\ey} $string {"&"} string .CE .PP Convert all non-ASCII and Tcl-significant characters into \eu escape sequences by using \fBregsub\fR and \fBsubst\fR in combination: +.PP .CS # This RE is just a character class for almost everything "bad" set RE {[][{};#\e\e\e$ \er\et\eu0080-\euffff]} @@ -173,9 +184,9 @@ set quoted [subst [string map {\en {\e\eu000a}} \e [\fBregsub\fR -all $RE $string $substitution]]] .CE .SH "SEE ALSO" -regexp(n), re_syntax(n), subst(n), -.VS 8.5 -string(n) -.VE +regexp(n), re_syntax(n), subst(n), string(n) .SH KEYWORDS -match, pattern, quoting, regular expression, substitute +match, pattern, quoting, regular expression, substitution +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/rename.n b/doc/rename.n index c207523..77dc095 100644 --- a/doc/rename.n +++ b/doc/rename.n @@ -14,7 +14,6 @@ rename \- Rename or delete a command .SH SYNOPSIS \fBrename \fIoldName newName\fR .BE - .SH DESCRIPTION .PP Rename the command that used to be called \fIoldName\fR so that it @@ -26,9 +25,11 @@ If a command is renamed into a different namespace, future invocations of it will execute in the new namespace. The \fBrename\fR command returns an empty string as result. .SH EXAMPLE +.PP The \fBrename\fR command can be used to wrap the standard Tcl commands with your own monitoring machinery. For example, you might wish to count how often the \fBsource\fR command is called: +.PP .CS \fBrename\fR ::source ::theRealSource set sourceCount 0 @@ -38,9 +39,7 @@ proc ::source args { uplevel 1 ::theRealSource $args } .CE - .SH "SEE ALSO" namespace(n), proc(n) - .SH KEYWORDS command, delete, namespace, rename diff --git a/doc/return.n b/doc/return.n index b08de4a..b59a93d 100644 --- a/doc/return.n +++ b/doc/return.n @@ -45,32 +45,38 @@ However, the \fB\-code\fR option may be used to generate an exceptional return from the procedure. \fICode\fR may have any of the following values: .TP 13 -\fBok (or 0)\fR +\fBok\fR (or \fB0\fR) +. Normal return: same as if the option is omitted. The return code of the procedure is 0 (\fBTCL_OK\fR). .TP 13 -\fBerror (1)\fR +\fBerror\fR (or \fB1\fR) +. Error return: the return code of the procedure is 1 (\fBTCL_ERROR\fR). The procedure command behaves in its calling context as if it -were the command \fBerror \fIresult\fR. See below for additional +were the command \fBerror\fR \fIresult\fR. See below for additional options. .TP 13 -\fBreturn (2)\fR +\fBreturn\fR (or \fB2\fR) +. The return code of the procedure is 2 (\fBTCL_RETURN\fR). The procedure command behaves in its calling context as if it were the command \fBreturn\fR (with no arguments). .TP 13 -\fBbreak (3)\fR +\fBbreak\fR (or \fB3\fR) +. The return code of the procedure is 3 (\fBTCL_BREAK\fR). The procedure command behaves in its calling context as if it were the command \fBbreak\fR. .TP 13 -\fBcontinue (4)\fR +\fBcontinue\fR (or \fB4\fR) +. The return code of the procedure is 4 (\fBTCL_CONTINUE\fR). The procedure command behaves in its calling context as if it were the command \fBcontinue\fR. .TP 13 \fIvalue\fR +. \fIValue\fR must be an integer; it will be returned as the return code for the current procedure. .LP @@ -87,7 +93,6 @@ an invocation of the \fBreturn \-code \fIcode\fR command will cause the return code of \fBsource\fR to be \fIcode\fR. .SH "RETURN OPTIONS" .PP -.VS 8.5 In addition to a result and a return code, evaluation of a command in Tcl also produces a dictionary of return options. In general usage, all \fIoption value\fR pairs given as arguments to \fBreturn\fR @@ -96,13 +101,13 @@ are acceptable except as noted below. The \fBcatch\fR command may be used to capture all of this information \(em the return code, the result, and the return options dictionary \(em that arise from evaluation of a script. -.VE 8.5 .PP As documented above, the \fB\-code\fR entry in the return options dictionary receives special treatment by Tcl. There are other return options also recognized and treated specially by Tcl. They are: .TP \fB\-errorcode \fIlist\fR +. The \fB\-errorcode\fR option receives special treatment only when the value of the \fB\-code\fR option is \fBTCL_ERROR\fR. Then the \fIlist\fR value is meant to be additional information about the error, @@ -114,6 +119,7 @@ to the default value of \fBNONE\fR. The \fB\-errorcode\fR return option will also be stored in the global variable \fBerrorCode\fR. .TP \fB\-errorinfo \fIinfo\fR +. The \fB\-errorinfo\fR option receives special treatment only when the value of the \fB\-code\fR option is \fBTCL_ERROR\fR. Then \fIinfo\fR is the initial stack trace, meant to provide to a human reader additional information @@ -130,8 +136,26 @@ the value of \fB\-errorinfo\fR in a return options dictionary captured by the \fBcatch\fR command (or from the copy of that information stored in the global variable \fBerrorInfo\fR). .TP +\fB\-errorstack \fIlist\fR +.VS 8.6 +The \fB\-errorstack\fR option receives special treatment only when the value +of the \fB\-code\fR option is \fBTCL_ERROR\fR. Then \fIlist\fR is the initial +error stack, recording actual argument values passed to each proc level. The error stack will +also be reachable through \fBinfo errorstack\fR. +If no \fB\-errorstack\fR option is provided to \fBreturn\fR when +the \fB\-code error\fR option is provided, Tcl will provide its own +initial error stack in the entry for \fB\-errorstack\fR. Tcl's +initial error stack will include only the call to the procedure, and +stack unwinding will append information about higher stack levels, but +there will be no information about the context of the error within +the procedure. Typically the \fIlist\fR value is supplied from +the value of \fB\-errorstack\fR in a return options dictionary captured +by the \fBcatch\fR command (or from the copy of that information from +\fBinfo errorstack\fR). +.VE 8.6 +.TP \fB\-level \fIlevel\fR -.VS 8.5 +. The \fB\-level\fR and \fB\-code\fR options work together to set the return code to be returned by one of the commands currently being evaluated. The \fIlevel\fR value must be a non-negative integer representing a number @@ -141,14 +165,12 @@ be \fIcode\fR. If no \fB\-level\fR option is provided, the default value of \fIlevel\fR is 1, so that \fBreturn\fR sets the return code that the current procedure returns to its caller, 1 level up the call stack. The mechanism by which these options work is described in more detail below. -.VE 8.5 .TP \fB\-options \fIoptions\fR -.VS 8.5 +. The value \fIoptions\fR must be a valid dictionary. The entries of that dictionary are treated as additional \fIoption value\fR pairs for the \fBreturn\fR command. -.VE 8.5 .SH "RETURN CODE HANDLING MECHANISMS" .PP Return codes are used in Tcl to control program flow. A Tcl script @@ -174,7 +196,6 @@ of \fBTCL_BREAK\fR or \fBTCL_CONTINUE\fR, the loop command can react in such a way as to give the \fBbreak\fR and \fBcontinue\fR commands their documented interpretation in loops. .PP -.VS 8.5 Procedure invocation also involves evaluation of a script, the body of the procedure. Procedure invocation provides special treatment when evaluation of the procedure body returns the return code @@ -202,20 +223,22 @@ of the \fB\-code\fR option (or \fBTCL_OK\fR by default). Any other value for the \fB\-level\fR option (including the default value of 1) will cause the return code of the \fBreturn\fR command itself to be \fBTCL_RETURN\fR, triggering a return from the enclosing procedure. -.VE 8.5 .SH EXAMPLES +.PP First, a simple example of using \fBreturn\fR to return from a procedure, interrupting the procedure body. +.PP .CS proc printOneLine {} { - puts "line 1" ;# This line will be printed. - \fBreturn\fR - puts "line 2" ;# This line will not be printed. + puts "line 1" ;# This line will be printed. + \fBreturn\fR + puts "line 2" ;# This line will not be printed. } .CE .PP Next, an example of using \fBreturn\fR to set the value returned by the procedure. +.PP .CS proc returnX {} {\fBreturn\fR X} puts [returnX] ;# prints "X" @@ -223,74 +246,81 @@ puts [returnX] ;# prints "X" .PP Next, a more complete example, using \fBreturn -code error\fR to report invalid arguments. +.PP .CS proc factorial {n} { - if {![string is integer $n] || ($n < 0)} { - \fBreturn\fR -code error \e - "expected non-negative integer,\e - but got \e"$n\e"" - } - if {$n < 2} { - \fBreturn\fR 1 - } - set m [expr {$n - 1}] - set code [catch {factorial $m} factor] - if {$code != 0} { - \fBreturn\fR -code $code $factor - } - set product [expr {$n * $factor}] - if {$product < 0} { - \fBreturn\fR -code error \e - "overflow computing factorial of $n" - } - \fBreturn\fR $product + if {![string is integer $n] || ($n < 0)} { + \fBreturn\fR -code error \e + "expected non-negative integer,\e + but got \e"$n\e"" + } + if {$n < 2} { + \fBreturn\fR 1 + } + set m [expr {$n - 1}] + set code [catch {factorial $m} factor] + if {$code != 0} { + \fBreturn\fR -code $code $factor + } + set product [expr {$n * $factor}] + if {$product < 0} { + \fBreturn\fR -code error \e + "overflow computing factorial of $n" + } + \fBreturn\fR $product } .CE .PP Next, a procedure replacement for \fBbreak\fR. +.PP .CS proc myBreak {} { - \fBreturn\fR -code break + \fBreturn\fR -code break } .CE .PP -.VS 8.5 With the \fB\-level 0\fR option, \fBreturn\fR itself can serve -as a replacement for \fBbreak\fR. +as a replacement for \fBbreak\fR, with the help of \fBinterp alias\fR. +.PP .CS interp alias {} Break {} \fBreturn\fR -level 0 -code break .CE .PP An example of using \fBcatch\fR and \fBreturn -options\fR to re-raise a caught error: +.PP .CS proc doSomething {} { - set resource [allocate] - catch { - # Long script of operations - # that might raise an error - } result options - deallocate $resource - \fBreturn\fR -options $options $result + set resource [allocate] + catch { + # Long script of operations + # that might raise an error + } result options + deallocate $resource + \fBreturn\fR -options $options $result } .CE .PP Finally an example of advanced use of the \fBreturn\fR options to create a procedure replacement for \fBreturn\fR itself: +.PP .CS proc myReturn {args} { - set result "" - if {[llength $args] % 2} { - set result [lindex $args end] - set args [lrange $args 0 end-1] - } - set options [dict merge {-level 1} $args] - dict incr options -level - \fBreturn\fR -options $options $result + set result "" + if {[llength $args] % 2} { + set result [lindex $args end] + set args [lrange $args 0 end-1] + } + set options [dict merge {-level 1} $args] + dict incr options -level + \fBreturn\fR -options $options $result } .CE -.VE 8.5 .SH "SEE ALSO" -break(n), catch(n), continue(n), dict(n), error(n), proc(n), source(n), tclvars(n) +break(n), catch(n), continue(n), dict(n), error(n), proc(n), +source(n), tclvars(n), throw(n), try(n) .SH KEYWORDS -break, catch, continue, error, procedure, return +break, catch, continue, error, exception, procedure, result, return +.\" Local Variables: +.\" mode: nroff +.\" End: @@ -9,7 +9,7 @@ .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME -Safe\ Base \- A mechanism for creating and manipulating safe interpreters +safe \- Creating and manipulating safe interpreters .SH SYNOPSIS \fB::safe::interpCreate\fR ?\fIslave\fR? ?\fIoptions...\fR? .sp @@ -36,15 +36,15 @@ Safe Tcl is a mechanism for executing untrusted Tcl scripts safely and for providing mediated access by such scripts to potentially dangerous functionality. .PP -The Safe Base ensures that untrusted Tcl scripts cannot harm the +Safe Tcl ensures that untrusted Tcl scripts cannot harm the hosting application. -The Safe Base prevents integrity and privacy attacks. Untrusted Tcl +It prevents integrity and privacy attacks. Untrusted Tcl scripts are prevented from corrupting the state of the hosting application or computer. Untrusted scripts are also prevented from disclosing information stored on the hosting computer or in the hosting application to any party. .PP -The Safe Base allows a master interpreter to create safe, restricted +Safe Tcl allows a master interpreter to create safe, restricted interpreters that contain a set of predefined aliases for the \fBsource\fR, \fBload\fR, \fBfile\fR, \fBencoding\fR, and \fBexit\fR commands and are able to use the auto-loading and package mechanisms. @@ -59,7 +59,7 @@ requested operation (see the section \fBSECURITY\fR below for details). Different levels of security can be selected by using the optional flags of the commands described below. .PP -All commands provided in the master interpreter by the Safe Base reside in +All commands provided in the master interpreter by Safe Tcl reside in the \fBsafe\fR namespace. .SH COMMANDS The following commands are provided in the master interpreter: @@ -76,7 +76,7 @@ If the \fIslave\fR argument is omitted, a name will be generated. \fB::safe::interpInit\fR \fIslave\fR ?\fIoptions...\fR? This command is similar to \fBinterpCreate\fR except it that does not create the safe interpreter. \fIslave\fR must have been created by some -other means, like \fBinterp create \-safe\fR. +other means, like \fBinterp create\fR \fB\-safe\fR. .TP \fB::safe::interpConfigure\fR \fIslave\fR ?\fIoptions...\fR? If no \fIoptions\fR are given, returns the settings for all options for the @@ -261,13 +261,13 @@ the system encoding, but allows all other subcommands including The calling interpreter is deleted and its computation is stopped, but the Tcl process in which this interpreter exists is not terminated. .SH SECURITY -The Safe Base does not attempt to completely prevent annoyance and +Safe Tcl does not attempt to completely prevent annoyance and denial of service attacks. These forms of attack prevent the application or user from temporarily using the computer to perform useful work, for example by consuming all available CPU time or all available screen real estate. These attacks, while aggravating, are deemed to be of lesser importance -in general than integrity and privacy attacks that the Safe Base +in general than integrity and privacy attacks that Safe Tcl is to prevent. .PP The commands available in a safe interpreter, in addition to @@ -354,3 +354,6 @@ interp(n), library(n), load(n), package(n), source(n), unknown(n) .SH KEYWORDS alias, auto\-loading, auto_mkindex, load, master interpreter, safe interpreter, slave interpreter, source +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -55,6 +55,7 @@ conversion character is \fB[\fR or \fBc\fR). Then it converts the next input characters according to the conversion specifier and stores the result in the variable given by the next argument to \fBscan\fR. +.SS "OPTIONAL POSITIONAL SPECIFIER" .PP If the \fB%\fR is followed by a decimal number and a \fB$\fR, as in .QW \fB%2$d\fR , @@ -66,8 +67,8 @@ specifiers must be positional. Every \fIvarName\fR on the argument list must correspond to exactly one conversion specifier or an error is generated, or in the inline case, any position can be specified at most once and the empty positions will be filled in with empty strings. +.SS "OPTIONAL SIZE MODIFIER" .PP -.VS 8.5 The size modifier field is used only when scanning a substring into one of Tcl's integer values. The size modifier field dictates the integer range acceptable to be stored in a variable, or, for the inline @@ -82,26 +83,36 @@ modifier. Either one indicates the integer range to be stored is limited to the same range produced by the \fBwide()\fR function of the \fBexpr\fR command. The \fBll\fR size modifier indicates that the integer range to be stored is unlimited. -.VE 8.5 +.SS "MANDATORY CONVERSION CHARACTER" .PP The following conversion characters are supported: -.TP 10 +.TP \fBd\fR +. The input substring must be a decimal integer. It is read in and the integer value is stored in the variable, truncated as required by the size modifier value. -.TP 10 +.TP \fBo\fR +. The input substring must be an octal integer. It is read in and the integer value is stored in the variable, truncated as required by the size modifier value. -.TP 10 +.TP \fBx\fR +. The input substring must be a hexadecimal integer. It is read in and the integer value is stored in the variable, truncated as required by the size modifier value. -.TP 10 +.TP +\fBb\fR +. +The input substring must be a binary integer. +It is read in and the integer value is stored in the variable, +truncated as required by the size modifier value. +.TP \fBu\fR +. The input substring must be a decimal integer. The integer value is truncated as required by the size modifier value, and the corresponding unsigned value for that truncated @@ -109,32 +120,37 @@ range is computed and stored in the variable as a decimal string. The conversion makes no sense without reference to a truncation range, so the size modifier \fBll\fR is not permitted in combination with conversion character \fBu\fR. -.TP 10 -\fBi\fR +.TP +\fBi\fR +. The input substring must be an integer. The base (i.e. decimal, binary, octal, or hexadecimal) is determined in the same fashion as described in \fBexpr\fR. The integer value is stored in the variable, truncated as required by the size modifier value. -.TP 10 +.TP \fBc\fR +. A single character is read in and its Unicode value is stored in the variable as an integer value. Initial white space is not skipped in this case, so the input substring may be a white-space character. -.TP 10 +.TP \fBs\fR +. The input substring consists of all the characters up to the next white-space character; the characters are copied to the variable. -.TP 10 +.TP \fBe\fR or \fBf\fR or \fBg\fR +. The input substring must be a floating-point number consisting of an optional sign, a string of decimal digits possibly containing a decimal point, and an optional exponent consisting of an \fBe\fR or \fBE\fR followed by an optional sign and a string of decimal digits. It is read in and stored in the variable as a floating-point value. -.TP 10 +.TP \fB[\fIchars\fB]\fR +. The input substring consists of one or more characters in \fIchars\fR. The matching string is stored in the variable. If the first character between the brackets is a \fB]\fR then @@ -145,8 +161,9 @@ contains a sequence of the form \fIa\fB\-\fIb\fR then any character between \fIa\fR and \fIb\fR (inclusive) will match. If the first or last character between the brackets is a \fB\-\fR, then it is treated as part of \fIchars\fR rather than indicating a range. -.TP 10 +.TP \fB[^\fIchars\fB]\fR +. The input substring consists of one or more characters not in \fIchars\fR. The matching string is stored in the variable. If the character immediately following the \fB^\fR is a \fB]\fR then it is @@ -158,11 +175,12 @@ character between \fIa\fR and \fIb\fR (inclusive) will be excluded from the set. If the first or last character between the brackets is a \fB\-\fR, then it is treated as part of \fIchars\fR rather than indicating a range value. -.TP 10 +.TP \fBn\fR +. No input is consumed from the input string. Instead, the total number of characters scanned from the input string so far is stored in the variable. -.LP +.PP The number of characters read from the input for a conversion is the largest number that makes sense for that particular conversion (e.g. as many decimal digits as possible for \fB%d\fR, as @@ -192,7 +210,9 @@ modifier has no \fBsscanf\fR counterpart. If the end of the input string is reached before any conversions have been performed and no variables are given, an empty string is returned. .SH EXAMPLES +.PP Convert a UNICODE character to its numeric value: +.PP .CS set char "x" set value [\fBscan\fR $char %c] @@ -200,6 +220,7 @@ set value [\fBscan\fR $char %c] .PP Parse a simple color specification of the form \fI#RRGGBB\fR using hexadecimal conversions with substring sizes: +.PP .CS set string "#08D03F" \fBscan\fR $string "#%2x%2x%2x" r g b @@ -208,60 +229,65 @@ set string "#08D03F" Parse a \fIHH:MM\fR time string, noting that this avoids problems with octal numbers by forcing interpretation as decimals (if we did not care, we would use the \fB%i\fR conversion instead): +.PP .CS set string "08:08" ;# *Not* octal! if {[\fBscan\fR $string "%d:%d" hours minutes] != 2} { - error "not a valid time string" + error "not a valid time string" } # We have to understand numeric ranges ourselves... if {$minutes < 0 || $minutes > 59} { - error "invalid number of minutes" + error "invalid number of minutes" } .CE .PP Break a string up into sequences of non-whitespace characters (note the use of the \fB%n\fR conversion so that we get skipping over leading whitespace correct): +.PP .CS set string " a string {with braced words} + leading space " set words {} while {[\fBscan\fR $string %s%n word length] == 2} { - lappend words $word - set string [string range $string $length end] + lappend words $word + set string [string range $string $length end] } .CE .PP Parse a simple coordinate string, checking that it is complete by looking for the terminating character explicitly: +.PP .CS set string "(5.2,-4e-2)" # Note that the spaces before the literal parts of # the scan pattern are significant, and that ")" is # the Unicode character \eu0029 if { - [\fBscan\fR $string " (%f ,%f %c" x y last] != 3 - || $last != 0x0029 + [\fBscan\fR $string " (%f ,%f %c" x y last] != 3 + || $last != 0x0029 } then { - error "invalid coordinate string" + error "invalid coordinate string" } puts "X=$x, Y=$y" .CE .PP -.VS 8.5 An interactive session demonstrating the truncation of integer values determined by size modifiers: +.PP .CS -% set tcl_platform(wordSize) +\fI%\fR set tcl_platform(wordSize) 4 -% scan 20000000000000000000 %d +\fI%\fR scan 20000000000000000000 %d 2147483647 -% scan 20000000000000000000 %ld +\fI%\fR scan 20000000000000000000 %ld 9223372036854775807 -% scan 20000000000000000000 %lld +\fI%\fR scan 20000000000000000000 %lld 20000000000000000000 .CE -.VE 8.5 .SH "SEE ALSO" format(n), sscanf(3) .SH KEYWORDS conversion specifier, parse, scan +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -14,7 +14,6 @@ seek \- Change the access position for an open channel .SH SYNOPSIS \fBseek \fIchannelId offset \fR?\fIorigin\fR? .BE - .SH DESCRIPTION .PP Changes the current access position for \fIchannelId\fR. @@ -30,20 +29,23 @@ for \fIchannelId\fR. \fIOffset\fR must be an integer (which may be negative) and \fIorigin\fR must be one of the following: .TP 10 \fBstart\fR +. The new access position will be \fIoffset\fR bytes from the start of the underlying file or device. .TP 10 \fBcurrent\fR +. The new access position will be \fIoffset\fR bytes from the current access position; a negative \fIoffset\fR moves the access position backwards in the underlying file or device. .TP 10 \fBend\fR +. The new access position will be \fIoffset\fR bytes from the end of the file or device. A negative \fIoffset\fR places the access position before the end of file, and a positive \fIoffset\fR places the access position after the end of file. -.LP +.PP The \fIorigin\fR argument defaults to \fBstart\fR. .PP The command flushes all buffered output for the channel before the command @@ -57,17 +59,20 @@ Note that \fIoffset\fR values are byte offsets, not character offsets. Both \fBseek\fR and \fBtell\fR operate in terms of bytes, not characters, unlike \fBread\fR. .SH EXAMPLES +.PP Read a file twice: +.PP .CS set f [open file.txt] set data1 [read $f] \fBseek\fR $f 0 set data2 [read $f] close $f -# $data1 == $data2 if the file wasn't updated +# $data1 eq $data2 if the file wasn't updated .CE .PP Read the last 10 bytes from a file: +.PP .CS set f [open file.data] # This is guaranteed to work with binary data but @@ -77,9 +82,7 @@ fconfigure $f -translation binary set data [read $f 10] close $f .CE - .SH "SEE ALSO" file(n), open(n), close(n), gets(n), tell(n), Tcl_StandardChannels(3) - .SH KEYWORDS access position, file, seek diff --git a/doc/self.n b/doc/self.n new file mode 100644 index 0000000..348c38f --- /dev/null +++ b/doc/self.n @@ -0,0 +1,152 @@ +'\" +'\" Copyright (c) 2007 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH self n 0.1 TclOO "TclOO Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +self \- method call internal introspection +.SH SYNOPSIS +.nf +package require TclOO + +\fBself\fR ?\fIsubcommand\fR? +.fi +.BE +.SH DESCRIPTION +The \fBself\fR command, which should only be used from within the context of a +call to a method (i.e. inside a method, constructor or destructor body) is +used to allow the method to discover information about how it was called. It +takes an argument, \fIsubcommand\fR, that tells it what sort of information is +actually desired; if omitted the result will be the same as if \fBself +object\fR was invoked. The supported subcommands are: +.TP +\fBself call\fR +. +This returns a two-element list describing the method implementations used to +implement the current call chain. The first element is the same as would be +reported by \fBinfo object\fR \fBcall\fR for the current method (except that this +also reports useful values from within constructors and destructors, whose +names are reported as \fB<constructor>\fR and \fB<destructor>\fR +respectively), and the second element is an index into the first element's +list that indicates which actual implementation is currently executing (the +first implementation to execute is always at index 0). +.TP +\fBself caller\fR +. +When the method was invoked from inside another object method, this subcommand +returns a three element list describing the containing object and method. The +first element describes the declaring object or class of the method, the +second element is the name of the object on which the containing method was +invoked, and the third element is the name of the method (with the strings +\fB<constructor>\fR and \fB<destructor>\fR indicating constructors and +destructors respectively). +.TP +\fBself class\fR +. +This returns the name of the class that the current method was defined within. +Note that this will change as the chain of method implementations is traversed +with \fBnext\fR, and that if the method was defined on an object then this +will fail. +.RS +.PP +If you want the class of the current object, you need to use this other +construct: +.PP +.CS +info object class [\fBself object\fR] +.CE +.RE +.TP +\fBself filter\fR +. +When invoked inside a filter, this subcommand returns a three element list +describing the filter. The first element gives the name of the object or class +that declared the filter (note that this may be different from the object or +class that provided the implementation of the filter), the second element is +either \fBobject\fR or \fBclass\fR depending on whether the declaring entity +was an object or class, and the third element is the name of the filter. +.TP +\fBself method\fR +. +This returns the name of the current method (with the strings +\fB<constructor>\fR and \fB<destructor>\fR indicating constructors and +destructors respectively). +.TP +\fBself namespace\fR +. +This returns the name of the unique namespace of the object that the method +was invoked upon. +.TP +\fBself next\fR +. +When invoked from a method that is not at the end of a call chain (i.e. where +the \fBnext\fR command will invoke an actual method implementation), this +subcommand returns a two element list describing the next element in the +method call chain; the first element is the name of the class or object that +declares the next part of the call chain, and the second element is the name +of the method (with the strings \fB<constructor>\fR and \fB<destructor>\fR +indicating constructors and destructors respectively). If invoked from a +method that is at the end of a call chain, this subcommand returns the emtpy +string. +.TP +\fBself object\fR +. +This returns the name of the object that the method was invoked upon. +.TP +\fBself target\fR +. +When invoked inside a filter implementation, this subcommand returns a two +element list describing the method being filtered. The first element will be +the name of the declarer of the method, and the second element will be the +actual name of the method. +.SH EXAMPLES +.PP +This example shows basic use of \fBself\fR to provide information about the +current object: +.PP +.CS +oo::class create c { + method foo {} { + puts "this is the [\fBself\fR] object" + } +} +c create a +c create b +a foo \fI\(-> prints "this is the ::a object"\fR +b foo \fI\(-> prints "this is the ::b object"\fR +.CE +.PP +This demonstrates what a method call chain looks like, and how traversing +along it changes the index into it: +.PP +.CS +oo::class create c { + method x {} { + puts "Cls: [\fBself call\fR]" + } +} +c create a +oo::objdefine a { + method x {} { + puts "Obj: [\fBself call\fR]" + next + puts "Obj: [\fBself call\fR]" + } +} +a x \fI\(-> Obj: {{method x object method} {method x ::c method}} 0\fR + \fI\(-> Cls: {{method x object method} {method x ::c method}} 1\fR + \fI\(-> Obj: {{method x object method} {method x ::c method}} 0\fR +.CE +.SH "SEE ALSO" +info(n), next(n) +.SH KEYWORDS +call, introspection, object +.\" Local variables: +.\" mode: nroff +.\" fill-column: 78 +.\" End: @@ -39,17 +39,21 @@ If a procedure is active and \fIvarName\fR is unqualified, then unless \fIvarName\fR was declared to resolve differently through one of the \fBglobal\fR, \fBvariable\fR or \fBupvar\fR commands. .SH EXAMPLES +.PP Store a random number in the variable \fIr\fR: +.PP .CS \fBset\fR r [expr {rand()}] .CE .PP Store a short message in an array element: +.PP .CS \fBset\fR anAry(msg) "Hello, World!" .CE .PP Store a short message in an array element specified by a variable: +.PP .CS \fBset\fR elemName "msg" \fBset\fR anAry($elemName) "Hello, World!" @@ -58,6 +62,7 @@ Store a short message in an array element specified by a variable: Copy a value into the variable \fIout\fR from a variable whose name is stored in the \fIvbl\fR (note that it is often easier to use arrays in practice instead of doing double-dereferencing): +.PP .CS \fBset\fR in0 "small random" \fBset\fR in1 "large random" diff --git a/doc/socket.n b/doc/socket.n index c020839..e3087c9 100644 --- a/doc/socket.n +++ b/doc/socket.n @@ -6,7 +6,7 @@ '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" .so man.macros -.TH socket n 8.0 Tcl "Tcl Built-In Commands" +.TH socket n 8.6 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME @@ -17,21 +17,19 @@ socket \- Open a TCP network connection .sp \fBsocket\fR \fB\-server \fIcommand\fR ?\fIoptions\fR? \fIport\fR .BE - .SH DESCRIPTION .PP -This command opens a network socket and returns a channel -identifier that may be used in future invocations of commands like -\fBread\fR, \fBputs\fR and \fBflush\fR. -At present only the TCP network protocol is supported; future -releases may include support for additional protocols. -The \fBsocket\fR command may be used to open either the client or -server side of a connection, depending on whether the \fB\-server\fR -switch is specified. +This command opens a network socket and returns a channel identifier +that may be used in future invocations of commands like \fBread\fR, +\fBputs\fR and \fBflush\fR. At present only the TCP network protocol +is supported over IPv4 and IPv6; future releases may include support +for additional protocols. The \fBsocket\fR command may be used to +open either the client or server side of a connection, depending on +whether the \fB\-server\fR switch is specified. .PP Note that the default encoding for \fIall\fR sockets is the system encoding, as returned by \fBencoding system\fR. Most of the time, you -will need to use \fBfconfigure\fR to alter this to something else, +will need to use \fBchan configure\fR to alter this to something else, such as \fIutf\-8\fR (ideal for communicating with other Tcl processes) or \fIiso8859\-1\fR (useful for many network protocols, especially the older ones). @@ -46,13 +44,14 @@ this port. \fIPort\fR is an integer port number (or service name, where supported and understood by the host operating system) and \fIhost\fR is either a domain-style name such as \fBwww.tcl.tk\fR or -a numerical IP address such as \fB127.0.0.1\fR. +a numerical IPv4 or IPv6 address such as \fB127.0.0.1\fR or \fB2001:DB8::1\fR. Use \fIlocalhost\fR to refer to the host on which the command is invoked. .PP The following options may also be present before \fIhost\fR to specify additional information about the connection: .TP \fB\-myaddr\fI addr\fR +. \fIAddr\fR gives the domain-style name or numerical IP address of the client-side network interface to use for the connection. This option may be useful if the client machine has multiple network @@ -60,6 +59,7 @@ interfaces. If the option is omitted then the client-side interface will be chosen by the system software. .TP \fB\-myport\fI port\fR +. \fIPort\fR specifies an integer port number (or service name, where supported and understood by the host operating system) to use for the client's @@ -67,48 +67,67 @@ side of the connection. If this option is omitted, the client's port number will be chosen at random by the system software. .TP \fB\-async\fR -The \fB\-async\fR option will cause the client socket to be connected -asynchronously. This means that the socket will be created immediately but -may not yet be connected to the server, when the call to \fBsocket\fR -returns. When a \fBgets\fR or \fBflush\fR is done on the socket before the -connection attempt succeeds or fails, if the socket is in blocking mode, the -operation will wait until the connection is completed or fails. If the -socket is in nonblocking mode and a \fBgets\fR or \fBflush\fR is done on -the socket before the connection attempt succeeds or fails, the operation -returns immediately and \fBfblocked\fR on the socket returns 1. Synchronous -client sockets may be switched (after they have connected) to operating in -asynchronous mode using: +. +This option will cause the client socket to be connected +asynchronously. This means that the socket will be created immediately +but may not yet be connected to the server, when the call to +\fBsocket\fR returns. + +When a \fBgets\fR or \fBflush\fR is done on the socket before the +connection attempt succeeds or fails, if the socket is in blocking +mode, the operation will wait until the connection is completed or +fails. If the socket is in nonblocking mode and a \fBgets\fR or +\fBflush\fR is done on the socket before the connection attempt +succeeds or fails, the operation returns immediately and +\fBfblocked\fR on the socket returns 1. Synchronous client sockets may +be switched (after they have connected) to operating in asynchronous +mode using: .RS +.PP .CS -\fBfconfigure \fIchan \fB\-blocking 0\fR +\fBchan configure \fIchan \fB\-blocking 0\fR .CE .PP -See the \fBfconfigure\fR command for more details. +See the \fBchan configure\fR command for more details. + +The Tcl event loop should be running while an asynchronous connection +is in progress, because it may have to do several connection attempts +in the background. Runnig the event loop also allows you to set up a +writable channel event on the socket to get notified when the +asyncronous connection has succeeded or failed. See the \fBvwait\fR +and the \fBchan\fR comands for more details on the event loop and +channel events. + .RE .SH "SERVER SOCKETS" .PP -If the \fB\-server\fR option is specified then the new socket -will be a server for the port given by \fIport\fR (either an integer -or a service name, where supported and understood by the host -operating system; if \fIport\fR is zero, the operating system will -allocate a free port to the server socket which may be discovered by -using \fBfconfigure\fR to read the \fB\-sockname\fR option). -Tcl will automatically accept connections to the given port. +If the \fB\-server\fR option is specified then the new socket will be +a server that listens on the given \fIport\fR (either an integer or a +service name, where supported and understood by the host operating +system; if \fIport\fR is zero, the operating system will allocate a +free port to the server socket which may be discovered by using +\fBchan configure\fR to read the \fB\-sockname\fR option). If the host +supports both, IPv4 and IPv6, the socket will listen on both address +families. Tcl will automatically accept connections to the given port. For each connection Tcl will create a new channel that may be used to -communicate with the client. Tcl then invokes \fIcommand\fR -with three additional arguments: the name of the new channel, the -address, in network address notation, of the client's host, and -the client's port number. +communicate with the client. Tcl then invokes \fIcommand\fR (properly +a command prefix list, see the \fBEXAMPLES\fR below) with three +additional arguments: the name of the new channel, the address, in +network address notation, of the client's host, and the client's port +number. .PP The following additional option may also be specified before \fIport\fR: .TP \fB\-myaddr\fI addr\fR -\fIAddr\fR gives the domain-style name or numerical IP address of -the server-side network interface to use for the connection. -This option may be useful if the server machine has multiple network -interfaces. If the option is omitted then the server socket is bound -to the special address INADDR_ANY so that it can accept connections from -any interface. +. +\fIAddr\fR gives the domain-style name or numerical IP address of the +server-side network interface to use for the connection. This option +may be useful if the server machine has multiple network interfaces. +If the option is omitted then the server socket is bound to the +wildcard address so that it can accept connections from any +interface. If \fIaddr\fR is a domain name that resolves to multiple IP +addresses that are available on the local machine, the socket will +listen on all of them. .PP Server channels cannot be used for input or output; their sole use is to accept new client connections. The channels created for each incoming @@ -125,13 +144,15 @@ will be accepted. If \fIport\fR is specified as zero, the operating system will allocate an unused port for use as a server socket. The port number actually allocated may be retrieved from the created server socket using the -\fBfconfigure\fR command to retrieve the \fB\-sockname\fR option as +\fBchan configure\fR command to retrieve the \fB\-sockname\fR option as described below. .SH "CONFIGURATION OPTIONS" -The \fBfconfigure\fR command can be used to query several readonly +.PP +The \fBchan configure\fR command can be used to query several readonly configuration options for socket channels: .TP \fB\-error\fR +. This option gets the current error status of the given socket. This is useful when you need to determine if an asynchronous connect operation succeeded. If there was an error, the error message is @@ -141,12 +162,23 @@ Note that the error status is reset by the read operation; this mimics the underlying getsockopt(SO_ERROR) call. .TP \fB\-sockname\fR -This option returns a list of three elements, the address, the host name -and the port number for the socket. If the host name cannot be computed, -the second element is identical to the address, the first element of the -list. +. +For client sockets (including the channels that get created when a +client connects to a server socket) this option returns a list of +three elements, the address, the host name and the port number for the +socket. If the host name cannot be computed, the second element is +identical to the address, the first element of the list. + +For server sockets this option returns a list of a multiple of three +elements each group of which have the same meaning as described +above. The list contains more than one group when the server socket +was created without \fB\-myaddr\fR or with the argument to +\fB\-myaddr\fR being a domain name that resolves multiple IP addresses +that are local to the invoking host. + .TP \fB\-peername\fR +. This option is not supported by server sockets. For client and accepted sockets, this option returns a list of three elements; these are the address, the host name and the port to which the peer socket is connected @@ -154,29 +186,40 @@ or bound. If the host name cannot be computed, the second element of the list is identical to the address, its first element. .PP .SH "EXAMPLES" +.PP Here is a very simple time server: +.PP .CS -proc Server {channel clientaddr clientport} { - puts "Connection from $clientaddr registered" - puts $channel [clock format [clock seconds]] - close $channel +proc Server {startTime channel clientaddr clientport} { + puts "Connection from $clientaddr registered" + set now [clock seconds] + puts $channel [clock format $now] + puts $channel "[expr {$now - $startTime}] since start" + close $channel } -\fBsocket\fR -server Server 9900 +\fBsocket -server\fR [list Server [clock seconds]] 9900 vwait forever .CE .PP -And here is the corresponding client to talk to the server: +And here is the corresponding client to talk to the server and extract +some information: +.PP .CS set server localhost set sockChan [\fBsocket\fR $server 9900] -gets $sockChan line +gets $sockChan line1 +gets $sockChan line2 close $sockChan -puts "The time on $server is $line" +puts "The time on $server is $line1" +puts "That is [lindex $line2 0]s since the server started" .CE - +.SH "HISTORY" +Support for IPv6 was added in Tcl 8.6. .SH "SEE ALSO" -fconfigure(n), flush(n), open(n), read(n) - +chan(n), flush(n), open(n), read(n) .SH KEYWORDS -bind, channel, connection, domain name, host, network address, socket, tcp +asynchronous I/O, bind, channel, connection, domain name, host, network address, socket, tcp +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/source.n b/doc/source.n index 69d383e..57a9fa2 100644 --- a/doc/source.n +++ b/doc/source.n @@ -15,9 +15,7 @@ source \- Evaluate a file or resource as a Tcl script .SH SYNOPSIS \fBsource \fIfileName\fR .sp -.VS 8.5 \fBsource\fR \fB\-encoding \fIencodingName fileName\fR -.VE 8.5 .BE .SH DESCRIPTION .PP @@ -45,22 +43,24 @@ or which will be safely substituted by the Tcl interpreter into .QW ^Z . .PP -.VS 8.5 The \fB\-encoding\fR option is used to specify the encoding of the data stored in \fIfileName\fR. When the \fB\-encoding\fR option is omitted, the system encoding is assumed. -.VE 8.5 .SH EXAMPLE +.PP Run the script in the file \fBfoo.tcl\fR and then the script in the file \fBbar.tcl\fR: +.PP .CS \fBsource\fR foo.tcl \fBsource\fR bar.tcl .CE +.PP Alternatively: +.PP .CS foreach scriptFile {foo.tcl bar.tcl} { - \fBsource\fR $scriptFile + \fBsource\fR $scriptFile } .CE .SH "SEE ALSO" diff --git a/doc/split.n b/doc/split.n index c289be0..e3259df 100644 --- a/doc/split.n +++ b/doc/split.n @@ -14,7 +14,6 @@ split \- Split a string into a proper Tcl list .SH SYNOPSIS \fBsplit \fIstring \fR?\fIsplitChars\fR? .BE - .SH DESCRIPTION .PP Returns a list created by splitting \fIstring\fR at each character @@ -29,34 +28,41 @@ If \fIsplitChars\fR is an empty string then each character of \fIstring\fR becomes a separate element of the result list. \fISplitChars\fR defaults to the standard white-space characters. .SH EXAMPLES +.PP Divide up a USENET group name into its hierarchical components: +.PP .CS -\fBsplit\fR "comp.lang.tcl.announce" . - \fI\(-> comp lang tcl announce\fR +\fBsplit\fR "comp.lang.tcl" . + \fI\(-> comp lang tcl\fR .CE .PP See how the \fBsplit\fR command splits on \fIevery\fR character in \fIsplitChars\fR, which can result in information loss if you are not careful: +.PP .CS \fBsplit\fR "alpha beta gamma" "temp" \fI\(-> al {ha b} {} {a ga} {} a\fR .CE .PP Extract the list words from a string that is not a well-formed list: +.PP .CS \fBsplit\fR "Example with {unbalanced brace character" \fI\(-> Example with \e{unbalanced brace character\fR .CE .PP Split a string into its constituent characters +.PP .CS \fBsplit\fR "Hello world" {} \fI\(-> H e l l o { } w o r l d\fR .CE .SS "PARSING RECORD-ORIENTED FILES" +.PP Parse a Unix /etc/passwd file, which consists of one entry per line, with each line consisting of a colon-separated list of fields: +.PP .CS ## Read the file set fid [open /etc/passwd] @@ -69,18 +75,19 @@ set records [\fBsplit\fR $content "\en"] ## Iterate over the records foreach rec $records { - ## Split into fields on colons - set fields [\fBsplit\fR $rec ":"] + ## Split into fields on colons + set fields [\fBsplit\fR $rec ":"] - ## Assign fields to variables and print some out... - lassign $fields \e - userName password uid grp longName homeDir shell - puts "$longName uses [file tail $shell] for a login shell" + ## Assign fields to variables and print some out... + lassign $fields \e + userName password uid grp longName homeDir shell + puts "$longName uses [file tail $shell] for a login shell" } .CE - .SH "SEE ALSO" join(n), list(n), string(n) - .SH KEYWORDS list, split, string +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/string.n b/doc/string.n index dfb5a90..d960b71 100644 --- a/doc/string.n +++ b/doc/string.n @@ -14,13 +14,13 @@ string \- Manipulate strings .SH SYNOPSIS \fBstring \fIoption arg \fR?\fIarg ...?\fR .BE - .SH DESCRIPTION .PP Performs one of several string operations, depending on \fIoption\fR. The legal \fIoption\fRs (which may be abbreviated) are: .TP \fBstring bytelength \fIstring\fR +. Returns a decimal string giving the number of bytes used to represent \fIstring\fR in memory. Because UTF\-8 uses one to three bytes to represent Unicode characters, the byte length will not be the same as @@ -29,8 +29,16 @@ the byte length are rare. In almost all cases, you should use the \fBstring length\fR operation (including determining the length of a Tcl ByteArray object). Refer to the \fBTcl_NumUtfChars\fR manual entry for more details on the UTF\-8 representation. +.RS +.PP +\fICompatibility note:\fR it is likely that this subcommand will be +withdrawn in a future version of Tcl. It is better to use the +\fBencoding convertto\fR command to convert a string to a known +encoding and then apply \fBstring length\fR to that. +.RE .TP \fBstring compare\fR ?\fB\-nocase\fR? ?\fB\-length int\fR? \fIstring1 string2\fR +. Perform a character-by-character comparison of strings \fIstring1\fR and \fIstring2\fR. Returns \-1, 0, or 1, depending on whether \fIstring1\fR is lexicographically less than, equal to, or greater @@ -40,6 +48,7 @@ first \fIlength\fR characters are used in the comparison. If specified, then the strings are compared in a case-insensitive manner. .TP \fBstring equal\fR ?\fB\-nocase\fR? ?\fB\-length int\fR? \fIstring1 string2\fR +. Perform a character-by-character comparison of strings \fIstring1\fR and \fIstring2\fR. Returns 1 if \fIstring1\fR and \fIstring2\fR are identical, or 0 when not. If \fB\-length\fR is specified, then only @@ -48,87 +57,50 @@ the first \fIlength\fR characters are used in the comparison. If specified, then the strings are compared in a case-insensitive manner. .TP \fBstring first \fIneedleString haystackString\fR ?\fIstartIndex\fR? +. Search \fIhaystackString\fR for a sequence of characters that exactly match the characters in \fIneedleString\fR. If found, return the index of the first character in the first such match within \fIhaystackString\fR. If not found, return \-1. If \fIstartIndex\fR is specified (in any of the -forms accepted by the \fBindex\fR method), then the search is +forms described in \fBSTRING INDICES\fR), then the search is constrained to start with the character in \fIhaystackString\fR specified by the index. For example, .RS +.PP .CS \fBstring first a 0a23456789abcdef 5\fR .CE +.PP will return \fB10\fR, but +.PP .CS \fBstring first a 0123456789abcdef 11\fR .CE +.PP will return \fB\-1\fR. .RE .TP \fBstring index \fIstring charIndex\fR +. Returns the \fIcharIndex\fR'th character of the \fIstring\fR argument. A \fIcharIndex\fR of 0 corresponds to the first character of the -string. \fIcharIndex\fR may be specified as follows: -.VS 8.5 +string. \fIcharIndex\fR may be specified as described in the +\fBSTRING INDICES\fR section. .RS -.IP \fIinteger\fR 10 -For any index value that passes \fBstring is integer -strict\fR, -the char specified at this integral index -(e.g. \fB2\fR would refer to the -.QW c -in -.QW abcd ). -.IP \fBend\fR 10 -The last char of the string -(e.g. \fBend\fR would refer to the -.QW d -in -.QW abcd ). -.IP \fBend\fR\-\fIN\fR 10 -The last char of the string minus the specified integer offset \fIN\fR -(e.g. \fBend\fR\-1 would refer to the -.QW c -in -.QW abcd ). -.IP \fBend\fR+\fIN\fR 10 -The last char of the string plus the specified integer offset \fIN\fR -(e.g. \fBend\fR+\-1 would refer to the -.QW c -in -.QW abcd ). -.IP \fIM\fR+\fIN\fR 10 -The char specified at the integral index that is the sum of -integer values \fIM\fR and \fIN\fR -(e.g. \fB1+1\fR would refer to the -.QW c -in -.QW abcd ). -.IP \fIM\fR\-\fIN\fR 10 -The char specified at the integral index that is the difference of -integer values \fIM\fR and \fIN\fR -(e.g. \fB2\-1\fR would refer to the -.QW b -in -.QW abcd ). -.PP -In the specifications above, the integer value \fIM\fR contains no -trailing whitespace and the integer value \fIN\fR contains no -leading whitespace. .PP If \fIcharIndex\fR is less than 0 or greater than or equal to the length of the string then this command returns an empty string. .RE -.VE .TP \fBstring is \fIclass\fR ?\fB\-strict\fR? ?\fB\-failindex \fIvarname\fR? \fIstring\fR +. Returns 1 if \fIstring\fR is a valid member of the specified character class, otherwise returns 0. If \fB\-strict\fR is specified, then an empty string returns 0, otherwise an empty string will return 1 on any class. If \fB\-failindex\fR is specified, then if the function returns 0, the index in the string where the class was no longer valid will be stored in the variable named \fIvarname\fR. The \fIvarname\fR -will not be set if the function returns 1. The following character +will not be set if \fBstring is\fR returns 1. The following character classes are recognized (the class name can be abbreviated): .RS .IP \fBalnum\fR 12 @@ -177,12 +149,10 @@ Any of the forms allowed to \fBTcl_GetBoolean\fR where the value is true. .IP \fBupper\fR 12 Any upper case alphabet character in the Unicode character set. -.VS 8.5 .IP \fBwideinteger\fR 12 Any of the valid forms for a wide integer in Tcl, with optional surrounding whitespace. In case of under/overflow in the value, 0 is returned and the \fIvarname\fR will contain \-1. -.VE 8.5 .IP \fBwordchar\fR 12 Any Unicode word character. That is any alphanumeric character, and any Unicode connector punctuation characters (e.g. underscore). @@ -195,25 +165,31 @@ function will return 0, then the \fIvarname\fR will always be set to .RE .TP \fBstring last \fIneedleString haystackString\fR ?\fIlastIndex\fR? +. Search \fIhaystackString\fR for a sequence of characters that exactly match the characters in \fIneedleString\fR. If found, return the index of the first character in the last such match within \fIhaystackString\fR. If there is no match, then return \-1. If \fIlastIndex\fR is specified (in any -of the forms accepted by the \fBindex\fR method), then only the +of the forms described in \fBSTRING INDICES\fR), then only the characters in \fIhaystackString\fR at or before the specified \fIlastIndex\fR will be considered by the search. For example, .RS +.PP .CS \fBstring last a 0a23456789abcdef 15\fR .CE +.PP will return \fB10\fR, but +.PP .CS \fBstring last a 0a23456789abcdef 9\fR .CE +.PP will return \fB1\fR. .RE .TP \fBstring length \fIstring\fR +. Returns a decimal string giving the number of characters in \fIstring\fR. Note that this is not necessarily the same as the number of bytes used to store the string. If the object is a @@ -221,6 +197,7 @@ ByteArray object (such as those returned from reading a binary encoded channel), then this will return the actual byte length of the object. .TP \fBstring map\fR ?\fB\-nocase\fR? \fImapping string\fR +. Replaces substrings in \fIstring\fR based on the key-value pairs in \fImapping\fR. \fImapping\fR is a list of \fIkey value key value ...\fR as in the form returned by \fBarray get\fR. Each instance of a @@ -232,21 +209,26 @@ appearing first in the list will be checked first, and so on. \fIstring\fR is only iterated over once, so earlier key replacements will have no affect for later key matches. For example, .RS +.PP .CS \fBstring map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc\fR .CE +.PP will return the string \fB01321221\fR. .PP Note that if an earlier \fIkey\fR is a prefix of a later one, it will completely mask the later one. So if the previous example is reordered like this, +.PP .CS \fBstring map {1 0 ab 2 a 3 abc 1} 1abcaababcabababc\fR .CE +.PP it will return the string \fB02c322c222c\fR. .RE .TP \fBstring match\fR ?\fB\-nocase\fR? \fIpattern\fR \fIstring\fR +. See if \fIpattern\fR matches \fIstring\fR; return 1 if it does, 0 if it does not. If \fB\-nocase\fR is specified, then the pattern attempts to match against the string in a case insensitive manner. For the two @@ -280,6 +262,7 @@ the special interpretation of the characters \fB*?[]\e\fR in .RE .TP \fBstring range \fIstring first last\fR +. Returns a range of consecutive characters from \fIstring\fR, starting with the character whose index is \fIfirst\fR and ending with the character whose index is \fIlast\fR. An index of 0 refers to the first @@ -291,9 +274,11 @@ equal to the length of the string then it is treated as if it were string is returned. .TP \fBstring repeat \fIstring count\fR +. Returns \fIstring\fR repeated \fIcount\fR number of times. .TP \fBstring replace \fIstring first last\fR ?\fInewstring\fR? +. Removes a range of consecutive characters from \fIstring\fR, starting with the character whose index is \fIfirst\fR and ending with the character whose index is \fIlast\fR. An index of 0 refers to the @@ -305,91 +290,146 @@ and if \fIlast\fR is greater than or equal to the length of the string then it is treated as if it were \fBend\fR. If \fIfirst\fR is greater than \fIlast\fR or the length of the initial string, or \fIlast\fR is less than 0, then the initial string is returned untouched. -.VS 8.5 .TP \fBstring reverse \fIstring\fR +. Returns a string that is the same length as \fIstring\fR but with its characters in the reverse order. -.VE 8.5 .TP \fBstring tolower \fIstring\fR ?\fIfirst\fR? ?\fIlast\fR? +. Returns a value equal to \fIstring\fR except that all upper (or title) case letters have been converted to lower case. If \fIfirst\fR is specified, it refers to the first char index in the string to start modifying. If \fIlast\fR is specified, it refers to the char index in the string to stop at (inclusive). \fIfirst\fR and \fIlast\fR may be -specified as for the \fBindex\fR method. +specified using the forms described in \fBSTRING INDICES\fR. .TP \fBstring totitle \fIstring\fR ?\fIfirst\fR? ?\fIlast\fR? +. Returns a value equal to \fIstring\fR except that the first character in \fIstring\fR is converted to its Unicode title case variant (or upper case if there is no title case variant) and the rest of the string is converted to lower case. If \fIfirst\fR is specified, it refers to the first char index in the string to start modifying. If \fIlast\fR is specified, it refers to the char index in the string to -stop at (inclusive). \fIfirst\fR and \fIlast\fR may be specified as -for the \fBindex\fR method. +stop at (inclusive). \fIfirst\fR and \fIlast\fR may be specified +using the forms described in \fBSTRING INDICES\fR. .TP \fBstring toupper \fIstring\fR ?\fIfirst\fR? ?\fIlast\fR? +. Returns a value equal to \fIstring\fR except that all lower (or title) case letters have been converted to upper case. If \fIfirst\fR is specified, it refers to the first char index in the string to start modifying. If \fIlast\fR is specified, it refers to the char index in the string to stop at (inclusive). \fIfirst\fR and \fIlast\fR may be -specified as for the \fBindex\fR method. +specified using the forms described in \fBSTRING INDICES\fR. .TP \fBstring trim \fIstring\fR ?\fIchars\fR? +. Returns a value equal to \fIstring\fR except that any leading or trailing characters present in the string given by \fIchars\fR are removed. If \fIchars\fR is not specified then white space is removed (spaces, tabs, newlines, and carriage returns). .TP \fBstring trimleft \fIstring\fR ?\fIchars\fR? +. Returns a value equal to \fIstring\fR except that any leading characters present in the string given by \fIchars\fR are removed. If \fIchars\fR is not specified then white space is removed (spaces, tabs, newlines, and carriage returns). .TP \fBstring trimright \fIstring\fR ?\fIchars\fR? +. Returns a value equal to \fIstring\fR except that any trailing characters present in the string given by \fIchars\fR are removed. If \fIchars\fR is not specified then white space is removed (spaces, tabs, newlines, and carriage returns). .TP \fBstring wordend \fIstring charIndex\fR +. Returns the index of the character just after the last one in the word containing character \fIcharIndex\fR of \fIstring\fR. \fIcharIndex\fR -may be specified as for the \fBindex\fR method. A word is +may be specified using the forms in \fBSTRING INDICES\fR. A word is considered to be any contiguous range of alphanumeric (Unicode letters or decimal digits) or underscore (Unicode connector punctuation) characters, or any single character other than these. .TP \fBstring wordstart \fIstring charIndex\fR -Returns the index of the first character in the word containing -character \fIcharIndex\fR of \fIstring\fR. \fIcharIndex\fR may be -specified as for the \fBindex\fR method. A word is considered to be any -contiguous range of alphanumeric (Unicode letters or decimal digits) -or underscore (Unicode connector punctuation) characters, or any -single character other than these. +. +Returns the index of the first character in the word containing character +\fIcharIndex\fR of \fIstring\fR. \fIcharIndex\fR may be specified using the +forms in \fBSTRING INDICES\fR. A word is considered to be any contiguous +range of alphanumeric (Unicode letters or decimal digits) or underscore +(Unicode connector punctuation) characters, or any single character other than +these. +.SH "STRING INDICES" +.PP +When referring to indices into a string (e.g., for \fBstring index\fR +or \fBstring range\fR) the following formats are supported: +.IP \fIinteger\fR 10 +For any index value that passes \fBstring is integer \-strict\fR, +the char specified at this integral index (e.g., \fB2\fR would refer to the +.QW c +in +.QW abcd ). +.IP \fBend\fR 10 +The last char of the string (e.g., \fBend\fR would refer to the +.QW d +in +.QW abcd ). +.IP \fBend\-\fIN\fR 10 +The last char of the string minus the specified integer offset \fIN\fR (e.g., +.QW \fBend\-1\fR +would refer to the +.QW c +in +.QW abcd ). +.IP \fBend+\fIN\fR 10 +The last char of the string plus the specified integer offset \fIN\fR (e.g., +.QW \fBend+\-1\fR +would refer to the +.QW c +in +.QW abcd ). +.IP \fIM\fB+\fIN\fR 10 +The char specified at the integral index that is the sum of +integer values \fIM\fR and \fIN\fR (e.g., +.QW \fB1+1\fR +would refer to the +.QW c +in +.QW abcd ). +.IP \fIM\fB\-\fIN\fR 10 +The char specified at the integral index that is the difference of +integer values \fIM\fR and \fIN\fR (e.g., +.QW \fB2\-1\fR +would refer to the +.QW b +in +.QW abcd ). +.PP +In the specifications above, the integer value \fIM\fR contains no +trailing whitespace and the integer value \fIN\fR contains no +leading whitespace. .SH EXAMPLE +.PP Test if the string in the variable \fIstring\fR is a proper non-empty prefix of the string \fBfoobar\fR. +.PP .CS set length [\fBstring length\fR $string] if {$length == 0} { - set isPrefix 0 + set isPrefix 0 } else { - set isPrefix [\fBstring equal\fR -length $length $string "foobar"] + set isPrefix [\fBstring equal\fR \-length $length $string "foobar"] } .CE - .SH "SEE ALSO" expr(n), list(n) - .SH KEYWORDS case conversion, compare, index, match, pattern, string, word, equal, ctype, character, reverse - .\" Local Variables: .\" mode: nroff .\" End: diff --git a/doc/subst.n b/doc/subst.n index 5a162c4..aba2bc9 100644 --- a/doc/subst.n +++ b/doc/subst.n @@ -62,19 +62,23 @@ itself will either return an error, or will complete successfully. When it performs its substitutions, \fIsubst\fR does not give any special treatment to double quotes or curly braces (except within command substitutions) so the script +.PP .CS set a 44 \fBsubst\fR {xyz {$a}} .CE +.PP returns .QW "\fBxyz {44}\fR" , not .QW "\fBxyz {$a}\fR" and the script +.PP .CS set a "p\e} q \e{r" \fBsubst\fR {xyz {$a}} .CE +.PP returns .QW "\fBxyz {p} q {r}\fR" , not @@ -82,10 +86,12 @@ not .PP When command substitution is performed, it includes any variable substitution necessary to evaluate the script. +.PP .CS set a 44 \fBsubst\fR -novariables {$a [format $a]} .CE +.PP returns .QW "\fB$a 44\fR" , not @@ -93,11 +99,13 @@ not Similarly, when variable substitution is performed, it includes any command substitution necessary to retrieve the value of the variable. +.PP .CS proc b {} {return c} array set a {c c [b] tricky} \fBsubst\fR -nocommands {[b] $a([b])} .CE +.PP returns .QW "\fB[b] c\fR" , not @@ -107,34 +115,42 @@ The continue and break exceptions allow command substitutions to prevent substitution of the rest of the command substitution and the rest of \fIstring\fR respectively, giving script authors more options when processing text using \fIsubst\fR. For example, the script +.PP .CS \fBsubst\fR {abc,[break],def} .CE +.PP returns .QW \fBabc,\fR , not .QW \fBabc,,def\fR and the script +.PP .CS \fBsubst\fR {abc,[continue;expr {1+2}],def} .CE +.PP returns .QW \fBabc,,def\fR , not .QW \fBabc,3,def\fR . .PP Other exceptional return codes substitute the returned value +.PP .CS \fBsubst\fR {abc,[return foo;expr {1+2}],def} .CE +.PP returns .QW \fBabc,foo,def\fR , not .QW \fBabc,3,def\fR and +.PP .CS \fBsubst\fR {abc,[return -code 10 foo;expr {1+2}],def} .CE +.PP also returns .QW \fBabc,foo,def\fR , not @@ -142,4 +158,7 @@ not .SH "SEE ALSO" Tcl(n), eval(n), break(n), continue(n) .SH KEYWORDS -backslash substitution, command substitution, variable substitution +backslash substitution, command substitution, quoting, substitution, variable substitution +.\" Local Variables: +.\" mode: nroff +.\" End: diff --git a/doc/switch.n b/doc/switch.n index defa849..acde6cb 100644 --- a/doc/switch.n +++ b/doc/switch.n @@ -31,32 +31,33 @@ command returns an empty string. .PP If the initial arguments to \fBswitch\fR start with \fB\-\fR then they are treated as options -.VS 8.5 unless there are exactly two arguments to \fBswitch\fR (in which case the first must the \fIstring\fR and the second must be the \fIpattern\fR/\fIbody\fR list). -.VE 8.5 The following options are currently supported: .TP 10 \fB\-exact\fR +. Use exact matching when comparing \fIstring\fR to a pattern. This is the default. .TP 10 \fB\-glob\fR +. When matching \fIstring\fR to the patterns, use glob-style matching (i.e. the same as implemented by the \fBstring match\fR command). .TP 10 \fB\-regexp\fR +. When matching \fIstring\fR to the patterns, use regular expression matching (as described in the \fBre_syntax\fR reference page). -'\" Options defined by TIP#75 -.VS 8.5 .TP 10 \fB\-nocase\fR +. Causes comparisons to be handled in a case-insensitive manner. .TP 10 \fB\-matchvar\fR \fIvarName\fR +. This option (only legal when \fB\-regexp\fR is also specified) specifies the name of a variable into which the list of matches found by the regular expression engine will be written. The first @@ -69,6 +70,7 @@ empty list written to it. This option may be specified at the same time as the \fB\-indexvar\fR option. .TP 10 \fB\-indexvar\fR \fIvarName\fR +. This option (only legal when \fB\-regexp\fR is also specified) specifies the name of a variable into which the list of indices referring to matching substrings @@ -83,15 +85,13 @@ capturing parenthesis in the regular expression that matched, and so on. When a \fBdefault\fR branch is taken, the variable will have the empty list written to it. This option may be specified at the same time as the \fB\-matchvar\fR option. -.VE 8.5 .TP 10 \fB\-\|\-\fR +. Marks the end of options. The argument following this one will be treated as \fIstring\fR even if it starts with a \fB\-\fR. -.VS 8.5 This is not required when the matching patterns and bodies are grouped together in a single argument. -.VE 8.5 .PP Two syntaxes are provided for the \fIpattern\fR and \fIbody\fR arguments. The first uses a separate argument for each of the patterns and commands; @@ -122,8 +122,10 @@ Beware of how you place comments in \fBswitch\fR commands. Comments should only be placed \fBinside\fR the execution body of one of the patterns, and not intermingled with the patterns. .SH "EXAMPLES" +.PP The \fBswitch\fR command can match against variables and not just literals, as shown here (the result is \fI2\fR): +.PP .CS set foo "abc" \fBswitch\fR abc a \- b {expr {1}} $foo {expr {2}} default {expr {3}} @@ -132,48 +134,49 @@ set foo "abc" Using glob matching and the fall-through body is an alternative to writing regular expressions with alternations, as can be seen here (this returns \fI1\fR): +.PP .CS \fBswitch\fR \-glob aaab { - a*b \- - b {expr {1}} - a* {expr {2}} - default {expr {3}} + a*b \- + b {expr {1}} + a* {expr {2}} + default {expr {3}} } .CE .PP Whenever nothing matches, the \fBdefault\fR clause (which must be last) is taken. This example has a result of \fI3\fR: +.PP .CS \fBswitch\fR xyz { - a \- - b { - # Correct Comment Placement - expr {1} - } - c { - expr {2} - } - default { - expr {3} - } + a \- + b { + # Correct Comment Placement + expr {1} + } + c { + expr {2} + } + default { + expr {3} + } } .CE .PP -.VS 8.5 When matching against regular expressions, information about what exactly matched is easily obtained using the \fB\-matchvar\fR option: +.PP .CS \fBswitch\fR \-regexp \-matchvar foo \-\- $bar { - a(b*)c { - puts "Found [string length [lindex $foo 1]] 'b's" - } - d(e*)f(g*)h { - puts "Found [string length [lindex $foo 1]] 'e's and\e - [string length [lindex $foo 2]] 'g's" - } + a(b*)c { + puts "Found [string length [lindex $foo 1]] 'b's" + } + d(e*)f(g*)h { + puts "Found [string length [lindex $foo 1]] 'e's and\e + [string length [lindex $foo 2]] 'g's" + } } .CE -.VE 8.5 .SH "SEE ALSO" for(n), if(n), regexp(n) .SH KEYWORDS diff --git a/doc/tailcall.n b/doc/tailcall.n new file mode 100644 index 0000000..6a88aca --- /dev/null +++ b/doc/tailcall.n @@ -0,0 +1,69 @@ +'\" +'\" Copyright (c) 1993 The Regents of the University of California. +'\" Copyright (c) 1994-1996 Sun Microsystems, Inc. +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH tailcall n 8.6 Tcl "Tcl Built-In Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +tailcall \- Replace the current procedure with another command +.SH SYNOPSIS +\fBtailcall \fIcommand\fR ?\fIarg ...\fR? +.BE +.SH DESCRIPTION +.PP +The \fBtailcall\fR command replaces the currently executing procedure, lambda +application, or method with another command. The \fIcommand\fR, which will +have \fIarg ...\fR passed as arguments if they are supplied, will be looked up +in the current namespace context, not in the caller's. Apart from that +difference in resolution, it is equivalent to: +.PP +.CS +return [uplevel 1 [list \fIcommand\fR ?\fIarg ...\fR?]] +.CE +.PP +This command may not be invoked from within an \fBuplevel\fR into a procedure +or inside a \fBcatch\fR inside a procedure or lambda. +'\" TODO: sort out the mess with the [try] command! +.SH EXAMPLE +.PP +Compute the factorial of a number. +.PP +.CS +proc factorial {n {accum 1}} { + if {$n < 2} { + return $accum + } + \fBtailcall\fR factorial [expr {$n - 1}] [expr {$accum * $n}] +} +.CE +.PP +Print the elements of a list with alternating lines having different +indentations. +.PP +.CS +proc printList {theList} { + if {[llength $theList]} { + puts "> [lindex $theList 0]" + \fBtailcall\fR printList2 [lrange $theList 1 end] + } +} +proc printList2 {theList} { + if {[llength $theList]} { + puts "< [lindex $theList 0]" + \fBtailcall\fR printList [lrange $theList 1 end] + } +} +.CE +.SH "SEE ALSO" +apply(n), proc(n), uplevel(n) +.SH KEYWORDS +call, recursion, tail recursion +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: diff --git a/doc/tclsh.1 b/doc/tclsh.1 index d9fe95e..2819408 100644 --- a/doc/tclsh.1 +++ b/doc/tclsh.1 @@ -14,7 +14,6 @@ tclsh \- Simple shell containing Tcl interpreter .SH SYNOPSIS \fBtclsh\fR ?-encoding \fIname\fR? ?\fIfileName arg arg ...\fR? .BE - .SH DESCRIPTION .PP \fBTclsh\fR is a shell-like application that reads Tcl commands @@ -28,15 +27,11 @@ If there exists a file \fB.tclshrc\fR (or \fBtclshrc.tcl\fR on the Windows platforms) in the home directory of the user, interactive \fBtclsh\fR evaluates the file as a Tcl script just before reading the first command from standard input. - .SH "SCRIPT FILES" .PP -.VS 8.5 If \fBtclsh\fR is invoked with arguments then the first few arguments specify the name of a script file, and, optionally, the encoding of -the text data stored in that script file. -.VE 8.5 -Any additional arguments +the text data stored in that script file. Any additional arguments are made available to the script as variables (see below). Instead of reading commands from standard input \fBtclsh\fR will read Tcl commands from the named file; \fBtclsh\fR will exit @@ -58,9 +53,11 @@ of a script file is presented on the \fBtclsh\fR command line, but the script file can always \fBsource\fR it if desired. .PP If you create a Tcl script in a file whose first line is +.PP .CS \fB#!/usr/local/bin/tclsh\fR .CE +.PP then you can invoke the script file directly from your shell if you mark the file as executable. This assumes that \fBtclsh\fR has been installed in the default @@ -72,11 +69,13 @@ executable can be accessed with a short file name. .PP An even better approach is to start your script files with the following three lines: +.PP .CS \fB#!/bin/sh # the next line restarts using tclsh \e exec tclsh "$0" ${1+"$@"}\fR .CE +.PP This approach has three advantages over the approach in the previous paragraph. First, the location of the \fBtclsh\fR binary does not have to be hard-wired into the script: it can be anywhere in your shell @@ -101,28 +100,30 @@ its version number as part of the name. This has the advantage of allowing multiple versions of Tcl to exist on the same system at once, but also the disadvantage of making it harder to write scripts that start up uniformly across different versions of Tcl. - .SH "VARIABLES" .PP \fBTclsh\fR sets the following Tcl variables: .TP 15 \fBargc\fR +. Contains a count of the number of \fIarg\fR arguments (0 if none), not including the name of the script file. .TP 15 \fBargv\fR +. Contains a Tcl list whose elements are the \fIarg\fR arguments, in order, or an empty string if there are no \fIarg\fR arguments. .TP 15 \fBargv0\fR +. Contains \fIfileName\fR if it was specified. Otherwise, contains the name by which \fBtclsh\fR was invoked. .TP 15 \fBtcl_interactive\fR +. Contains 1 if \fBtclsh\fR is running interactively (no \fIfileName\fR was specified and standard input is a terminal-like device), 0 otherwise. - .SH PROMPTS .PP When \fBtclsh\fR is invoked interactively it normally prompts for each @@ -137,13 +138,10 @@ The variable \fBtcl_prompt2\fR is used in a similar way when a newline is typed but the current command is not yet complete; if \fBtcl_prompt2\fR is not set then no prompt is output for incomplete commands. - .SH "STANDARD CHANNELS" .PP See \fBTcl_StandardChannels\fR for more explanations. - .SH "SEE ALSO" encoding(n), fconfigure(n), tclvars(n) - .SH KEYWORDS -argument, interpreter, prompt, script file, shell +application, argument, interpreter, prompt, script file, shell diff --git a/doc/tcltest.n b/doc/tcltest.n index 9ac8f66..731bed7 100644 --- a/doc/tcltest.n +++ b/doc/tcltest.n @@ -16,52 +16,52 @@ tcltest \- Test harness support code and utilities .SH SYNOPSIS .nf -\fBpackage require tcltest ?2.3?\fR -.sp -\fBtcltest::test \fIname description ?option value ...?\fR -\fBtcltest::test \fIname description ?constraints? body result\fR -.sp +\fBpackage require tcltest\fR ?\fB2.3\fR? + +\fBtcltest::test \fIname description\fR ?\fI\-option value ...\fR? +\fBtcltest::test \fIname description\fR ?\fIconstraints\fR? \fIbody result\fR + \fBtcltest::loadTestedCommands\fR -\fBtcltest::makeDirectory \fIname ?directory?\fR -\fBtcltest::removeDirectory \fIname ?directory?\fR -\fBtcltest::makeFile \fIcontents name ?directory?\fR -\fBtcltest::removeFile \fIname ?directory?\fR -\fBtcltest::viewFile \fIname ?directory?\fR -\fBtcltest::cleanupTests \fI?runningMultipleTests?\fR +\fBtcltest::makeDirectory \fIname\fR ?\fIdirectory\fR? +\fBtcltest::removeDirectory \fIname\fR ?\fIdirectory\fR? +\fBtcltest::makeFile \fIcontents name\fR ?\fIdirectory\fR? +\fBtcltest::removeFile \fIname\fR ?\fIdirectory\fR? +\fBtcltest::viewFile \fIname\fR ?\fIdirectory\fR? +\fBtcltest::cleanupTests \fR?\fIrunningMultipleTests\fR? \fBtcltest::runAllTests\fR -.sp + \fBtcltest::configure\fR -\fBtcltest::configure \fIoption\fR -\fBtcltest::configure \fIoption value ?option value ...?\fR +\fBtcltest::configure \fI\-option\fR +\fBtcltest::configure \fI\-option value\fR ?\fI\-option value ...\fR? \fBtcltest::customMatch \fImode command\fR -\fBtcltest::testConstraint \fIconstraint ?value?\fR -\fBtcltest::outputChannel \fI?channelID?\fR -\fBtcltest::errorChannel \fI?channelID?\fR -\fBtcltest::interpreter \fI?interp?\fR -.sp -\fBtcltest::debug \fI?level?\fR -\fBtcltest::errorFile \fI?filename?\fR -\fBtcltest::limitConstraints \fI?boolean?\fR -\fBtcltest::loadFile \fI?filename?\fR -\fBtcltest::loadScript \fI?script?\fR -\fBtcltest::match \fI?patternList?\fR -\fBtcltest::matchDirectories \fI?patternList?\fR -\fBtcltest::matchFiles \fI?patternList?\fR -\fBtcltest::outputFile \fI?filename?\fR -\fBtcltest::preserveCore \fI?level?\fR -\fBtcltest::singleProcess \fI?boolean?\fR -\fBtcltest::skip \fI?patternList?\fR -\fBtcltest::skipDirectories \fI?patternList?\fR -\fBtcltest::skipFiles \fI?patternList?\fR -\fBtcltest::temporaryDirectory \fI?directory?\fR -\fBtcltest::testsDirectory \fI?directory?\fR -\fBtcltest::verbose \fI?level?\fR -.sp +\fBtcltest::testConstraint \fIconstraint\fR ?\fIvalue\fR? +\fBtcltest::outputChannel \fR?\fIchannelID\fR? +\fBtcltest::errorChannel \fR?\fIchannelID\fR? +\fBtcltest::interpreter \fR?\fIinterp\fR? + +\fBtcltest::debug \fR?\fIlevel\fR? +\fBtcltest::errorFile \fR?\fIfilename\fR? +\fBtcltest::limitConstraints \fR?\fIboolean\fR? +\fBtcltest::loadFile \fR?\fIfilename\fR? +\fBtcltest::loadScript \fR?\fIscript\fR? +\fBtcltest::match \fR?\fIpatternList\fR? +\fBtcltest::matchDirectories \fR?\fIpatternList\fR? +\fBtcltest::matchFiles \fR?\fIpatternList\fR? +\fBtcltest::outputFile \fR?\fIfilename\fR? +\fBtcltest::preserveCore \fR?\fIlevel\fR? +\fBtcltest::singleProcess \fR?\fIboolean\fR? +\fBtcltest::skip \fR?\fIpatternList\fR? +\fBtcltest::skipDirectories \fR?\fIpatternList\fR? +\fBtcltest::skipFiles \fR?\fIpatternList\fR? +\fBtcltest::temporaryDirectory \fR?\fIdirectory\fR? +\fBtcltest::testsDirectory \fR?\fIdirectory\fR? +\fBtcltest::verbose \fR?\fIlevel\fR? + \fBtcltest::test \fIname description optionList\fR \fBtcltest::bytestring \fIstring\fR \fBtcltest::normalizeMsg \fImsg\fR \fBtcltest::normalizePath \fIpathVar\fR -\fBtcltest::workingDirectory \fI?dir?\fR +\fBtcltest::workingDirectory \fR?\fIdir\fR? .fi .BE .SH DESCRIPTION @@ -90,7 +90,8 @@ of how to use the commands of \fBtcltest\fR to produce test suites for your Tcl-enabled code. .SH COMMANDS .TP -\fBtest\fR \fIname description ?option value ...?\fR +\fBtest\fR \fIname description\fR ?\fI\-option value ...\fR? +. Defines and possibly runs a test with the name \fIname\fR and description \fIdescription\fR. The name and description of a test are used in messages reported by \fBtest\fR during the @@ -103,7 +104,8 @@ See \fBTESTS\fR below for a complete description of the valid options and how they define a test. The \fBtest\fR command returns an empty string. .TP -\fBtest\fR \fIname description ?constraints? body result\fR +\fBtest\fR \fIname description\fR ?\fIconstraints\fR? \fIbody result\fR +. This form of \fBtest\fR is provided to support test suites written for version 1 of the \fBtcltest\fR package, and also a simpler interface for a common usage. It is the same as @@ -115,6 +117,7 @@ all \fIoption\fRs begin with .QW \- . .TP \fBloadTestedCommands\fR +. Evaluates in the caller's context the script specified by \fBconfigure \-load\fR or \fBconfigure \-loadfile\fR. Returns the result of that script evaluation, including any error @@ -122,7 +125,8 @@ raised by the script. Use this command and the related configuration options to provide the commands to be tested to the interpreter running the test suite. .TP -\fBmakeFile\fR \fIcontents name ?directory?\fR +\fBmakeFile\fR \fIcontents name\fR ?\fIdirectory\fR? +. Creates a file named \fIname\fR relative to directory \fIdirectory\fR and write \fIcontents\fR to that file using the encoding \fBencoding system\fR. @@ -137,14 +141,16 @@ of \fBcleanupTests\fR, unless it is removed by Returns the full path of the file created. Use this command to create any text file required by a test with contents as needed. .TP -\fBremoveFile\fR \fIname ?directory?\fR +\fBremoveFile\fR \fIname\fR ?\fIdirectory\fR? +. Forces the file referenced by \fIname\fR to be removed. This file name should be relative to \fIdirectory\fR. The default value of \fIdirectory\fR is the directory \fBconfigure \-tmpdir\fR. Returns an empty string. Use this command to delete files created by \fBmakeFile\fR. .TP -\fBmakeDirectory\fR \fIname ?directory?\fR +\fBmakeDirectory\fR \fIname\fR ?\fIdirectory\fR? +. Creates a directory named \fIname\fR relative to directory \fIdirectory\fR. The directory will be removed by the next evaluation of \fBcleanupTests\fR, unless it is removed by \fBremoveDirectory\fR first. @@ -153,7 +159,8 @@ The default value of \fIdirectory\fR is the directory Returns the full path of the directory created. Use this command to create any directories that are required to exist by a test. .TP -\fBremoveDirectory\fR \fIname ?directory?\fR +\fBremoveDirectory\fR \fIname\fR ?\fIdirectory\fR? +. Forces the directory referenced by \fIname\fR to be removed. This directory should be relative to \fIdirectory\fR. The default value of \fIdirectory\fR is the directory @@ -161,7 +168,8 @@ The default value of \fIdirectory\fR is the directory Returns an empty string. Use this command to delete any directories created by \fBmakeDirectory\fR. .TP -\fBviewFile\fR \fIfile ?directory?\fR +\fBviewFile\fR \fIfile\fR ?\fIdirectory\fR? +. Returns the contents of \fIfile\fR, except for any final newline, just as \fBread \-nonewline\fR would return. This file name should be relative to \fIdirectory\fR. @@ -174,6 +182,7 @@ the system encoding, so its usefulness is limited to text files. .TP \fBcleanupTests\fR +. Intended to clean up and summarize after several tests have been run. Typically called once per test file, at the end of the file after all tests have been completed. For best effectiveness, be @@ -188,28 +197,32 @@ in the directory \fBconfigure \-tmpdir\fR created since the last \fBcleanupTests\fR, but not created by \fBmakeFile\fR or \fBmakeDirectory\fR are printed to \fBoutputChannel\fR. This command also restores the original -shell environment, as described by the \fB::env\fR +shell environment, as described by the global \fBenv\fR array. Returns an empty string. .RE .TP \fBrunAllTests\fR +. This is a master command meant to run an entire suite of tests, spanning multiple files and/or directories, as governed by the configurable options of \fBtcltest\fR. See \fBRUNNING ALL TESTS\fR below for a complete description of the many variations possible with \fBrunAllTests\fR. -.SH "CONFIGURATION COMMANDS" +.SS "CONFIGURATION COMMANDS" .TP \fBconfigure\fR +. Returns the list of configurable options supported by \fBtcltest\fR. See \fBCONFIGURABLE OPTIONS\fR below for the full list of options, their valid values, and their effect on \fBtcltest\fR operations. .TP \fBconfigure \fIoption\fR +. Returns the current value of the supported configurable option \fIoption\fR. Raises an error if \fIoption\fR is not a supported configurable option. .TP -\fBconfigure \fIoption value ?option value ...?\fR +\fBconfigure \fIoption value\fR ?\fI\-option value ...\fR? +. Sets the value of each configurable option \fIoption\fR to the corresponding value \fIvalue\fR, in order. Raises an error if an \fIoption\fR is not a supported configurable option, or if @@ -220,13 +233,14 @@ arguments are not processed. .RS .PP If the environment variable \fB::env(TCLTEST_OPTIONS)\fR exists when -the \fBtcltest\fR package is loaded (by \fBpackage require tcltest\fR) +the \fBtcltest\fR package is loaded (by \fBpackage require\fR \fBtcltest\fR) then its value is taken as a list of arguments to pass to \fBconfigure\fR. This allows the default values of the configuration options to be set by the environment. .RE .TP \fBcustomMatch \fImode script\fR +. Registers \fImode\fR as a new legal value of the \fB\-match\fR option to \fBtest\fR. When the \fB\-match \fImode\fR option is passed to \fBtest\fR, the script \fIscript\fR will be evaluated @@ -239,81 +253,119 @@ The completed script is expected to return a boolean value indicating whether or not the results match. The built-in matching modes of \fBtest\fR are \fBexact\fR, \fBglob\fR, and \fBregexp\fR. .TP -\fBtestConstraint \fIconstraint ?boolean?\fR +\fBtestConstraint \fIconstraint\fR ?\fIboolean\fR? +. Sets or returns the boolean value associated with the named \fIconstraint\fR. See \fBTEST CONSTRAINTS\fR below for more information. .TP -\fBinterpreter\fR \fI?executableName?\fR +\fBinterpreter\fR ?\fIexecutableName\fR? +. Sets or returns the name of the executable to be \fBexec\fRed by \fBrunAllTests\fR to run each test file when \fBconfigure \-singleproc\fR is false. The default value for \fBinterpreter\fR is the name of the currently running program as returned by \fBinfo nameofexecutable\fR. .TP -\fBoutputChannel\fR \fI?channelID?\fR -Sets or returns the output channel ID. This defaults to stdout. +\fBoutputChannel\fR ?\fIchannelID\fR? +. +Sets or returns the output channel ID. This defaults to \fBstdout\fR. Any test that prints test related output should send that output to \fBoutputChannel\fR rather than letting -that output default to stdout. +that output default to \fBstdout\fR. .TP -\fBerrorChannel\fR \fI?channelID?\fR -Sets or returns the error channel ID. This defaults to stderr. +\fBerrorChannel\fR ?\fIchannelID\fR? +. +Sets or returns the error channel ID. This defaults to \fBstderr\fR. Any test that prints error messages should send that output to \fBerrorChannel\fR rather than printing -directly to stderr. -.SH "SHORTCUT COMMANDS" -.TP -\fBdebug \fI?level?\fR -Same as \fBconfigure \-debug \fI?level?\fR. -.TP -\fBerrorFile \fI?filename?\fR -Same as \fBconfigure \-errfile \fI?filename?\fR. -.TP -\fBlimitConstraints \fI?boolean?\fR -Same as \fBconfigure \-limitconstraints \fI?boolean?\fR. -.TP -\fBloadFile \fI?filename?\fR -Same as \fBconfigure \-loadfile \fI?filename?\fR. -.TP -\fBloadScript \fI?script?\fR -Same as \fBconfigure \-load \fI?script?\fR. -.TP -\fBmatch \fI?patternList?\fR -Same as \fBconfigure \-match \fI?patternList?\fR. -.TP -\fBmatchDirectories \fI?patternList?\fR -Same as \fBconfigure \-relateddir \fI?patternList?\fR. -.TP -\fBmatchFiles \fI?patternList?\fR -Same as \fBconfigure \-file \fI?patternList?\fR. -.TP -\fBoutputFile \fI?filename?\fR -Same as \fBconfigure \-outfile \fI?filename?\fR. -.TP -\fBpreserveCore \fI?level?\fR -Same as \fBconfigure \-preservecore \fI?level?\fR. -.TP -\fBsingleProcess \fI?boolean?\fR -Same as \fBconfigure \-singleproc \fI?boolean?\fR. -.TP -\fBskip \fI?patternList?\fR -Same as \fBconfigure \-skip \fI?patternList?\fR. -.TP -\fBskipDirectories \fI?patternList?\fR -Same as \fBconfigure \-asidefromdir \fI?patternList?\fR. -.TP -\fBskipFiles \fI?patternList?\fR -Same as \fBconfigure \-notfile \fI?patternList?\fR. -.TP -\fBtemporaryDirectory \fI?directory?\fR -Same as \fBconfigure \-tmpdir \fI?directory?\fR. -.TP -\fBtestsDirectory \fI?directory?\fR -Same as \fBconfigure \-testdir \fI?directory?\fR. -.TP -\fBverbose \fI?level?\fR -Same as \fBconfigure \-verbose \fI?level?\fR. -.SH "OTHER COMMANDS" +directly to \fBstderr\fR. +.SS "SHORTCUT CONFIGURATION COMMANDS" +.TP +\fBdebug\fR ?\fIlevel\fR? +. +Same as +.QW "\fBconfigure \-debug\fR ?\fIlevel\fR?" . +.TP +\fBerrorFile\fR ?\fIfilename\fR? +. +Same as +.QW "\fBconfigure \-errfile\fR ?\fIfilename\fR?" . +.TP +\fBlimitConstraints\fR ?\fIboolean\fR? +. +Same as +.QW "\fBconfigure \-limitconstraints\fR ?\fIboolean\fR?" . +.TP +\fBloadFile\fR ?\fIfilename\fR? +. +Same as +.QW "\fBconfigure \-loadfile\fR ?\fIfilename\fR?" . +.TP +\fBloadScript\fR ?\fIscript\fR? +. +Same as +.QW "\fBconfigure \-load\fR ?\fIscript\fR?" . +.TP +\fBmatch\fR ?\fIpatternList\fR? +. +Same as +.QW "\fBconfigure \-match\fR ?\fIpatternList\fR?" . +.TP +\fBmatchDirectories\fR ?\fIpatternList\fR? +. +Same as +.QW "\fBconfigure \-relateddir\fR ?\fIpatternList\fR?" . +.TP +\fBmatchFiles\fR ?\fIpatternList\fR? +. +Same as +.QW "\fBconfigure \-file\fR ?\fIpatternList\fR?" . +.TP +\fBoutputFile\fR ?\fIfilename\fR? +. +Same as +.QW "\fBconfigure \-outfile\fR ?\fIfilename\fR?" . +.TP +\fBpreserveCore\fR ?\fIlevel\fR? +. +Same as +.QW "\fBconfigure \-preservecore\fR ?\fIlevel\fR?" . +.TP +\fBsingleProcess\fR ?\fIboolean\fR? +. +Same as +.QW "\fBconfigure \-singleproc\fR ?\fIboolean\fR?" . +.TP +\fBskip\fR ?\fIpatternList\fR? +. +Same as +.QW "\fBconfigure \-skip\fR ?\fIpatternList\fR?" . +.TP +\fBskipDirectories\fR ?\fIpatternList\fR? +. +Same as +.QW "\fBconfigure \-asidefromdir\fR ?\fIpatternList\fR?" . +.TP +\fBskipFiles\fR ?\fIpatternList\fR? +. +Same as +.QW "\fBconfigure \-notfile\fR ?\fIpatternList\fR?" . +.TP +\fBtemporaryDirectory\fR ?\fIdirectory\fR? +. +Same as +.QW "\fBconfigure \-tmpdir\fR ?\fIdirectory\fR?" . +.TP +\fBtestsDirectory\fR ?\fIdirectory\fR? +. +Same as +.QW "\fBconfigure \-testdir\fR ?\fIdirectory\fR?" . +.TP +\fBverbose\fR ?\fIlevel\fR? +. +Same as +.QW "\fBconfigure \-verbose\fR ?\fIlevel\fR?" . +.SS "OTHER COMMANDS" .PP The remaining commands provided by \fBtcltest\fR have better alternatives provided by \fBtcltest\fR or \fBTcl\fR itself. They @@ -321,6 +373,7 @@ are retained to support existing test suites, but should be avoided in new code. .TP \fBtest\fR \fIname description optionList\fR +. This form of \fBtest\fR was provided to enable passing many options spanning several lines to \fBtest\fR as a single argument quoted by braces, rather than needing to backslash quote @@ -344,13 +397,15 @@ the source code of \fBtcltest\fR if you want to know the substitution details, or just enclose the third through last argument to \fBtest\fR in braces and hope for the best. .TP -\fBworkingDirectory\fR \fI?directoryName?\fR +\fBworkingDirectory\fR ?\fIdirectoryName\fR? +. Sets or returns the current working directory when the test suite is running. The default value for workingDirectory is the directory in which the test suite was launched. The Tcl commands \fBcd\fR and \fBpwd\fR are sufficient replacements. .TP -\fBnormalizeMsg\fR \fImsg\fR +\fBnormalizeMsg \fImsg\fR +. Returns the result of removing the .QW extra newlines from \fImsg\fR, where @@ -360,20 +415,23 @@ processing commands to modify strings as you wish, and \fBcustomMatch\fR allows flexible matching of actual and expected results. .TP -\fBnormalizePath\fR \fIpathVar\fR +\fBnormalizePath \fIpathVar\fR +. Resolves symlinks in a path, thus creating a path without internal redirection. It is assumed that \fIpathVar\fR is absolute. \fIpathVar\fR is modified in place. The Tcl command \fBfile normalize\fR is a sufficient replacement. .TP -\fBbytestring\fR \fIstring\fR +\fBbytestring \fIstring\fR +. Construct a string that consists of the requested sequence of bytes, as opposed to a string of properly formed UTF-8 characters using the value supplied in \fIstring\fR. This allows the tester to create denormalized or improperly formed strings to pass to C procedures that are supposed to accept strings with embedded NULL types and confirm that a string result has a certain pattern of bytes. This is -exactly equivalent to the Tcl command \fBencoding convertfrom identity\fR. +exactly equivalent to the Tcl command \fBencoding convertfrom\fR +\fBidentity\fR. .SH TESTS .PP The \fBtest\fR command is the heart of the \fBtcltest\fR package. @@ -388,15 +446,15 @@ The valid options for \fBtest\fR are summarized: .PP .CS \fBtest\fR \fIname\fR \fIdescription\fR - ?-constraints \fIkeywordList|expression\fR? - ?-setup \fIsetupScript\fR? - ?-body \fItestScript\fR? - ?-cleanup \fIcleanupScript\fR? - ?-result \fIexpectedAnswer\fR? - ?-output \fIexpectedOutput\fR? - ?-errorOutput \fIexpectedError\fR? - ?-returnCodes \fIcodeList\fR? - ?-match \fImode\fR? + ?\fB\-constraints \fIkeywordList|expression\fR? + ?\fB\-setup \fIsetupScript\fR? + ?\fB\-body \fItestScript\fR? + ?\fB\-cleanup \fIcleanupScript\fR? + ?\fB\-result \fIexpectedAnswer\fR? + ?\fB\-output \fIexpectedOutput\fR? + ?\fB\-errorOutput \fIexpectedError\fR? + ?\fB\-returnCodes \fIcodeList\fR? + ?\fB\-match \fImode\fR? .CE .PP The \fIname\fR may be any string. It is conventional to choose @@ -432,7 +490,8 @@ a bug, include the bug ID in the description. .PP Valid attributes and associated values are: .TP -\fB\-constraints \fIkeywordList|expression\fR +\fB\-constraints \fIkeywordList\fR|\fIexpression\fR +. The optional \fB\-constraints\fR attribute can be list of one or more keywords or an expression. If the \fB\-constraints\fR value is a list of keywords, each of these keywords should be the name of a constraint @@ -454,24 +513,30 @@ See \fBTEST CONSTRAINTS\fR below for a list of built-in constraints and information on how to add your own constraints. .TP \fB\-setup \fIscript\fR +. The optional \fB\-setup\fR attribute indicates a \fIscript\fR that will be run before the script indicated by the \fB\-body\fR attribute. If evaluation of \fIscript\fR raises an error, the test will fail. The default value is an empty script. .TP \fB\-body \fIscript\fR +. The \fB\-body\fR attribute indicates the \fIscript\fR to run to carry out the -test. It must return a result that can be checked for correctness. -If evaluation of \fIscript\fR raises an error, the test will fail. +test, which must return a result that can be checked for correctness. +If evaluation of \fIscript\fR raises an error, the test will fail +(unless the \fB\-returnCodes\fR option is used to state that an error +is expected). The default value is an empty script. .TP \fB\-cleanup \fIscript\fR +. The optional \fB\-cleanup\fR attribute indicates a \fIscript\fR that will be run after the script indicated by the \fB\-body\fR attribute. If evaluation of \fIscript\fR raises an error, the test will fail. The default value is an empty script. .TP \fB\-match \fImode\fR +. The \fB\-match\fR attribute determines how expected answers supplied by \fB\-result\fR, \fB\-output\fR, and \fB\-errorOutput\fR are compared. Valid values for \fImode\fR are \fBregexp\fR, \fBglob\fR, \fBexact\fR, and @@ -479,27 +544,31 @@ any value registered by a prior call to \fBcustomMatch\fR. The default value is \fBexact\fR. .TP \fB\-result \fIexpectedValue\fR +. The \fB\-result\fR attribute supplies the \fIexpectedValue\fR against which the return value from script will be compared. The default value is an empty string. .TP \fB\-output \fIexpectedValue\fR +. The \fB\-output\fR attribute supplies the \fIexpectedValue\fR against which any output sent to \fBstdout\fR or \fBoutputChannel\fR during evaluation of the script(s) will be compared. Note that only output printed using -\fB::puts\fR is used for comparison. If \fB\-output\fR is not specified, -output sent to \fBstdout\fR and \fBoutputChannel\fR is not processed for -comparison. +the global \fBputs\fR command is used for comparison. If \fB\-output\fR is +not specified, output sent to \fBstdout\fR and \fBoutputChannel\fR is not +processed for comparison. .TP \fB\-errorOutput \fIexpectedValue\fR +. The \fB\-errorOutput\fR attribute supplies the \fIexpectedValue\fR against which any output sent to \fBstderr\fR or \fBerrorChannel\fR during evaluation of the script(s) will be compared. Note that only output -printed using \fB::puts\fR is used for comparison. If \fB\-errorOutput\fR -is not specified, output sent to \fBstderr\fR and \fBerrorChannel\fR is -not processed for comparison. +printed using the global \fBputs\fR command is used for comparison. If +\fB\-errorOutput\fR is not specified, output sent to \fBstderr\fR and +\fBerrorChannel\fR is not processed for comparison. .TP \fB\-returnCodes \fIexpectedCodeList\fR +. The optional \fB\-returnCodes\fR attribute supplies \fIexpectedCodeList\fR, a list of return codes that may be accepted from evaluation of the \fB\-body\fR script. If evaluation of the \fB\-body\fR script returns @@ -507,7 +576,7 @@ a code not in the \fIexpectedCodeList\fR, the test fails. All return codes known to \fBreturn\fR, in both numeric and symbolic form, including extended return codes, are acceptable elements in the \fIexpectedCodeList\fR. Default value is -.QW \fBok return\fR. +.QW "\fBok return\fR" . .PP To pass, a test must successfully evaluate its \fB\-setup\fR, \fB\-body\fR, and \fB\-cleanup\fR scripts. The return code of the \fB\-body\fR script and @@ -524,12 +593,12 @@ In default operation, a successful test produces no output. The output messages produced by \fBtest\fR are controlled by the \fBconfigure \-verbose\fR option as described in \fBCONFIGURABLE OPTIONS\fR below. Any output produced by the test scripts themselves should be -produced using \fB::puts\fR to \fBoutputChannel\fR or +produced using \fBputs\fR to \fBoutputChannel\fR or \fBerrorChannel\fR, so that users of the test suite may easily capture output with the \fBconfigure \-outfile\fR and \fBconfigure \-errfile\fR options, and so that the \fB\-output\fR and \fB\-errorOutput\fR attributes work properly. -.SH "TEST CONSTRAINTS" +.SS "TEST CONSTRAINTS" .PP Constraints are used to determine whether or not a test should be skipped. Each constraint has a name, which may be any string, and a boolean @@ -557,112 +626,141 @@ The following is a list of constraints pre-defined by the \fBtcltest\fR package itself: .TP \fIsingleTestInterp\fR -test can only be run if all test files are sourced into a single interpreter +. +This test can only be run if all test files are sourced into a single +interpreter. .TP \fIunix\fR -test can only be run on any Unix platform +. +This test can only be run on any Unix platform. .TP \fIwin\fR -test can only be run on any Windows platform +. +This test can only be run on any Windows platform. .TP \fInt\fR -test can only be run on any Windows NT platform +. +This test can only be run on any Windows NT platform. .TP \fI95\fR -test can only be run on any Windows 95 platform +. +This test can only be run on any Windows 95 platform. .TP \fI98\fR -test can only be run on any Windows 98 platform +. +This test can only be run on any Windows 98 platform. .TP \fImac\fR -test can only be run on any Mac platform +. +This test can only be run on any Mac platform. .TP \fIunixOrWin\fR -test can only be run on a Unix or Windows platform +. +This test can only be run on a Unix or Windows platform. .TP \fImacOrWin\fR -test can only be run on a Mac or Windows platform +. +This test can only be run on a Mac or Windows platform. .TP \fImacOrUnix\fR -test can only be run on a Mac or Unix platform +. +This test can only be run on a Mac or Unix platform. .TP \fItempNotWin\fR -test can not be run on Windows. This flag is used to temporarily +. +This test can not be run on Windows. This flag is used to temporarily disable a test. .TP \fItempNotMac\fR -test can not be run on a Mac. This flag is used +. +This test can not be run on a Mac. This flag is used to temporarily disable a test. .TP \fIunixCrash\fR -test crashes if it is run on Unix. This flag is used to temporarily +. +This test crashes if it is run on Unix. This flag is used to temporarily disable a test. .TP \fIwinCrash\fR -test crashes if it is run on Windows. This flag is used to temporarily +. +This test crashes if it is run on Windows. This flag is used to temporarily disable a test. .TP \fImacCrash\fR -test crashes if it is run on a Mac. This flag is used to temporarily +. +This test crashes if it is run on a Mac. This flag is used to temporarily disable a test. .TP \fIemptyTest\fR -test is empty, and so not worth running, but it remains as a +. +This test is empty, and so not worth running, but it remains as a place-holder for a test to be written in the future. This constraint has value false to cause tests to be skipped unless the user specifies otherwise. .TP \fIknownBug\fR -test is known to fail and the bug is not yet fixed. This constraint +. +This test is known to fail and the bug is not yet fixed. This constraint has value false to cause tests to be skipped unless the user specifies otherwise. .TP \fInonPortable\fR -test can only be run in some known development environment. +. +This test can only be run in some known development environment. Some tests are inherently non-portable because they depend on things like word length, file system configuration, window manager, etc. This constraint has value false to cause tests to be skipped unless the user specifies otherwise. .TP \fIuserInteraction\fR -test requires interaction from the user. This constraint has +. +This test requires interaction from the user. This constraint has value false to causes tests to be skipped unless the user specifies otherwise. .TP \fIinteractive\fR -test can only be run in if the interpreter is in interactive mode +. +This test can only be run in if the interpreter is in interactive mode (when the global tcl_interactive variable is set to 1). .TP \fInonBlockFiles\fR -test can only be run if platform supports setting files into -nonblocking mode +. +This test can only be run if platform supports setting files into +nonblocking mode. .TP \fIasyncPipeClose\fR -test can only be run if platform supports async flush and async close -on a pipe +. +This test can only be run if platform supports async flush and async close +on a pipe. .TP \fIunixExecs\fR -test can only be run if this machine has Unix-style commands +. +This test can only be run if this machine has Unix-style commands \fBcat\fR, \fBecho\fR, \fBsh\fR, \fBwc\fR, \fBrm\fR, \fBsleep\fR, -\fBfgrep\fR, \fBps\fR, \fBchmod\fR, and \fBmkdir\fR available +\fBfgrep\fR, \fBps\fR, \fBchmod\fR, and \fBmkdir\fR available. .TP \fIhasIsoLocale\fR -test can only be run if can switch to an ISO locale +. +This test can only be run if can switch to an ISO locale. .TP \fIroot\fR -test can only run if Unix user is root +. +This test can only run if Unix user is root. .TP \fInotRoot\fR -test can only run if Unix user is not root +. +This test can only run if Unix user is not root. .TP \fIeformat\fR -test can only run if app has a working version of sprintf with respect +. +This test can only run if app has a working version of sprintf with respect to the .QW e format of floating-point numbers. .TP \fIstdio\fR -test can only be run if \fBinterpreter\fR can be \fBopen\fRed +. +This test can only be run if \fBinterpreter\fR can be \fBopen\fRed as a pipe. .PP The alternative mode of constraint control is enabled by setting @@ -685,7 +783,7 @@ up a configuration with .PP to run exactly those tests that exercise known bugs, and discover whether any of them pass, indicating the bug had been fixed. -.SH "RUNNING ALL TESTS" +.SS "RUNNING ALL TESTS" .PP The single command \fBrunAllTests\fR is evaluated to run an entire test suite, spanning many files and directories. The configuration @@ -748,17 +846,19 @@ The \fBconfigure\fR command is used to set and query the configurable options of \fBtcltest\fR. The valid options are: .TP \fB\-singleproc \fIboolean\fR +. Controls whether or not \fBrunAllTests\fR spawns a child process for each test file. No spawning when \fIboolean\fR is true. Default value is false. .TP \fB\-debug \fIlevel\fR +. Sets the debug level to \fIlevel\fR, an integer value indicating how -much debugging information should be printed to stdout. Note that -debug messages always go to stdout, independent of the value of +much debugging information should be printed to \fBstdout\fR. Note that +debug messages always go to \fBstdout\fR, independent of the value of \fBconfigure \-outfile\fR. Default value is 0. Levels are defined as: .RS -.IP 0 +.IP 0 4 Do not display any debug information. .IP 1 Display information regarding whether a test is skipped because it @@ -769,41 +869,45 @@ print warnings about possible lack of cleanup or balance in test files. Also print warnings about any re-use of test names. .IP 2 Display the flag array parsed by the command line processor, the -contents of the ::env array, and all user-defined variables that exist -in the current namespace as they are used. +contents of the global \fBenv\fR array, and all user-defined variables +that exist in the current namespace as they are used. .IP 3 Display information regarding what individual procs in the test harness are doing. .RE .TP \fB\-verbose \fIlevel\fR +. Sets the type of output verbosity desired to \fIlevel\fR, a list of zero or more of the elements \fBbody\fR, \fBpass\fR, \fBskip\fR, \fBstart\fR, \fBerror\fR and \fBline\fR. Default value -is \fB{body error}\fR. +is +.QW "\fBbody error\fR" . Levels are defined as: .RS -.IP "body (b)" +.IP "body (\fBb\fR)" Display the body of failed tests -.IP "pass (p)" +.IP "pass (\fBp\fR)" Print output when a test passes -.IP "skip (s)" +.IP "skip (\fBs\fR)" Print output when a test is skipped -.IP "start (t)" +.IP "start (\fBt\fR)" Print output whenever a test starts -.IP "error (e)" +.IP "error (\fBe\fR)" Print errorInfo and errorCode, if they exist, when a test return code does not match its expected return code -.IP "line (l)" +.IP "line (\fBl\fR)" Print source file line information of failed tests -.RE +.PP The single letter abbreviations noted above are also recognized so that .QW "\fBconfigure \-verbose pt\fR" is the same as .QW "\fBconfigure \-verbose {pass start}\fR" . +.RE .TP \fB\-preservecore \fIlevel\fR +. Sets the core preservation level to \fIlevel\fR. This level determines how stringent checks for core files are. Default value is 0. Levels are defined as: @@ -820,16 +924,19 @@ copy of each core file produced in \fBconfigure \-tmpdir\fR. .RE .TP \fB\-limitconstraints \fIboolean\fR +. Sets the mode by which \fBtest\fR honors constraints as described in \fBTESTS\fR above. Default value is false. .TP \fB\-constraints \fIlist\fR +. Sets all the constraints in \fIlist\fR to true. Also used in combination with \fBconfigure \-limitconstraints true\fR to control an alternative constraint mode as described in \fBTESTS\fR above. Default value is an empty list. .TP \fB\-tmpdir \fIdirectory\fR +. Sets the temporary directory to be used by \fBmakeFile\fR, \fBmakeDirectory\fR, \fBviewFile\fR, \fBremoveFile\fR, and \fBremoveDirectory\fR as the default directory where @@ -837,55 +944,66 @@ temporary files and directories created by test files should be created. Default value is \fBworkingDirectory\fR. .TP \fB\-testdir \fIdirectory\fR +. Sets the directory searched by \fBrunAllTests\fR for test files and subdirectories. Default value is \fBworkingDirectory\fR. .TP \fB\-file \fIpatternList\fR +. Sets the list of patterns used by \fBrunAllTests\fR to determine what test files to evaluate. Default value is .QW \fB*.test\fR . .TP \fB\-notfile \fIpatternList\fR +. Sets the list of patterns used by \fBrunAllTests\fR to determine what test files to skip. Default value is .QW \fBl.*.test\fR , so that any SCCS lock files are skipped. .TP \fB\-relateddir \fIpatternList\fR +. Sets the list of patterns used by \fBrunAllTests\fR to determine what subdirectories to search for an \fBall.tcl\fR file. Default value is .QW \fB*\fR . .TP \fB\-asidefromdir \fIpatternList\fR +. Sets the list of patterns used by \fBrunAllTests\fR to determine what subdirectories to skip when searching for an \fBall.tcl\fR file. Default value is an empty list. .TP \fB\-match \fIpatternList\fR +. Set the list of patterns used by \fBtest\fR to determine whether a test should be run. Default value is .QW \fB*\fR . .TP \fB\-skip \fIpatternList\fR +. Set the list of patterns used by \fBtest\fR to determine whether a test should be skipped. Default value is an empty list. .TP \fB\-load \fIscript\fR +. Sets a script to be evaluated by \fBloadTestedCommands\fR. Default value is an empty script. .TP \fB\-loadfile \fIfilename\fR +. Sets the filename from which to read a script to be evaluated by \fBloadTestedCommands\fR. This is an alternative to \fB\-load\fR. They cannot be used together. .TP \fB\-outfile \fIfilename\fR +. Sets the file to which all output produced by tcltest should be written. A file named \fIfilename\fR will be \fBopen\fRed for writing, and the resulting channel will be set as the value of \fBoutputChannel\fR. .TP \fB\-errfile \fIfilename\fR +. Sets the file to which all error output produced by tcltest should be written. A file named \fIfilename\fR will be \fBopen\fRed for writing, and the resulting channel will be set as the value @@ -948,7 +1066,9 @@ Test with a constraint. .PP At the next higher layer of organization, several \fBtest\fR commands are gathered together into a single test file. Test files should have -names with the \fB.test\fR extension, because that is the default pattern +names with the +.QW \fB.test\fR +extension, because that is the default pattern used by \fBrunAllTests\fR to find test files. It is a good rule of thumb to have one test file for each source code file of your project. It is good practice to edit the test file and the source code file @@ -976,7 +1096,7 @@ guard: .PP .CS if $myRequirement { - test badConditionalTest {} { + \fBtest\fR badConditionalTest {} { #body } result } @@ -1066,7 +1186,7 @@ to continue to support existing test suites written to the older interface specifications, many of those deprecated commands and variables still work as before. For example, in many circumstances, \fBconfigure\fR will be automatically called shortly after -\fBpackage require tcltest 2.1\fR succeeds with arguments +\fBpackage require\fR \fBtcltest 2.1\fR succeeds with arguments from the variable \fB::argv\fR. This is to support test suites that depend on the old behavior that \fBtcltest\fR was automatically configured from command line arguments. New test files should not @@ -1076,6 +1196,12 @@ depend on this, but should explicitly include eval \fB::tcltest::configure\fR $::argv .CE .PP +or +.PP +.CS +\fB::tcltest::configure\fR {*}$::argv +.CE +.PP to establish a configuration from command line arguments. .SH "KNOWN ISSUES" There are two known issues related to nested evaluations of \fBtest\fR. @@ -1117,12 +1243,15 @@ and refer to tests that were run at the same test level as test level-1.1. .PP Implementation of output and error comparison in the test command -depends on usage of ::puts in your application code. Output is -intercepted by redefining the ::puts command while the defined test +depends on usage of \fBputs\fR in your application code. Output is +intercepted by redefining the global \fBputs\fR command while the defined test script is being run. Errors thrown by C procedures or printed -directly from C applications will not be caught by the test command. +directly from C applications will not be caught by the \fBtest\fR command. Therefore, usage of the \fB\-output\fR and \fB\-errorOutput\fR options to \fBtest\fR is useful only for pure Tcl applications -that use \fB::puts\fR to produce output. +that use \fBputs\fR to produce output. .SH KEYWORDS test, test harness, test suite +.\" Local Variables: +.\" mode: nroff +.\" End: diff --git a/doc/tclvars.n b/doc/tclvars.n index 885de34..44a8e11 100644 --- a/doc/tclvars.n +++ b/doc/tclvars.n @@ -10,7 +10,7 @@ .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME -tclvars \- Variables used by Tcl +argc, argv, argv0, auto_path, env, errorCode, errorInfo, tcl_interactive, tcl_library, tcl_nonwordchars, tcl_patchLevel, tcl_pkgPath, tcl_platform, tcl_precision, tcl_rcFileName, tcl_traceCompile, tcl_traceEval, tcl_wordchars, tcl_version \- Variables used by Tcl .BE .SH DESCRIPTION .PP @@ -18,7 +18,27 @@ The following global variables are created and managed automatically by the Tcl library. Except where noted below, these variables should normally be treated as read-only by application-specific code and by users. .TP +\fBauto_path\fR +. +If set, then it must contain a valid Tcl list giving directories to +search during auto-load operations (including for package index +files when using the default \fBpackage unknown\fR handler). +This variable is initialized during startup to contain, in order: +the directories listed in the \fBTCLLIBPATH\fR environment variable, +the directory named by the \fBtcl_library\fR global variable, +the parent directory of \fBtcl_library\fR, +the directories listed in the \fBtcl_pkgPath\fR variable. +Additional locations to look for files and package indices should +normally be added to this variable using \fBlappend\fR. +.RS +.PP +Additional variables relating to package management exist. More +details are listed in the \fBVARIABLES\fR section of the \fBlibrary\fR +manual page. +.RE +.TP \fBenv\fR +. This variable is maintained by Tcl as an array whose elements are the environment variables for the process. Reading an element will return the value of the corresponding @@ -80,13 +100,26 @@ Tcl format, using as the path separator, regardless of platform. This variable is only used when initializing the \fBauto_path\fR variable. .TP +\fBenv(TCL_TZ)\fR, \fBenv(TZ)\fR +. +These specify the default timezone used for parsing and formatting times and +dates in the \fBclock\fR command. On many platforms, the TZ environment +variable is set up by the operating system. +.TP +\fBenv(LC_ALL)\fR, \fBenv(LC_MESSAGES)\fR, \fBenv(LANG)\fR +. +These environment variables are used by the \fBmsgcat\fR package to +determine what locale to format messages using. +.TP \fBenv(TCL_INTERP_DEBUG_FRAME)\fR . -If existing, it has the same effect as running \fBinterp debug {} -frame 1\fR +If existing, it has the same effect as running \fBinterp debug\fR +\fB{} -frame 1\fR as the very first command of each new Tcl interpreter. .RE .TP \fBerrorCode\fR +. This variable holds the value of the \fB\-errorcode\fR return option set by the most recent error that occurred in this interpreter. This list value represents additional information about the error @@ -116,6 +149,7 @@ and system libraries. .RE .TP \fBCHILDKILLED\fI pid sigName msg\fR +. This format is used when a child process has been killed because of a signal. The \fIpid\fR element will be the process's identifier (in decimal). The \fIsigName\fR element will be the symbolic name of the signal that caused @@ -127,12 +161,14 @@ describing the signal, such as for \fBSIGPIPE\fR. .TP \fBCHILDSTATUS\fI pid code\fR +. This format is used when a child process has exited with a non-zero exit status. The \fIpid\fR element will be the process's identifier (in decimal) and the \fIcode\fR element will be the exit code returned by the process (also in decimal). .TP \fBCHILDSUSP\fI pid sigName msg\fR +. This format is used when a child process has been suspended because of a signal. The \fIpid\fR element will be the process's identifier, in decimal. @@ -145,6 +181,7 @@ describing the signal, such as for \fBSIGTTIN\fR. .TP \fBNONE\fR +. This format is used for errors where no additional information is available for an error besides the message returned with the error. In these cases the \fB\-errorcode\fR return option @@ -152,6 +189,7 @@ will consist of a list containing a single element whose contents are \fBNONE\fR. .TP \fBPOSIX \fIerrName msg\fR +. If the first element is \fBPOSIX\fR, then the error occurred during a POSIX kernel call. The \fIerrName\fR element will contain the symbolic name @@ -161,6 +199,11 @@ The \fImsg\fR element will be a human-readable message corresponding to \fIerrName\fR, such as .QW "no such file or directory" for the \fBENOENT\fR case. +.TP +\fBTCL\fR ... +. +Indicates some sort of problem generated in relation to Tcl itself, e.g. a +failure to look up a channel or variable. .PP To set the \fB\-errorcode\fR return option, applications should use library procedures such as \fBTcl_SetObjErrorCode\fR, \fBTcl_SetReturnOptions\fR, @@ -170,13 +213,9 @@ If none of these methods for setting the error code has been used, the Tcl interpreter will reset the variable to \fBNONE\fR after the next error. .RE -.\" .TP -.\" \fBTCL\fR ... -.\" . -.\" Indicates some sort of problem generated in relation to Tcl itself, -.\" e.g. a failure to look up a channel or variable. .TP \fBerrorInfo\fR +. This variable holds the value of the \fB\-errorinfo\fR return option set by the most recent error that occurred in this interpreter. This string value will contain one or more lines @@ -186,6 +225,7 @@ Its contents take the form of a stack trace showing the various nested Tcl commands that had been invoked at the time of the error. .TP \fBtcl_library\fR +. This variable holds the name of a directory containing the system library of Tcl scripts, such as those used for auto-loading. The value of this variable is returned by the \fBinfo library\fR command. @@ -216,14 +256,16 @@ The value of this variable is returned by the \fBinfo patchlevel\fR command. .TP \fBtcl_pkgPath\fR +. This variable holds a list of directories indicating where packages are normally installed. It is not used on Windows. It typically contains either one or two entries; if it contains two entries, the first is normally a directory for platform-dependent packages (e.g., shared library binaries) and the second is normally a directory for platform-independent packages (e.g., script files). Typically a package is installed as a -subdirectory of one of the entries in \fB$tcl_pkgPath\fR. The directories -in \fB$tcl_pkgPath\fR are included by default in the \fBauto_path\fR +subdirectory of one of the entries in the \fBtcl_pkgPath\fR +variable. The directories in the \fBtcl_pkgPath\fR variable are +included by default in the \fBauto_path\fR variable, so they and their immediate subdirectories are automatically searched for packages during \fBpackage require\fR commands. Note: \fBtcl_pkgPath\fR is not intended to be modified by the application. Its @@ -233,6 +275,7 @@ directories for packages you should add the names of those directories to \fBauto_path\fR, not \fBtcl_pkgPath\fR. .TP \fBtcl_platform\fR +. This is an associative array whose elements contain information about the platform on which the application is running, such as the name of the operating system, its current release number, and the machine's @@ -244,10 +287,12 @@ predefined elements are: .RS .TP \fBbyteOrder\fR +. The native byte order of this machine: either \fBlittleEndian\fR or \fBbigEndian\fR. .TP \fBdebug\fR +. If this variable exists, then the interpreter was compiled with and linked to a debug-enabled C run-time. This variable will only exist on Windows, so extension writers can specify which package to load depending on the @@ -255,11 +300,13 @@ C run-time library that is in use. This is not an indication that this core contains symbols. .TP \fBmachine\fR +. The instruction set executed by this machine, such as \fBintel\fR, \fBPPC\fR, \fB68k\fR, or \fBsun4m\fR. On UNIX machines, this is the value returned by \fBuname -m\fR. .TP -\fBos\fR +\fBos\fR +. The name of the operating system running on this machine, such as \fBWindows 95\fR, \fBWindows NT\fR, or \fBSunOS\fR. On UNIX machines, this is the value returned by \fBuname -s\fR. @@ -268,32 +315,45 @@ On Windows 95 and Windows 98, the value returned will be \fBWindows distinguish between the two, check the \fBosVersion\fR. .TP \fBosVersion\fR +. The version number for the operating system running on this machine. On UNIX machines, this is the value returned by \fBuname -r\fR. On Windows 95, the version will be 4.0; on Windows 98, the version will be 4.10. .TP +\fBpathSeparator\fR +.VS 8.6 +'\" Defined by TIP #315 +The character that should be used to \fBsplit\fR PATH-like environment +variables into their corresponding list of directory names. +.VE 8.6 +.TP \fBplatform\fR +. Either \fBwindows\fR, or \fBunix\fR. This identifies the general operating environment of the machine. .TP +\fBpointerSize\fR +. +This gives the size of the native-machine pointer in bytes (strictly, it +is same as the result of evaluating \fIsizeof(void*)\fR in C.) +.TP \fBthreaded\fR +. If this variable exists, then the interpreter was compiled with threads enabled. .TP \fBuser\fR +. This identifies the current user based on the login information available on the platform. This comes from the USER or LOGNAME environment variable on Unix, and the value from GetUserName on Windows. .TP \fBwordSize\fR +. This gives the size of the native-machine word in bytes (strictly, it is same as the result of evaluating \fIsizeof(long)\fR in C.) -.TP -\fBpointerSize\fR -This gives the size of the native-machine pointer in bytes (strictly, it -is same as the result of evaluating \fIsizeof(void*)\fR in C.) .RE .TP \fBtcl_precision\fR @@ -352,6 +412,7 @@ Valid values for \fBtcl_precision\fR range from 0 to 17. .RE .TP \fBtcl_rcFileName\fR +. This variable is used during initialization to indicate the name of a user-specific startup file. If it is set by application-specific initialization, then the Tcl startup code will check for the existence @@ -360,13 +421,14 @@ the variable is set to \fB~/.wishrc\fR for Unix and \fB~/wishrc.tcl\fR for Windows. .TP \fBtcl_traceCompile\fR +. The value of this variable can be set to control how much tracing information is displayed during bytecode compilation. -By default, tcl_traceCompile is zero and no information is displayed. -Setting tcl_traceCompile to 1 generates a one-line summary in stdout +By default, \fBtcl_traceCompile\fR is zero and no information is displayed. +Setting \fBtcl_traceCompile\fR to 1 generates a one-line summary in \fBstdout\fR whenever a procedure or top-level command is compiled. -Setting it to 2 generates a detailed listing in stdout of the +Setting it to 2 generates a detailed listing in \fBstdout\fR of the bytecode instructions emitted during every compilation. This variable is useful in tracking down suspected problems with the Tcl compiler. @@ -377,18 +439,19 @@ This variable and functionality only exist if .RE .TP \fBtcl_traceExec\fR +. The value of this variable can be set to control how much tracing information is displayed during bytecode execution. -By default, tcl_traceExec is zero and no information is displayed. -Setting tcl_traceExec to 1 generates a one-line trace in stdout +By default, \fBtcl_traceExec\fR is zero and no information is displayed. +Setting \fBtcl_traceExec\fR to 1 generates a one-line trace in \fBstdout\fR on each call to a Tcl procedure. Setting it to 2 generates a line of output whenever any Tcl command is invoked that contains the name of the command and its arguments. Setting it to 3 produces a detailed trace showing the result of executing each bytecode instruction. -Note that when tcl_traceExec is 2 or 3, +Note that when \fBtcl_traceExec\fR is 2 or 3, commands such as \fBset\fR and \fBincr\fR that have been entirely replaced by a sequence of bytecode instructions are not shown. @@ -402,6 +465,7 @@ This variable and functionality only exist if .RE .TP \fBtcl_wordchars\fR +. The value of this variable is a regular expression that can be set to control what are considered .QW word @@ -412,6 +476,7 @@ but a Unicode space character. Otherwise it defaults to \fB\ew\fR, which is any Unicode word character (number, letter, or underscore). .TP \fBtcl_nonwordchars\fR +. The value of this variable is a regular expression that can be set to control what are considered .QW non-word @@ -422,6 +487,7 @@ character. Otherwise it defaults to \fB\eW\fR, which is anything but a Unicode word character (number, letter, or underscore). .TP \fBtcl_version\fR +. When an interpreter is created Tcl initializes this variable to hold the version number for this version of Tcl in the form \fIx.y\fR. Changes to \fIx\fR represent major changes with probable @@ -430,33 +496,71 @@ bug fixes that retain backward compatibility. The value of this variable is returned by the \fBinfo tclversion\fR command. .SH "OTHER GLOBAL VARIABLES" +.PP The following variables are only guaranteed to exist in \fBtclsh\fR and \fBwish\fR executables; the Tcl library does not define them itself but many Tcl environments do. .TP 6 \fBargc\fR +. The number of arguments to \fBtclsh\fR or \fBwish\fR. .TP 6 \fBargv\fR +. Tcl list of arguments to \fBtclsh\fR or \fBwish\fR. .TP 6 \fBargv0\fR +. The script that \fBtclsh\fR or \fBwish\fR started executing (if it was specified) or otherwise the name by which \fBtclsh\fR or \fBwish\fR was invoked. .TP 6 \fBtcl_interactive\fR +. Contains 1 if \fBtclsh\fR or \fBwish\fR is running interactively (no script was specified and standard input is a terminal-like device), 0 otherwise. +.SH EXAMPLES .PP -The \fBwish\fR executable additionally specifies the following global -variable: -.TP 6 -\fBgeometry\fR -If set, contains the user-supplied geometry specification to use for -the main Tk window. +To add a directory to the collection of locations searched by +\fBpackage require\fR, e.g., because of some application-specific +packages that are used, the \fBauto_path\fR variable needs to be +updated: +.PP +.CS +lappend ::\fBauto_path\fR [file join [pwd] "theLibDir"] +.CE +.PP +A simple though not very robust way to handle command line arguments +of the form +.QW "\-foo 1 \-bar 2" +is to load them into an array having first loaded in the default settings: +.CS +array set arguments {-foo 0 -bar 0 -grill 0} +array set arguments $::\fBargv\fR +puts "foo is $arguments(-foo)" +puts "bar is $arguments(-bar)" +puts "grill is $arguments(-grill)" +.CE +.PP +The \fBargv0\fR global variable can be used (in conjunction with the +\fBinfo script\fR command) to determine whether the current script is +being executed as the main script or loaded as a library. This is +useful because it allows a single script to be used as both a library +and a demonstration of that library: +.PP +.CS +if {$::\fBargv0\fR eq [info script]} { + # running as: tclsh example.tcl +} else { + package provide Example 1.0 +} +.CE .SH "SEE ALSO" -eval(n), tclsh(1), wish(1) +eval(n), library(n), tclsh(1), tkvars(n), wish(1) .SH KEYWORDS -arithmetic, bytecode, compiler, error, environment, POSIX, precision, subprocess, variables +arithmetic, bytecode, compiler, error, environment, POSIX, precision, +subprocess, user, variables +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -14,7 +14,6 @@ tell \- Return current access position for an open channel .SH SYNOPSIS \fBtell \fIchannelId\fR .BE - .SH DESCRIPTION .PP Returns an integer string giving the current access position in @@ -29,7 +28,9 @@ Tcl standard channel (\fBstdin\fR, \fBstdout\fR, or \fBstderr\fR), the return value from an invocation of \fBopen\fR or \fBsocket\fR, or the result of a channel creation command provided by a Tcl extension. .SH EXAMPLE +.PP Read a line from a file channel only if it starts with \fBfoobar\fR: +.PP .CS # Save the offset in case we need to undo the read... set offset [\fBtell\fR $chan] @@ -41,9 +42,7 @@ if {[read $chan 6] eq "foobar"} { seek $chan $offset } .CE - .SH "SEE ALSO" file(n), open(n), close(n), gets(n), seek(n), Tcl_StandardChannels(3) - .SH KEYWORDS access position, channel, seeking diff --git a/doc/throw.n b/doc/throw.n new file mode 100644 index 0000000..d49fb24 --- /dev/null +++ b/doc/throw.n @@ -0,0 +1,48 @@ +'\" +'\" Copyright (c) 2008 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH throw n 8.6 Tcl "Tcl Built-In Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +throw \- Generate a machine-readable error +.SH SYNOPSIS +\fBthrow\fI type message\fR +.BE +.SH DESCRIPTION +.PP +This command causes the current evaluation to be unwound with an error. The +error created is described by the \fItype\fR and \fImessage\fR arguments: +\fItype\fR must contain a list of words describing the error in a form that is +machine-readable (and which will form the error-code part of the result +dictionary), and \fImessage\fR should contain text that is intended for +display to a human being. +.PP +The stack will be unwound until the error is trapped by a suitable \fBcatch\fR +or \fBtry\fR command. If it reaches the event loop without being trapped, it +will be reported through the \fBbgerror\fR mechanism. If it reaches the top +level of script evaluation in \fBtclsh\fR, it will be printed on the console +before, in the non-interactive case, causing an exit (the behavior in other +programs will depend on the details of how Tcl is embedded and used). +.PP +By convention, the words in the \fItype\fR argument should go from most +general to most specific. +.SH EXAMPLES +.PP +The following produces an error that is identical to that produced by +\fBexpr\fR when trying to divide a value by zero. +.PP +.CS +\fBthrow\fR {ARITH DIVZERO {divide by zero}} {divide by zero} +.CE +.SH "SEE ALSO" +catch(n), error(n), return(n), tclvars(n), try(n) +.SH "KEYWORDS" +error, exception +'\" Local Variables: +'\" mode: nroff +'\" End: @@ -14,21 +14,23 @@ time \- Time the execution of a script .SH SYNOPSIS \fBtime \fIscript\fR ?\fIcount\fR? .BE - .SH DESCRIPTION .PP This command will call the Tcl interpreter \fIcount\fR times to evaluate \fIscript\fR (or once if \fIcount\fR is not specified). It will then return a string of the form +.PP .CS -\fB503 microseconds per iteration\fR +\fB503.2 microseconds per iteration\fR .CE +.PP which indicates the average amount of time required per iteration, in microseconds. Time is measured in elapsed time, not CPU time. .SH EXAMPLE Estimate how long it takes for a simple Tcl \fBfor\fR loop to count to a thousand: +.PP .CS time { for {set i 0} {$i<1000} {incr i} { @@ -36,9 +38,10 @@ time { } } .CE - .SH "SEE ALSO" clock(n) - .SH KEYWORDS script, time +.\" Local Variables: +.\" mode: nroff +.\" End: @@ -19,6 +19,7 @@ tm \- Facilities for locating and loading of Tcl Modules .fi .BE .SH DESCRIPTION +.PP This document describes the facilities for locating and loading Tcl Modules (see \fBMODULE DEFINITION\fR for the definition of a Tcl Module). The following commands are supported: @@ -75,9 +76,11 @@ The command has been exposed to allow a build system to define additional root paths beyond those described by this document. .RE .SH "MODULE DEFINITION" +.PP A Tcl Module is a Tcl Package contained in a single file, and no other files required by it. This file has to be \fBsource\fRable. In other words, a Tcl Module is always imported via: +.PP .CS source module_file .CE @@ -91,6 +94,7 @@ attached data in any it chooses to fully import and activate the package. .PP The name of a module file has to match the regular expression: +.PP .CS ([_[:alpha:]][:_[:alnum:]]*)-([[:digit:]].*)\e.tm .CE @@ -99,11 +103,12 @@ The first capturing parentheses provides the name of the package, the second clause its version. In addition to matching the pattern, the extracted version number must not raise an error when used in the command: +.PP .CS package vcompare $version 0 .CE -.PP .SH "FINDING MODULES" +.PP The directory tree for storing Tcl modules is separate from other parts of the filesystem and independent of \fBauto_path\fR. .PP @@ -164,10 +169,13 @@ Note that packages in module form have \fIno\fR control over the \fIindex\fR and \fIprovide script\fRs entered into the package database for them. For a module file \fBMF\fR the \fIindex script\fR is always: +.PP .CS package ifneeded \fBPNAME PVERSION\fR [list source \fBMF\fR] .CE +.PP and the \fIprovide script\fR embedded in the above is: +.PP .CS source \fBMF\fR .CE @@ -175,6 +183,7 @@ source \fBMF\fR Both package name \fBPNAME\fR and package version \fBPVERSION\fR are extracted from the filename \fBMF\fR according to the definition below: +.PP .CS \fBMF\fR = /module_path/\fBPNAME\(fm\fR-\fBPVERSION\fR.tm .CE @@ -199,6 +208,7 @@ package \fBFoo\fR is deployed in the form of a Tcl Module, packages like \fBfoo\fR, \fBfOo\fR, etc. are not allowed anymore. .SH "DEFAULT PATHS" +.PP The default list of paths on the module path is computed by a \fBtclsh\fR as follows, where \fIX\fR is the major version of the Tcl interpreter and \fIy\fR is less than or equal to the minor version of @@ -223,6 +233,7 @@ to the minor version of the interpreter. .RS .PP For example for Tcl 8.4 the paths searched are: +.PP .CS \fB[info library]/../tcl8/8.4\fR \fB[info library]/../tcl8/8.3\fR @@ -274,8 +285,9 @@ These paths are seen and therefore shared by all Tcl shells in the \fB$::env(PATH)\fR of the user. .PP Note that \fIX\fR and \fIy\fR follow the general rules set out -above. In other words, Tcl 8.4, for example, will look at these 5 +above. In other words, Tcl 8.4, for example, will look at these 10 environment variables: +.PP .CS \fB$::env(TCL8.4_TM_PATH)\fR \fB$::env(TCL8_4_TM_PATH)\fR \fB$::env(TCL8.3_TM_PATH)\fR \fB$::env(TCL8_3_TM_PATH)\fR @@ -291,3 +303,6 @@ package(n), Tcl Improvement Proposal #189 (online at http://tip.tcl.tk/190.html) .SH "KEYWORDS" modules, package +.\" Local Variables: +.\" mode: nroff +.\" End: diff --git a/doc/trace.n b/doc/trace.n index 9d40123..940a1e9 100644 --- a/doc/trace.n +++ b/doc/trace.n @@ -54,9 +54,11 @@ execute them. When the trace triggers, depending on the operations being traced, a number of arguments are appended to \fIcommandPrefix\fR so that the actual command is as follows: +.PP .CS \fIcommandPrefix oldName newName op\fR .CE +.PP \fIOldName\fR and \fInewName\fR give the traced command's current (old) name, and the name to which it is being renamed (the empty string if this is a .QW delete @@ -121,9 +123,11 @@ number of arguments are appended to \fIcommandPrefix\fR so that the actual command is as follows: .PP For \fBenter\fR and \fBenterstep\fR operations: +.PP .CS \fIcommandPrefix command-string op\fR .CE +.PP \fICommand-string\fR gives the complete current command being executed (the traced command for a \fBenter\fR operation, an arbitrary command for a \fBenterstep\fR operation), including @@ -137,9 +141,11 @@ course when the command is subsequently executed, an error will occur. .PP For \fBleave\fR and \fBleavestep\fR operations: +.PP .CS \fIcommand command-string code result op\fR .CE +.PP \fICommand-string\fR gives the complete current command being executed (the traced command for a \fBenter\fR operation, an arbitrary command for a \fBenterstep\fR operation), including @@ -217,9 +223,11 @@ interpreter in which to execute them. .PP When the trace triggers, three arguments are appended to \fIcommandPrefix\fR so that the actual command is as follows: +.PP .CS \fIcommandPrefix name1 name2 op\fR .CE +.PP \fIName1\fR and \fIname2\fR give the name(s) for the variable being accessed: if the variable is a scalar then \fIname1\fR gives the variable's name and \fIname2\fR is an empty string; @@ -368,9 +376,11 @@ future version of Tcl. They use an older syntax in which \fBarray\fR, list, but simply a string concatenation of the operations, such as \fBrwua\fR. .SH EXAMPLES +.PP Print a message whenever either of the global variables \fBfoo\fR and \fBbar\fR are updated, even if they have a different local name at the time (which can be done with the \fBupvar\fR command): +.PP .CS proc tracer {varname args} { upvar #0 $varname var @@ -382,6 +392,7 @@ proc tracer {varname args} { .PP Ensure that the global variable \fBfoobar\fR always contains the product of the global variables \fBfoo\fR and \fBbar\fR: +.PP .CS proc doMult args { global foo bar foobar @@ -393,6 +404,7 @@ proc doMult args { .PP Print a trace of what commands are executed during the processing of a Tcl procedure: +.PP .CS proc x {} { y } proc y {} { z } @@ -409,3 +421,6 @@ x set(n), unset(n) .SH KEYWORDS read, command, rename, variable, write, trace, unset +.\" Local Variables: +.\" mode: nroff +.\" End: diff --git a/doc/transchan.n b/doc/transchan.n new file mode 100644 index 0000000..e308e13 --- /dev/null +++ b/doc/transchan.n @@ -0,0 +1,160 @@ +'\" +'\" Copyright (c) 2008 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH transchan n 8.6 Tcl "Tcl Built-In Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +transchan \- command handler API of channel transforms +.SH SYNOPSIS +\fBcmdPrefix \fIoption\fR ?\fIarg arg ...\fR? +.BE +.SH DESCRIPTION +.PP +The Tcl-level handler for a channel transformation has to be a command with +subcommands (termed an \fIensemble\fR despite not implying that it must be +created with \fBnamespace ensemble create\fR; this mechanism is not tied to +\fBnamespace ensemble\fR in any way). Note that \fIcmdPrefix\fR is whatever +was specified in the call to \fBchan push\fR, and may consist of multiple +arguments; this will be expanded to multiple words in place of the prefix. +.PP +Of all the possible subcommands, the handler \fImust\fR support +\fBinitialize\fR and \fBfinalize\fR. Transformations for writable channels +must also support \fBwrite\fR, and transformations for readable channels must +also support \fBread\fR. +.PP +Note that in the descriptions below \fIcmdPrefix\fR may be more than one word, +and \fIhandle\fR is the value returned by the \fBchan push\fR call used to +create the transformation. +.SS "GENERIC SUBCOMMANDS" +.PP +The following subcommands are relevant to all types of channel. +.TP +\fIcmdPrefix \fBclear \fIhandle\fR +. +This optional subcommand is called to signify to the transformation that any +data stored in internal buffers (either incoming or outgoing) must be +cleared. It is called when a \fBchan seek\fR is performed on the channel being +transformed. +.TP +\fIcmdPrefix \fBfinalize \fIhandle\fR +. +This mandatory subcommand is called last for the given \fIhandle\fR, and then +never again, and it exists to allow for cleaning up any Tcl-level data +structures associated with the transformation. \fIWarning!\fR Any errors +thrown by this subcommand will be ignored. It is not guaranteed to be called +if the interpreter is deleted. +.TP +\fIcmdPrefix \fBinitialize \fIhandle mode\fR +. +This mandatory subcommand is called first, and then never again (for the given +\fIhandle\fR). Its responsibility is to initialize all parts of the +transformation at the Tcl level. The \fImode\fR is a list containing any of +\fBread \fRand \fBwrite\fR. +.RS +.TP +\fBwrite\fR +. +implies that the channel is writable. +.TP +\fBread\fR +. +implies that the channel is readable. +.PP +The return value of the subcommand should be a list containing the names of +all subcommands supported by this handler. Any error thrown by the subcommand +will prevent the creation of the transformation. The thrown error will appear +as error thrown by \fBchan push\fR. +.RE +.SS "READ-RELATED SUBCOMMANDS" +.PP +These subcommands are used for handling transformations applied to readable +channels; though strictly \fBread \fRis optional, it must be supported if any +of the others is or the channel will be made non-readable. +.TP +\fIcmdPrefix \fBdrain \fIhandle\fR +. +This optional subcommand is called whenever data in the transformation input +(i.e. read) buffer has to be forced upward, i.e. towards the user or script. +The result returned by the method is taken as the \fIbinary\fR data to push +upward to the level above this transformation (the reader or a higher-level +transformation). +.RS +.PP +In other words, when this method is called the transformation cannot defer the +actual transformation operation anymore and has to transform all data waiting +in its internal read buffers and return the result of that action. +.RE +.TP +\fIcmdPrefix \fBlimit? \fIhandle\fR +. +This optional subcommand is called to allow the Tcl I/O engine to determine +how far ahead it should read. If present, it should return an integer number +greater than zero which indicates how many bytes ahead should be read, or an +integer less than zero to indicate that the I/O engine may read as far ahead +as it likes. +.TP +\fIcmdPrefix \fBread \fIhandle buffer\fR +. +This subcommand, which must be present if the transformation is to work with +readable channels, is called whenever the base channel, or a transformation +below this transformation, pushes data upward. The \fIbuffer\fR contains the +binary data which has been given to us from below. It is the responsibility of +this subcommand to actually transform the data. The result returned by the +subcommand is taken as the binary data to push further upward to the +transformation above this transformation. This can also be the user or script +that originally read from the channel. +.RS +.PP +Note that the result is allowed to be empty, or even less than the data we +received; the transformation is not required to transform everything given to +it right now. It is allowed to store incoming data in internal buffers and to +defer the actual transformation until it has more data. +.RE +.SS "WRITE-RELATED SUBCOMMANDS" +.PP +These subcommands are used for handling transformations applied to writable +channels; though strictly \fBwrite\fR is optional, it must be supported if any +of the others is or the channel will be made non-writable. +.TP +\fIcmdPrefix \fBflush \fIhandle\fR +. +This optional subcommand is called whenever data in the transformation 'write' +buffer has to be forced downward, i.e. towards the base channel. The result +returned by the subcommand is taken as the binary data to write to the +transformation below the current transformation. This can be the base channel +as well. +.RS +.PP +In other words, when this subcommand is called the transformation cannot defer +the actual transformation operation anymore and has to transform all data +waiting in its internal write buffers and return the result of that action. +.RE +.TP +\fIcmdPrefix \fBwrite \fIhandle buffer\fR +. +This subcommand, which must be present if the transformation is to work with +writable channels, is called whenever the user, or a transformation above this +transformation, writes data downward. The \fIbuffer\fR contains the binary +data which has been written to us. It is the responsibility of this subcommand +to actually transform the data. +.RS +.PP +The result returned by the subcommand is taken as the binary data to write to +the transformation below this transformation. This can be the base channel as +well. Note that the result is allowed to be empty, or less than the data we +got; the transformation is not required to transform everything which was +written to it right now. It is allowed to store this data in internal buffers +and to defer the actual transformation until it has more data. +.RE +.SH "SEE ALSO" +chan(n), refchan(n) +.SH KEYWORDS +API, channel, ensemble, prefix, transformation +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/try.n b/doc/try.n new file mode 100644 index 0000000..393fe5b --- /dev/null +++ b/doc/try.n @@ -0,0 +1,103 @@ +'\" +'\" Copyright (c) 2008 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH try n 8.6 Tcl "Tcl Built-In Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +try \- Trap and process errors and exceptions +.SH SYNOPSIS +\fBtry\fI body\fR ?\fIhandler...\fR? ?\fBfinally\fI script\fR? +.BE +.SH DESCRIPTION +.PP +This command executes the script \fIbody\fR and, depending on what the outcome +of that script is (normal exit, error, or some other exceptional result), runs +a handler script to deal with the case. Once that has all happened, if the +\fBfinally\fR clause is present, the \fIscript\fR it includes will be run and +the result of the handler (or the \fIbody\fR if no handler matched) is allowed +to continue to propagate. Note that the \fBfinally\fR clause is processed even +if an error occurs and irrespective of which, if any, \fIhandler\fR is used. +.PP +The \fIhandler\fR clauses are each expressed as several words, and must have +one of the following forms: +.TP +\fBon \fIcode variableList script\fR +. +This clause matches if the evaluation of \fIbody\fR completed with the +exception code \fIcode\fR. The \fIcode\fR may be expressed as an integer or +one of the following literal words: \fBok\fR, \fBerror\fR, \fBreturn\fR, +\fBbreak\fR, or \fBcontinue\fR. Those literals correspond to the integers 0 +through 4 respectively. +.TP +\fBtrap \fIpattern variableList script\fR +. +This clause matches if the evaluation of \fIbody\fR resulted in an error and +the prefix of the \fB\-errorcode\fR from the interpreter's status dictionary +is equal to the \fIpattern\fR. The number of prefix words taken from the +\fB\-errorcode\fR is equal to the list-length of \fIpattern\fR, and inter-word +spaces are normalized in both the \fB\-errorcode\fR and \fIpattern\fR before +comparison. +.PP +The \fIvariableList\fR word in each \fIhandler\fR is always interpreted as a +list of variable names. If the first word of the list is present and +non-empty, it names a variable into which the result of the evaluation of +\fIbody\fR (from the main \fBtry\fR) will be placed; this will contain the +human-readable form of any errors. If the second word of the list is present +and non-empty, it names a variable into which the options dictionary of the +interpreter at the moment of completion of execution of \fIbody\fR +will be placed. +.PP +The \fIscript\fR word of each \fIhandler\fR is also always interpreted the +same: as a Tcl script to evaluate if the clause is matched. If \fIscript\fR is +a literal +.QW \- +and the \fIhandler\fR is not the last one, the \fIscript\fR of the following +\fIhandler\fR is invoked instead (just like with the \fBswitch\fR command). +.PP +Note that \fIhandler\fR clauses are matched against in order, and that the +first matching one is always selected. At most one \fIhandler\fR clause will +selected. As a consequence, an \fBon error\fR will mask any subsequent +\fBtrap\fR in the \fBtry\fR. Also note that \fBon error\fR is equivalent to +\fBtrap {}\fR. +.PP +If an exception (i.e. any non-\fBok\fR result) occurs during the evaluation of +either the \fIhandler\fR or the \fBfinally\fR clause, the original exception's +status dictionary will be added to the new exception's status dictionary under +the \fB\-during\fR key. +.SH EXAMPLES +.PP +Ensure that a file is closed no matter what: +.PP +.CS +set f [open /some/file/name a] +\fBtry\fR { + puts $f "some message" + # ... +} \fBfinally\fR { + close $f +} +.CE +.PP +Handle different reasons for a file to not be openable for reading: +.PP +.CS +\fBtry\fR { + set f [open /some/file/name] +} \fBtrap\fR {POSIX EISDIR} {} { + puts "failed to open /some/file/name: it's a directory" +} \fBtrap\fR {POSIX ENOENT} {} { + puts "failed to open /some/file/name: it doesn't exist" +} +.CE +.SH "SEE ALSO" +catch(n), error(n), return(n), throw(n) +.SH "KEYWORDS" +cleanup, error, exception, final, resource management +'\" Local Variables: +'\" mode: nroff +'\" End: diff --git a/doc/unknown.n b/doc/unknown.n index c258daa..fc2a5a1 100644 --- a/doc/unknown.n +++ b/doc/unknown.n @@ -88,4 +88,4 @@ proc \fBunknown\fR args { .SH "SEE ALSO" info(n), proc(n), interp(n), library(n), namespace(n) .SH KEYWORDS -error, non-existent command +error, non-existent command, unknown diff --git a/doc/unload.n b/doc/unload.n index f060cd6..4c0b292 100644 --- a/doc/unload.n +++ b/doc/unload.n @@ -88,8 +88,11 @@ detached from the process. .SS "UNLOAD HOOK PROTOTYPE" .PP The unload procedure must match the following prototype: +.PP .CS -typedef int Tcl_PackageUnloadProc(Tcl_Interp *\fIinterp\fR, int \fIflags\fR); +typedef int \fBTcl_PackageUnloadProc\fR( + Tcl_Interp *\fIinterp\fR, + int \fIflags\fR); .CE .PP The \fIinterp\fR argument identifies the interpreter from which the @@ -142,12 +145,16 @@ library is still loaded), it may be dangerous to use \fBunload\fR on such a library (as the library will be completely detached from the application while some interpreters will continue to use it). .SH EXAMPLE +.PP If an unloadable module in the file \fBfoobar.dll\fR had been loaded using the \fBload\fR command like this (on Windows): +.PP .CS load c:/some/dir/foobar.dll .CE +.PP then it would be unloaded like this: +.PP .CS \fBunload\fR c:/some/dir/foobar.dll .CE @@ -160,3 +167,6 @@ without having to shut down the overall Tcl process. info sharedlibextension, load(n), safe(n) .SH KEYWORDS binary code, unloading, safe interpreter, shared library +.\" Local Variables: +.\" mode: nroff +.\" End: diff --git a/doc/unset.n b/doc/unset.n index 29d7e7c..64b334d 100644 --- a/doc/unset.n +++ b/doc/unset.n @@ -13,7 +13,7 @@ .SH NAME unset \- Delete variables .SH SYNOPSIS -\fBunset \fR?\fI\-nocomplain\fR? ?\fI\-\-\fR? ?\fIname name name ...\fR? +\fBunset \fR?\fB\-nocomplain\fR? ?\fB\-\-\fR? ?\fIname name name ...\fR? .BE .SH DESCRIPTION .PP @@ -25,19 +25,21 @@ element is removed without affecting the rest of the array. If a \fIname\fR consists of an array name with no parenthesized index, then the entire array is deleted. The \fBunset\fR command returns an empty string as result. -If \fI\-nocomplain\fR is specified as the first argument, any possible +If \fB\-nocomplain\fR is specified as the first argument, any possible errors are suppressed. The option may not be abbreviated, in order to -disambiguate it from possible variable names. The option \fI\-\-\fR +disambiguate it from possible variable names. The option \fB\-\-\fR indicates the end of the options, and should be used if you wish to remove a variable with the same name as any of the options. -If an error occurs, any variables after the named one causing the error -are not +If an error occurs during variable deletion, any variables after the named one +causing the error are not deleted. An error can occur when the named variable does not exist, or the name refers to an array element but the variable is a scalar, or the name refers to a variable in a non-existent namespace. .SH EXAMPLE +.PP Create an array containing a mapping from some numbers to their squares and remove the array elements for non-prime numbers: +.PP .CS array set squares { 1 1 6 36 @@ -60,3 +62,7 @@ parray squares set(n), trace(n), upvar(n) .SH KEYWORDS remove, variable +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: diff --git a/doc/update.n b/doc/update.n index 555766c..0c77c5f 100644 --- a/doc/update.n +++ b/doc/update.n @@ -14,7 +14,6 @@ update \- Process pending events and idle callbacks .SH SYNOPSIS \fBupdate\fR ?\fBidletasks\fR? .BE - .SH DESCRIPTION .PP This command is used to bring the application @@ -43,7 +42,9 @@ the application to respond to events such as user interactions; if you occasionally call \fBupdate\fR then user input will be processed during the next call to \fBupdate\fR. .SH EXAMPLE +.PP Run computations for about a second and then finish: +.PP .CS set x 1000 set done 0 @@ -58,9 +59,7 @@ while {!$done} { \fBupdate\fR } .CE - .SH "SEE ALSO" after(n), interp(n) - .SH KEYWORDS -event, flush, handler, idle, update +asynchronous I/O, event, flush, handler, idle, update diff --git a/doc/uplevel.n b/doc/uplevel.n index c8ef0ff..6c8a957 100644 --- a/doc/uplevel.n +++ b/doc/uplevel.n @@ -40,16 +40,20 @@ at top-level (only global variables will be visible). The \fBuplevel\fR command causes the invoking procedure to disappear from the procedure calling stack while the command is being executed. In the above example, suppose \fBc\fR invokes the command +.PP .CS \fBuplevel\fR 1 {set x 43; d} .CE +.PP where \fBd\fR is another Tcl procedure. The \fBset\fR command will modify the variable \fBx\fR in \fBb\fR's context, and \fBd\fR will execute at level 3, as if called from \fBb\fR. If it in turn executes the command +.PP .CS \fBuplevel\fR {set x 42} .CE +.PP then the \fBset\fR command will modify the same variable \fBx\fR in \fBb\fR's context: the procedure \fBc\fR does not appear to be on the call stack when \fBd\fR is executing. The \fBinfo level\fR command may @@ -75,6 +79,7 @@ control constructs. This example shows how (without error handling) it can be used to create a \fBdo\fR command that is the counterpart of \fBwhile\fR except for always performing the test after running the loop body: +.PP .CS proc do {body while condition} { if {$while ne "while"} { @@ -92,4 +97,7 @@ proc do {body while condition} { .SH "SEE ALSO" apply(n), namespace(n), upvar(n) .SH KEYWORDS -context, level, namespace, stack frame, variables +context, level, namespace, stack frame, variable +.\" Local Variables: +.\" mode: nroff +.\" End: diff --git a/doc/upvar.n b/doc/upvar.n index a255485..60e5324 100644 --- a/doc/upvar.n +++ b/doc/upvar.n @@ -21,8 +21,7 @@ This command arranges for one or more local variables in the current procedure to refer to variables in an enclosing procedure call or to global variables. \fILevel\fR may have any of the forms permitted for the \fBuplevel\fR -command, and may be omitted if the first letter of the first \fIotherVar\fR -is not \fB#\fR or a digit (it defaults to \fB1\fR). +command, and may be omitted (it defaults to \fB1\fR). For each \fIotherVar\fR argument, \fBupvar\fR makes the variable by that name in the procedure frame given by \fIlevel\fR (or at global level, if \fIlevel\fR is \fB#0\fR) accessible @@ -43,16 +42,18 @@ The \fBupvar\fR command simplifies the implementation of call-by-name procedure calling and also makes it easier to build new control constructs as Tcl procedures. For example, consider the following procedure: +.PP .CS proc \fIadd2\fR name { - \fBupvar\fR $name x - set x [expr {$x + 2}] + \fBupvar\fR $name x + set x [expr {$x + 2}] } .CE +.PP If \fIadd2\fR is invoked with an argument giving the name of a variable, it adds two to the value of that variable. Although \fIadd2\fR could have been implemented using \fBuplevel\fR -instead of \fBupvar\fR, \fBupvar\fR makes it simpler for \fBadd2\fR +instead of \fBupvar\fR, \fBupvar\fR makes it simpler for \fIadd2\fR to access the variable in the caller's procedure frame. .PP \fBnamespace eval\fR is another way (besides procedure calls) @@ -60,7 +61,7 @@ that the Tcl naming context can change. It adds a call frame to the stack to represent the namespace context. This means each \fBnamespace eval\fR command counts as another call level for \fBuplevel\fR and \fBupvar\fR commands. -For example, \fBinfo level 1\fR will return a list +For example, \fBinfo level\fR \fB1\fR will return a list describing a command that is either the outermost procedure call or the outermost \fBnamespace eval\fR command. Also, \fBuplevel #0\fR evaluates a script @@ -83,13 +84,14 @@ will be .QW "\fIlocalVar\fR" rather than .QW "\fIoriginalVar\fR" : +.PP .CS proc \fItraceproc\fR { name index op } { - puts $name + puts $name } proc \fIsetByUpvar\fR { name value } { - \fBupvar\fR $name localVar - set localVar $value + \fBupvar\fR $name localVar + set localVar $value } set originalVar 1 trace variable originalVar w \fItraceproc\fR @@ -104,15 +106,17 @@ made to \fImyVar\fR will not be passed to subprocesses correctly. .SH EXAMPLE A \fBdecr\fR command that works like \fBincr\fR except it subtracts the value from the variable instead of adding it: +.PP .CS proc decr {varName {decrement 1}} { \fBupvar\fR 1 $varName var incr var [expr {-$decrement}] } .CE - .SH "SEE ALSO" global(n), namespace(n), uplevel(n), variable(n) - .SH KEYWORDS -context, frame, global, level, namespace, procedure, variable +context, frame, global, level, namespace, procedure, upvar, variable +.\" Local Variables: +.\" mode: nroff +.\" End: diff --git a/doc/variable.n b/doc/variable.n index 3a60485..96263b6 100644 --- a/doc/variable.n +++ b/doc/variable.n @@ -12,9 +12,10 @@ .SH NAME variable \- create and initialize a namespace variable .SH SYNOPSIS -\fBvariable \fR?\fIname value...\fR? \fIname \fR?\fIvalue\fR? +\fBvariable \fR\fIname\fR +.sp +\fBvariable \fR?\fIname value...\fR? .BE - .SH DESCRIPTION .PP This command is normally used within a @@ -57,7 +58,9 @@ After the variable has been declared, elements within the array can be set using ordinary \fBset\fR or \fBarray\fR commands. .SH EXAMPLES +.PP Create a variable in a namespace: +.PP .CS namespace eval foo { \fBvariable\fR bar 12345 @@ -65,6 +68,7 @@ namespace eval foo { .CE .PP Create an array in a namespace: +.PP .CS namespace eval someNS { \fBvariable\fR someAry @@ -76,6 +80,7 @@ namespace eval someNS { .CE .PP Access variables in namespaces from a procedure: +.PP .CS namespace eval foo { proc spong {} { @@ -89,9 +94,7 @@ namespace eval foo { } } .CE - .SH "SEE ALSO" global(n), namespace(n), upvar(n) - .SH KEYWORDS global, namespace, procedure, variable diff --git a/doc/vwait.n b/doc/vwait.n index e7289e1..38a8081 100644 --- a/doc/vwait.n +++ b/doc/vwait.n @@ -13,44 +13,57 @@ vwait \- Process events until a variable is written .SH SYNOPSIS \fBvwait\fR \fIvarName\fR .BE - .SH DESCRIPTION .PP This command enters the Tcl event loop to process events, blocking the application if no events are ready. It continues processing -events until some event handler sets the value of variable +events until some event handler sets the value of the global variable \fIvarName\fR. Once \fIvarName\fR has been set, the \fBvwait\fR command will return as soon as the event handler that modified -\fIvarName\fR completes. \fIvarName\fR must be globally scoped -(either with a call to \fBglobal\fR for the \fIvarName\fR, or with -the full namespace path specification). +\fIvarName\fR completes. The \fIvarName\fR argument is always interpreted as +a variable name with respect to the global namespace, but can refer to any +namespace's variables if the fully-qualified name is given. .PP In some cases the \fBvwait\fR command may not return immediately -after \fIvarName\fR is set. This can happen if the event handler +after \fIvarName\fR is set. This happens if the event handler that sets \fIvarName\fR does not complete immediately. For example, if an event handler sets \fIvarName\fR and then itself calls \fBvwait\fR to wait for a different variable, then it may not return for a long time. During this time the top-level \fBvwait\fR is blocked waiting for the event handler to complete, so it cannot -return either. +return either. (See the \fBNESTED VWAITS BY EXAMPLE\fR below.) +.PP +To be clear, \fImultiple \fBvwait\fI calls will nest and will not happen in +parallel\fR. The outermost call to \fBvwait\fR will not return until all the +inner ones do. It is recommended that code should never nest \fBvwait\fR +calls (by avoiding putting them in event callbacks) but when that is not +possible, care should be taken to add interlock variables to the code to +prevent all reentrant calls to \fBvwait\fR that are not \fIstrictly\fR +necessary. Be aware that the synchronous modes of operation of some Tcl +packages (e.g.,\ \fBhttp\fR) use \fBvwait\fR internally; if using the event +loop, it is best to use the asynchronous callback-based modes of operation of +those packages where available. .SH EXAMPLES +.PP Run the event-loop continually until some event calls \fBexit\fR. (You can use any variable not mentioned elsewhere, but the name \fIforever\fR reminds you at a glance of the intent.) +.PP .CS \fBvwait\fR forever .CE .PP Wait five seconds for a connection to a server socket, otherwise close the socket and continue running the script: +.PP .CS # Initialise the state after 5000 set state timeout set server [socket -server accept 12345] proc accept {args} { - global state connectionInfo - set state accepted - set connectionInfo $args + global state connectionInfo + set state accepted + set connectionInfo $args } # Wait for something to happen @@ -62,18 +75,172 @@ after cancel set state timeout # Do something based on how the vwait finished... switch $state { - timeout { - puts "no connection on port 12345" - } - accepted { - puts "connection: $connectionInfo" - puts [lindex $connectionInfo 0] "Hello there!" - } + timeout { + puts "no connection on port 12345" + } + accepted { + puts "connection: $connectionInfo" + puts [lindex $connectionInfo 0] "Hello there!" + } +} +.CE +.PP +A command that will wait for some time delay by waiting for a namespace +variable to be set. Includes an interlock to prevent nested waits. +.PP +.CS +namespace eval example { + variable v done + proc wait {delay} { + variable v + if {$v ne "waiting"} { + set v waiting + after $delay [namespace code {set v done}] + \fBvwait\fR [namespace which -variable v] + } + return $v + } +} +.CE +.PP +When running inside a \fBcoroutine\fR, an alternative to using \fBvwait\fR is +to \fByield\fR to an outer event loop and to get recommenced when the variable +is set, or at an idle moment after that. +.PP +.CS +coroutine task apply {{} { + # simulate [after 1000] + after 1000 [info coroutine] + yield + + # schedule the setting of a global variable, as normal + after 2000 {set var 1} + + # simulate [\fBvwait\fR var] + proc updatedVar {task args} { + after idle $task + trace remove variable ::var write "updatedVar $task" + } + trace add variable ::var write "updatedVar [info coroutine]" + yield +}} +.CE +.SS "NESTED VWAITS BY EXAMPLE" +.PP +This example demonstrates what can happen when the \fBvwait\fR command is +nested. The script will never finish because the waiting for the \fIa\fR +variable never finishes; that \fBvwait\fR command is still waiting for a +script scheduled with \fBafter\fR to complete, which just happens to be +running an inner \fBvwait\fR (for \fIb\fR) even though the event that the +outer \fBvwait\fR was waiting for (the setting of \fIa\fR) has occurred. +.PP +.CS +after 500 { + puts "waiting for b" + \fBvwait\fR b + puts "b was set" } +after 1000 { + puts "setting a" + set a 10 +} +puts "waiting for a" +\fBvwait\fR a +puts "a was set" +puts "setting b" +set b 42 +.CE +.PP +If you run the above code, you get this output: +.PP +.CS +waiting for a +waiting for b +setting a +.CE +.PP +The script will never print +.QW "a was set" +until after it has printed +.QW "b was set" +because of the nesting of \fBvwait\fR commands, and yet \fIb\fR will not be +set until after the outer \fBvwait\fR returns, so the script has deadlocked. +The only ways to avoid this are to either structure the overall program in +continuation-passing style or to use \fBcoroutine\fR to make the continuations +implicit. The first of these options would be written as: +.PP +.CS +after 500 { + puts "waiting for b" + trace add variable b write {apply {args { + global a b + trace remove variable ::b write \e + [lrange [info level 0] 0 1] + puts "b was set" + set ::done ok + }}} +} +after 1000 { + puts "setting a" + set a 10 +} +puts "waiting for a" +trace add variable a write {apply {args { + global a b + trace remove variable a write [lrange [info level 0] 0 1] + puts "a was set" + puts "setting b" + set b 42 +}}} +\fBvwait\fR done .CE +.PP +The second option, with \fBcoroutine\fR and some helper procedures, is done +like this: +.PP +.CS +# A coroutine-based wait-for-variable command +proc waitvar globalVar { + trace add variable ::$globalVar write \e + [list apply {{v c args} { + trace remove variable $v write \e + [lrange [info level 0] 0 3] + after 0 $c + }} ::$globalVar [info coroutine]] + yield +} +# A coroutine-based wait-for-some-time command +proc waittime ms { + after $ms [info coroutine] + yield +} +coroutine task-1 eval { + puts "waiting for a" + waitvar a + puts "a was set" + puts "setting b" + set b 42 +} +coroutine task-2 eval { + waittime 500 + puts "waiting for b" + waitvar b + puts "b was set" + set done ok +} +coroutine task-3 eval { + waittime 1000 + puts "setting a" + set a 10 +} +\fBvwait\fR done +.CE .SH "SEE ALSO" global(n), update(n) - .SH KEYWORDS -event, variable, wait +asynchronous I/O, event, variable, wait +'\" Local Variables: +'\" mode: nroff +'\" fill-column: 78 +'\" End: diff --git a/doc/while.n b/doc/while.n index 33aa415..5416e25 100644 --- a/doc/while.n +++ b/doc/while.n @@ -14,7 +14,6 @@ while \- Execute script repeatedly as long as a condition is met .SH SYNOPSIS \fBwhile \fItest body\fR .BE - .SH DESCRIPTION .PP The \fBwhile\fR command evaluates \fItest\fR as an expression @@ -41,6 +40,7 @@ expression is evaluated (before each loop iteration), so changes in the variables will be visible. For an example, try the following script with and without the braces around \fB$x<10\fR: +.PP .CS set x 0 \fBwhile\fR {$x<10} { @@ -49,17 +49,17 @@ set x 0 } .CE .SH EXAMPLE +.PP Read lines from a channel until we get to the end of the stream, and print them out with a line-number prepended: +.PP .CS set lineCount 0 \fBwhile\fR {[gets $chan line] >= 0} { puts "[incr lineCount]: $line" } .CE - .SH "SEE ALSO" break(n), continue(n), for(n), foreach(n) - .SH KEYWORDS -boolean value, loop, test, while +boolean, loop, test, while diff --git a/doc/zlib.n b/doc/zlib.n new file mode 100644 index 0000000..9fa83c6 --- /dev/null +++ b/doc/zlib.n @@ -0,0 +1,390 @@ +'\" +'\" Copyright (c) 2008 Donal K. Fellows +'\" +'\" See the file "license.terms" for information on usage and redistribution +'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. +'\" +.so man.macros +.TH zlib n 8.6 Tcl "Tcl Built-In Commands" +.BS +'\" Note: do not modify the .SH NAME line immediately below! +.SH NAME +zlib \- compression and decompression operations +.SH SYNOPSIS +.nf +\fBzlib \fIsubcommand arg ...\fR +.fi +.BE +.SH DESCRIPTION +.PP +The \fBzlib\fR command provides access to the compression and check-summing +facilities of the Zlib library by Jean-loup Gailly and Mark Adler. It has the +following subcommands. +.SS "COMPRESSION SUBCOMMANDS" +.TP +\fBzlib compress\fI string\fR ?\fIlevel\fR? +. +Returns the zlib-format compressed binary data of the binary string in +\fIstring\fR. If present, \fIlevel\fR gives the compression level to use (from +0, which is uncompressed, to 9, maximally compressed). +.TP +\fBzlib decompress\fI string\fR ?\fIbufferSize\fR? +. +Returns the uncompressed version of the raw compressed binary data in +\fIstring\fR. If present, \fIbufferSize\fR is a hint as to what size of buffer +is to be used to receive the data. +.TP +\fBzlib deflate\fI string\fR ?\fIlevel\fR? +. +Returns the raw compressed binary data of the binary string in \fIstring\fR. +If present, \fIlevel\fR gives the compression level to use (from 0, which is +uncompressed, to 9, maximally compressed). +.TP +\fBzlib gunzip\fI string\fR ?\fB\-headerVar \fIvarName\fR? +. +Return the uncompressed contents of binary string \fIstring\fR, which must +have been in gzip format. If \fB\-headerVar\fR is given, store a dictionary +describing the contents of the gzip header in the variable called +\fIvarName\fR. The keys of the dictionary that may be present are: +.RS +.TP +\fBcomment\fR +. +The comment field from the header, if present. +.TP +\fBcrc\fR +. +A boolean value describing whether a CRC of the header is computed. +.TP +\fBfilename\fR +. +The filename field from the header, if present. +.TP +\fBos\fR +. +The operating system type code field from the header (if not the +QW unknown +value). See RFC 1952 for the meaning of these codes. +.TP +\fBsize\fR +. +The size of the uncompressed data. +.TP +\fBtime\fR +. +The time field from the header if non-zero, expected to be time that the file +named by the \fBfilename\fR field was modified. Suitable for use with +\fBclock format\fR. +.TP +\fBtype\fR +. +The type of the uncompressed data (\fBbinary\fR or \fBtext\fR) if known. +.RE +.TP +\fBzlib gzip\fI string\fR ?\fB\-level \fIlevel\fR? ?\fB\-header \fIdict\fR? +. +Return the compressed contents of binary string \fIstring\fR in gzip format. +If \fB\-level\fR is given, \fIlevel\fR gives the compression level to use +(from 0, which is uncompressed, to 9, maximally compressed). If \fB\-header\fR +is given, \fIdict\fR is a dictionary containing values used for the gzip +header. The following keys may be defined: +.RS +.TP +\fBcomment\fR +. +Add the given comment to the header of the gzip-format data. +.TP +\fBcrc\fR +. +A boolean saying whether to compute a CRC of the header. Note that if the data +is to be interchanged with the \fBgzip\fR program, a header CRC should +\fInot\fR be computed. +.TP +\fBfilename\fR +. +The name of the file that the data to be compressed came from. +.TP +\fBos\fR +. +The operating system type code, which should be one of the values described in +RFC 1952. +.TP +\fBtime\fR +. +The time that the file named in the \fBfilename\fR key was last modified. This +will be in the same as is returned by \fBclock seconds\fR or \fBfile mtime\fR. +.TP +\fBtype\fR +. +The type of the data being compressed, being \fBbinary\fR or \fBtext\fR. +.RE +.TP +\fBzlib inflate\fI string\fR ?\fIbufferSize\fR? +. +Returns the uncompressed version of the raw compressed binary data in +\fIstring\fR. If present, \fIbufferSize\fR is a hint as to what size of buffer +is to be used to receive the data. +.SS "CHANNEL SUBCOMMAND" +.TP +\fBzlib push\fI mode channel\fR ?\fIoptions ...\fR? +. +Pushes a compressing or decompressing transformation onto the channel +\fIchannel\fR. +The transformation can be removed again with \fBchan pop\fR. +The \fImode\fR argument determines what type of transformation +is pushed; the following are supported: +.RS +.TP +\fBcompress\fR +. +The transformation will be a compressing transformation that produces +zlib-format data on \fIchannel\fR, which must be writable. +.TP +\fBdecompress\fR +. +The transformation will be a decompressing transformation that reads +zlib-format data from \fIchannel\fR, which must be readable. +.TP +\fBdeflate\fR +. +The transformation will be a compressing transformation that produces raw +compressed data on \fIchannel\fR, which must be writable. +.TP +\fBgunzip\fR +. +The transformation will be a decompressing transformation that reads +gzip-format data from \fIchannel\fR, which must be readable. +.TP +\fBgzip\fR +. +The transformation will be a compressing transformation that produces +gzip-format data on \fIchannel\fR, which must be writable. +.TP +\fBinflate\fR +. +The transformation will be a decompressing transformation that reads raw +compressed data from \fIchannel\fR, which must be readable. +.PP +The following options may be set when creating a transformation via +the +.QW "\fIoptions ...\fR" +to the \fBzlib push\fR command: +.TP +\fB\-header\fI dictionary\fR +. +Passes a description of the gzip header to create, in the same format that +\fBzlib gzip\fR understands. +.TP +\fB\-level\fI compressionLevel\fR +. +How hard to compress the data. Must be an integer from 0 (uncompressed) to 9 +(maximally compressed). +'\".TP +'\"\fB\-limit\fI readaheadLimit\fR +'\". +'\"The maximum number of bytes ahead to read. +'\"\fITODO: not yet implemented!\fR +.PP +Both compressing and decompressing channel transformations add extra +configuration options that may be accessed through \fBchan configure\fR. Each +option is either a read-only or a write-only option. The options are: +.TP +\fB\-flush\fI type\fR +. +This write-only operation flushes the current state of the compressor to the +underlying channel. It is only valid for compressing transformations. The +\fItype\fR must be either \fBsync\fR or \fBfull\fR for a normal flush or an +expensive flush respectively. Flushing degrades the compression ratio, but +makes it easier for a decompressor to recover more of the file in the case of +data corruption. +.TP +\fB\-checksum\fR +. +This read-only option, valid for both compressing and decompressing +transforms, gets the current checksum for the uncompressed data that the +compression engine has seen so far. The compression algorithm depends on what +format is being produced or consumed. +.TP +\fB\-header\fR +. +This read-only option, only valid for decompressing transforms that are +processing gzip-format data, returns the dictionary describing the header read +off the data stream. +.RE +.SS "STREAMING SUBCOMMAND" +.TP +\fBzlib stream\fI mode\fR ?\fIlevel\fR? +. +Creates a streaming compression or decompression command based on the +\fImode\fR, and return the name of the command. For a description of how that +command works, see \fBSTREAMING INSTANCE COMMAND\fR below. The following modes +are supported: +.RS +.TP +\fBzlib stream compress\fR ?\fIlevel\fR? +. +The stream will be a compressing stream that produces zlib-format output, +using compression level \fIlevel\fR (if specified) which will be an integer +from 0 to 9. +.TP +\fBzlib stream decompress\fR +. +The stream will be a decompressing stream that takes zlib-format input and +produces uncompressed output. +.TP +\fBzlib stream deflate\fR ?\fIlevel\fR? +. +The stream will be a compressing stream that produces raw output, using +compression level \fIlevel\fR (if specified) which will be an integer from 0 +to 9. +.TP +\fBzlib stream gunzip\fR +. +The stream will be a decompressing stream that takes gzip-format input and +produces uncompressed output. +.TP +\fBzlib stream gzip\fR ?\fIlevel\fR? +. +The stream will be a compressing stream that produces gzip-format output, +using compression level \fIlevel\fR (if specified) which will be an integer +from 0 to 9. +'\" TODO: Header dictionary! +.TP +\fBzlib stream inflate\fR +. +The stream will be a decompressing stream that takes raw compressed input and +produces uncompressed output. +.RE +.SS "CHECKSUMMING SUBCOMMANDS" +.TP +\fBzlib adler32\fI string\fR ?\fIinitValue\fR? +. +Compute a checksum of binary string \fIstring\fR using the Adler-32 algorithm. +If given, \fIinitValue\fR is used to initialize the checksum engine. +.TP +\fBzlib crc32\fI string\fR ?\fIinitValue\fR? +. +Compute a checksum of binary string \fIstring\fR using the CRC-32 algorithm. +If given, \fIinitValue\fR is used to initialize the checksum engine. +.SH "STREAMING INSTANCE COMMAND" +.PP +Streaming compression instance commands are produced by the \fBzlib stream\fR +command. They are used by calling their \fBput\fR subcommand one or more times +to load data in, and their \fBget\fR subcommand one or more times to extract +the transformed data. +.PP +The full set of subcommands supported by a streaming instance command, +\fIstream\fR, is as follows: +.TP +\fIstream \fBadd\fR ?\fIoption\fR? \fIdata\fR +. +A short-cut for +.QW "\fIstream \fBput \fIoption data\fR" +followed by +.QW "\fIstream \fBget\fR" . +.TP +\fIstream \fBchecksum\fR +. +Returns the checksum of the uncompressed data seen so far by this stream. +.TP +\fIstream \fBclose\fR +. +Deletes this stream and frees up all resources associated with it. +.TP +\fIstream \fBeof\fR +. +Returns a boolean indicating whether the end of the stream (as determined by +the compressed data itself) has been reached. Not all formats support +detection of the end of the stream. +.TP +\fIstream \fBfinalize\fR +. +A short-cut for +.QW "\fIstream \fBput \-finalize {}\fR" . +.TP +\fIstream \fBflush\fR +. +A short-cut for +.QW "\fIstream \fBput \-flush {}\fR" . +.TP +\fIstream \fBfullflush\fR +. +A short-cut for +.QW "\fIstream \fBput \-fullflush {}\fR" . +.TP +\fIstream \fBget \fR?\fIcount\fR? +. +Return up to \fIcount\fR bytes from \fIstream\fR's internal buffers with the +transformation applied. If \fIcount\fR is omitted, the entire contents of the +buffers are returned. +.TP +\fIstream \fBput\fR ?\fIoption\fR? \fIdata\fR +. +Append the contents of the binary string \fIdata\fR to \fIstream\fR's internal +buffers while applying the transformation. If present, \fIoption\fR must be +one of the following (or an unambiguous prefix) which are used to modify the +way in which the transformation is applied: +.RS +.TP +\fB\-finalize\fR +. +Mark the stream as finished, ensuring that all bytes have been wholly +compressed or decompressed. For gzip streams, this also ensures that the +footer is written to the stream. The stream will need to be reset before +having more data written to it after this, though data can still be read out +of the stream with the \fBget\fR subcommand. +.TP +\fB\-flush\fR +. +Ensure that a decompressor consuming the bytes that the current (compressing) +stream is producing will be able to produce all the bytes that have been +compressed so far, at some performance penalty. +.TP +\fB\-fullflush\fR +. +Ensure that not only can a decompressor handle all the bytes produced so far +(as with \fB\-flush\fR above) but also that it can restart from this point if +it detects that the stream is partially corrupt. This incurs a substantial +performance penalty. +.RE +.TP +\fIstream \fBreset\fR +. +Puts any stream, including those that have been finalized or that have reached +eof, back into a state where it can process more data. Throws away all +internally buffered data. +.SH EXAMPLES +.PP +To compress a Tcl string, it should be first converted to a particular charset +encoding since the \fBzlib\fR command always operates on binary strings. +.PP +.CS +set binData [encoding convertto utf-8 $string] +set compData [\fBzlib compress\fR $binData] +.CE +.PP +When converting back, it is also important to reverse the charset encoding: +.PP +.CS +set binData [\fBzlib decompress\fR $compData] +set string [encoding convertfrom utf-8 $binData] +.CE +.PP +The compression operation from above can also be done with streams, which is +especially helpful when you want to accumulate the data by stages: +.PP +.CS +set strm [\fBzlib stream\fR compress] +$\fIstrm \fBput\fR [encoding convertto utf-8 $string] +# ... +$\fIstrm \fBfinalize\fR +set compData [$\fIstrm \fBget\fR] +$\fIstrm \fBclose\fR +.CE +.SH "SEE ALSO" +binary(n), chan(n), encoding(n), Tcl_ZlibDeflate(3), RFC1950 \- RFC1952 +.SH "KEYWORDS" +compress, decompress, deflate, gzip, inflate +'\" Local Variables: +'\" mode: nroff +'\" End: |