ActiveTcl 8.3.4.1 Documentation Index

Tcl | Tk | Tcllib | TkCon | TclXML | Img
TclX | [incr Tcl] | [incr Tk] | IWidgets | TclDOM | tkHTML
Expect | TkTable | BWidgets | TclSOAP | Snack

Sitemap

Tcl, Tk

Tcl/Tk Applications
Tcl Commands
Tk Commands
Tcl Library
Tk Library
Keywords
Copyright

Tcllib

base64
cmdline
comm
control
counter
csv
fileutil
ftpd
ftp
html
htmlparse
javascript
log
math
md5
mime
smtp
ncgi
nntp
pop3
profiler
report
sha1
stats
graph
matrix
queue
stack
tree
textutil
uri

TkCon

Documentation
Purpose & Features
Limitations
To Do
License
Online Demo
Using TkCon with other Tk Languages
Screenshot
Getting Started
Special Bindings
tkcon Procedures
dump proc
tkcon proc
idebug proc
observe proc

TclX

Writing C language extensions to Tcl.
Writing C language extensions to Tcl (Tcl_Obj-based commands).
Tcl_HandleAlloc, Tcl_HandleFree, Tcl_HandleTblInit, Tcl_HandleTblRelease, Tcl_HandleTblUseCount , Tcl_HandleWalk, Tcl_HandleXlate
TclX_NewKeyedListObj, TclX_KeyedListGet, TclX_KeyedListSet, TclX_KeyedListDelete, TclX_KeyedListGetKeys
ckalloc, ckfree, memory, Tcl_DisplayMemory, Tcl_InitMemory, Tcl_ValidateAllMemory
Tclx_Init, Tclxcmd_Init, TclX_Main, Tkx_Init, TkX_Main Extended
TclX commands

[incr Tcl]

itclsh
body
code
delete
find
itcl_class
itclvars
scope
class
configbody
ensemble
itcl
itcl_info
local

[incr Tk]

itkwish
Archetype
Toplevel
Widget
itk
itkvars
usual

IWidgets

buttonbox
calendar
canvasprintbox
canvasprintdialog
checkbox
combobox
dateentry
datefield
dialog
dialogshell
disjointlistbox
entryfield
extbutton
extfileselectionbox
extfileselectiondialog
feedback
fileselectionbox
fileselectiondialog
finddialog
hierarchy
hyperhelp
labeledframe
labeledwidget
mainwindow
menubar
messagebox
messagedialog
notebook
optionmenu
panedwindow
promptdialog
pushbutton
radiobox
scopedobject
scrolledcanvas
scrolledframe
scrolledhtml
scrolledlistbox
scrolledtext
selectionbox
selectiondialog
shell
spindate
spinint
spinner
spintime
tabnotebook
tabset
timeentry
timefield
toolbar
watch

Expect

expect
expectk
expect C library API

BWidgets

Label
Entry
Button
ArrowButton
ProgressBar
ScrollView
Separator
MainFrame
LabelFrame
TitleFrame
ScrolledWindow
ScrollableFrame
PanedWindow
ButtonBox
PagesManager
NoteBook
Dialog
LabelEntry
ComboBox
SpinBox
Tree
ListBox
MessageDlg
ProgressDlg
PasswdDlg
SelectFont
SelectColor
Widget
DynamicHelp
DragSite
DropSite
BWidget
Copyright © 2001 ActiveState


Tcl8.3/Tk8.3 Manual

Tcl/Tk Applications
The interpreters which implement Tcl and Tk.
Tcl Commands
The commands which the tclsh interpreter implements.
Tk Commands
The additional commands which the wish interpreter implements.
Tcl Library
The C functions which a Tcl extended C program may use.
Tk Library
The additional C functions which a Tk extended C program may use.
Keywords
The keywords from the Tcl/Tk man pages.
Source
More information about these man pages.
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation
Copyright © 1995-1997 Roger E. Critchlow Jr.


Tcl/Tk Applications Manual

Tcl/Tk Applications

tclsh wish
Copyright © 1991-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Commands Manual

Tcl Commands

Http | continue | history | pid | switch
Safe Base | dde | if | pkg::create | tcl_endOfWord
Tcl | encoding | incr | pkg_mkIndex | tcl_findLibrary
Tcltest | eof | info | proc | tcl_startOfNextWord
after | error | interp | puts | tcl_startOfPreviousWord
append | eval | join | pwd | tcl_wordBreakAfter
array | exec | lappend | re_syntax | tcl_wordBreakBefore
auto_execok | exit | lindex | read | tclvars
auto_import | expr | linsert | regexp | tell
auto_load | fblocked | list | registry | time
auto_mkindex | fconfigure | llength | regsub | trace
auto_mkindex_old | fcopy | load | rename | unknown
auto_qualify | file | lrange | resource | unset
auto_reset | fileevent | lreplace | return | update
bgerror | filename | lsearch | scan | uplevel
binary | flush | lsort | seek | upvar
break | for | memory | set | variable
catch | foreach | msgcat | socket | vwait
cd | format | namespace | source | while
clock | gets | open | split
close | glob | package | string
concat | global | parray | subst
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1992-1995 Karl Lehenbauer and Mark Diekhans.
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-2000 Ajuba Solutions.
Copyright © 1998-2000 Scriptics Corporation.


Tk Commands Manual

Tk Commands

bell | destroy | label | photo | tk_bisque | tk_optionMenu
bind | entry | listbox | place | tk_chooseColor | tk_popup
bindtags | event | loadTk | radiobutton | tk_chooseDirectory | tk_setPalette
bitmap | focus | lower | raise | tk_dialog | tkerror
button | font | menu | scale | tk_focusFollowsMouse | tkvars
canvas | frame | menubutton | scrollbar | tk_focusNext | tkwait
checkbutton | grab | message | selection | tk_focusPrev | toplevel
clipboard | grid | option | send | tk_getOpenFile | winfo
colors | image | options | text | tk_getSaveFile | wm
cursors | keysyms | pack | tk | tk_messageBox
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994 The Australian National University
Copyright © 1994-1997 Sun Microsystems, Inc.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998-2000 Ajuba Solutions.


Tcl Library Manual

Tcl Library

 | Tcl_DeleteTimerHandler | Tcl_GetUnicode | Tcl_ServiceAll
TCL_MEM_DEBUG | Tcl_DeleteTrace | Tcl_GetVar | Tcl_ServiceEvent
Tcl_Access | Tcl_DetachPids | Tcl_GetVar2 | Tcl_SetAssocData
Tcl_AddErrorInfo | Tcl_DiscardResult | Tcl_GetVar2Ex | Tcl_SetBooleanObj
Tcl_AddObjErrorInfo | Tcl_DoOneEvent | Tcl_GetVersion | Tcl_SetByteArrayLength
Tcl_AlertNotifier | Tcl_DoWhenIdle | Tcl_Gets | Tcl_SetByteArrayObj
Tcl_Alloc | Tcl_DontCallWhenDeleted | Tcl_GetsObj | Tcl_SetChannelBufferSize
Tcl_AllowExceptions | Tcl_DumpActiveMemory | Tcl_GlobalEval | Tcl_SetChannelOption
Tcl_AppInit | Tcl_DuplicateObj | Tcl_GlobalEvalObj | Tcl_SetCommandInfo
Tcl_AppendAllObjTypes | Tcl_Eof | Tcl_HashStats | Tcl_SetDefaultEncodingDir
Tcl_AppendElement | Tcl_ErrnoId | Tcl_HideCommand | Tcl_SetDoubleObj
Tcl_AppendObjToObj | Tcl_ErrnoMsg | Tcl_IncrRefCount | Tcl_SetErrno
Tcl_AppendResult | Tcl_Eval | Tcl_Init | Tcl_SetErrorCode
Tcl_AppendResultVA | Tcl_EvalEx | Tcl_InitHashTable | Tcl_SetErrorCodeVA
Tcl_AppendStringsToObj | Tcl_EvalFile | Tcl_InitMemory | Tcl_SetHashValue
Tcl_AppendStringsToObjVA | Tcl_EvalObjEx | Tcl_InitNotifier | Tcl_SetIntObj
Tcl_AppendToObj | Tcl_EvalObjv | Tcl_InitStubs | Tcl_SetListObj
Tcl_AppendUnicodeToObj | Tcl_EvalTokens | Tcl_InputBlocked | Tcl_SetLongObj
Tcl_AsyncCreate | Tcl_EventuallyFree | Tcl_InputBuffered | Tcl_SetMainLoop
Tcl_AsyncDelete | Tcl_Exit | Tcl_Interp | Tcl_SetMaxBlockTime
Tcl_AsyncInvoke | Tcl_ExitThread | Tcl_InterpDeleted | Tcl_SetObjErrorCode
Tcl_AsyncMark | Tcl_ExposeCommand | Tcl_InvalidateStringRep | Tcl_SetObjLength
Tcl_AsyncReady | Tcl_ExprBoolean | Tcl_IsSafe | Tcl_SetObjResult
Tcl_BackgroundError | Tcl_ExprBooleanObj | Tcl_IsShared | Tcl_SetRecursionLimit
Tcl_Backslash | Tcl_ExprDouble | Tcl_JoinPath | Tcl_SetResult
Tcl_BadChannelOption | Tcl_ExprDoubleObj | Tcl_LinkVar | Tcl_SetServiceMode
Tcl_CallWhenDeleted | Tcl_ExprLong | Tcl_ListObjAppendElement | Tcl_SetStdChannel
Tcl_CancelIdleCall | Tcl_ExprLongObj | Tcl_ListObjAppendList | Tcl_SetStringObj
Tcl_ChannelBlockModeProc | Tcl_ExprObj | Tcl_ListObjGetElements | Tcl_SetSystemEncoding
Tcl_ChannelClose2Proc | Tcl_ExprString | Tcl_ListObjIndex | Tcl_SetTimer
Tcl_ChannelCloseProc | Tcl_ExternalToUtf | Tcl_ListObjLength | Tcl_SetUnicodeObj
Tcl_ChannelFlushProc | Tcl_ExternalToUtfDString | Tcl_ListObjReplace | Tcl_SetVar
Tcl_ChannelGetHandleProc | Tcl_Finalize | Tcl_LogCommandInfo | Tcl_SetVar2
Tcl_ChannelGetOptionProc | Tcl_FinalizeNotifier | Tcl_Main | Tcl_SetVar2Ex
Tcl_ChannelHandlerProc | Tcl_FinalizeThread | Tcl_MakeFileChannel | Tcl_Sleep
Tcl_ChannelInputProc | Tcl_FindExecutable | Tcl_MakeSafe | Tcl_SourceRCFile
Tcl_ChannelName | Tcl_FindHashEntry | Tcl_MakeTcpClientChannel | Tcl_SplitList
Tcl_ChannelOutputProc | Tcl_FirstHashEntry | Tcl_Merge | Tcl_SplitPath
Tcl_ChannelSeekProc | Tcl_Flush | Tcl_MutexFinalize | Tcl_StackChannel
Tcl_ChannelSetOptionProc | Tcl_Free | Tcl_MutexLock | Tcl_Stat
Tcl_ChannelVersion | Tcl_FreeEncoding | Tcl_MutexUnlock | Tcl_StaticPackage
Tcl_ChannelWatchProc | Tcl_FreeParse | Tcl_NewBooleanObj | Tcl_StringCaseMatch
Tcl_Chdir | Tcl_FreeResult | Tcl_NewByteArrayObj | Tcl_StringMatch
Tcl_Close | Tcl_GetAlias | Tcl_NewDoubleObj | Tcl_Tell
Tcl_CommandComplete | Tcl_GetAliasObj | Tcl_NewIntObj | Tcl_ThreadAlert
Tcl_Concat | Tcl_GetAssocData | Tcl_NewListObj | Tcl_ThreadQueueEvent
Tcl_ConcatObj | Tcl_GetBoolean | Tcl_NewLongObj | Tcl_TraceVar
Tcl_ConditionFinalize | Tcl_GetBooleanFromObj | Tcl_NewObj | Tcl_TraceVar2
Tcl_ConditionNotify | Tcl_GetByteArrayFromObj | Tcl_NewStringObj | Tcl_TranslateFileName
Tcl_ConditionWait | Tcl_GetChannel | Tcl_NewUnicodeObj | Tcl_Ungets
Tcl_ConvertCountedElement | Tcl_GetChannelBufferSize | Tcl_NextHashEntry | Tcl_UniChar
Tcl_ConvertElement | Tcl_GetChannelHandle | Tcl_NotifyChannel | Tcl_UniCharAtIndex
Tcl_ConvertToType | Tcl_GetChannelInstanceData | Tcl_NumUtfChars | Tcl_UniCharLen
Tcl_CreateAlias | Tcl_GetChannelMode | Tcl_ObjGetVar2 | Tcl_UniCharNcmp
Tcl_CreateAliasObj | Tcl_GetChannelName | Tcl_ObjSetVar2 | Tcl_UniCharToLower
Tcl_CreateChannel | Tcl_GetChannelNames | Tcl_OpenCommandChannel | Tcl_UniCharToTitle
Tcl_CreateChannelHandler | Tcl_GetChannelNamesEx | Tcl_OpenFileChannel | Tcl_UniCharToUpper
Tcl_CreateCloseHandler | Tcl_GetChannelOption | Tcl_OpenTcpClient | Tcl_UniCharToUtf
Tcl_CreateCommand | Tcl_GetChannelType | Tcl_OpenTcpServer | Tcl_UniCharToUtfDString
Tcl_CreateEncoding | Tcl_GetCharLength | Tcl_ParseBraces | Tcl_UnlinkVar
Tcl_CreateEventSource | Tcl_GetCommandInfo | Tcl_ParseCommand | Tcl_UnregisterChannel
Tcl_CreateExitHandler | Tcl_GetCommandName | Tcl_ParseExpr | Tcl_UnsetVar
Tcl_CreateFileHandler | Tcl_GetCurrentThread | Tcl_ParseQuotedString | Tcl_UnsetVar2
Tcl_CreateHashEntry | Tcl_GetCwd | Tcl_ParseVar | Tcl_UnstackChannel
Tcl_CreateInterp | Tcl_GetDefaultEncodingDir | Tcl_ParseVarName | Tcl_UntraceVar
Tcl_CreateMathFunc | Tcl_GetDouble | Tcl_PkgPresent | Tcl_UntraceVar2
Tcl_CreateObjCommand | Tcl_GetDoubleFromObj | Tcl_PkgPresentEx | Tcl_UpVar
Tcl_CreateSlave | Tcl_GetEncoding | Tcl_PkgProvide | Tcl_UpVar2
Tcl_CreateThread | Tcl_GetEncodingName | Tcl_PkgProvideEx | Tcl_UpdateLinkedVar
Tcl_CreateThreadExitHandler | Tcl_GetEncodingNames | Tcl_PkgRequire | Tcl_UtfAtIndex
Tcl_CreateTimerHandler | Tcl_GetErrno | Tcl_PkgRequireEx | Tcl_UtfBackslash
Tcl_CreateTrace | Tcl_GetHashKey | Tcl_PosixError | Tcl_UtfCharComplete
Tcl_DStringAppend | Tcl_GetHashValue | Tcl_Preserve | Tcl_UtfFindFirst
Tcl_DStringAppendElement | Tcl_GetHostName | Tcl_PrintDouble | Tcl_UtfFindLast
Tcl_DStringEndSublist | Tcl_GetIndexFromObj | Tcl_QueueEvent | Tcl_UtfNext
Tcl_DStringFree | Tcl_GetIndexFromObjStruct | Tcl_Read | Tcl_UtfPrev
Tcl_DStringGetResult | Tcl_GetInt | Tcl_ReadChars | Tcl_UtfToExternal
Tcl_DStringInit | Tcl_GetIntFromObj | Tcl_Realloc | Tcl_UtfToExternalDString
Tcl_DStringLength | Tcl_GetInterpPath | Tcl_ReapDetachedProcs | Tcl_UtfToLower
Tcl_DStringResult | Tcl_GetLongFromObj | Tcl_RecordAndEval | Tcl_UtfToTitle
Tcl_DStringSetLength | Tcl_GetMaster | Tcl_RecordAndEvalObj | Tcl_UtfToUniChar
Tcl_DStringStartSublist | Tcl_GetNameOfExecutable | Tcl_RegExpCompile | Tcl_UtfToUniCharDString
Tcl_DStringValue | Tcl_GetObjResult | Tcl_RegExpExec | Tcl_UtfToUpper
Tcl_DecrRefCount | Tcl_GetObjType | Tcl_RegExpExecObj | Tcl_ValidateAllMemory
Tcl_DeleteAssocData | Tcl_GetOpenFile | Tcl_RegExpGetInfo | Tcl_VarEval
Tcl_DeleteChannelHandler | Tcl_GetPathType | Tcl_RegExpMatch | Tcl_VarEvalVA
Tcl_DeleteCloseHandler | Tcl_GetRange | Tcl_RegExpMatchObj | Tcl_VarTraceInfo
Tcl_DeleteCommand | Tcl_GetRegExpFromObj | Tcl_RegExpRange | Tcl_VarTraceInfo2
Tcl_DeleteCommandFromToken | Tcl_GetServiceMode | Tcl_RegisterChannel | Tcl_WaitForEvent
Tcl_DeleteEventSource | Tcl_GetSlave | Tcl_RegisterObjType | Tcl_WaitPid
Tcl_DeleteEvents | Tcl_GetStackedChannel | Tcl_Release | Tcl_WinTCharToUtf
Tcl_DeleteExitHandler | Tcl_GetStdChannel | Tcl_ResetResult | Tcl_WinUtfToTChar
Tcl_DeleteFileHandler | Tcl_GetString | Tcl_RestoreResult | Tcl_Write
Tcl_DeleteHashEntry | Tcl_GetStringFromObj | Tcl_SaveResult | Tcl_WriteChars
Tcl_DeleteHashTable | Tcl_GetStringResult | Tcl_ScanCountedElement | Tcl_WriteObj
Tcl_DeleteInterp | Tcl_GetThreadData | Tcl_ScanElement | Tcl_WrongNumArgs
Tcl_DeleteThreadExitHandler | Tcl_GetUniChar | Tcl_Seek
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1994-1998 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation
Copyright © 1998-2000 Scriptics Corporation.


Tk Library Manual

Tk Library

Tk_3DBorderColor | Tk_DeleteSelHandler | Tk_GetItemTypes | Tk_NameToWindow
Tk_3DBorderGC | Tk_Depth | Tk_GetJoinStyle | Tk_Offset
Tk_3DHorizontalBevel | Tk_DestroyWindow | Tk_GetJustify | Tk_Offset
Tk_3DVerticalBevel | Tk_Display | Tk_GetJustifyFromObj | Tk_OwnSelection
Tk_AddOption | Tk_DisplayName | Tk_GetMMFromObj | Tk_Parent
Tk_Alloc3DBorderFromObj | Tk_DistanceToTextLayout | Tk_GetNumMainWindows | Tk_ParseArgv
Tk_AllocBitmapFromObj | Tk_Draw3DPolygon | Tk_GetOption | Tk_PathName
Tk_AllocColorFromObj | Tk_Draw3DRectangle | Tk_GetOptionInfo | Tk_PhotoBlank
Tk_AllocCursorFromObj | Tk_DrawChars | Tk_GetOptionValue | Tk_PhotoExpand
Tk_AllocFontFromObj | Tk_DrawFocusHighlight | Tk_GetPixels | Tk_PhotoGetImage
Tk_Attributes | Tk_DrawTextLayout | Tk_GetPixelsFromObj | Tk_PhotoGetSize
Tk_BindEvent | Tk_Fill3DPolygon | Tk_GetPixmap | Tk_PhotoPutBlock
Tk_CanvasDrawableCoords | Tk_Fill3DRectangle | Tk_GetRelief | Tk_PhotoPutZoomedBlock
Tk_CanvasEventuallyRedraw | Tk_FindPhoto | Tk_GetReliefFromObj | Tk_PhotoSetSize
Tk_CanvasGetCoord | Tk_FontId | Tk_GetRootCoords | Tk_PointToChar
Tk_CanvasPsBitmap | Tk_Free3DBorder | Tk_GetScreenMM | Tk_PostscriptFontName
Tk_CanvasPsColor | Tk_Free3DBorderFromObj | Tk_GetScrollInfo | Tk_QueueWindowEvent
Tk_CanvasPsFont | Tk_FreeBitmap | Tk_GetScrollInfoObj | Tk_RedrawImage
Tk_CanvasPsPath | Tk_FreeBitmapFromObj | Tk_GetSelection | Tk_ReqHeight
Tk_CanvasPsStipple | Tk_FreeColor | Tk_GetUid | Tk_ReqWidth
Tk_CanvasPsY | Tk_FreeColorFromObj | Tk_GetVRootGeometry | Tk_ResizeWindow
Tk_CanvasSetStippleOrigin | Tk_FreeColormap | Tk_GetVisual | Tk_RestackWindow
Tk_CanvasTagsOption | Tk_FreeConfigOptions | Tk_Grab | Tk_RestoreSavedOptions
Tk_CanvasTextInfo | Tk_FreeCursor | Tk_HWNDToWindow | Tk_RestrictEvents
Tk_CanvasTkwin | Tk_FreeCursorFromObj | Tk_HandleEvent | Tk_SafeInit
Tk_CanvasWindowCoords | Tk_FreeFont | Tk_Height | Tk_Screen
Tk_ChangeWindowAttributes | Tk_FreeFontFromObj | Tk_IdToWindow | Tk_ScreenNumber
Tk_Changes | Tk_FreeGC | Tk_ImageChanged | Tk_SetAppName
Tk_CharBbox | Tk_FreeImage | Tk_Init | Tk_SetBackgroundFromBorder
Tk_Class | Tk_FreeOptions | Tk_InitImageArgs | Tk_SetClass
Tk_ClearSelection | Tk_FreePixmap | Tk_InitOptions | Tk_SetGrid
Tk_ClipboardAppend | Tk_FreeSavedOptions | Tk_InitStubs | Tk_SetInternalBorder
Tk_ClipboardClear | Tk_FreeTextLayout | Tk_InternAtom | Tk_SetOptions
Tk_Colormap | Tk_FreeXId | Tk_InternalBorderWidth | Tk_SetWindowBackground
Tk_ComputeTextLayout | Tk_GeometryRequest | Tk_IntersectTextLayout | Tk_SetWindowBackgroundPixmap
Tk_ConfigureInfo | Tk_Get3DBorder | Tk_IsContainer | Tk_SetWindowBorder
Tk_ConfigureValue | Tk_Get3DBorderFromObj | Tk_IsEmbedded | Tk_SetWindowBorderPixmap
Tk_ConfigureWidget | Tk_GetAllBindings | Tk_IsMapped | Tk_SetWindowBorderWidth
Tk_ConfigureWindow | Tk_GetAnchor | Tk_IsTopLevel | Tk_SetWindowColormap
Tk_CoordsToWindow | Tk_GetAnchorFromObj | Tk_Main | Tk_SetWindowVisual
Tk_CreateBinding | Tk_GetAtomName | Tk_MainLoop | Tk_SizeOfBitmap
Tk_CreateBindingTable | Tk_GetBinding | Tk_MainWindow | Tk_SizeOfImage
Tk_CreateErrorHandler | Tk_GetBitmap | Tk_MaintainGeometry | Tk_StrictMotif
Tk_CreateEventHandler | Tk_GetBitmapFromData | Tk_MakeWindowExist | Tk_TextLayoutToPostscript
Tk_CreateGenericHandler | Tk_GetBitmapFromObj | Tk_ManageGeometry | Tk_TextWidth
Tk_CreateImageType | Tk_GetCapStyle | Tk_MapWindow | Tk_Uid
Tk_CreateItemType | Tk_GetColor | Tk_MeasureChars | Tk_UndefineCursor
Tk_CreateOptionTable | Tk_GetColorByValue | Tk_MoveResizeWindow | Tk_UnderlineChars
Tk_CreatePhotoImageFormat | Tk_GetColorFromObj | Tk_MoveToplevelWindow | Tk_UnderlineTextLayout
Tk_CreateSelHandler | Tk_GetColormap | Tk_MoveWindow | Tk_Ungrab
Tk_CreateWindow | Tk_GetCursor | Tk_Name | Tk_UnmaintainGeometry
Tk_CreateWindowFromPath | Tk_GetCursorFromData | Tk_NameOf3DBorder | Tk_UnmapWindow
Tk_DefineBitmap | Tk_GetCursorFromObj | Tk_NameOfAnchor | Tk_UnsetGrid
Tk_DefineCursor | Tk_GetDash | Tk_NameOfBitmap | Tk_Visual
Tk_DeleteAllBindings | Tk_GetFont | Tk_NameOfCapStyle | Tk_Width
Tk_DeleteBinding | Tk_GetFontFromObj | Tk_NameOfColor | Tk_WindowId
Tk_DeleteBindingTable | Tk_GetFontMetrics | Tk_NameOfCursor | Tk_X
Tk_DeleteErrorHandler | Tk_GetGC | Tk_NameOfFont | Tk_Y
Tk_DeleteEventHandler | Tk_GetHINSTANCE | Tk_NameOfImage
Tk_DeleteGenericHandler | Tk_GetHWND | Tk_NameOfJoinStyle
Tk_DeleteImage | Tk_GetImage | Tk_NameOfJustify
Tk_DeleteOptionTable | Tk_GetImageMasterData | Tk_NameOfRelief
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994 The Australian National University
Copyright © 1994-1998 Sun Microsystems, Inc.
Copyright © 1998-2000 Scriptics Corporation.
Copyright © 1999 Scriptics Corportation
Copyright © 1995-1997 Roger E. Critchlow Jr.


Tcl/Tk Keywords

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


tcllib Manual

Tcllib

Modules

base64 | Procedures to encode and decode base64
cmdline | Procedures to process command lines and options.
comm | A remote communications facility for Tcl (7.6, 8.0, and later)
control | Procedures for control flow structures.
counter | Procedures for counters and histograms.
csv | Procedures to handle CSV data
fileutil | Procedures implementing some file utilities
ftpd | Tcl FTP server implementation
ftp | Client-side tcl implementation of the ftp protocol
html | Procedures to generate HTML structures.
htmlparse | Procedures to parse HTML string
javascript | Procedures to generate HTML and Java Script structures.
log | Procedures to log messages of libraries and applications.
math | Tcl math library
md5 | Perform md5 hashing
mime | Manipulation of MIME body parts
smtp | Client-side tcl implementation of the smtp protocol
ncgi | Procedures to manipulate CGI values.
nntp | Tcl client for the NNTP protocol
pop3 | Tcl client for POP3 email protocol
profiler | Tcl source code profiler
report | Create and manipulate report objects
sha1 | Perform sha1 hashing
stats | Procedures for counters, histograms, and statistics.
graph | Create and manipulate directed graph objects
matrix | Create and manipulate matrix objects
queue | Create and manipulate queue objects
stack | Create and manipulate stack objects
tree | Create and manipulate tree objects
textutil | Procedures to manipulate texts and strings..
uri | URI utilities

tcllib

[ tcllib ]
Copyright © 2001 ActiveState.


tcllib base64

 Table of Contents

_________________________________________________________________

Name

::base64 - Procedures to encode and decode base64

Synopsis

package require Tcl 8

package require base64 ?2.2?

::base64::encode ?-maxlen maxlen? ?-wrapchar char? string

::base64::decode string
_________________________________________________________________

Description

This package provides procedures to encode binary data into base64 and back.

::base64::encode ?-maxlen maxlen? ?-wrapchar wrapchar? string
Base64 encodes the given binary string and returns the encoded result. Inserts the character wrapchar every maxlen characters of output. wrapchar defaults to newline. maxlen defaults to 60.

::base64::decode string
Base64 decodes the given string and returns the binary data. The decoder ignores whitespace in the string.

Keywords

encoding, base64

Table of Contents

  • Name
  • Synopsis
  • Description
  • Keywords


tcllib cmdline

 Table of Contents

_________________________________________________________________

Name

::cmdline - Procedures to process command lines and options.

Synopsis

package require Tcl 8.2

package require cmdline ?1.1.1?

::cmdline::getopt argvVar optstring optVar valVar

::cmdline::getoptions arglistVar optlist ?usage?

::cmdline::usage optlist ?usage?

::cmdline::getfiles patterns quiet

::cmdline::getArgv0
_________________________________________________________________

Description

This package provides commands to parse command lines and options.

::cmdline::getopt argvVar optstring optVar valVar This command works in a fashion like the standard C based getopt function. Given an option string and a pointer to an array or args this command will process the first argument and return info on how to procede. The command returns 1 if an option was found, 0 if no more options were found, and -1 if an error occurred.

argvVar contains the name of the argv list to process. If options are found the arg list is modified and the processed arguments are removed from the start of the list.

optstring contains a list of command options that the application will accept. If the option ends in «.arg» the command will use the next argument as an argument to the option. Otherwise the option is a boolean that is set to 1 if present.

optVar refers to the variable the command will store the found option into (without the leading `-' and without the .arg extension).

valVar refers to the variable to store either the value for the specified option into upon success or an error message in the case of failure. The stored value comes from the command line for .arg options, otherwise the value is 1.

::cmdline::getoptions arglistVar optlist ?usage? Processes the set of command line options found in the list variable named by arglistVar and fills in defaults for those not specified. This also generates an error message that lists the allowed flags if an incorrect flag is specified. The optional usage-argument contains a string to include in front of the generated message. If not present it defaults to «options:".

optlist contains a list of lists where each element specifies an option in the form: flag default com_ment

If flag ends in «.arg» then the value is taken from the command line. Otherwise it is a boolean and appears in the result if present on the command line. If flag ends in «.secret", it will not be displayed in the usage.

::cmdline::usage optlist ?usage?
Generates and returns an error message that lists the allowed flags. optlist is defined as for ::cmdline::getoptions. The optional usage-argument contains a string to include in front of the generated message. If not present it defaults to «options:".

::cmdline::getfiles patterns quiet
Given a list of file patterns this command computes the set of valid files. On windows, file globbing is performed on each argument. On Unix, only file existence is tested. If a file argument produces no valid files, a warning is optionally generated (set quiet to true).

This code also uses the full path for each file. If not given it prepends the current working directory to the filename. This ensures that these files will never conflict with files in a wrapped zip file. The last sentence refers to the pro-tools.

::cmdline::getArgv0
This command returns the «sanitized» version of argv0. It will strip off the leading path and removes the «.bin» extensions that the pro-apps use because they must be wrapped by a shell script.

Keywords

cmdline processing

Table of Contents

  • Name
  • Synopsis
  • Description
  • Keywords


tcllib counter

 Table of Contents

_________________________________________________________________

Name

::counter - Procedures for counters and histograms.

Synopsis

package require Tcl 8

package require counter ?2.0?

counter::init tag args

counter::count tag {delta 1} args

counter::reset tag

counter::get tag args

counter::start tag

counter::stop tag

counter::exists tag

counter::names tag

counter::histHtmlDisplay tag args
_________________________________________________________________

Description

The ::counter package provides a counter facility and can compute statistics and histograms over the collected data.

counter::init tag args
This defines a counter with the name tag. The args determines the characteristics of the counter. The args are

-group name
Keep a grouped counter where the name of the histogram bucket is passed into counter::count.
-hist bucketsize
Accumulate the counter into histogram buckets of size bucketsize. For example, if the samples are millisecond time values and bucketsize is 10, then each histogram bucket represents time values of 0 to 10 msec, 10 to 20 msec, 20 to 30 msec, and so on.
-hist2x bucketsize
Accumulate the statistic into histogram buckets. The size of the first bucket is bucketsize, each other bucket holds values 2 times the size of the previous bucket. For example, if bucketsize is 10, then each histogram bucket represents time values of 0 to 10 msec, 10 to 20 msec, 20 to 40 msec, 40 to 80 msec, and so on.
-hist10x bucketsize
Accumulate the statistic into histogram buckets. The size of the first bucket is bucketsize, each other bucket holds values 10 times the size of the previous bucket. For example, if bucketsize is 10, then each histogram bucket represents time values of 0 to 10 msec, 10 to 100 msec, 100 to 1000 msec, and so on.
-lastn N
Save the last N values of the counter to maintain a «running average» over the last N values.
-timehist secsPerMinute
Keep a time-based histogram. The counter is summed into a histogram bucket based on the current time. There are 60 per-minute buckets that have a size determined by secsPerMinute, which is normally 60, but for testing purposes can be less. Every «hour" (i.e., 60 «minutes") the contents of the per-minute buckets are summed into the next hourly bucket. Every 24 «hours» the contents of the per-hour buckets are summed into the next daily bucket. The counter package keeps all time-based histograms in sync, so the first secsPerMinute value seen by the package is used for all subsequent time-based histograms.

counter::count tag {delta 1} {instance {}} Increment the counter identified by tag. The default increment is 1, although you can increment by any value, integer or real, by specifying delta. You must declare each counter with counter::init to define the characteristics of counter before you start to use it. If the counter type is -group, then the counter identified by instance is incremented.

counter::start tag instance
Record the starting time of an interval. The tag is the name of the counter defined as a -hist value-based histogram. The instance is used to distinguish this interval from any other intervals that might be overlapping this one.

counter::stop tag instance
Record the ending time of an interval. The delta time since the corresponding countStart call for instance is recorded in the histogram identified by tag.

counter::get tag args
Return statistics about a counter identified by tag. The args determine what value to return:

-total Return the total value of the counter.
This is the default if args is not specified.
-totalVar
Return the name of the total variable. Useful for specifying with -textvariable in a Tk widget.
-N
Return the number of samples accumulated into the counter.
-avg
Return the average of samples accumulated into the counter.
-avgn
Return the average over the last N samples taken. The N value is set in the counter::init call.
-hist bucket
If bucket is specified, then the value in that bucket of the histogram is returned. Otherwise the complete histogram is returned in array get format sorted by bucket.
-histVar
Return the name of the histogram array variable.
-histHour
Return the complete hourly histogram in array get format sorted by bucket.
-histHourVar
Return the name of the hourly histogram array variable.
-histDay
Return the complete daily histogram in array get format sorted by bucket.
-histDayVar
Return the name of the daily histogram array variable.
-resetDate
Return the clock seconds value recorded when the counter was last reset.
-all
Return an array get of the array used to store the counter. This includes the total, the number of samples (N), and any type-specific information. This does not include the histogram array.

counter::exists tag
Returns 1 if the counter is defined.

counter::names
Returns a list of all counters defined.

counter::histHtmlDisplay tag args
Generate HTML to display a histogram for a counter. The args control the format of the display. They are:

-title string
Label to display above bar chart
-unit unit
Specify minutes, hours, or days for the time-base histograms. For value-based histograms, the unit is used in the title.
-images url
URL of /images directory.
-gif filename
Image for normal histogram bars. The filename is relative to the -images directory.
-ongif filename
Image for the active histogram bar. The filename is relative to the -images directory.
-max N Maximum number of value-based buckets to display.
-height N
Pixel height of the highest bar.
-width N
Pixel width of each bar.
-skip N
Buckets to skip when labeling value-based histograms.
-format string
Format used to display labels of buckets.
-text boolean
If 1, a text version of the histogram is dumped, otherwise a graphical one is generated.

Table of Contents

  • Name
  • Synopsis
  • Description


tcllib csv

 Table of Contents

_________________________________________________________________

Name

::csv - Procedures to handle CSV data

Synopsis

package require Tcl 8.3

package require csv ?0.1?

::csv::join values {sepChar ,}

::csv::joinlist values {sepChar ,}

::csv::read2matrix chan m {sepChar ,}

::csv::read2queue chan q {sepChar ,}

::csv::report cmd matrix ?chan?

::csv::split line {sepChar ,}

::csv::split2queue q line {sepChar ,}

::csv::writematrix m chan {sepChar ,}

::csv::writequeue q chan {sepChar ,}

_________________________________________________________________

Description

The ::csv package provides commands to manipulate information in CSV format (CSV = Comma Separated Values).

Commands

The following commands are available:

::csv::join values {sepChar ,}
Takes a list of values and returns a string in CSV format containing these values. The separator character can be defined by the caller, but this is optional. The default is «,".

::csv::joinlist values {sepChar ,}
Takes a list of lists of values and returns a string in CSV format containing these values. The separator character can be defined by the caller, but this is optional. The default is «,". Each element of the outer list is considered a record, these are separated by newlines in the result. The elements of each record are formatted as usual (via ::csv::join).

::csv::read2matrix chan m {sepChar ,}
A wrapper around ::csv::split2matrix (see below) reading from CSV-formatted lines from the specified channel (until EOF) and adding it to the given matrix.

::csv::read2queue chan q {sepChar ,}
A wrapper around ::csv::split2queue (see below) reading from CSV-formatted lines from the specified channel (until EOF) and adding it to the given queue.

::csv::report cmd matrix ?chan?
A report command which can be used by the matrix methods format 2string and format 2chan. For the latter this command delegates the work to ::csv::writematrix. cmd is expected to be either «printmatrix» or «printmatrix2channel". The channel argument, chan, has to be present for the latter and must not be present for the first.

::csv::split line {sepChar ,}
converts a line in CSV format into a list of the values contained in the line. The character used to separate the values from each other can be defined by the caller, via sepChar, but this is optional. The default is «,".

::csv::split2matrix m line {sepChar ,}
The same as ::csv::split, but appends the resulting list as a new row to the matrix m, using the method add row. It is the responsibility of the caller to ensure that the matrix has enough columns to contain the full line. If there are not enough columns the list of values is silently truncated at the end to fit.

::csv::split2queue q line {sepChar ,}
The same as ::csv::split, but appending the resulting list as a single item to the queue q, using the method put.

::csv::writematrix m chan {sepChar ,}
A wrapper around ::csv::join taking all rows in the matrix m and writing them CSV formatted into the channel chan.

::csv::writequeue q chan {sepChar ,}
A wrapper around ::csv::join taking all items in the queue q (assumes that they are lists) and writing them CSV formatted into the channel chan.

Format

Each record of a csv file (comma-separated values, as exported e.g. by Excel) is a set of ASCII values separated by «,". For other languages it may be «;» however, although this is not important for this case (The functions provided here allow any separator character).

If a value contains itself the separator «,", then it (the value) is put between «".

If a value contains «, it is replaced by «".

Example

The record

*
123,"123,521.2","Mary says «"Hello, I am Mary"""

is parsed as follows:

a)
123
b)
123,521.2
c)
Mary says «Hello, I am Mary"

See Also

Keywords

csv

Table of Contents

  • Name
  • Synopsis
  • Description
  • Commands
  • Format
  • Example
  • See Also
  • Keywords


tcllib fileutil

 Table of Contents

_________________________________________________________________

Name

::fileutil - Procedures implementing some file utilities

Synopsis

package require Tcl 8

package require fileutil ?1.2?

::fileutil::cat filename

::fileutil::find ?basedir ?filtercmd??

::fileutil::findByPattern basedir ?-regexp|-glob? ?--? patterns

::fileutil::foreachLine var filename cmd

::fileutil::grep pattern ?files?
_________________________________________________________________

Description

This package provides implementations of standard unix utilities

::fileutil::cat filename
A tcl implementation of the UNIX «cat» command. Returns the contents of the specified file. The first argument is the name of the file to read.

::fileutil::find ?basedir ?filtercmd??
An implementation of the unix command find. Adapted from the Tcler's Wiki. Takes at most two arguments, the path to the directory to start searching from and a command to use to evaluate interest in each file. The path defaults to ., i.e. the current directory. The command defaults to the empty string, which means that all files are of interest. The command takes care not to loose itself in infinite loops upon encountering circular link structures. The result of the command is a list containing the paths to the interesting files.

::fileutil::findByPattern basedir ?-regexp|-glob? ?--? patterns
This command is based upon the TclX command recursive_glob, except that it doesn't allow recursion over more than one directory at a time. It uses ::fileutil::find internally and is thus able to and does follow symbolic links, something the TclX command does not do. First argument is the directory to start the search in, second argument is a list of patterns. The command returns a list of all files reachable through basedir whose names match at least one of the patterns. The options before the pattern-list determine the style of matching, either regexp or glob. glob-style matching is the default if no options are given. Usage of the option -- stops option processing. This allows the use of a leading `-' in the patterns.

::fileutil::foreachLine var filename cmd The command reads the file filename and executes the script cmd for every line in the file. During the execution of the script the variable var is set to the contents of the current line. The return value of this command is the result of the last invocation of the script cmd or the empty string if the file was empty.

::fileutil::grep pattern ?files?
Implementation of grep. Adapted from the Tcler's Wiki. The first argument defines the pattern to search for. This is followed by a list of files to search through. The list is optional and stdin will be used if is missing. The result of the procedures is a list containing the matches. Each match is a single element of the list and contains filename, number and contents of the matching line, separated by a colons.

Keywords

file utilities

Table of Contents

  • Name
  • Synopsis
  • Description
  • Keywords


tcllib ftpd

 Table of Contents

_________________________________________________________________

Name

ftpd - Tcl FTP server implementation

Synopsis

package require Tcl 8.2

package require ftpd ?1.1?

::ftpd::server ?myaddr?

::ftpd::config ?option value? ?option value ...?

_________________________________________________________________

Description

The ftpd package provides a simple Tcl-only server library for the FTP protocol. It works by listening on the standard FTP socket. Most server errors are returned as error messages with the appropriate code attached to them. Since the server code for the ftp daemon is executed in the event loop, it is possible that a bgerror will be thrown on the server if there are problems with the code in the module.

Commands

::ftpd::server ?myaddr?
Open a listening socket to listen to and accept ftp connections. myaddr is an optional argument. myaddr is the domain-style name or numerical IP address of the client-side network interface to use for the connection.

::ftpd::config ?option value? ?option value ...? The value is always the proc to call as the callback. The option specifies which callback should be configured. See the CALLBACKS section for descriptions of the arguments and return values for each of the callbacks.

-authIpCmd proc
Callback to authenticate new connections based on the ip-address of the peer.
-authUsrCmd proc
Callback to authenticate new connections based on the user logging in (and the users password).
-authFileCmd proc
Callback to accept or deny a users access to read and write to a specific path or file.
-logCmd proc
Callback for log information generated by the FTP engine.
-fsCmd proc
Callback to connect the engine to the filesystem it operates on.
CALLBACKS

authIpCmd callback
The authIpCmd receives the ip-address of the peer attempting to connect to the ftp server as its argument. It returns a 1 to allow users from the specified IP to attempt to login and a 0 to reject the login attempt from the specified IP.

authUsrCmd callback
The authUsrCmd receives the username and password as its two arguments. It returns a 1 to accept the attempted login to the ftpd and a 0 to reject the attempted login.

authFileCmd callback
The authFileCmd receives the user (that is currently logged in), the path or filename that is about to be read or written, and read or write as its three arguments. It returns a 1 to allow the path or filename to be read or written, and a 0 to reject the attempted read or write with a permissions error code.

logCmd callback
The logCmd receives a severity and a message as its two arguments. The severities used within the ftpd package are note, debug, and error. The logCmd doesn't return anything.

fsCmd callback
The fsCmd receives a subcommand, a filename or path, and optional additional arguments (depending on the subcommand). The subcommands supported by the fsCmd are:

append <path>
The append subcommand receives the filename to append to as its argument. It returns a writable tcl channel as its return value.

delete <path> <channel-to-write-to> The delete subcommand receives the filename to delete, and a channel to write to as its two arguments. The file specified is deleted and the appropriate ftp message is written to the channel that is passed as the second argument. The delete subcommand returns nothing.

dlist <path> <style> <channel-to-write-dir-list-to> The dlist subcommand receives the path that it should list the files that are in, the style in which the files should be listed which is either nlst or list, and a channel to write to as its three arguments. The files in the specified path are printed to the specified channel one per line. If the style is nlst only the name of the file is printed to the channel. If the style is list then the file permissions, number of links to the file, the name of the user that owns the file, the name of the group that owns the file, the size (in bytes) of the file, the modify time of the file, and the filename are printed out to the channel in a formatted space separated format. The dlist subcommand returns nothing.

exists <path>
The exists subcommand receives the name of a file to check the existence of as its only argument. The exists subcommand returns a 1 if the path specified exists and the path is not a directory.

mkdir <path> <channel-to-write-to> The mkdir subcommand receives the path of a directory to create and a channel to write to as its two arguments. The mkdir subcommand creates the specified directory if necessary and possible. The mkdir subcommand then prints the appropriate success or failure message to the channel. The mkdir subcommand returns nothing.

mtime <path> <channel-to-write-mtime-to> The mtime subcommand receives the path of a file to check the modify time on and a channel as its two arguments. If the file exists the mtime is printed to the channel in the proper FTP format, otherwise an appropriate error message and code are printed to the channel. The mtime subcommand returns nothing.

permissions <path>
The permissions subcommand receives the path of a file to retrieve the permissions of. The permissions subcommand returns the octal file permissions of the specified file. The file is expected to exist.

rename <path> <newpath> <channel-to-write-to> The rename subcommand receives the path of the current file, the new file path, and a channel to write to as its three arguments. The rename subcommand renames the current file to the new file path if the path to the new file exists, and then prints out the appropriate message to the channel. If the new file path doesn't exist the appropriate error message is printed to the channel. The rename subcommand returns nothing.

retr <path>
The retr subcommand receives the path of a file to read as its only argument. The retr subcommand returns a readable channel that the specified file can be read from.

rmdir <path> <channel-to-write-to> The rmdir subcommand receives the path of a directory to remove and a channel to write to as its two arguments. The rmdir subcommand removes the specified directory (if possible) and prints the appropriate message to the channel (which may be an error if the specified directory does not exist or is not empty). The rmdir subcommand returns nothing.

size <path> <channel-to-write-size-to> The size subcommand receives the path of a file to get the size (in bytes) of and a channel to write to as its two arguments. The size subcommand prints the appropriate code and the size of the file if the specified path is a file, otherwise an appropriate error code and message are printed to the channel. The size subcommand returns nothing.

store <path>
The store subcommand receives the path of a file to write as its only argument. The store subcommand returns a writable channel.

VARIABLES
::ftpd::cwd The current working directory for a session when someone first connects to the FTPD or when the REIN ftp command is received.

::ftpd::contact
The e-mail address of the person that is the contact for the ftp server. This address is printed out as part of the response to the FTP HELP command.

::ftpd::port
The port that the ftp server should listen on.

::ftpd::welcome
The message that is printed out when the user first connects to the ftp server.

KEYWORDS
ftpd, ftp, ftpserver, services, RFC 959

Table of Contents

  • Name
  • Synopsis
  • Description
  • Commands


tcllib html

 Table of Contents

_________________________________________________________________

Name

::html - Procedures to generate HTML structures.

Synopsis

_________________________________________________________________

package require Tcl 8.2

package require html ?1.1.1?

html::author author

html::bodyTag args

html::cell param value {tag td}

html::checkbox name value

html::checkSet key sep list

html::checkValue name {value 1}

html::closeTag

html::default key {param {}}

html::description description

html::end

html::eval arg ?args?

html::extractParam param key {val «"}

html::font args

html::for start test next body

html::foreach varlist1 list1 ?varlist2 list2 ...? body

html::formatCode code

html::formValue name {defvalue {}}

html::getFormInfo args

html::getTitle

html::h level string {param {}}

html::h1 string {param {}} html::h2 string {param {}}

html::h3 string {param {}}

html::h4 string {param {}}

html::h5 string {param {}}

html::h6 string {param {}}

html::hdrRow args

html::head title

html::headTag string

html::if expr1 body1 ?elseif expr2 body2 ...? ?else bodyN?

html::keywords args

html::mailto email {subject {}}

html::meta args

html::minorMenu list {sep { | }}

html::openTag tag args

html::passwordInput {name password}

html::passwordInputRow label {name password}

html::quoteFormValue value

html::radioSet key sep list

html::radioValue name value

html::refresh seconds {url {}}

html::init {nvlist {}}

html::row args

html::select name param choices {current {}}

html::selectPlain name param choices {current {}}

html::set var val

html::submit label {name submit}

html::tableFromArray arrname {param {}} {pat *} html::tableFromList querylist {param {}}

html::textarea name {param {}} {current {}}

html::textInput name args

html::textInputRow label name args

html::title title

html::varEmpty name

html::while test body
_________________________________________________________________

Description

The ::html package provides commands that generate HTML. These commands typically return an HTML string as their result. In particular, they do not output their result to stdout.

The html::init procedure should be called early to initialize the module. You can also use this procedure to define default values for HTML tag parameters.

html::author author
Side effect only. Call this before html::head to define an author for the page. The author is noted in a comment in the HEAD section.

html::bodyTag args
Generate a BODY tag. The tag parameters are taken from args or from the body.* attributes define with html::init

html::cell param value {tag td}
Generate a TD (or TH) tag, a value, and a closing TD (or TH) tag. The tag parameters come from param or TD.* attributes defined with html::init. This uses html::font to insert a standard FONT tag into the table cell.

html::checkbox name value
Generate a CHECKBOX form element with the specified name and value. This uses html::checkValue.

html::checkSet key sep list
Generate a set of CHECKBOX form elements and associated labels. The list should contain an alternating list of labels and values. This uses html::checkbox.

html::checkValue name {value 1}
Generate the «name=name value=val for a CHECKBOX form element. If the CGI variable name has the value val, then SELECTED is added to the return value.

html::closeTag
Pop a tag off the stack created by html::openTag and generate the corresponding close tag (e.g., /BODY)

html::default key {param {}}
This procedure is used by html::tagParam to generate the name, value list of parameters for a tag. The html::default procedure is used to generate default values for those items not already in param. If the value identified by key matches a value in param then this procedure returns the empty string. Otherwise, it returns a parame_ter=value string for a form element identified by key. The key has the form tag.parameter (e.g., body.bgcolor). Use html::init to register default values.

html::description description
Side effect only. Call this before html::head to define a description META tag for the page. This tag is generated later in the call to html::head.

html::end
Pop all open tags from the stack and generate the corresponding close HTML tags, (e.g., </body></html>).

html::eval arg ?args?
This procedure is similar to the built-in Tcl eval command. The only difference is that it returns «" so it can be called from an HTML template file without appending unwanted results.

html::extractParam param key {varName «"} This is a parsing procedure that extracts the value of key from param, which is a HTML-style name=quot_edvalue list. varName is used as the name of a Tcl variable that is changed to have the value found in the parameters. The function returns 1 if the parameter was found in param, otherwise it returns 0. If the varName is not specified, then key is used as the variable name.

html::font args
Generate a standard FONT tag. The parameters to the tag are taken from args and the HTML defaults defined with html::init.

html::for start test next body
This procedure is similar to the built-in Tcl for control structure. Rather than evaluating the body, it returns the subst'ed body. Each iteration of the loop causes another string to be concatenated to the result value.

html::foreach varlist1 list1 ?varlist2 list2 ...? body This procedure is similar to the built-in Tcl foreach control structure. Rather than evaluating the body, it returns the subst'ed body. Each iteration of the loop causes another string to be concatenated to the result value.

html::formValue name {defvalue {}}
Return a name and value pair, where the value is initialized from existing CGI data, if any. The result has this form:

name="fred» value="freds value"

html::getFormInfo args
Generate hidden fields to capture form values. If args is empty, then hidden fields are generated for all CGI values. Otherwise args is a list of string match patterns for form element names.

html::getTitle
Return the title string, with out the surrounding TITLE tag, set with a previous call to html::title.

html::h level string {param {}}
Generate a heading (e.g., H1) tag. The string is nested in the heading, and param is used for the tag parameters.

html::h1 string {param {}}
Generate an H1 tag. See html::h

html::h2 string {param {}}
Generate an H2 tag. See html::h

html::h3 string {param {}}
Generate an H3 tag. See html::h

html::h4 string {param {}}
Generate an H4 tag. See html::h

html::h5 string {param {}}
Generate an H5 tag. See html::h

html::h6 string {param {}}
Generate an H6 tag. See html::h

html::hdrRow args
Generate a table row, including TR and TH tags. Each value in args is place into its own table cell. This uses html::cell.

html::head title
Generate the HEAD section that includes the page TITLE. If previous calls have been made to html::author, html::keywords, html::description, of html::meta then additional tags are inserted into the HEAD section. This leaves an open HTML tag pushed on the stack with openTag.

html::headTag string
Save a tag for inclusion in the HEAD section generated by html::head. The string is everything in the tag except the enclosing angle brackets, < >.

html::if expr1 body1 ?elseif expr2 body2 ...? ?else bodyN? This procedure is similar to the built-in Tcl if control structure. Rather than evaluating the body of the branch that is taken, it returns the subst'ed body. Note that the syntax is slightly more restrictive than that of the built-in Tcl if control structure.

html::keywords args
Side effect only. Call this before html::head to define a keyword META tag for the page. The META tag is included in the result of html::head.

html::mailto email {subject {}}
Generate a hypertext link to a mailto: URL.

html::meta args
Side effect only. Call this before html::head to define a META tag for the page. The args is a Tclstyle name, value list that is used for the name= and value= parameters for the META tag. The META tag is included in the result of html::head.

html::minorMenu list {sep { | }}
Generate a series of hypertext links. The list is a Tcl-style name, value list of labels and urls for the links. The sep is the text to put between each link.

html::openTag tag args
Push tag onto a stack and generate the opening tag for tag. Use html::closeTag to pop the tag from the stack.

html::passwordInput {name password}
Generate an INPUT tag of type PASSWORD.

html::passwordInputRow label {name password} Format a table row containing a label and an INPUT tag of type PASSWORD.

html::quoteFormValue value
Quote special characters in value by replacing them with HTML entities for quotes, ampersand, and angle brackets.

html::radioSet key sep list
Generate a set of INPUT tags of type RADIO and an associated text label. All the radio buttons share the same key for their name. The sep is text used to separate the elements. The list is a Tcl-style label, value list.

html::radioValue name value
Generate the «name=name value=val for a RADIO form element. If the CGI variable name has the value val, then SELECTED is added to the return value.

html::refresh seconds url
Set up a refresh META tag. Call this before html::head and the HEAD section will contain a META tag that causes the document to refresh in seconds seconds. The url is optional. If specified, it specifies a new page to load after the refresh interval.

html::init {list {}}
html::init accepts a Tcl-style name-value list that defines values for items with a name of the form tag.parameter. For example, a default with key body.bgcolor defines the background color for the BODY tag.

html::row args
Generate a table row, including TR and TD tags. Each value in args is place into its own table cell. This uses html::cell.

html::select name param choices {current {}} Generate a SELECT form element and nested OPTION tags. The name and param are used to generate the SELECT tag. The choice list is a Tcl-style name, value list.

html::selectPlain name param choices {current {}} Like html::select except that choices is a Tcl list of values used for the OPTION tags. The label and the value for each OPTION are the same.

html::submit label {name submit}
Generate an INPUT tag of type SUBMIT.

html::set var val
This procedure is similar to the built-in Tcl set command. The main difference is that it returns «" so it can be called from an HTML template file without appending unwanted results. The other difference is that it must take two arguments.

html::tableFromArray arrname {param {}} {pat *} Generate a TABLE and nested rows to display a Tcl array. The param are for the TABLE tag. The pat is a string match pattern used to select array elements.

html::tableFromList querylist {param {}} Generate a TABLE and nested rows to display querylist, which is a Tcl-style name, value list. The param are for the TABLE tag.

html::textarea name {param {}} {current {}} Generate a TEXTAREA tag wrapped around its current values.

html::textInput name args
Generate an INPUT form tag with type TEXT. This uses html::formValue. The args is any additional tag attributes you want to put into the INPUT tag.

html::textInputRow label name args
Generate an INPUT form tag with type TEXT formatted into a table row with an associated label. The args is any additional tag attributes you want to put into the INPUT tag.

html::title title
Side effect only. Call this before html::head to define the TITLE for a page.

html::varEmpty name
This returns 1 if the named variable either does not exist or has the empty string for its value.

html::while test body
This procedure is similar to the built-in Tcl while control structure. Rather than evaluating the body, it returns the subst'ed body. Each iteration of the loop causes another string to be concatenated to the result value.

See Also

ncgi

Keywords

html, form, table, checkbox, radiobutton, checkbutton

Table of Contents

  • Name
  • Synopsis
  • Description
  • See Also
  • Keywords


tcllib htmlparse

 Table of Contents

_________________________________________________________________

Name

::htmlparse - Procedures to parse HTML string

Synopsis

package require Tcl 8.2

package require struct 1

package require cmdline 1.1

package require htmlparse ?0.2?

::htmlparse::parse ?-cmd cmd? ?-vroot tag? ?-split n? ?-incvar var? ?-queue q? html

::htmlparse::debugCallback ?clientdata? tag slash param textBehindTheTag

::htmlparse::mapEscapes html

::htmlparse::2tree html tree

::htmlparse::removeVisualFluff tree

::htmlparse::removeFormDefs tree

_________________________________________________________________

Description

The ::htmlparse package provides commands that allow libraries and applications to parse HTML in a string into a representation of their choice.

The following commands are available:

::htmlparse::parse ?-cmd cmd? ?-vroot tag? ?-split n? ?-incvar var? ?-queue q? html

This command is the basic parser for HTML. It takes a HTML string, parses it and invokes a command prefix for every tag encountered. It is not necessary for the HTML to be valid for this parser to function. It is the responsibility of the command invoked for every tag to check this. Another responsibility of the invoked command is the handling of tag attributes and character entities (escaped characters). The parser provides the uninterpreted tag attributes to the invoked command to aid in the former, and the package at large provides a helper command, ::htmlparse::mapEscapes, to aid in the handling of the latter. The parser does ignore leading DOCTYPE declarations and all valid

HTML comments it encounters.

All information beyond the HTML string itself is specified via options, these are explained below.

To help understanding the options some more background information about the parser.

It is capable to detect incomplete tags in the HTML string given to it. Under normal circumstances this will cause the parser to throw an error, but if the option -incvar is used to specify a global (or namespace) variable the parser will store the incomplete part of the input into this variable instead. This will aid greatly in the handling of incrementally arriving HTML as the parser will handle whatever he can and defer the handling of the incomplete part until more data has arrived.

Another feature of the parser are its two possible modes of operation. The normal mode is activated if the option -queue is not present on the command line invoking the parser. If it is present the parser will go into the incremental mode instead.

The main difference is that a parser in normal mode will immediately invoke the command prefix for each tag it encounters. In incremental mode however the parser will generate a number of scripts which invoke the command prefix for groups of tags in the HTML string and then store these scripts in the specified queue. It is then the responsibility of the caller of the parser to ensure the execution of the scripts in the queue.

Note: The queue object given to the parser has to provide the same interface as the queue defined in tcllib -> struct. This does for example mean that all queues created via that part of tcllib can be immediately used here. Still, the queue doesn't have to come from tcllib -> struct as long as the same interface is provided.

In both modes the parser will return an empty string to the caller.

To a parser in incremental mode the option -split can be given and will specify the size of the groups he creates. In other words, -split 5 means that each of the generated scripts will invoke the command prefix for 5 consecutive tags in the HTML string. A parser in normal mode will ignore this option and its value.

The option -vroot specifies a virtual root tag. A parser in normal mode will invoke the command prefix for it immediately before and after he processes the tags in the HTML, thus simulating that the HTML string is enclosed in a <vroot> </vroot> combination. In incremental mode however the parser is unable to provide the closing virtual root as he never knows when the input is complete. In this case the first script generated by each invocation of the parser will contain an invocation of the command prefix for the virtual root as its first command.

The following options are available:

-cmd cmd
The command prefix to invoke for every tag in the HTML string. Defaults to ::html_parse::debugCallback.
-vroot tag
The virtual root tag to add around the HTML in normal mode. In incremental mode it is the first tag in each chunk processed by the parser, but there will be no closing tags. Defaults to hmstart.
-split n
The size of the groups produced by an incremental mode parser. Ignored when in normal mode. Defaults to 10. Values <= 0 are not allowed.
-incvar var
The name of the variable where to store any incomplete HTML into. This makes most sense for the incremental mode. The parser will throw an error if he sees incomplete HTML and has no place to store it to. This makes sense for the normal mode. Only incomplete tags are detected, not missing tags. Optional, defaults to `no variable'.

Interface to the command prefix
In normal mode the parser will invoke the command prefix with for arguments appended. See ::htmlparse::debugCallback for a description.

In incremental mode however the generated scripts will invoke the command prefix with five arguments appended. The last four of these are the same which were mentioned above. The first however is a placeholder string (\win\) for a clientdata value to be supplied later during the actual execution of the generated scripts. This could be a tk window path, for example. This allows the user of this package to preprocess HTML strings without committing them to a specific window, object, whatever during parsing. This connection can be made later. This also means that it is possible to cache preprocessed HTML. Of course, nothing prevents the user of the parser to replace the placeholder with an empty string.

::htmlparse::debugCallback ?clientdata? tag slash param textBe- hindTheTag
This command is the standard callback used by the parser in ::htmlparse::parse if none was specified by the user. It simply dumps its arguments to stdout. This callback can be used for both normal and incremental mode of the calling parser. In other words, it accepts four or five arguments. The last four arguments are described below. The optional fifth argument contains the clientdata value given to the callback by a parser in incremental mode. All callbacks have to follow the signature of this command in the last four arguments, and callbacks used in incremental parsing have to follow this signature in the last five arguments.

The first argument, clientdata, is optional and present only if this command is invoked by a parser in incremental mode. It contains whatever the user of this package wishes.

The second argument, tag, contains the name of the tag which is currently processed by the parser.

The third argument, slash, is either empty or contains a slash character. It allows the callback to distinguish between opening (slash is empty) and closing tags (slash contains a slash character).

The fourth argument, param, contains the un-interpreted list of parameters to the tag.

The fifth and last argument, textBehindTheTag, contains the text found by the parser behind the tag named in tag.

::htmlparse::mapEscapes html
This command takes a HTML string, substitutes all escape sequences with their actual characters and then returns the resulting string. HTML strings which do not contain escape sequences are returned unchanged.

::htmlparse::2tree html tree

This command is a wrapper around ::htmlparse::parse which takes a HTML string (in html) and converts it into a tree containing the logical structure of the parsed document. The name of the tree is given to the command as its second argument (tree). The command does not generate the tree by itself but expects that the caller provided it with an existing and empty tree. It also expects that the specified tree object follows the same interface as the tree object in tcllib -> struct. It doesn't have to be from tcllib -> struct, but it has to provide the same interface.

The internal callback does some basic checking of HTML validity and tries to recover from the most basic errors. The command returns the contents of its second argument. Side effects are the creation and manipulation of a tree object.

::htmlparse::removeVisualFluff tree
This command walks a tree as generated by ::htmlparse::2tree and removes all the nodes which represent visual tags and not structural ones. The purpose of the command is to make the tree easier to navigate without getting bogged down in visual information not relevant to the search. Its only argument is the name of the tree to cut down.

::htmlparse::removeFormDefs tree
Like ::htmlparse::removeVisualFluff this command is here to cut down on the size of the tree as generated by ::htmlparse::2tree. It removes all nodes representing forms and form elements. Its only argument is the name of the tree to cut down.

See Also

Keywords

html, parsing

Table of Contents

  • Name
  • Synopsis
  • Description
  • See Also
  • Keywords


tcllib javascript

 Table of Contents

_________________________________________________________________

Name

::javascript - Procedures to generate HTML and Java Script structures.

Synopsis

_________________________________________________________________

package require Tcl 8

package require ncgi 1

package require javascript ?1.0?

javascript::makeSelectorWidget id leftLabel leftValueList rightLabel rightValueList rightNameList length {minWidth 32}

javascript::makeSubmitButton name value

javascript::makeProtectedSubmitButton name value msg

javascript::makeMasterButton master value slaves boolean

javascript::makeParentCheckbox parentName childName

javascript::makeChildCheckbox parentName childName _________________________________________________________________

Description

The ::javascript package provides commands that generate HTML and Java Script code. These commands typically return an HTML string as their result. In particular, they do not output their result to stdout.

javascript::makeSelectorWidget id leftLabel leftValueList rightLabel rightValueList rightNameList length {minWidth 32} Construct HTML code to create a dualmulti-selection megawidget. This megawidget consists of two side-by-side multi-selection boxes separated by a left arrow and a right arrow button. The right arrow button moves all items selected in the left box to the right box. The left arrow button moves all items selected in the right box to the left box. The id argument is the suffix of all HTML objects in this megawidget. The leftLabel argument is the text that appears above the left selection box. The leftValueList argument is the values of items in the left selection box. The leftNameList argument is the names to appear in the left selection box. The rightLabel argument is the text that appears above the right selection box.

The rightValueList argument is the values of items in the right selection box. The rightNameList argument is the names to appear in the right selection box. The length argument (optional) The number of elts to show before adding a vertical scrollbar; it defaults to 8. The minWidth argument (optional) is the number of spaces to determine the minimum box width; it defaults to 32.

javascript:: makeSubmitButton name value Create an HTML submit button that resets a hidden field for each registered multi-selection box. The name argument is the name of the HTML button object to create. The value argument is the label of the HTML button object to create.

javascript::makeProtectedSubmitButton name value msg Create an HTML submit button that prompts the user with a continue/cancel shutdown warning before the form is submitted. The name argument is the name of the HTML button object to create. The value argument is the label of the HTML button object to create. The msg argument is the message to display when the button is pressed.

javascript:: makeMasterButton master value slavePattern boolean Create an HTML button that sets it's slave checkboxs to the boolean value. The master argument is the name of the child's parent html checkbox object. The value argument is the value of the master. The slaves argument is the name of child html checkbox object to create. The boolean argument is the java script boolean value that will be given to all the slaves; it must be «true» or «false".

javascript:: makeParentCheckbox parentName childName Create an HTML checkbox and tie its value to that of it's child checkbox. If the parent is unchecked, the child is automatically unchecked. The parentName argument is the name of parent html checkbox object to create. The childName argument is the name of the parent's child html checkbox object.

javascript:: makeChildCheckbox parentName childName Create an HTML checkbox and tie its value to that of it's parent checkbox. If the child is checked, the parent is automatically checked. The parentName argument is the name of the child's parent html checkbox object. The childName argument is the name of child html checkbox object to create.

See Also

html ncgi

Keywords

javascript, html, checkbox, submitbutton, selectionbox

Table of Contents

  • Name
  • Synopsis
  • Description
  • See Also
  • Keywords


tcllib log

 Table of Contents

_________________________________________________________________

Name

::log - Procedures to log messages of libraries and applications.

Synopsis

package require Tcl 8

package require log ?1.0?

::log::levels

::log::lv2longform level

::log::lv2color level

::log::lv2priority level

::log::lv2cmd level

::log::lv2channel level

::log::lvCompare level1 level2

::log::lvSuppress level {suppress 1}

::log::lvSuppressLE level {suppress 1}

::log::lvIsSuppressed level

::log::lvCmd level cmd

::log::lvCmdForall cmd

::log::lvChannel level chan

::log::lvChannelForall chan

::log::lvColor level color

::log::lvColorForall color

::log::log level text

::log::logMsg text

::log::logError text

::log::Puts level text

_________________________________________________________________

Description

The ::log package provides commands that allow libraries and applications to selectively log information about their internal operation and state.

Each message given to the log facility is associated with a level determining the importance of the message. The user can then select which levels to log, what commands to use for the logging of each level and the channel to write the message to. The latter is relevant only if the standard command (::log::Puts) to log messages provided by ::log is used. Apprehending the usage of this facility in graphical applications, i.e. tk-based ones, it also allows the user to associate colors with the message levels.

The following commands are available:

::log::levels
Returns the names of all known levels, in alphabetical order.

::log::lv2longform level
Converts any unique abbreviation of a level name to the full level name.

::log::lv2color level
Converts any level name including unique abbreviations to the corresponding color.

::log::lv2priority level
Converts any level name including unique abbreviations to the corresponding priority.

::log::lv2cmd level
Converts any level name including unique abbreviations to the command prefix used to write messages with that level.

::log::lv2channel level
Converts any level name including unique abbreviations to the channel used by ::log::Puts to write messages with that level.

::log::lvCompare level1 level2
Compares two levels (including unique abbreviations) with respect to their priority. This command can be used by the -command option of lsort. The result is one of -1, 0 or 1 or an error. A result of -1 signals that level1 is of less priority than level2. 0 signals that both levels have the same priority. 1 signals that level1 has higher priority than level2.

::log::lvSuppress level {suppress 1}
(Un)suppresses the output of messages having the specified level. Unique abbreviations for the level are allowed here too.

::log::lvSuppressLE level {suppress 1}
(Un)suppresses the output of messages having the specified level or one of lesser priority. Unique abbreviations for the level are allowed here too.

::log::lvIsSuppressed level
Asks the package whether the specified level is currently suppressed. Unique abbreviations of level names are allowed.

::log::lvCmd level cmd
Defines for the specified level with which command to write the messages having this level. Unique abbreviations of level names are allowed. The command is actually a command prefix and this facility will append 2 arguments before calling it, the level of the message and the message itself, in this order.

::log::lvCmdForall cmd
Defines for all known levels with which command to write the messages having this level. The command is actually a command prefix and this facility will append 2 arguments before calling it, the level of the message and the message itself, in this order.

::log::lvChannel level chan
Defines for the specified level into which channel ::log::Puts (the standard command) shall write the messages having this level. Unique abbreviations of level names are allowed. The command is actually a command prefix and this facility will append 2 arguments before calling it, the level of the message and the message itself, in this order.

::log::lvChannelForall chan
Defines for all known levels with which which channel ::log::Puts (the standard command) shall write the messages having this level. The command is actually a command prefix and this facility will append 2 arguments before calling it, the level of the message and the message itself, in this order.

::log::lvColor level color
Defines for the specified level the color to return for it in a call to ::log::lv2color. Unique abbreviations of level names are allowed.

::log::lvColorForall color
Defines for all known levels the color to return for it in a call to ::log::lv2color. Unique abbreviations of level names are allowed.

::log::log level text
Log a message according to the specifications for commands, channels and suppression. In other words: The command will do nothing if the specified level is suppressed. If it is not suppressed the actual logging is delegated to the specified command. If there is no command specified for the level the message won't be logged. The standard command ::log::Puts will write the message to the channel specified for the given level. If no channel is specified for the level the message won't be logged. Unique abbreviations of level names are allowed. Errors in the actual logging command are not caught, but propagated to the caller, as they may indicate misconfigurations of the log facility or errors in the callers code itself.

::log::logMsg text
Convenience wrapper around ::log::log. Equivalent
to ::log::log info text.

::log::logError text
Convenience wrapper around ::log::log. Equivalent
to ::log::log error text.

::log::Puts level text
The standard log command, it writes messages and their levels to user-specified channels. Assumes that the suppression checks were done by the caller. Expects full level names, abbreviations are not allowed.

See Also

Keywords

log, log level, message level, message

Table of Contents

  • Name
  • Synopsis
  • Description
  • See Also
  • Keywords


tcllib math

 Table of Contents

_________________________________________________________________

Name

math - Tcl math library

Synopsis

package require Tcl 8.2

package require math ?1.0?

::math::cov value value ?value? ?value ...?

::math::fibonacci n

::math::max value ?value? ?value ...?

::math::mean value ?value? ?value ...?

::math::min value ?value? ?value ...?

::math::prod value ?value ...?

::math::random ?value? ?value?

::math::sigma value value ?value? ?value ...?

::math::stats value value ?value? ?value ...?

::math::sum value ?value ...?

::math::dot values rows cols

::math::cross values rows cols

::math::det values rows cols

::math::integrate list of xy value pairs

_________________________________________________________________

Description

The math package provides utility math functions.

Commands

::math::cov value value ?value? ?value ...? Return the coefficient of variation expressed as percent of two or more numeric values.

::math::integrate list of xy value pairs Return the area under a «curve» defined by a set of x,y pairs and the error bound as a list. ::math::fibonacci n Return the n'th Fibonacci number. ::math::max value ?value? ?value ...? Return the maximum of one or more numeric values.

::math::mean value ?value? ?value ...?
Return the mean, or «average» of one or more numeric values.

::math::min value ?value? ?value ...?
Return the minimum of one or more numeric values.

::math::prod value ?value ...?
Return the product of one or more numeric values.

::math::random ?value1? ?value2?
Return a random number. If no arguments are given, the number is a floating point value between 0 and 1. If one argument is given, the number is an integer value between 0 and value1. If two arguments are given, the number is an integer value between value1 and value2.

::math::sigma value value ?value? ?value ...? Return the population standard deviation of two or more numeric values.

::math::stats value value ?value? ?value ...? Return the mean, standard deviation, and coefficient of variation as percent as a list.

::math::sum value ?value ...?
Return the sum of one or more numeric values.

Keywords

math statistics

Table of Contents

  • Name
  • Synopsis
  • Description
  • Commands
  • Keywords


tcllib md5

 Table of Contents

_________________________________________________________________

Name

::md5::md5 - Perform md5 hashing

Synopsis

package require Tcl 8.2

package require md5 ?1.4.1?

::md5::md5 msg?

::md5::hmac key text

_________________________________________________________________

Description

This package provides commands to compute a MD5 digests of arbitrary messages.

Commands

::md5::md5 msg
The command takes a message and returns the MD5 digest of this message as a hexadecimal string.

::md5::hmac key text
The command takes a key string and a text and returns the hmac of the text under the chosen key as a hexadecimal string.

Examples

% md5::md5 «hello world"
5eb63bbbe01eeed093cb22bb8f5acdc3

% md5::hmac «our little secret» «hello world" 61a922114c8aaf5050098be6d3a7daf0

Keywords

md5, hashing, security

Table of Contents

  • Name
  • Synopsis
  • Description
  • Commands
  • Examples
  • Keywords


The README file: Tcl MIME

TOC
The README file | M.T. Rose
 | Dover Beach Consulting, Inc.
 | February 22, 2000

Tcl MIME

Abstract

Tcl MIME generates and parses MIME body parts.

TOC

Table of Contents

    1. SYNOPSIS
     1.1 Requirements
     1.2 Copyrights
     2. SYNTAX
     3. SEMANTICS
     3.1 mime::initialize
     3.2 mime::finalize
     3.3 mime::getproperty
     3.4 mime::getheader
     3.5 mime::setheader
     3.6 mime::getbody
     3.7 mime::copymessage
     3.7 mime::buildmessage
     3.8 smtp::sendmessage
     3.9 mime::parseaddress
     3.10 mime::parsedatetime
     3.10 mime::mapencoding
     3.10 mime::reversemapencoding
     4. EXAMPLES
     § References
     § Author's Address
     A. TODO List
     B. Acknowledgements

TOC

1. SYNOPSIS

    package provide mime 1.2
    package provide smtp 1.2

Tcl MIME is an implementation of a Tcl package that generates and parses MIME[1] body parts.

Each MIME part consists of a header (zero or more key/value pairs), an empty line, and a structured body. A MIME part is either a "leaf" or has (zero or more) subordinates.

MIME defines four keys that may appear in the headers:

Content-Type:
describes the data contained in the body ("the content");
Content-Transfer-Encoding:
describes how the content is encoded for transmission in an ASCII stream;
Content-Description:
a textual description of the content; and,
Content-ID:
a globally-unique identifier for the content.

Consult [2] for a list of standard content types. Further, consult [3] for a list of several other header keys (e.g., "To", "cc", etc.)

A simple example might be:

    Date: Sun, 04 July 1999 10:38:25 -0600
    From: Marshall Rose <mrose@dbc.mtview.ca.us>
    To: Andreas Kupries <a.kupries@westend.com>
    cc: dnew@messagemedia.com (Darren New)
    MIME-Version: 1.0
    Content-Type: text/plain; charset="us-ascii"
    Content-Description: a simple example
    Content-ID: <4294407315.931384918.1@dbc.mtview.ca.us>

    Here is the body. In this case, simply plain text.

In addition to an implementation of the mime package, Tcl MIME includes an implementation of the smtp package.

1.1 Requirements

This package requires:

  • Tcl/Tk version 8.0.3 or later

In addition, this package requires one of the following:

  • Trf version 2.0p5 or later
  • base 64 version 2.0 or later (included with tcllib)

If it is available, Trf will be used to provide better performance; if not, Tcl-only equivalent functions, based on the base64 package, are used.

1.2 Copyrights

(c) 1999-2000 Marshall T. Rose

Hold harmless the author, and any lawful use is allowed.

TOC

2. SYNTAX

mime::initialize returns a token. Parameters:

    ?-canonical type/subtype
        ?-param    {key value}?...
        ?-encoding value?
        ?-header   {key value}?... ?
    (-file name | -string value | -parts {token1 ... tokenN})

mime::finalize returns an empty string. Parameters:

    token ?-subordinates "all" | "dynamic" | "none"?

mime::getproperty returns a string or a list of strings. Parameters:

    token ?property | -names?

mime::getheader returns a list of strings. Parameters:

    token ?key | -names?

mime::setheader returns a list of strings. Parameters:

    token key value ?-mode "write" | "append" | "delete"?

mime::getbody returns a string. Parameters:

    ?-command callback ?-blocksize octets? ?

mime::copymessage returns an empty string. Parameters:

    token channel

mime::buildmessage returns a string. Parameters:

    token

smtp::sendmessage returns a list. Parameters:

    token ?-servers list? ?-ports list?
          ?-queue boolean?     ?-atleastone boolean?
          ?-originator string? ?-recipients string?
          ?-header {key value}?...

mime::parseaddress returns a list of serialized arrays. Parameters:

    string

mime::parsedatetime returns a string. Parameters:

    [string | -now] property

mime::mapencoding returns a string. Parameters:

    encoding_name

mime::reversemapencoding returns a string. Parameters:

    mime_charset

TOC

3. SEMANTICS

3.1 mime::initialize

mime::initialize creates a MIME part:

  • If the -canonical option is present, then the body is in canonical (raw) form and is found by consulting either the -file, -string, or -part option.

    In addition, both the -param and -header options may occur zero or more times to specify "Content-Type" parameters (e.g., "charset") and header keyword/values (e.g., "Content-Disposition"), respectively.

    Also, -encoding, if present, specifies the "Content-Transfer-Encoding" when copying the body.
  • If the -canonical option is not present, then the MIME part contained in either the -file or the -string option is parsed, dynamically generating subordinates as appropriate.

3.2 mime::finalize

mime::finalize destroys a MIME part.

If the -subordinates option is present, it specifies which subordinates should also be destroyed. The default value is "dynamic".

3.3 mime::getproperty

mime::getproperty returns the properties of a MIME part.

The properties are:

    property    value
    ========    =====
    content     the type/subtype describing the content
    encoding    the "Content-Transfer-Encoding"
    params      a list of "Content-Type" parameters
    parts       a list of tokens for the part's subordinates
    size        the approximate size of the content (unencoded)

The "parts" property is present only if the MIME part has subordinates.

If mime::getproperty is invoked with the name of a specific property, then the corresponding value is returned; instead, if -names is specified, a list of all properties is returned; otherwise, a serialized array of properties and values is returned.

3.4 mime::getheader

mime::getheader returns the header of a MIME part.

A header consists of zero or more key/value pairs. Each value is a list containing one or more strings.

If mime::getheader is invoked with the name of a specific key, then a list containing the corresponding value(s) is returned; instead, if -names is specified, a list of all keys is returned; otherwise, a serialized array of keys and values is returned. Note that when a key is specified (e.g., "Subject"), the list returned usually contains exactly one string; however, some keys (e.g., "Received") often occur more than once in the header, accordingly the list returned usually contains more than one string.

3.5 mime::setheader

mime::setheader writes, appends to, or deletes the value associated with a key in the header.

The value for -mode is one of:

write:
the key/value is either created or overwritten (the default);
append:
a new value is appended for the key (creating it as necessary); or,
delete:
all values associated with the key are removed (the "value" parameter is ignored).

Regardless, mime::setheader returns the previous value associated with the key.

3.6 mime::getbody

mime::getbody returns the body of a leaf MIME part in canonical form.

If the -command option is present, then it is repeatedly invoked with a fragment of the body as this:

    uplevel #0 $callback [list "data" $fragment]

(The -blocksize option, if present, specifies the maximum size of each fragment passed to the callback.)

When the end of the body is reached, the callback is invoked as:

    uplevel #0 $callback "end"

Alternatively, if an error occurs, the callback is invoked as:

    uplevel #0 $callback [list "error" reason]

Regardless, the return value of the final invocation of the callback is propagated upwards by mime::getbody.

If the -command option is absent, then the return value of mime::getbody is a string containing the MIME part's entire body.

3.7 mime::copymessage

mime::copymessage copies the MIME part to the specified channel.

mime::copymessage operates synchronously, and uses fileevent to allow asynchronous operations to proceed independently.

3.7 mime::buildmessage

mime::buildmessage returns the MIME part as a string. It is similar to mime::copymessage, only it returns the data as a return string instead of writing to a channel.

3.8 smtp::sendmessage

smtp::sendmessage sends a MIME part to an SMTP server. (Note that this procedure is in the "smtp" package, not the "mime" package.)

The options are:

-servers:
a list of SMTP servers (the default is "localhost");
-ports:
a list of SMTP ports (the default is 25);
-queue:
indicates that the SMTP server should be asked to queue the message for later processing;
-atleastone:
indicates that the SMTP server must find at least one recipient acceptable for the message to be sent;
-originator:
a string containing an 822-style address specification (if present the header isn't examined for an originator address);
-recipients:
a string containing one or more 822-style address specifications (if present the header isn't examined for recipient addresses); and,
-header:
a keyword/value pairing (may occur zero or more times).

If the -originator option is not present, the originator address is taken from "From" (or "Resent-From"); similarly, if the -recipients option is not present, recipient addresses are taken from "To", "cc", and "Bcc" (or "Resent-To", and so on). Note that the header key/values supplied by the "-header" option (not those present in the MIME part) are consulted. Regardless, header key/values are added to the outgoing message as necessary to ensure that a valid 822-style message is sent.

smtp::sendmessage returns a list indicating which recipients were unacceptable to the SMTP server. Each element of the list is another list, containing the address, an SMTP error code, and a textual diagnostic. Depending on the -atleastone option and the intended recipients,, a non-empty list may still indicate that the message was accepted by the server.

3.9 mime::parseaddress

mime::parseaddr takes a string containing one or more 822-style address specifications and returns a list of serialized arrays, one element for each address specified in the argument.

Each serialized array contains these properties:

    property    value
    ========    =====
    address     local@domain
    comment     822-style comment
    domain      the domain part (rhs)
    error       non-empty on a parse error
    group       this address begins a group
    friendly    user-friendly rendering
    local       the local part (lhs)
    memberP     this address belongs to a group
    phrase      the phrase part
    proper      822-style address specification
    route       822-style route specification (obsolete)

Note that one or more of these properties may be empty.

3.10 mime::parsedatetime

mime::parsedatetime takes a string containing an 822-style date-time specification and returns the specified property.

The list of properties and their ranges are:

    property     range
    ========     =====
    hour         0 .. 23
    lmonth       January, February, ..., December
    lweekday     Sunday, Monday, ... Saturday
    mday         1 .. 31
    min          0 .. 59
    mon          1 .. 12
    month        Jan, Feb, ..., Dec
    proper       822-style date-time specification
    rclock       elapsed seconds between then and now
    sec          0 .. 59
    wday         0 .. 6 (Sun .. Mon)
    weekday      Sun, Mon, ..., Sat
    yday         1 .. 366
    year         1900 ...
    zone         -720 .. 720 (minutes east of GMT)

3.10 mime::mapencoding

mime::mapencoding takes a string containing the name of a tcl encoding (see [encoding names]) and returns the MIME charset name for that encoding (or "" if the charset name is unknown).

3.10 mime::reversemapencoding

mime::reversemapencoding takes a string containing the name of a MIME charset tcl encoding (see [encoding names]) and returns the MIME charset name for that encoding (or "" if no known tcl encoding maps to the mime charset type).

TOC

4. EXAMPLES

package require mime 1.0
package require smtp 1.0

# create an image

set imageT [mime::initialize -canonical image/gif \
                             -file logo.gif]

# parse a message

set messageT [mime::initialize -file example.msg]

# recursively traverse a message looking for primary recipients

proc traverse {token} {
    set result ""

# depth-first search
    if {![catch { mime::getproperty $token parts } parts]} {
        foreach part $parts {
            set result [concat $result [traverse $part]]
        }
    }

# one value for each line occuring in the header
    foreach value [mime::getheader $token To] {
        foreach addr [mime::parseaddress $value] {
            catch { unset aprops }
            array set aprops $addr
            lappend result $aprops(address)
        }
    }

    return $result
}

# create a multipart containing both, and a timestamp

set multiT [mime::initialize -canonical multipart/mixed
                             -parts [list $imageT $messageT]]

# send it to some friends

smtp::sendmessage $multiT \
      -header [list From "Marshall Rose <mrose@dbc.mtview.ca.us>"] \
      -header [list To "Andreas Kupries <a.kupries@westend.com>"] \
      -header [list cc "dnew@messagemedia.com (Darren New)"] \
      -header [list Subject "test message..."]

# clean everything up

mime::finalize $multiT -subordinates all

TOC

References

[1] | Freed, N. and N.S. Borenstein, "Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies", RFC 2045, November 1996.
[2] | Freed, N. and N.S. Borenstein, "Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types", RFC 2046, November 1995.
[3] | Crocker, D., "Standard for the format of ARPA Internet Text Messages", RFC 822, STD 11, August 1982.
TOC

Author's Address

 | Marshall T. Rose
 | Dover Beach Consulting, Inc.
 | POB 255268
 | Sacramento, CA 95865-5268
 | US
Phone: | +1 916 483 8878
Fax: | +1 916 483 8848
EMail: | mrose@dbc.mtview.ca.us
TOC

Appendix A. TODO List

mime::initialize
  • well-defined errorCode values
  • catch nested errors when processing a multipart

TOC

Appendix B. Acknowledgements

This package is influenced by the safe-tcl package (Borenstein and Rose, circa 1993), and also by Darren New's unpublished package of 1999.

This package makes use of Andreas Kupries's excellent Trf package.


tcllib ncgi

 Table of Contents

_________________________________________________________________

Name

::ncgi - Procedures to manipulate CGI values.

Synopsis

_________________________________________________________________

package require Tcl 8.2

package require ncgi ?1.2?

ncgi::cookie cookie

ncgi::decode str

ncgi::empty name

ncgi::encode string

ncgi::header {type text/html} args

ncgi::import cginame {tclname {}}

ncgi::importAll args

ncgi::input {fakeinput {}} {fakecookie {}}

ncgi::multipart type query

ncgi::nvlist

ncgi::parse

ncgi::parseMimeValue value

ncgi::query

ncgi::redirect url

ncgi::reset args

ncgi::setCookie args

ncgi::setDefaultValue key defvalue

ncgi::setDefaultValueList key defvaluelist

ncgi::setValue key value

ncgi::setValueList key valuelist

ncgi::type ncgi::urlStub {url {}}

ncgi::value key {default {}}

ncgi::valueList key {default {}}
_________________________________________________________________

Description

The ::ncgi package provides commands that manipulate CGI values. These are values that come from Web forms and are processed either by CGI scripts or web pages with embedded Tcl code. Use the ::ncgi package to query these values, set and get cookies, and encode and decode www-url-encoded values.

In the simplest case, a CGI script first calls ncgi::parse and then calls ncgi::value to get different form values. If a CGI value is repeated, you should use ncgi::valueList to get back the complete list of values.

An alternative to ncgi::parse is ncgi::input, which has semantics similar to Don Libes' cgi_input procedure. ncgi::input restricts repeated CGI values to have names that end with «List". In this case, ncgi::value will return the complete list of values, and ncgi::input will raise errors if it find repeated form elements without the right name.

The ncgi::reset procedure can be used in test suites and Web servers to initialize the source of the CGI values. Otherwise the values are read in from the CGI environment.

The complete set of procedures is described below.

ncgi::cookie cookie
Return a list of values for cookie, if any. It is possible that more than one cookie with the same name can be present, so this procedure returns a list.

ncgi::decode str
Decode strings in www-url-encoding, which represents special characters with a %xx sequence, where xx is the character code in hex.

ncgi::empty name
Returns 1 if the CGI variable name is not present or has the empty string as its value.

ncgi::encode string
Encode string into www-url-encoded format.

ncgi::header {type text/html} args
Output the CGI header to standard output. This emits a Content-Type: header and additional headers based on args, which is a list of header names and header values.

ncgi::import cginame {tclname {}}
This creates a variable in the current scope with the value of the CGI variable cginame. The name of the variable is tclname, or cginame if tclname is empty.

ncgi::importAll args
This imports several CGI variables as Tcl variables. If args is empty, then every CGI vale is imported. Otherwise each CGI variable listed in args is imported.

ncgi::input {fakeinput {}} {fakecookie {}} This reads and decodes the CGI values from the environment. It restricts repeated form values to have a trailing «List» in their name. The CGI values are obtained later with the ncgi::value procedure.

ncgi::multipart type query
This procedure parses a multipart/form-data query. This is used by ncgi::nvlist and not normally called directly. It returns an alternating list of names and structured values. Each structure value is in turn a list of two elements. The first element is meta-data from the multipart/form-data structure. The second element is the form value. If you use ncgi::value you just get the form value. If you use ncgi::valueList you get the structured value with meta data and the value.

The type is the whole Content-Type, including the parameters like boundary. This returns a list of names and values that describe the multipart data. The values are a nested list structure that has some descriptive information first, and the actual form value second. The descriptive information is list of header names and values that describe the content.

ncgi::nvlist
This returns all the query data as a name, value list. In the case of multipart/form-data, the values are structured as described in ncgi::multipart.

ncgi::parse
This reads and decodes the CGI values from the environment. The CGI values are obtained later with the ncgi::value procedure. IF a CGI value is repeated, then you should use ncgi::valueList to get the complete list of values.

ncgi::parseMimeValue value
This decodes the Content-Type and other MIME headers that have the form of «primary value; param=val; p2=v2» It returns a list, where the first element is the primary value, and the second element is a list of parameter names and values.

ncgi::query
This returns the raw query data.

ncgi::redirect url
Generate a response that causes a 302 redirect by the Web server. The url is the new URL that is the target of the redirect. The URL will be qualified with the current server and current directory, if necessary, to convert it into a full URL.

ncgi::reset query type
Set the query data and Content-Type for the current CGI session. This is used by the test suite and by Web servers to initialize the ncgi module so it does not try to read standard input or use environment variables to get its data. If neither query or type are specified, then the ncgi module will look in the standard CGI environment for its data.

ncgi::setCookie args
Set a cookie value that will be returned as part of the reply. This must be done before ncgi::header or ncgi::redirect is called in order for the cookie to be returned properly. The args are a set of flags and values: -name name
-value value
-expires date
-path path restriction
-domain domain restriction

ncgi::setDefaultValue key defvalue
Set a CGI value if it does not already exists. This affects future calls to ncgi::value (but not future calls to ncgi::nvlist). If the CGI value already is present, then this procedure has no side effects.

ncgi::setDefaultValueList key defvaluelist Like ncgi::setDefaultValue except that the value already has list structure to represent multiple checkboxes or a multi-selection.

ncgi::setValue key value
Set a CGI value, overriding whatever was present in the CGI environment already. This affects future calls to ncgi::value (but not future calls to ncgi::nvlist).

ncgi::setValueList key valuelist
Like ncgi::setValue except that the value already has list structure to represent multiple checkboxes or a multi-selection.

ncgi::type
Returns the Content-Type of the current CGI values.

ncgi::urlStub {url {}}
Returns the current URL, but without the protocol, server, and port. If url is specified, then it defines the URL for the current session. That value will be returned by future calls to ncgi::urlStub

ncgi::value key {default {}}
Return the CGI value identified by key. If the CGI value is not present, then the default value is returned instead. If the form value key is repeated, then there are two cases: if ncgi::parse was called, then ncgi::value only returns the first value associated with key. If ncgi::input was called, then ncgi::value returns a Tcl list value and key must end in «List» (e.g., «skuList"). In the case of multipart/form-data, this procedure just returns the value of the form element. If you want the meta-data associated with each form value, then use ncgi::valueList.

ncgi::valueList key {default {}}
Like ncgi::value, but this always returns a list of values (even if there is only one value). In the case of multipart/form-data, this procedure returns a list of two elements. The first element is metadata in the form of a parameter, value list. The second element is the form value.

See Also

html

Keywords

CGI, form, html, cookie

Table of Contents

  • Name
  • Synopsis
  • Description
  • See Also
  • Keywords


tcllib nntp

 Table of Contents

_________________________________________________________________

Name

nntp - Tcl client for the NNTP protocol

Synopsis

package require Tcl 8.2

package require nntp ?0.1?

::nntp::nntp ?host? ?port? ?nntpName?

_________________________________________________________________

Description

The nntp package provides a simple Tcl-only client library for the NNTP protocol. It works by opening the standard NNTP socket on the server, and then providing a Tcl API to access the NNTP protocol commands. All server errors are returned as Tcl errors (thrown) which must be caught with the Tcl catch command. The ::nntp::nntp command creates a new nntp object with an associated Tcl command whose name is returned by the ::nntp::nntp command (nntpName). This command may be used to access the various NNTP protocol commands. Some of the commands supported by this package are not part of the nntp rfc (rfc 977) and will not be available (or implemented) on all nntp servers. The commands have the following general form:
nntpName option ?arg arg ...?
Option and the args determine the exact behavior of the command.

Commands

::nntp::nntp ?host? ?port? ?nntpName?
Open a socket connection to a NNTP server. The command returns the name of the global command that can be used to access the nntp connection subsequently. The default port number is 119 and the default server is news which can be overridden with the environment variables NNTPPORT and NNTPHOST respectively.

nntpName article ?msgid?
Query the server for article msgid from the current group. The article is returned as a valid tcl list which contains the headers, followed by a blank line, and then followed by the body of the article. Each element in the list is one line of the article.

nntpName authinfo ?user? ?pass?
Send authentication information (username and password) to the server.

nntpName body ?msgid?
Query the server for the body of the article msgid from the current group. The body of the article is returned as a valid tcl list. Each element in the list is one line of the body of the article.

nntpName date
Query the server for the servers current date. The date is returned in the format YYYYMMDDHHMMSS

nntpName group ?group?
Optionally set the current group, and retrieve information about the currently selected group. Returns the estimated number of articles in the group followed by the number of the first article in the group, followed by the last article in the group, followed by the name of the group.

nntpName head ?msgid?
Query the server for the headers of the article msgid from the current group. The headers of the article are returned as a valid tcl list. Each element in the list is one line of the headers of the article.

nntpName help
Retrieves a list of the commands that are supported by the news server that is currently attached to.

nntpName last
Sets the current article pointer to point to the previous message (if there is one) and returns the msgid of that message.

nntpName list
Returns a tcl list of valid newsgroups and associated information. Each newsgroup is returned as an element in the tcl list with the following format:

group last first p

where <group> is the name of the newsgroup, <last> is the number of the last known article currently in that newsgroup, <first> is the number of the first article currently in the newsgroup, and <p> is either `y' or `n' indicating whether posting to this newsgroup is allowed ('y') or prohibited ('n').

The <first> and <last> fields will always be numeric. They may have leading zeros. If the <last> field evaluates to less than the <first> field, there are no articles currently on file in the newsgroup.

nntpName listgroup ?group?
Query the server for a list of all the messages (message numbers) in the group specified by the argument group or by the current group if the group argument was not passed.

nntpName mode_reader
Query the server for its nntp `MODE READER' response string.

nntpName newgroups since
Query the server for a list of all the new newsgroups created since the time specified by the argument since. The argument since can be any time string that is understood by clock scan. The tcl list of newsgroups is returned in a similar form to the list of groups returned by the nntpName list command. Each element of the list has the form:

group last first p

where <group> is the name of the newsgroup, <last> is the number of the last known article currently in that newsgroup, <first> is the number of the first article currently in the newsgroup, and <p> is either `y' or `n' indicating whether posting to this newsgroup is allowed ('y') or prohibited ('n').

nntpName newnews
Query the server for a list of new articles posted to the current group in the last day.

nntpName newnews since
Query the server for a list of new articles posted to the current group since the time specified by the argument since. The argument since can be any time string that is understood by clock scan.

nntpName newnews group ?since?
Query the server for a list of new articles posted to the group specified by the argument group since the time specified by the argument since (or in the past day if no since argument is passed. The argument since can be any time string that is understood by clock scan.

nntpName next
Sets the current article pointer to point to the next message (if there is one) and returns the msgid of that message.

nntpName post article
Posts an article of the form specified in RFC 850 to the current news group.

nntpName slave
Identifies a connection as being made from a slave nntp server. This might be used to indicate that the connection is serving multiple people and should be given priority. Actual use is entirely implementation dependent and may vary from server to server.

nntpName stat ?msgid?
The stat command is similar to the article command except that no text is returned. When selecting by message number within a group, the stat command serves to set the current article pointer without sending text. The returned acknowledgment response will contain the message-id, which may be of some value. Using the stat command to select by message-id is valid but of questionable value, since a selection by message-id does NOT alter the «current article pointer"

nntpName quit
Gracefully close the connection after sending a NNTP QUIT command down the socket.

nntpName xgtitle ?group_pattern?
Returns a tcl list where each element is of the form:

newsgroup description

If a group_pattern is specified then only newsgroups that match the pattern will have their name and description returned.

nntpName xhdr field ?range?
Returns the specified header field value for the current message or for a list of messages from the current group. field is the title of a field in the header such as from, subject, date, etc. If range is not specified or is «» then the current message is queried. The command returns a list of elements where each element has the form of:

msgid value

Where msgid is the number of the message and value is the value set for the queried field. The range argument can be in any of the following forms:

«»
The current message is queried.

msgid1-msgid2
All messages between msgid1 and msgid2 (including msgid1 and msgid2) are queried.

msgid1 msgid2
All messages between msgid1 and msgid2 (including msgid1 and msgid2) are queried.

nntpName xover ?range?
Returns header information for the current message or for a range of messages from the current group. The information is returned in a tcl list where each element is of the form:

msgid subject from date idstring bodysize headersize xref

If range is not specified or is «» then the current message is queried. The range argument can be in any of the following forms:

«»
The current message is queried.

msgid1-msgid2
All messages between msgid1 and msgid2 (including msgid1 and msgid2) are queried.

msgid1 msgid2
All messages between msgid1 and msgid2 (including msgid1 and msgid2) are queried.

nntpName xpat field range ?pattern_list? Returns the specified header field value for a specified message or for a list of messages from the current group where the messages match the pattern(s) given in the pattern_list. field is the title of a field in the header such as from, subject, date, etc. The information is returned in a tcl list where each element is of the form:

msgid value

Where msgid is the number of the message and value is the value set for the queried field. The range argument can be in any of the following forms:

msgid The message specified by msgid is queried.

msgid1-msgid2
All messages between msgid1 and msgid2 (including msgid1 and msgid2) are queried.

msgid1 msgid2
All messages between msgid1 and msgid2 (including msgid1 and msgid2) are queried.

KEYWORDS
news, nntp, nntpclient

Table of Contents

  • Name
  • Synopsis
  • Description
  • Commands


tcllib pop3

 Table of Contents

_________________________________________________________________

Name

pop3 - Tcl client for POP3 email protocol

Synopsis

package require Tcl 8.2

package require pop3 ?1.5?

::pop3::open ?-msex 0|1? ?-retr-mode retr|list|slow? host user Ipassword ?port?

::pop3::status chan

::pop3::last chan

::pop3::retrieve chan startIndex ?endIndex?

::pop3::delete chan startIndex ?endIndex?

::pop3::list chan ?msg?

::pop3::top chan msg n

::pop3::uidl chan ?msg?

::pop3::close chan

_________________________________________________________________

Description

The pop3 package provides a simple Tcl-only client library for the POP3 email protocol (RFC1939). It works by opening the standard POP3 socket on the server, transmitting the username and password, then providing a Tcl API to access the POP3 protocol commands. All server errors are returned as Tcl errors (thrown) which must be caught with the Tcl catch command.

Commands

::pop3::open ?-msex 0|1? ?-retr-mode retr|list|slow? host user- name password ?port?
Open a socket connection to the server specified by host, transmit the username and password as login information to the server. The default port number is 110, which can be overridden using the optional port argument. The return value is a channel used by all of the other ::pop3 functions.

The command recognizes the options -msex and -retr_mode. The first of them can be used to notify the package of the fact that the server to talk to is an MS Exchange server (which has some oddities we have to work around). The default is 0.

The retrieval mode determines how exactly messages are read from the server. The allowed values are retr, list and slow. The default is retr. See ::pop3::retrieve for more information.

::pop3::status chan
Query the server for the status of the mail spool. The status is returned as a list containing two elements, the first is the number of email messages on the server and the second is the size (in octets, 8 byte blocks) of the entire mail spool.

::pop3::last chan
Query the server for the last email message read from the spool. This value includes all messages read from all clients connecting to the login account. This command may not be supported by the email server, in which case the server may return 0 or an error.

::pop3::retrieve chan startIndex ?endIndex? Retrieve a range of messages from the server. If the endIndex is not specified, only one message will be retrieved. The return value is a list containing each message as a separate element. See the startIndex and endIndex descriptions below.

The retrieval mode determines how exactly messages are read from the server. The mode retr assumes that the RETR command delivers the size of the message as part of the command status and uses this to read the message efficiently. In mode list RETR does not deliver the size, but the LIST command does and we use this to retrieve the message size before the actual retrieval, which can then be done efficiently. In the last mode, slow, the system is unable to obtain the size of the message to retrieve in any manner and falls back to reading the message from the server line by line.

It should also be noted that the system checks upon the configured mode and falls back to the slower modes if the above assumptions are not true.

::pop3::delete chan startIndex ?endIndex? Delete a range of messages from the server. If the endIndex is not specified, only one message will be deleted. Note, the indices are not reordered on the server, so if you delete message 1, then the first message in the queue is message 2 (message index 1 is no longer valid). See the startIndex and endIndex descriptions below.

startIndex
The startIndex may be an index of a specific message starting with the index 1, or it have any of the following values:

start This is a logical value for the first message in the spool, equivalent to the value 1.

next The message immediately following the last message read, see ::pop3::last.

end
The most recent message in the spool (the end of the spool). This is useful to retrieve only the most recent message.

endIndex
The endIndex is an optional parameter and defaults to the value -1, which indicates to only retrieve the one message specified by startIndex. If specified, it may be an index of a specific message starting with the index 1, or it have any of the following values:

last The message is the last message read by a POP3 client, see ::pop3::last.

end
The most recent message in the spool (the end of the spool).

::pop3::list chan ?msg?
Returns the scan listing of the mailbox. If parameter msg is given, then the listing only for that message is returned.

::pop3::top chan msg n
Optional POP3 command, not all servers may support this. ::pop3::top retrieves headers of a message, specified by parameter msg, and number of n lines from the message body.

::pop3::uidl chan ?msg?
Optional POP3 command, not all servers may support this. ::pop3::uidl returns the uid listing of the mailbox. If the parameter msg is specified, then the listing only for that message is returned.

::pop3::close chan
Gracefully close the connect after sending a POP3 QUIT command down the socket.

Keywords

mail, email, pop, pop3, RFC1939

Table of Contents

  • Name
  • Synopsis
  • Description
  • Commands
  • Keywords


tcllib profiler

 Table of Contents

_________________________________________________________________

Name

profiler - Tcl source code profiler

Synopsis

package require Tcl 8.3

package require profiler ?0.2?

::profiler::suspend ?pattern?

::profiler::resume ?pattern?

::profiler::init

::profiler::dump ?pattern?

::profiler::print ?pattern?

::profiler::reset ?pattern?

::profiler::sortFunctions key

_________________________________________________________________

Description

The profiler package provides a simple Tcl source code profiler. It is a function-level profiler; that is, it collects only function-level information, not the more detailed line-level information. It operates by redefining the Tcl proc command. Profiling is initiated via the ::profiler::init command.

Commands

::profiler::init
Initiate profiling. All procedures created after this command is called will be profiled. To profile an entire application, this command must be called before any other commands.

::profiler::dump pattern
Dump profiling information for the all functions matching pattern. If no pattern is specified, information for all functions will be returned. The result is a list of key/value pairs that maps function names to information about that function. The information about each function is in turn a list of key/value pairs. The keys used and their values are:

totalCalls
The total number of times functionName was called.

callerDist
A list of key/value pairs mapping each calling function that called functionName to the number of times it called functionName.

compileTime
The runtime, in clock clicks, of function_N ame the first time that it was called.

totalRuntime
The sum of the runtimes of all calls of functionName.

averageRuntime
Average runtime of functionName.

descendantTime
Sum of the time spent in descendants of functionName.

averageDescendantTime
Average time spent in descendants of func_tionName.

::profiler::print ?pattern?
Print profiling information for all functions matching pattern. If no pattern is specified, information about all functions will be displayed. The return result is a human readable display of the profiling information.

::profiler::reset
Reset profiling information for all functions matching pattern. If no pattern is specified, information will be reset for all functions.

::profiler::suspend ?pattern?
Suspend profiling for all functions matching pat_tern. If no pattern is specified, profiling will be suspended for all functions. It stops gathering profiling information after this command is issued. However, it does not erase any profiling information that has been gathered previously. Use resume command to re-enable profiling.

::profiler::resume ?pattern?
Resume profiling for all functions matching pat_tern. If no pattern is specified, profiling will be resumed for all functions. This command should be invoked after suspending the profiler in the code.

::profiler::sortFunctions key
Return a list of functions sorted by a particular profiling statistic. Supported values for key are: calls, exclusiveTime, compileTime, nonCompileTime, totalRuntime, avgExclusiveTime, and avgRuntime. The return result is a list of lists, where each sublist consists of a function name and the value of key for that function.

Keywords

profile, performance, speed

Table of Contents

  • Name
  • Synopsis
  • Description
  • Commands
  • Keywords


tcllib report

 Table of Contents

_________________________________________________________________

Name

::report::report - Create and manipulate report objects

Synopsis

package require Tcl 8.2

package require report ?0.2?

::report::report reportName columns ?style style arg...?

::report::defstyle styleName arguments script

::report::rmstyle styleName

::report::stylearguments styleName

::report::stylebody styleName

::report::styles

_________________________________________________________________

Description

This package provides report objects which can be used by the formatting methods of matrix objects to generate tabular reports of the matrix in various forms. The report objects defined here break each report down into three regions and ten classes of lines (various separator- and data-lines). See the following section for more detailed explanations.

::report::report reportName columns ?style style arg...? Creates a new report object for a report having columns columns with an associated global Tcl command whose name is reportName. This command may be used to invoke various configuration operations on the report. It has the following general form: reportName option ?arg arg ...?

Option and the args determine the exact behavior of the command. See section REPORT METHODS for more explanations. If no style is specified the report will use the builtin style plain as its default configuration.

::report::defstyle styleName arguments script Defines the new style styleName. See section STYLES for more information.

::report::rmstyle styleName
Deletes the style styleName. Trying to delete an unknown or builtin style will result in an error.

Beware, this command will not check that there are no other styles depending on the deleted one. Deleting a style which is still used by another style FOO will result in a runtime error when FOO is applied to a newly instantiated report.

::report::stylearguments styleName
This introspection command returns the list of arguments associated with the style styleName.

::report::stylebody styleName
This introspection command returns the script associated with the style styleName.

::report::styles
This introspection command returns a list containing the names of all styles known to the package at the time of the call. The order of the names in the list reflects the order in which the styles were created. In other words, the first item is the predefined style plain, followed by the first style defined by the user, and so on.

Regions

The three regions are the top caption, data area and bottom caption. These are, roughly speaking, the title, the values to report and a title at the bottom. The size of the caption regions can be specified by the user as the number of rows they occupy in the matrix to format. The size of the data area is specified implicitly.

Lines

Each of the ten line classes can have a template (see section below) associated with it defining the formatting for this kind of line. The user is able to enable and disable the separator lines at will, but not the data lines. Their usage is solely determined by the number of rows contained in the three regions. Data lines and all enabled separators must have a template associated with them.

Note that the data-lines in a report and the rows in the matrix the report was generated from are not in a 1:1 relationship if any row in the matrix has a height greater than one.

The different kinds of lines and the codes used by the report methods to address them are:

top
The topmost line of a report. Separates the report from anything which came before it. The user can enable the usage of this line at will.

topdatasep
This line is used to separate the data rows in the top caption region, if it contains more than one row and the user enabled its usage.

topcapsep
This line is used to separate the top caption and data regions, if the top caption is not empty and the user enabled its usage.

datasep
This line is used to separate the data rows in the data region, if it contains more than one row and the user enabled its usage.

botcapsep
This line is used to separate the data and bottom caption regions, if the bottom caption is not empty and the user enabled its usage.

botdatasep
This line is used to separate the data rows in the bottom caption region, if it contains more than one row and the user enabled its usage.

bottom The bottommost line of a report. Separates the report from anything which comes after it. The user can enable the usage of this line at will.

topdata
This line defines the format of data lines in the top caption region of the report.

data This line defines the format of data lines in the data region of the report.

botdata
This line defines the format of data lines in the bottom caption region of the report.

Templates

Each template is a list of strings used to format the line it is associated with. For a report containing n columns a template for a data line has to contain «n+1» items and a template for a separator line «2*n+1» items.

The items in a data template specify the strings used to separate the column information. Together with the corresponding items in the separator templates they form the vertical lines in the report.

Note that the corresponding items in all defined templates have to be of equal length. This will be checked by the report object. The first item defines the leftmost vertical line and the last item defines the rightmost vertical line. The item at index k ("1",...,"n-2") separates the information in the columns «k-1» and «k".

The items in a separator template having an even-numbered index ("0","2",...) specify the column separators. The item at index «2*k» ("0","2",...,"2*n") corresponds to the items at index «k» in the data templates.

The items in a separator template having an odd-numbered index ("1","3",...) specify the strings used to form the horizontal lines in the separator lines. The item at index «2*k+1» ("1","3",...,"2*n+1") corresponds to column «k". When generating the horizontal lines the items are replicated to be at least as long as the size of their column and then cut to the exact size.

Styles

Styles are a way for the user of this package to define common configurations for report objects and then use them later during the actual instantiation of report objects. They are defined as tcl scripts which when executed configure the report object into the requested configuration.

The command to define styles is ::report::defstyle. Its last argument is the tcl script performing the actual reconfiguration of the report object to obtain the requested style.

In this script the names of all previously defined styles are available as commands, as are all commands found in a safe interpreter and the configuration methods of report objects. The latter implicitly operate on the object currently executing the style script. The arguments declared here are available in the script as variables. When calling the command of a previously declared style all the arguments expected by it have to be defined in the call.

Report Methods

The following commands are possible for report objects:

reportName destroy
Destroys the report, including its storage space and associated command.

reportName templatecode disable|enable
Enables or disables the usage of the template addressed by the templatecode. Only the codes for separator lines are allowed here. It is not possible to enable or disable data lines.

Enabling a template causes the report to check all used templates for inconsistencies in the definition of the vertical lines (See section TEMPLATES).

reportName templatecode enabled
Returns the whether the template addressed by the templatecode is currently enabled or not.

reportName templatecode get
Returns the template currently associated with the kind of line addressed by the templatecode. All known templatecodes are allowed here.

reportName templatecode set templatedata Sets the template associated with the kind of line addressed by the templatecode to the new value in templatedata. See section TEMPLATES for constraints on the length of templates.

reportName tcaption ?size?
Specifies the size of the top caption region as the number rows it occupies in the matrix to be formatted. Only numbers greater than or equal to zero are allowed. If no size is specified the command will return the current size instead.

Setting the size of the top caption to a value greater than zero enables the corresponding data template and causes the report to check all used templates for inconsistencies in the definition of the vertical lines (See section TEMPLATES).

reportName bcaption size
Specifies the size of the bottom caption region as the number rows it occupies in the matrix to be formatted. Only numbers greater than or equal to zero are allowed. If no size is specified the command will return the current size instead.

Setting the size of the bottom caption to a value greater than zero enables the corresponding data template and causes the report to check all used templates for inconsistencies in the definition of the vertical lines (See section TEMPLATES).

reportName size column ?number|dyn?
Specifies the size of the column in the output. The value dyn means that the columnwidth returned by the matrix to be formatted for the specified column shall be used. The formatting of the column is «dynamic". If a fixed number is used instead of dyn it means that the column has a width of that many characters (padding excluded). Only numbers greater than zero are allowed here.

If no size specification is given the command will return the current size of the column instead.

reportName sizes ?size-list?
This method allows the user to specify the sizes of all columns in one call. Its argument is a list containing the sizes to associate with the columns. The first item is associated with column 0, the next with column 1, and so on.

If no size-list is specified the command will return a list containing the currently set sizes instead.

reportName pad column ?left|right|both ?padstring?? This method allows the user to specify padding on the left, right or both sides of a column. If the padstring is not specified it defaults to a single space character. Note: An alternative way of specifying the padding is to use vertical separator strings longer than one character in the templates (See section TEMPLATES).

If no pad specification is given at all the command will return the current state of padding for the column instead. This will be a list containing two elements, the first element the left padding, the second describing the right padding.

reportName justify column ?left|right|center? Declares how the cell values for a column are filled into the report given the specified size of a column in the report.

For left and right justification a cell value shorter than the width of the column is bound with its named edge to the same edge of the column. The other side is filled with spaces. In the case of center the spaces are placed to both sides of the value and the left number of spaces is at most one higher than the right number of spaces.

For a value longer than the width of the column the value is cut at the named edge. This means for left justification that the tail (i.e. the right part) of the value is made visible in the output. For center the value is cut at both sides to fit into the column and the number of characters cut at the left side of the value is at most one less than the number of characters cut from the right side.

If no justification was specified the command will return the current justification for the column instead.

reportName printmatrix matrix
Formats the matrix according to the configuration of the report and returns the resulting string. The matrix has to have the same number of columns as the report. The matrix also has to have enough rows so that the top and bottom caption regions do not overlap. The data region is allowed to be empty.

reportName printmatrix2channel matrix chan Formats the matrix according to the configuration of the report and writes the result into the channel chan. The matrix has to have the same number of columns as the report. The matrix also has to have enough rows so that the top and bottom caption regions do not overlap. The data region is allowed to be empty.

reportName columns
Returns the number of columns in the report.

The methods size, pad and justify all take a column index as their first argument. This index is allowed to use all the forms of an index as accepted by the lindex command. The allowed range for indices is «0,...,[reportName columns]-1".

Examples

Our examples define some generally useful report styles.

A simple table with lines surrounding all information and vertical separators, but without internal horizontal separators.

::report::defstyle simpletable {} {

data set [split «[string repeat «| «
[columns]]|"] top set [split «[string repeat «+ - « [columns]]+"] bottom set [top get] top enable bottom enable }

An extension of a simpletable, see above, with a title area.

::report::defstyle captionedtable {{n 1}} { simpletable
topcapsep set [top get]
topcapsep enable
tcaption $n
}

Keywords

matrix, report, table

Table of Contents

  • Name
  • Synopsis
  • Description
  • Regions
  • Lines
  • Templates
  • Styles
  • Report Methods
  • Examples
  • Keywords


tcllib sha1

 Table of Contents

_________________________________________________________________

Name

::sha1::sha1 - Perform sha1 hashing

Synopsis

package require Tcl 8.2

package require sha1 ?1.0.1?

::sha1::sha1 msg?

::sha1::hmac key text

_________________________________________________________________

Description

This package provides commands to compute a SHA1 digests of arbitrary messages.

Commands

::sha1::sha1 msg
The command takes a message and returns the SHA1 digest of this message as a hexadecimal string.

::sha1::hmac key text
The command takes a key string and a text and returns the hmac of the text under the chosen key as a hexadecimal string.

Examples

% sha1::sha1 «hello world"
2aae6c35c94fcfb415dbe95f408b9ce91ee846ed

% sha1::hmac «our little secret» «hello world" a7ed9d62819b9788e22171d9108a00c370104526

Keywords

sha1, hashing, security

Table of Contents

  • Name
  • Synopsis
  • Description
  • Commands
  • Examples
  • Keywords


tcllib stats

 Table of Contents

_________________________________________________________________

Name

::stats - Procedures for counters, histograms, and statistics.

Synopsis

_________________________________________________________________

stats::countInit tag args

stats::count tag {delta 1} args

stats::countReset tag

stats::countGet tag args

stats::countStart tag

stats::countStop tag

stats::countExists tag

stats::countNames tag

stats::histHtmlDisplay tag args
_________________________________________________________________

Description

The ::stats package provides a counter facility and can compute statistics and histograms over the collected data.

stats::countInit tag args
This defines a counter with the name tag. The args determines the characteristics of the counter. The args are

-group name
Keep a grouped counter where the name of the histogram bucket is passed into stats::count.
-hist bucketsize
Accumulate the counter into histogram buckets of size bucketsize. For example, if the samples are millisecond time values and bucketsize is 10, then each histogram bucket represents time values of 0 to 10 msec, 10 to 20 msec, 20 to 30 msec, and so on.
-hist2x bucketsize
Accumulate the statistic into histogram buckets. The size of the first bucket is bucketsize, each other bucket holds values 2 times the size of the previous bucket. For example, if bucketsize is 10, then each histogram bucket represents time values of 0 to 10 msec, 10 to 20 msec, 20 to 40 msec, 40 to 80 msec, and so on.
-hist10x bucketsize
Accumulate the statistic into histogram buckets. The size of the first bucket is bucketsize, each other bucket holds values 10 times the size of the previous bucket. For example, if bucketsize is 10, then each histogram bucket represents time values of 0 to 10 msec, 10 to 100 msec, 100 to 1000 msec, and so on.
-lastn N
Save the last N values of the counter to maintain a «running average» over the last N values.
-timehist secsPerMinute
Keep a time-based histogram. The counter is summed into a histogram bucket based on the current time. There are 60 per-minute buckets that have a size determined by secsPerMinute, which is normally 60, but for testing purposes can be less. Every «hour" (i.e., 60 «minutes") the contents of the per-minute buckets are summed into the next hourly bucket. Every 24 «hours» the contents of the per-hour buckets are summed into the next daily bucket. The stats package keeps all time-based histograms in sync, so the first secsPerMinute value seen by the package is used for all subsequent time-based histograms.

stats::count tag {delta 1} {instance {}} Increment the counter identified by tag. The default increment is 1, although you can increment by any value, integer or real, by specifying delta. You must declare each counter with stats::countInit to define the characteristics of counter before you start to use it. If the counter type is -group, then the counter identified by instance is incremented.

stats::countStart tag instance
Record the starting time of an interval. The tag is the name of the counter defined as a -hist value-based histogram. The instance is used to distinguish this interval from any other intervals that might be overlapping this one.

stats::countStop tag instance
Record the ending time of an interval. The delta time since the corresponding countStart call for instance is recorded in the histogram identified by tag.

stats::countGet tag args
Return statistics about a counter identified by tag. The args determine what value to return:

-total Return the total value of the counter.
This is the default if args is not specified.
-totalVar
Return the name of the total variable. Useful for specifying with -textvariable in a Tk widget.
-N
Return the number of samples accumulated into the counter.
-avg
Return the average of samples accumulated into the counter.
-avgn
Return the average over the last N samples taken. The N value is set in the stats::countInit call.
-hist bucket
If bucket is specified, then the value in that bucket of the histogram is returned. Otherwise the complete histogram is returned in array get format sorted by bucket.
-histVar
Return the name of the histogram array variable.
-histHour
Return the complete hourly histogram in array get format sorted by bucket.
-histHourVar
Return the name of the hourly histogram array variable.
-histDay
Return the complete daily histogram in array get format sorted by bucket.
-histDayVar
Return the name of the daily histogram array variable.
-resetDate
Return the clock seconds value recorded when the counter was last reset.
-all
Return an array get of the array used to store the counter. This includes the total, the number of samples (N), and any type-specific information. This does not include the histogram array.

stats::countExists tag
Returns 1 if the counter is defined.

stats::countNames
Returns a list of all counters defined.

stats::histHtmlDisplay tag args
Generate HTML to display a histogram for a counter. The args control the format of the display. They are:

-title string
Label to display above bar chart
-unit unit
Specify minutes, hours, or days for the time-base histograms. For value-based histograms, the unit is used in the title.
-images url
URL of /images directory.
-gif filename
Image for normal histogram bars. The filename is relative to the -images directory.
-ongif filename
Image for the active histogram bar. The filename is relative to the -images directory.
-max N Maximum number of value-based buckets to display.
-height N
Pixel height of the highest bar.
-width N
Pixel width of each bar.
-skip N
Buckets to skip when labeling value-based histograms.
-format string
Format used to display labels of buckets.
-text boolean
If 1, a text version of the histogram is dumped, otherwise a graphical one is generated.

Table of Contents

  • Name
  • Synopsis
  • Description


tcllib graph

 Table of Contents

_________________________________________________________________

Name

::struct::graph - Create and manipulate directed graph objects

Synopsis

package require Tcl 8.2

package require struct ?1.1.1?

::struct::graph graphName

_________________________________________________________________

Description

The ::struct::graph command creates a new graph object with an associated global Tcl command whose name is graph_N ame. This command may be used to invoke various operations on the graph. It has the following general form: graphName option ?arg arg ...?
Option and the args determine the exact behavior of the command.

A directed graph is a structure containing two collections of elements, called nodes and arcs resp., together with a relation ("connectivity") that places a general structure upon the nodes and arcs.

Each arc is connected to two nodes, one of which is called the source and the other the target. This imposes a direction upon the arc, which is said to go from the source to the target. It is allowed that source and target of an arc are the same node. Such an arc is called a loop. Whenever a node is source or target of an arc both are said to be adjacent. This extends into a relation between nodes, i.e. if two nodes are connected through at least one arc they are said to be adjacent too.

Each node can be the source and target for any number of arcs. The former are called the outgoing arcs of the node, the latter the incoming arcs of the node. The number of edges in either set is called the in- resp. the out-degree of the node.

In addition to maintaining the node and arc relationships, this graph implementation allows any number of keyed values to be associated with each node and arc.

The following commands are possible for graph objects:

graphName destroy
Destroy the graph, including its storage space and associated command.

graphName arc delete arc ?arc ...?
Remove the specified arcs from the graph.

graphName arc exists arc
Return true if the specified arc exists in the graph.

graphName arc get arc ?-key key?
Return the value associated with the key key for the arc. If no key is specified, the key data is assumed.

graphName arc insert start end ?child? Insert an arc named child into the graph beginning at the node start and ending at the node end. If the name of the new arc is not specified the system will generate a unique name of the form arc x.

graphName arc set arc ?-key key? ?value? Set or get one of the keyed values associated with an arc. If no key is specified, the key data is assumed. Each arc that is added to a graph has the value «» assigned to the key data automatically. An arc may have any number of keyed values associated with it. If value is not specified, this command returns the current value assigned to the key; if value is specified, this command assigns that value to the key.

graphName arc source arc
Return the node the given arc begins at.

graphName arc target arc
Return the node the given arc ends at.

graphName arc unset arc ?-key key?
Remove a keyed value from the arc arc. If no key is specified, the key data is assumed.

graphName arcs ?-in|-out|-adj|-inner|-embedding nodelist?

Return a list of arcs in the graph. If no restriction is specified a list containing all arcs is returned. If one of the five possible restrictions is specified only arcs satisfying that restriction are returned. All restrictions involve a list of nodes, specified after the key for the restriction itself.

-in
Return a list of all arcs whose target is one of the nodes in the nodelist.
-out Return a list of all arcs whose source is
one of the nodes in the nodelist. -adj Return a list of all arcs adjacent to at least one of the nodes in the nodelist. This is the union of the nodes returned by -in and -out.
-inner Return a list of all arcs adjacent to two of
the nodes in the nodelist. This is the set of arcs in the subgraph spawned by the specified nodes.
-embedding
Return a list of all arcs adjacent to exactly one of the nodes in the nodelist. This is the set of arcs connecting the subgraph spawned by the specified nodes to the rest of the graph.

graphName node degree ?-in|-out? node
Return the number of arcs adjacent to the specified node. If one of the restrictions -in or -out is given only the incoming resp. outgoing arcs are counted.

graphName node delete node ?node ...?
Remove the specified nodes from the graph. All of the nodes' arcs will be removed as well to prevent unconnected arcs.

graphName node exists node
Return true if the specified node exists in the graph.

graphName node get node ?-key key?
Return the value associated with the key key for the node. If no key is specified, the key data is assumed.

graphName node insert ?child?
Insert a node named child into the graph. The nodes has no arcs connected to it. If the name of the new child is not specified the system will generate a unique name of the form node x.

graphName node opposite node arc
Return the node at the other end of the specified arc, which has to be adjacent to the given node.

graphName node set node ?-key key? ?value? Set or get one of the keyed values associated with a node. If no key is specified, the key data is assumed. Each node that is added to a graph has the value «» assigned to the key data automatically. A node may have any number of keyed values associated with it. If value is not specified, this command returns the current value assigned to the key; if value is specified, this command assigns that value to the key.

graphName node unset node ?-key key?
Remove a keyed value from the node node. If no key is specified, the key data is assumed.

graphName nodes ?-in|-out|-adj|-inner|-embedding nodelist? Return a list of nodes in the graph. If no restriction is specified a list containing all nodes is returned. If one of the five possible restrictions is specified only nodes satisfying that restriction are returned. All restrictions involve a list of nodes, specified after the key for the restriction itself.

The possible restrictions are the same as for method arcs. The set of nodes to return is computed as the union of all source and target nodes for all the arcs satisfying the restriction as defined for arcs.

graphName swap node1 node2
Swap the position of node1 and node2 in the graph.

graphName walk node ?-order order? ?-type type? ?-dir direction? -command cmd

Perform a breadth-first or depth-first walk of the graph starting at the node node going in either the direction of outgoing or opposite to the incoming arcs.

The type of walk, breadth-first or depth-first, is determined by the value of type; bfs indicates breadth-first, dfs indicates depth-first. Depthfirst is the default.

The order of the walk, pre-order, post-order or both-order is determined by the value of order; pre indicates pre-order, post indicates post-order, both indicates both-order. Pre-order is the default. Pre-order walking means that a node is visited before any of its neighbors (as defined by the direction, see below). Post-order walking means that a parent is visited after any of its neighbors. Both-order walking means that a node is visited before and after any of its neighbors. The combination of a bread-first walk with post- or both-order is illegal.

The direction of the walk is determined by the value of dir; backward indicates the direction opposite to the incoming arcs, forward indicates the direction of the outgoing arcs.

As the walk progresses, the command cmd will be evaluated at each node, with the mode of the call (enter or leave) and values graphName and the name of the current node appended. For a pre-order walk all nodes are Bentered, for a post-order all nodes are left. In a both-order walk the first visit of a node enters it, the second visit leaves it.

Keywords

graph

Table of Contents

  • Name
  • Synopsis
  • Description
  • Keywords


tcllib matrix

 Table of Contents

_________________________________________________________________

Name

::struct::matrix - Create and manipulate matrix objects

Synopsis

package require Tcl 8.2

package require struct ?1.1.1?

::struct::matrix matrixName

_________________________________________________________________

Description

The ::struct::matrix command creates a new matrix object with an associated global Tcl command whose name is matrixName. This command may be used to invoke various operations on the matrix. It has the following general form:
matrixName option ?arg arg ...?
Option and the args determine the exact behavior of the command.

A matrix is a rectangular collection of cells, i.e. organized in rows and columns. Each cell contains exactly one value of arbitrary form. The cells in the matrix are addressed by pairs of integer numbers, with the first (left) number in the pair specifying the column and the second (right) number specifying the row the cell is in. These indices are counted from 0 upward. The special nonnumeric index end refers to the last row or column in the matrix, depending on the context. Indices of the form end -number are counted from the end of the row or column, like they are for standard Tcl lists. Trying to access non-existing cells causes an error.

The matrices here are created empty, i.e. they have neither rows nor columns. The user then has to add rows and columns as needed by his application. A specialty of this structure is the ability to export an array-view onto its contents. Such can be used by tkTable, for example, to link the matrix into the display.

The following commands are possible for matrix objects:

matrixName add column ?values?
Extends the matrix by one column and then acts like setcolumn (see below) on this new column if there were values supplied. Without values the new cells will be set to the empty string. The new column is appended immediately behind the last existing column.

matrixName add row ?values?
Extends the matrix by one row and then acts like setrow (see below) on this new row if there were values supplied. Without values the new cells will be set to the empty string. The new row is appended immediately behind the last existing row.

matrixName add columns n
Extends the matrix by n columns. The new cells will be set to the empty string. The new columns are appended immediately behind the last existing column. A value of n equal to or smaller than 0 is not allowed.

matrixName add rows n
Extends the matrix by n rows. The new cells will be set to the empty string. The new rows are appended immediately behind the last existing row. A value of n equal to or smaller than 0 is not allowed.

matrixName cells
Returns the number of cells currently managed by the matrix. This is the product of rows and columns.

matrixName cellsize column row
Returns the length of the string representation of the value currently contained in the addressed cell.

matrixName columns
Returns the number of columns currently managed by the matrix.

matrixName columnwidth column
Returns the length of the longest string representation of all the values currently contained in the cells of the addressed column if these are all spanning only one line. For cell values spanning multiple lines the length of their longest line goes into the computation.

matrixName delete column column
Deletes the specified column from the matrix and shifts all columns with higher indices one index down.

matrixName delete row row
Deletes the specified row from the matrix and shifts all row with higher indices one index down.

matrixName destroy
Destroys the matrix, including its storage space and associated command.

matrixName format 2string report
Formats the matrix using the specified report object and returns the string containing the result of this operation. The report has to support the printmatrix method.

matrixName format 2chan report channel
Formats the matrix using the specified report object and writes the string containing the result of this operation into the channel. The report has to support the printmatrix2channel method.

matrixName get cell column row
Returns the value currently contained in the cell identified by row and column index.

matrixName get column column
Returns a list containing the values from all cells in the column identified by the index. The contents of the cell in row 0 are stored as the first element of this list.

matrixName get rect column_tl row_tl column_br row_br Returns a list of lists of cell values. The values stored in the result come from the sub-matrix whose top-left and bottom-right cells are specified by column_tl, row_tl and column_br, row_br resp. Note that the following equations have to be true: col_umn_tl <= column_br and row_tl <= row_br. The result is organized as follows: The outer list is the list of rows, its elements are lists representing a single row. The row with the smallest index is the first element of the outer list. The elements of the row lists represent the selected cell values. The cell with the smallest index is the first element in each row list.

matrixName get row row
Returns a list containing the values from all cells in the row identified by the index. The contents of the cell in column 0 are stored as the first element of this list.

matrixName insert column column ?values? Extends the matrix by one column and then acts like setcolumn (see below) on this new column if there were values supplied. Without values the new cells will be set to the empty string. The new column is inserted just before the column specified by the given index. This means, if column is less than or equal to zero, then the new column is inserted at the beginning of the matrix, before the first column. If column has the value end, or if it is greater than or equal to the number of columns in the matrix, then the new column is appended to the matrix, behind the last column. The old column at the chosen index and all columns with higher indices are shifted one index upward.

matrixName insert row row ?values?
Extends the matrix by one row and then acts like setrow (see below) on this new row if there were values supplied. Without values the new cells will be set to the empty string. The new row is inserted just before the row specified by the given index. This means, if row is less than or equal to zero, then the new row is inserted at the beginning of the matrix, before the first row. If row has the value end, or if it is greater than or equal to the number of rows in the matrix, then the new row is appended to the matrix, behind the last row. The old row at that index and all rows with higher indices are shifted one index upward.

matrixName link ?-transpose? arrayvar
Links the matrix to the specified array variable. This means that the contents of all cells in the matrix is stored in the array too, with all changes to the matrix propagated there too. The contents of the cell (column,row) is stored in the array using the key column,row. If the option -transpose is specified the key row,column will be used instead. It is possible to link the matrix to more than one array. Note that the link is bidirectional, i.e. changes to the array are mirrored in the matrix too.

matrixName rowheight row
Returns the height of the specified row in lines. This is the highest number of lines spanned by a cell over all cells in the row.

matrixName rows
Returns the number of rows currently managed by the matrix.

matrixName set cell column row value
Sets the value in the cell identified by row and column index to the data in the third argument.

matrixName set column column values
Sets the values in the cells identified by the column index to the elements of the list provided as the third argument. Each element of the list is assigned to one cell, with the first element going into the cell in row 0 and then upward. If there are less values in the list than there are rows the remaining rows are set to the empty string. If there are more values in the list than there are rows the superfluous elements are ignored. The matrix is not extended by this operation.

matrixName set rect column row values
Takes a list of lists of cell values and writes them into the submatrix whose top-left cell is specified by the two indices. If the sublists of the outerlist are not of equal length the shorter sublists will be filled with empty strings to the length of the longest sublist. If the submatrix specified by the top-left cell and the number of rows and columns in the values extends beyond the matrix we are modifying the over-extending parts of the values are ignored, i.e. essentially cut off. This subcommand expects its input in the format as returned by getrect.

matrixName set row row values
Sets the values in the cells identified by the row index to the elements of the list provided as the third argument. Each element of the list is assigned to one cell, with the first element going into the cell in column 0 and then upward. If there are less values in the list than there are columns the remaining columns are set to the empty string. If there are more values in the list than there are columns the superfluous elements are ignored. The matrix is not extended by this operation.

matrixName swap columns column_a column_b Swaps the contents of the two specified columns.

matrixName swap rows row_a row_b
Swaps the contents of the two specified rows.

matrixName unlink arrayvar
Removes the link between the matrix and the specified arrayvariable, if there is one.

Examples

The examples below assume a 5x5 matrix M with the first row containing the values 1 to 5, with 1 in the top-left cell. Each other row contains the contents of the row above it, rotated by one cell to the right.

So

M getrect 0 0 4 4

returns

{{1 2 3 4 5} {5 1 2 3 4} {4 5 1 2 3} {3 4 5 1 2} {2 3 4 5 1}}

And

M setrect 1 1 {{0 0 0} {0 0 0} {0 0 0}}

M getrect 0 0 4 4

returns

{{1 2 3 4 5} {5 0 0 0 4} {4 0 0 0 3} {3 0 0 0 2} {2 3 4 5 1}}

Keywords

matrix

Table of Contents

  • Name
  • Synopsis
  • Description
  • Examples
  • Keywords


tcllib queue

 Table of Contents

_________________________________________________________________

Name

::struct::queue - Create and manipulate queue objects

Synopsis

package require Tcl 8.2

package require struct ?1.1.1?

::struct::queue queueName

_________________________________________________________________

Description

The ::struct::queue command creates a new queue object with an associated global Tcl command whose name is queue_N ame. This command may be used to invoke various operations on the queue. It has the following general form: queueName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for queue objects:

queueName clear
Remove all items from the queue.

queueName destroy
Destroy the queue, including its storage space and associated command.

queueName get ?count?
Return the front count items of the queue and remove them from the queue. If count is not specified, it defaults to 1. If count is 1, the result is a simple string; otherwise, it is a list. If specified, count must be greater than or equal to 1. If there are no items in the queue, this command will return count empty strings.

queueName peek ?count?
Return the front count items of the queue, without removing them from the queue. If count is not specified, it defaults to 1. If count is 1, the result is a simple string; otherwise, it is a list. If specified, count must be greater than or equal to 1. If there are no items in the queue, this command will return count empty strings.

queueName put item ?item ...?
Put the item or items specified into the queue. If more than one item is given, they will be added in the order they are listed.

queueName size
Return the number of items in the queue.

Keywords

stack, queue

Table of Contents

  • Name
  • Synopsis
  • Description
  • Keywords


tcllib stack

 Table of Contents

_________________________________________________________________

Name

::struct::stack - Create and manipulate stack objects

Synopsis

package require Tcl 8.2

package require struct ?1.1.1?

::struct::stack stackName

_________________________________________________________________

Description

The ::struct::stack command creates a new stack object with an associated global Tcl command whose name is stack_N ame. This command may be used to invoke various operations on the stack. It has the following general form: stackName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for stack objects:

stackName clear
Remove all items from the stack.

stackName destroy
Destroy the stack, including its storage space and associated command.

stackName peek ?count?
Return the top count items of the stack, without removing them from the stack. If count is not specified, it defaults to 1. If count is 1, the result is a simple string; otherwise, it is a list. If specified, count must be greater than or equal to 1. If there are no items on the stack, this command will return count empty strings.

stackName pop ?count?
Return the top count items of the stack and remove them from the stack. If count is not specified, it defaults to 1. If count is 1, the result is a simple string; otherwise, it is a list. If specified, count must be greater than or equal to 1. If there are no items on the stack, this command will return count empty strings.

stackName push item ?item ...?
Push the item or items specified onto the stack. If more than one item is given, they will be pushed in the order they are listed.

stackName size
Return the number of items on the stack.

Keywords

stack, queue

Table of Contents

  • Name
  • Synopsis
  • Description
  • Keywords


tcllib tree

 Table of Contents

_________________________________________________________________

Name

::struct::tree - Create and manipulate tree objects

Synopsis

package require Tcl 8.2

package require struct ?1.1.1?

::struct::tree treeName

_________________________________________________________________

Description

The ::struct::tree command creates a new tree object with an associated global Tcl command whose name is treeName. This command may be used to invoke various operations on the tree. It has the following general form: treeName option ?arg arg ...?
Option and the args determine the exact behavior of the command.

A tree is a collection of elements, called nodes, one of which is distinguished as a root, along with a relation ("parenthood") that places a hierarchical structure on the nodes. (Data Structures and Algorithms; Aho, Hopcroft and Ullman; Addison-Wesley, 1987). In addition to maintaining the node relationships, this tree implementation allows any number of keyed values to be associated with each node.

The following commands are possible for tree objects:

treeName children node
Return a list of the children of node.

treeName cut node
Removes the node specified by node from the tree, but not its children. The children of node are made children of the parent of the node, at the index at which node was located.

treeName delete node ?node ...?
Remove the specified nodes from the tree. All of the nodes' children will be removed as well to prevent orphaned nodes.

treeName depth node
Return the number of steps from node node to the root node.

treeName destroy
Destroy the tree, including its storage space and associated command.

treeName exists node
Remove true if the specified node exists in the tree.

treeName get node ?-key key?
Return the value associated with the key key for the node node. If no key is specified, the key data is assumed.

treeName index node
Returns the index of node in its parent's list of children. For example, if a node has nodeFoo, nodeBar, and nodeBaz as children, in that order, the index of nodeBar is 1.

treeName insert parent index ?child ?child ...?? Insert one or more nodes into the tree as children of the node parent. The nodes will be added in the order they are given. If parent is root, it refers to the root of the tree. The new nodes will be added to the parent node's child list at the index given by index. The index can be end in which case the new nodes will be added after the current last child.

If any of the specified children already exist in treeName, those nodes will be moved from their original location to the new location indicated by this command.

If no child is specified, a single node will be added, and a name will be generated for the new node. The generated name is of the form node x, where x is a number. If names are specified they must neither contain whitespace nor colons (:).

The return result from this command is a list of nodes added.

treeName isleaf node
Returns true if node is a leaf of the tree (if node has no children), false otherwise.

treeName move parent index node ?node ...? Make the specified nodes children of parent, inserting them into the parent's child list at the index given by index.

treeName next node
Return the right sibling of node, or the empty string if node was the last child of its parent.

treeName numchildren node
Return the number of immediate children of node.

treeName parent node
Return the parent of node.

treeName previous node
Return the left sibling of node, or the empty string if node was the first child of its parent.

treeName set node ?-key key? ?value?
Set or get one of the keyed values associated with a node. If no key is specified, the key data is assumed. Each node that is added to a tree has the value «» assigned to the key data automatically. A node may have any number of keyed values associated with it. If value is not specified, this command returns the current value assigned to the key; if value is specified, this command assigns that value to the key.

treeName size ?node?
Return a count of the number of descendants of the node node; if no node is specified, root is assumed.

treeName splice parent from ?to? ?child? Insert a node named child into the tree as a child of the node parent. If parent is root, it refers to the root of the tree. The new node will be added to the parent node's child list at the index given by from. The children of parent which are in the range of the indices from and to are made children of child. If the value of to is not specified it defaults to end. If no name is given for child, a name will be generated for the new node. The generated name is of the form node x, where x is a number. The return result from this command is the name of the new node.

treeName swap node1 node2
Swap the position of node1 and node2 in the tree.

treeName unset node ?-key key?
Remove a keyed value from the node node. If no key is specified, the key data is assumed.

treeName walk node ?-order order? ?-type type? -command cmd

Perform a breadth-first or depth-first walk of the tree starting at the node node. The type of walk, breadth-first or depth-first, is determined by the value of type; bfs indicates breadth-first, dfs indicates depth-first. Depth-first is the default. The order of the walk, pre-, post-, both- or inorder is determined by the value of order; pre indicates pre-order, post indicates post-order, both indicates both-order and in indicates inorder. Pre-order is the default.

Pre-order walking means that a parent node is visited before any of its children. For example, a breadth-first search starting from the root will visit the root, followed by all of the root's children, followed by all of the root's grandchildren. Post-order walking means that a parent node is visited after any of its children. Both-order walking means that a parent node is visited before and after any of its children. In-order walking means that a parent node is visited after its first child and before the second. This is a generalization of in-order walking for binary trees and will do the right thing if a binary is walked. The combination of a breadth-first walk with in-order is illegal.

As the walk progresses, the command cmd will be evaluated at each node. Percent substitution will be performed on cmd before evaluation, just as in a bind script. The following substitutions are recognized:

%%
Insert the literal % character.
%t
Name of the tree object.
%n
Name of the current node.
%a
Name of the action occurring; one of enter, leave, or visit. enter actions occur during pre-order walks; leave actions occur during post-order walks; visit actions occur during in-order walks. In a both-order walk, the command will be evaluated twice for each node; the action is enter for the first evaluation, and leave for the second.

Keywords

tree

Table of Contents

  • Name
  • Synopsis
  • Description
  • Keywords


tcllib textutil

 Table of Contents

_________________________________________________________________

Name

::textutil - Procedures to manipulate texts and strings..

Synopsis

_________________________________________________________________ package require Tcl 8.2

package require textutil ?0.3?

textutil::adjust string args
0]+}
textutil::splitx string {regexp [

textutil::tabify string {num 8}

textutil::tabify2 string {num 8}

textutil::trim string {regexp [ ]+}

textutil::trimleft string {regexp [ ]+}

textutil::trimright string {regexp [ ]+}

textutil::untabify string {num 8}

textutil::untabify2 string {num 8}

textutil::strRepeat string num
_________________________________________________________________

Description

The ::textutil package provides commands that manipulate strings or texts (a.k.a. long strings or string with embedded newlines or paragraphs).

The complete set of procedures is described below.

textutil::adjust string args
Do a justification on the string according to args. The string is taken as one big paragraph, ignoring any newlines. Then the line is formatted according to the options used, and the command return a new string with enough lines to contain all the printable chars in the input string. A line is a set of chars between the beginning of the string and a newline, or between 2 newlines, or between a newline and the end of the string. If the input string is small enough, the returned string won't contain any newlines.

By default, any occurrence of spaces characters or tabulation are
replaced by a single space so each word in a line is separated from the next one by exactly one space char, and this forms a real line. Each real line is placed in a logical line, which have exactly a given length (see -length option below). The real line may have a lesser length. Again by default, any trailing spaces are ignored before returning the string (see -full option below). The following options may be used after the string parameter, and change the way the command place a real line in a logical line.

-full boolean
if set to false, any trailing space chars are deleted before returning the string. If set to true, any trailing space chars are left in the string. Default to false.
-justify (center|left|plain|right)
set the justification of the returned string to center, left, plain or right. By default, it is set to left. The justification means that any line in the returned string but the last one is build according to the value. If the justification is set to plain and the number of printable chars in the last line is less than 90% of the length of a line (see -length), then this line is justified with the left value, avoiding the expansion of this line when it is too small. The meaning of each value is:

centerthe real line is centered in the logical line. If needed, a set of space char are added at the beginning (half of the needed set) and at the end (half of the needed set) of the line if required (see -full option).

left
the real line is set on the left of the logical line. It means that there are no space chars at the beginning of this line. If required, all needed space chars are added at the end of the line (see -full option).

plain the real line is exactly set in the logical line. It means that there are no leading or trailing space chars. All the needed space chars are added in the real line, between 2 (or more) words.

right the real line is set on the right of the logical line. It means that there are no space chars at the end of this line, and there may be some space chars at the beginning, despite of the -full option.

-length integer
set the length of the logical line in the string to integer. integer must be a positive integer value. Default to 72.
0]+}
textutil::splitx string {regexp [ Split the string and return a list. The string is split according to the regular expression regexp instead of a simple list of chars. Note that if you add parenthesis into the regexp, the parentheses part of separator would be added into list as additional element.

textutil::tabify string {num 8}
Tabify the string by replacing any substring of num space chars by a tabulation and return the result as a new string.

textutil::tabify2 string {num 8}
Similar to textutil::tabify this command tabifies the string and returns the result as a new string. A different algorithm is used however. Instead of replacing any substring of num spaces this comand works more like an editor.

Each line of the text in string is treated as if there are tabstops every num columns. Only sequences of space characters containing more than one space character and found immediately before a tabstop are replaced with tabs.

textutil::trim string {regexp [
]+} Remove in string any leading and trailing substring according to the regular expression regexp and return the result as a new string. This apply on any line in the string, that is any substring between 2 newline chars, or between the beginning of the string and a newline, or between a newline and the end of the string, or, if the string contain no newline, between the beginning and the end of the string.
textutil::trimleft string {regexp [
]+} Remove in string any leading substring according to the regular expression regexp and return the result as a new string. This apply on any line in the string, that is any substring between 2 newline chars, or between the beginning of the string and a newline, or between a newline and the end of the string, or, if the string contain no newline, between the beginning and the end of the string.
textutil::trimright string {regexp [
]+} Remove in string any trailing substring according to the regular expression regexp and return the result as a new string. This apply on any line in the string, that is any substring between 2 newline chars, or between the beginning of the string and a newline, or between a newline and the end of the string, or, if the string contain no newline, between the beginning and the end of the string.

textutil::untabify string {num 8}
Untabify the string by replacing any tabulation char by a substring of num space chars and return the result as a new string.

textutil::untabify2 string {num 8}

Untabify the string by replacing any tabulation char by a substring of at most num space chars and return the result as a new string. Unlike textutil::untabify each tab is not replaced by a fixed number of space characters. The command overlays each line in the string with tabstops every num columns instead and replaces tabs with just enough space characters to reach the next tabstop. This is the complement of the actions taken by textutil::tabify2.

There is one asymmetry though: A tab can be replaced with a single space, but not the other way around.

textutil::strRepeat text num
The implementation depends on the core executing the package. Used string repeat if it is present, or a fast tcl implementation if it is not. Returns a string containing the text repeated num times. The repetitions are joined without characters between them. A value of num <= 0 causes the command to return an empty string.

See Also

regexp, split, string

Keywords

string, regular expression

Table of Contents

  • Name
  • Synopsis
  • Description
  • See Also
  • Keywords


tcllib uri

 Table of Contents

_________________________________________________________________

Name

uri - URI utilities

Synopsis

package require Tcl 8.2

package require uri ?1.0?

uri::split
url
uri::join
?key value?...
uri::resolve
base url uri::isrelative url
uri::geturl
url ?options...? uri::canonicalize uri _________________________________________________________________

Description

This package contains two parts. First it provides regular expressions for a number of url/uri schemes. Second it provides a number of commands for manipulating urls/uris and fetching data specified by them. For the latter this package analyses the requested url/uri and then dispatches it to the appropriate package (http, ftp, ...) for actual fetching.

Commands

uri::split takes a single url, decodes it and then returns a list of key/value pairs suitable for array set containing the constituents of the url. If the scheme is missing from the url it defaults to http. Currently only the schemes http, ftp, mailto and file are supported. See section EXTENDING on how to expand that range.

uri::join takes a list of key/value pairs (generated by uri::split, for example) and returns the canonical url they represent. Currently only the schemes http, ftp, mailto and file are supported. See section EXTENDING on how to expand that range.

uri::isrelative determines whether the specified url is absolute or relative.

uri::resolve resolves the specified url relative to base. In other words: A non-relative url is returned unchanged, whereas for a relative url the missing parts are taken from base and prepended to it. The result of this operation is returned. For an empty url the result is base.

uri::geturl decodes the specified url and then dispatches the request to the package appropriate for the scheme found in the url. The command assumes that the package to handle the given scheme has the same name as the scheme itself (including possible capitalization). It further assumes that the package provides a geturl-command in the namespace of the same name as the package itself. This command is called with the given url and all given options. Currently geturl does not handle any options itself.

Note: file-urls are an exception to the rule described above. They are handled internally.

It is not possible to specify results of the command. They depend on the geturl-command for the scheme the request was dispatched to.

uri::canonicalize returns the canonical form of a URI. The canonical form of a URI is one where relative path specifications, ie. . and .., have been resolved.

Schemes

In addition to the commands mentioned above this package provides regular expression to recognize urls for a number of url schemes.

For each supported scheme a namespace of the same name as the scheme itself is provided inside of the namespace uri containing the variable url whose contents are a regular expression to recognize urls of that scheme. Additional variables may contain regular expressions for parts of urls for that scheme.

The variable boldt uri::schemes] contains a list of all supported schemes. Currently these are ftp, file, http, gopher, mailto, news, wais and prospero.

Extending

Extending the range of schemes supported by uri::split and uri::join is easy because both commands do not handle the request by themselves but dispatch it to another command in the uri namespace using the scheme of the url as criterion.

uri:split and uri:join call Split[string totitle <scheme>] and Join[string totitle <scheme>] respectively.

See Also

Credits

Original code by Andreas Kupries. Modularisation by Steve Ball.

Keywords

uri, url, fetching information, www, http, ftp, mailto, gopher, wais, prospero, file

Table of Contents

  • Name
  • Synopsis
  • Description
  • Commands
  • Schemes
  • Extending
  • See Also
  • Credits
  • Keywords


tkcon: Documentation

tkcon Documentation (June 2001) SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages

Release Archives (high speed server)

Screenshot

Please read the following pages carefully to fully understand the features AND limitations of TkCon. I'm always open to suggestions for improvement. Send them to my suggestion box.

Getting Started | Special Bindings | tkcon Procedures | Screenshot
dump proc | tkcon proc | idebug proc | observe proc
© Jeffrey Hobbs


tkcon: Getting Started

tkcon: Getting Started SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages
Getting Started | Special Bindings | Procedures | Screenshot
dump | tkcon | idebug | observe

Resource File:

TkCon will search for a resource file in "$env(HOME)/.tkconrc" (Unix), "$env(HOME)/tkcon.cfg" (Windows) or "$env(PREF_FOLDER)/tkcon.cfg" (Macintosh). On DOS machines, "$env(HOME)" usually refers to "C:\". TkCon never sources the "~/.wishrc" file. The resource file is sourced by each new instance of the console. An example resource file is provided below.

Command Line Arguments

Except for -rcfile, command line arguments are handled after the TkCon resource file is sourced, but before the slave interpreter or the TkCon user interface is initialized. -rcfile is handled right before it would be sourced, allowing you to specify any alternate file. Command line arguments are passed to each new console and will be evaluated by each. To prevent this from happening, you have to say tkcon main set argv {}; tkcon main set argc 0.

For these options, any unique substring is allowed.

-argv (also --)
Causes TkCon to stop evaluating arguments and set the remaining args to be argv/argc (with -- prepended). This carries over for any further consoles. This is meant only for wrapping TkCon around programs that require their own arguments.
-color-<color> color
Sets the requested color type to the specified color for tkcon. See the Variables section for the recognized <color> names.
-eval (also -main or -e)
A tcl script to eval in each main interpreter. This is evaluated after the resource file is loaded and the slave interpreter is created. Multiple -eval switches will be recognized (in order).
-exec slavename
Sets the named slave that tkcon operates in. In general, this is only useful to set to "" (empty), indicating to tkcon to avoid the multi-interpreter model and operate in the main environment. When this is empty, any further arguments will be only used in the first tkcon console and not passed onto further new consoles. This is useful when using tkcon as a console for extended wish executables that don't load there commands into slave interpreters.
-font font
Sets the font that tkcon uses for its text windows. If this isn't a fixed width font, tkcon will override it.
-nontcl TCL_BOOLEAN
Sets TKCON(nontcl) to TCL_BOOLEAN. Needed when attaching to non-Tcl interpreters.
-package package_name (also -load)
Packages to automatically load into the slave interpreters (ie - "Tk").
-rcfile filename
Specify an alternate tkcon resource file name.
-root widgetname
Makes the named widget the root name of all consoles (ie - .tkcon).
-slave tcl_script
A tcl script to eval in each slave interpreter. This will append the one specified in the tkcon resource file, if any.
Some examples of tkcon command line startup situations:
megawish tkcon.tcl -exec "" -root .tkcon mainfile.tcl
Use tkcon as a console for your megawish application. You can avoid starting the line with megawish if that is the default wish that tkcon would use. The -root ensures that tkcon will not conflict with the
tkcon.tcl -font "Courier 12" -load Tk
Use the courier font for tkcon and always load Tk in slave interpreters at startup.
tkcon.tcl -rcfile ~/.wishrc -color,bg white
Use the ~/.wishrc file as the resource file, and a white background for tkcon's text widgets.

Variables:

Certain variables in TkCon can be modified to suit your needs. It's easiest to do this in the resource file, but you can do it when time the program is running (and some can be changed via the Prefs menu). All these are part of the master interpreter's ::tkcon namespace. The modifiable array variables are ::tkcon::COLOR and ::tkcon::OPT. You can call 'tkcon set ::tkcon::COLOR' when the program is running to check its state. Here is an explanation of certain variables you might change or use:
::tkcon::COLOR(bg)
The background color for tkcon text widgets. Defaults to the operating system default (determined at startup).
::tkcon::COLOR(blink)
The background color of the electric brace highlighting, if on. Defaults to yellow.
::tkcon::COLOR(cursor)
The background color for the insertion cursor in tkcon. Defaults to black.
::tkcon::COLOR(disabled)
The foreground color for disabled menu items. Defaults to dark grey.
::tkcon::COLOR(proc)
The foreground color of a recognized proc, if command highlighting is on. Defaults to dark green.
::tkcon::COLOR(var)
The background color of a recognized var, if command highlighting is on. Defaults to pink.
::tkcon::COLOR(prompt)
The foreground color of the prompt as output in the console. Defaults to brown.
::tkcon::COLOR(stdin)
The foreground color of the stdin for the console. Defaults to black.
::tkcon::COLOR(stdout)
The foreground color of the stdout as output in the console. Defaults to blue.
::tkcon::COLOR(stderr)
The foreground color of stderr as output in the console. Defaults to red.

::tkcon::OPT(autoload)
Packages to automatically load into the slave interpreter (ie - 'Tk'). This is a list. Defaults to {} (none).
::tkcon::OPT(blinktime)
The amount of time (in millisecs) that braced sections should blink for. Defaults to 500 (.5 secs), must be at least 100.
::tkcon::OPT(blinkrange)
Whether to blink the entire range for electric brace matching or to just blink the actual matching braces (respectively 1 or 0, defaults to 1).
::tkcon::OPT(buffer)
The size of the console scroll buffer (in lines). Defaults to 512.
::tkcon::OPT(calcmode)
Whether to allow expr commands to be run at the command line without prefixing them with expr (just a convenience).
::tkcon::OPT(cols)
Number of columns for the console to start out with. Defaults to 80.
::tkcon::OPT(dead)
What to do with dead connected interpreters. If dead is leave, TkCon automatically exits the dead interpreter. If dead is ignore then it remains attached waiting for the interpreter to reappear. Otherwise TkCon will prompt you.
::tkcon::OPT(exec)
This corresponds to the -exec option above
::tkcon::OPT(font)
Font to use for tkcon text widgets (also specified with -font). Defaults to the system default, or a fixed width equivalent.
::tkcon::OPT(gets)
Controls whether tkcon will overload the gets command to work with tkcon. The valid values are: congets (the default), which will redirect stdin requests to the tkcon window; gets, which will pop up a dialog to get input; and {} (empty string) which tells tkcon not to overload gets. This value must be set at startup to alter tkcon's behavior.
::tkcon::OPT(history)
The size of the history list to keep. Defaults to 48.
::tkcon::OPT(hoterrors)
Whether hot errors are enabled or not. When enabled, errors that are returned to the console are marked with a link to the error info that will pop up in an minimal editor. This requires more memory because each error that occurs will maintain bindings for this feature, as long as the error is in the text widget. Defaults to on.
::tkcon::OPT(library)
The path to any tcl library directories (these are appended to the auto_path when the after the resource file is loaded in).
::tkcon::OPT(lightbrace)
Whether to use the brace highlighting feature or not (respectively 1 or 0, defaults to 1).
::tkcon::OPT(lightcmd)
Whether to use the command highlighting feature or not (respectively 1 or 0, defaults to 1).
::tkcon::OPT(maineval)
A tcl script to execute in the main interpreter after the slave interpreter is created and the user interface is initialized.
::tkcon::OPT(maxmenu)
A number that specifies the maximum number of packages to show vertically in the Interp->Packages menu before breaking into another column. Defaults to 15.
::tkcon::OPT(nontcl)
For those who might be using non-Tcl based Tk attachments, set this to 1. It prevents TkCon from trying to evaluate its own Tcl code in an attached interpreter. Also see my notes for non-Tcl based Tk interpreters.
::tkcon::OPT(prompt1)
Like tcl_prompt1, except it doesn't require you use 'puts'. No equivalent for tcl_prompt2 is available (it's unnecessary IMHO).
Defaults to {([file tail [pwd]]) [history nextid] % }.
::tkcon::OPT(rows)
Number of rows for the console to start out with. Defaults to 20.
::tkcon::OPT(scollypos)
Y scrollbar position. Valid values are left or right. Defaults to left.
::tkcon::OPT(showmenu)
Show the menubar on startup (1 or 0, defaults to 1).
::tkcon::OPT(showmultiple)
Show multiple matches for path/proc/var name expansion (1 or 0, defaults to 1).
::tkcon::OPT(slaveeval)
A tcl script to execute in each slave interpreter right after it's created. This allows the user to have user defined info always available in a slave. Example:
    set TKCON(slaveeval) {
        proc foo args { puts $args }
        lappend auto_path .
    }
::tkcon::OPT(slaveexit)
Allows the prevention of exit in slaves from exitting the entire application. If it is equal to exit, exit will exit as usual, otherwise it will just close down that interpreter (and any children). Defaults to close.
::tkcon::OPT(subhistory)
Allow history substitution to occur (0 or 1, defaults to 1). The history list is maintained in a single interpreter per TkCon console instance. Thus you have history which can range over a series of attached interpreters.

An example TkCon resource file might look like:

######################################################
## My TkCon Resource File

# Use a fixed default font
#tkcon font fixed; # valid on unix
#tkcon font systemfixed; # valid on win
tkcon font Courier 12; # valid everywhere

# Keep 50 commands in history
set ::tkcon::OPT(history) 50

# Use a pink prompt
set ::tkcon::COLOR(prompt) pink
######################################################

© Jeffrey Hobbs


tkcon: Special Bindings

tkcon: Special Bindings SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages
Getting Started | Special Bindings | Procedures | Screenshot
dump | tkcon | idebug | observe

Most of the bindings are the same as for the Text widget. Some have been modified to make sure that the integrity of the console is maintained. Others have been added to enhance the usefulness of the console. Only the modified or new bindings are listed here.

Control-x or Cut (on Sparc5 keyboards)
Cut
Control-c or Copy (on Sparc5 keyboards)
Copy
Control-v or Paste (on Sparc5 keyboards)
Paste
Insert
Insert (duh).

Up
Goes up one level in the commands line history when cursor is on the prompt line, otherwise it moves through the buffer
Down
Goes down one level in the commands line history when cursor is on the last line of the buffer, otherwise it moves through the buffer
Control-p
Goes up one level in the commands line history
Control-n
Goes down one level in the commands line history

Tab
Tries to expand file path names, then variable names, then proc names.
Escape
Tries to expand file path names.
Control-P
Tries to expand procedure names. The procedure names will be those that are actually in the attached interpreter (unless nontcl is specified, in which case it always does the lookup in the default slave interpreter).
Control-V
Tries to expand variable names (those returned by [info vars]). It's search behavior is like that for procedure names.

Return or Enter
Evaluates the current command line if it is a complete command, otherwise it just goes to a new line
Control-a
Go to the beginning of the current command line
Control-l
Clear the entire console buffer
Control-r
Searches backwards in the history for a command starting with the current command line. Repeatable to search farther back.
Control-s
As above, but searches forward (only useful if you searched too far back).
Control-t
Transposes characters
Control-u
Clear the current command line
Control-z
Saves current command line in a buffer that can be retrieved with another Control-z. If the current command line is empty, then any saved command is retrieved without being overwritten, otherwise the current contents get swapped with what's in the saved command buffer.

Control-Key-1
Attaches console to the console's slave interpreter
Control-Key-2
Attaches console to the console's master interpreter
Control-Key-3
Attaches console to main TkCon interpreter
Control-A
Pops up the "About" dialog
Control-N
Creates a new console. Each console has separate state, including it's own widget hierarchy (it's a slave interpreter).
Control-q
Close the current console OR Quit the program (depends on the value of TKCON(slaveexit)).
Control-w
Closes the current console. Closing the main console will exit the program (something has to control all the slaves...)
TkCon also has electric bracing (similar to that in emacs). It will highlight matching pairs of {}'s, []'s, ()'s and ""'s. For the first three, if there is no matching left element for the right, then it blinks the entire current command line. For the double quote, if there is no proper match then it just blinks the current double quote character. It does properly recognize most escaping (except escaped escapes), but does not look for commenting (why would you interactively put comments in?).
© Jeffrey Hobbs


tkcon: Procedures

tkcon: Procedures SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages
Getting Started | Special Bindings | Procedures | Screenshot
dump | tkcon | idebug | observe

There are several new procedures introduced in TkCon to improve productivity and/or account for lost functionality in the Tcl environment that users are used to in native environments. There are also some redefined procedures. Here is a non-comprehensive list:

alias ?sourceCmd targetCmd ?arg arg ...??
Simple alias mechanism. It will overwrite existing commands. When called without args, it returns current aliases. Note that TkCon makes some aliases for you (in slaves). Don't delete those.
clear ?percentage?
Clears the text widget. Same as the <Control-l> binding, except this will accept a percentage of the buffer to clear (1-100, 100 default).
dir ?-all? ?-full? ?-long? ?pattern pattern ...?
Cheap way to get directory listings. Uses glob style pattern matching.
dump type ?-nocomplain? ?-filter pattern? ?--? pattern ?pattern ...?
The dump command provides a way for the user to spit out state information about the interpreter in a Tcl readable (and human readable) form. See further dump docs for details.
echo ?arg arg ...?
Concatenates the args and spits the result to the console (stdout).
edit ?-type type? ?-find str? ?-attach interp? arg NEW in v1.4, still under construction
Opens an editor with the data from arg. The optional type argument can be one of: proc, var or file. For proc or var, the arg may be a pattern.
idebug command ?args?
Interactive debugging command. See further idebug docs for details.
lremove ?-all? ?-regexp -glob? list items
Removes one or more items from a list and returns the new list. If -all is specified, it removes all instances of each item in the list. If -regexp or -glob is specified, it interprets each item in the items list as a regexp or glob pattern to match against.
less
Aliased to edit.
ls
Aliased to dir -full.
more
Aliased to edit.
observe type ?args?
This command provides passive runtime debugging output for variables and commands. See further observe docs for details.
puts (same options as always)
Redefined to put the output into TkCon
tkcon method ?args?
Multi-purpose command. See further tkcon docs for details.
tclindex ?-extensions patternlist? ?-index TCL_BOOLEAN? ?-package TCL_BOOLEAN? ?dir1 dir2 ...?
Convenience proc to update the tclIndex (controlled by -index switch) and/or pkgIndex.tcl (controlled by -package switch) file in the named directories based on the given pattern for files. It defaults to creating the tclIndex but not the pkgIndex.tcl file, with the directory defaulting to [pwd]. The extension defaults to *.tcl, with *.[info sharelibextension] added when -package is true.
unalias cmd
unaliases command
what string
The what command will identify the word given in string in the Tcl environment and return a list of types that it was recognized as. Possible types are: alias, procedure, command, variable, directory, file, widget, and executable. Used by procedures dump and which.
which command
Like the 'which' command of Unix shells, this will tell you if a particular command is known, and if so, whether it is internal or external to the interpreter. If it is an internal command and there is a slot in auto_index for it, it tells you the file that auto_index would load. This does not necessarily mean that that is where the file came from, but if it were not in the interpreter previously, then that is where the command was found.
There are several procedures that I use as helpers that some may find helpful in there coding (ie - expanding pathnames). Feel free to lift them from the code (but do assign proper attribution).
© Jeffrey Hobbs


tkcon: dump procedure

tkcon: dump procedure SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages
Getting Started | Special Bindings | Procedures | Screenshot
dump | tkcon | idebug | observe

The dump command provides a way for the user to spit out state information about the interpreter in a Tcl readable (and human readable) form. It takes the general form:

dump method ?-nocomplain? ?-filter pattern? ?--? pattern ?pattern ...?
The patterns represent glob-style patterns (as in string match pattern $str). -nocomplain will prevent dump from throwing an error if no items matched the pattern. -filter is interpreted as appropriate for the method. The various methods are:
dump command args
Outputs one or more commands.
dump procedure args
Outputs one or more procs in sourceable form.
dump variable args
Outputs the values of variables in sourceable form. Recognizes nested arrays. The -filter pattern is used as to filter array element names and is interepreted as a glob pattern (defaults to {*}). It is passed down for nested arrays.
dump widget args
Outputs one or more widgets by giving their configuration options. The -filter pattern is used as to filter the config options and is interpreted as a case insensitive regexp pattern (defaults to {.*})
© Jeffrey Hobbs


tkcon: tkcon procedure

tkcon: tkcon procedure SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages
Getting Started | Special Bindings | Procedures | Screenshot
dump | tkcon | idebug | observe

This provides lots of useful control over a console:

tkcon attach interpreter
Attaches tkcon to the named interpreter. The name must be that returned by [tk appname] or a valid path to a slave interpreter. It's best to use this via the Console->Attach Console menu.
tkcon buffer ?size?
Sets or queries the allowed size of the console text widget in lines. The text widget will automatically delete leading lines once this number has been exceeded (read: this is the scroll buffer size).
tkcon bgerror ?msg errorInfo?
Does bgerror stuff in the tkcon master interpreter.
tkcon close or tkcon destroy
Destroys this tkcon widget.
tkcon congets
Behaves like the traditional Tcl gets, but instead of using stdin, it uses the tkcon console window. By default, tkcon replaces the standard gets with this command. This behavior can be controlled by altering the ::tkcon::OPT(gets) parameter at startup. This should not be called directly - instead rely on the overloaded gets, which has support for the optional varName parameter.
tkcon console args
Passes the args to the tkcon text widget (the console).
tkcon error
Pops up a dialog that gives the user a full trace of the last error received in the tkcon console.
tkcon find string ?-case TCL_BOOLEAN -regexp TCL_BOOLEAN?
Highlights all instances of string in the console. If the string is empty, it clears any previous highlighting.
tkcon font ?fontname?
Sets or returns the font used by tkcon text widgets.
tkcon gets
Behaves like the traditional Tcl gets, but instead of needing stdin, it pops a dialog box up for the user. The overloaded gets has support for the optional varName parameter.
tkcon getcommand
A variation of the congets method that requires a full command to be input before returning.
tkcon hide
Withdraw the tkcon display from the screen (make sure you have a way to get it back).
tkcon history ?-newline?
Displays the tkcon history in sourceable form. If -newline is specified, it separates each command by an extra newline.
tkcon iconify
Iconifies the tkcon display.
tkcon load filename
Sources named file into the slave interpreter. If no filename is given, it will attempt to call tk_getOpenFile to pop up the file select box.
tkcon main ?arg arg ...?
Passes the args to the main tkcon interpreter to be evaluated and returns the result.
tkcon master args
Passes the args to the master interpreter to be evaluated and returns the result.
tkcon new
Creates a new tkcon widget.
tkcon save ?filename ?type??
Saves the console buffer to the given filename. If no filename is given, it will attempt to call tk_getSaveFile to pop up the file select box. If no type is given, a dialog will ask you to specify what portion of the text you want to save.
tkcon set var ?value?
Queries or sets a master interpreter variable.
tkcon append var ?value?
Like set, but uses append on the variable.
tkcon lappend var ?value?
Like set, but uses lappend on the variable.
tkcon show or tkcon deiconify
Redisplays tkcon on the screen.
tkcon slave ?slavename ?arg arg ...??
If called with no args, it returns the name of all the tkcon interpreters. Otherwise given an interp name it passes the args to the named interpreter to be evaluated and returns the result. If no args are passed, then it returns the [tk appname] of that interpreter.
tkcon title ?title?
Sets or returns the title for tkcon.
tkcon version
Returns of version of tkcon.
© Jeffrey Hobbs


tkcon: idebug procedure

tkcon: idebug procedure SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages
Getting Started | Special Bindings | Procedures | Screenshot
dump | tkcon | idebug | observe

The idebug command provides an interactive debugging environment for procedures via TkCon. You can place idebug break commands into your procedure to create breakpoints. It will pop up the TkCon console and put you into a "debugging" mode. The body, show & trace methods are intended for internal use only.

This procedure is experimental (to say the least). Comments are encouraged.

idebug body ?level?
Prints out the body of the command (if it is a procedure) at the specified level. level defaults to the current level.
idebug break ?id?
Creates a breakpoint within a procedure. This will only trigger if idebug is on and the id matches the pattern. If so, TkCon will pop to the front with the prompt changed to an idebug prompt. You are given the basic ability to observe the call stack an query/set variables or execute Tcl commands at any level. A separate history is maintained in debugging mode.
idebug {echo ?id?} ?args?
Behaves just like echo, but only triggers when idebug is on. You can specify an optional id to further restrict triggering. If no id is specified, it defaults to the name of the command in which the call was made.
idebug id ?id?
Query or set the idebug id. This id is used by other idebug methods to determine if they should trigger or not. The idebug id can be a glob pattern and defaults to *.
idebug off
Turns idebug off.
idebug on ?id?
Turns idebug on. If id is specified, it sets the id to it.
idebug {puts ?id?} args
Behaves just like puts, but only triggers when idebug is on. You can specify an optional id to further restrict triggering. If no id is specified, it defaults to the name of the command in which the call was made.
idebug show type ?level? ?VERBOSE?
type must be one of vars, locals or globals. This method will output the variables/locals/globals present in a particular level. If VERBOSE is added, then it actually 'dump's out the values as well. level defaults to the level in which this method was called.
idebug trace ?level?
Prints out the stack trace from the specified level up to the top level. level defaults to the current level.
© Jeffrey Hobbs


tkcon: observe procedure

tkcon: observe procedure SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages
Getting Started | Special Bindings | Procedures | Screenshot
dump | tkcon | idebug | observe

This command provides runtime debugging output for variables and commands without the need to edit your code. For variables, the underlying mechanism uses trace and dump var. For commands, it renames the observed procedure and uses a special wrapper procedure. WARNING: using this procedure after checkpointing state will result in major problems if you clean state because the renamed (true) commands will be lost.

This procedure is experimental. Comments are encouraged.

observe command cmdname ?maxlevel?
This will create a wrapper command which prints out (using dump) the call stack to the console. maxlevel represents the maximum number of levels of the call stack which will be printed (defaults to 4).
observe cdelete cmdname
Removes the wrapper around an observed command.
observe cinfo cmdname
Prints out useless info.
observe variable varname operation ?args?
Currently a wrapper around trace that uses dump to print out the value of the named variable whenever the specified operation on that variable occurs (must be read, write or unset).
observe vdelete varname operation
Deletes the trace wrapper around the named variable.
observe vinfo varname
Prints out trace info about the named variable.
© Jeffrey Hobbs


expect Manual

expect

expect expectk

expect Library

expect C library API

expect

[ expect ]
Copyright © 2001 ActiveState


TclX Manual

TclX

TclX Library

Writing C language extensions to Tcl.
Writing C language extensions to Tcl (Tcl_Obj-based commands).

Handles

Tcl_HandleAlloc, Tcl_HandleFree, Tcl_HandleTblInit, Tcl_HandleTblRelease, Tcl_HandleTblUseCount , Tcl_HandleWalk, Tcl_HandleXlate

Keyed Lists

TclX_NewKeyedListObj, TclX_KeyedListGet, TclX_KeyedListSet, TclX_KeyedListDelete, TclX_KeyedListGetKeys

Memory validation

ckalloc, ckfree, memory, Tcl_DisplayMemory, Tcl_InitMemory, Tcl_ValidateAllMemory

Initialization

Tclx_Init, Tclxcmd_Init, TclX_Main, Tkx_Init, TkX_Main Extended

TclX commands

TclX commands

tclX

[ TclX ]
Copyright © 2001 ActiveState


TclX TclX

 Table of Contents

Name

TclX - Extended Tcl: Extended command set for Tcl

Synopsis

package require Tclx

Introduction

This man page contains the documentation for all of the extensions that are added to Tcl 8.0 by Extended Tcl (TclX 8.0.0). TclX extends Tcl's capabilities by adding new commands to it, without changing the syntax of standard Tcl. Extended Tcl is a superset of standard Tcl and is built alongside the standard Tcl sources.

Extended Tcl was created by Karl Lehenbauer (karl@neosoft.com) and Mark Diekhans (markd@grizzly.com) and is freely redistributable for any use without license or fee.

Available over the Internet since 1989, Extended Tcl, also known as TclX, not only adds capabilities to Tcl, but has also been the source of many of the capabilities of the baseline Tcl release, including arrays, files, sockets, file events, and date and time handling, among others.

Extended Tcl has three basic functional areas: A set of new commands, a Tcl shell (i.e. a Unix shell-style command line and interactive environment), and a user-extensible library of useful Tcl procedures, any of which can be automatically loaded on the first attempt to execute it.

The command descriptions are separated into several sections:

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

General Commands

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

dirs This procedure lists the directories in the directory stack.

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

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

The following options are available:

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

In interactive mode, the results of set commands with two arguments are not printed. error, it can be used to delete the current command being type without aborting the program in progress.

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

infox option

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

version
Return the version number of Extended Tcl. The version number for Extended Tcl is generated by combining the base version of the standard Tcl code with another number indicating the version of Extended Tcl being used.

patchlevel
Return the patchlevel for Extended Tcl.

have_fchown
Return 1 if the fchown system call is available. This supports the -fileid option on the chown and chgrp commands.

have_fchmod
Return 1 if the fchmod system call is available. This supports the -fileid option on the chmod command.

have_flock
Return 1 if the flock command defined, 0 if it is not available.

have_fsync
Return 1 if the fsync system call is available and the sync command will sync individual files. 0 if it is not available and the sync command will always sync all file buffers.

have_ftruncate
Return 1 if the ftruncate or chsize system call is available. If it is, the ftruncate command -fileid option maybe used.

have_msgcats
Return 1 if XPG message catalogs are available, 0 if they are not. The catgets is designed to continue to function without message catalogs, always returning the default string.

have_posix_signals
Return 1 if Posix signals are available (block and unblock options available for the signal command). 0 is returned if Posix signals are not available.

have_signal_restart
Return 1 if restartable signals are available (-restart option available for the signal command). 0 is returned if restartable signals are not available.

have_truncate
Return 1 if the truncate system call is available. If it is, the ftruncate command may truncate by file path.

have_waitpid
Return 1 if the waitpid system call is available and the wait command has full functionality. 0 if the wait command has limited functionality.

appname
Return the symbolic application name of the current application linked with the Extended be set by the application to return an application specific value for this variable.

applongname
Return a natural language name for the current application. The C variable tclLongAppName must be set by the application to return an application specific value for this variable.

appversion
Return the version number for the current application. The C variable tclAppVersion must be set by the application to return an application-specific value for this variable.

apppatchlevel
Return the patchlevel for the current application. The C variable tclAppPatchlevel must be set by the application to return an application-specific value for this variable.

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

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

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

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

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

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

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

popd This procedure pops the top directory entry from the directory stack and make it the current directory.

pushd ?dir?
This procedure pushs the current directory onto the directory stack and cd to the specified directory. If the directory is not specified, then the current directory is pushed, but remains unchanged.

recursive_glob dirlist globlist
This procedure returns a list of recursively matches files. All directories in dirlist are recursively searched (breadth-first), comparing each file found against the file glob patterns in globlist. Symbolic links are not followed.

showproc ?procname ...?
This procedure lists the definition of the named procedures. Loading them if it is not already loaded. If no procedure names are supplied, the definitions of all currently loaded procedures are returned.

try_eval code catch ?finally?

The try_eval command evaluates code in the current context.

If an error occurs during the evaluation and catch is not empty, then catch is evaluated to handler the error. The result of the command, containing the error message, will be stored in a global variable errorResult. The global variables errorResult, errorInfo and errorCode will be imported into the current scope, there is no need to execute a global command. The result of the catch command becomes the result of the try_eval command. If the error that caused the catch to be evaluate is to be continued, the following command should be used:
error $errorResult $errorCode $errorInfo

If the finally argument is supplied and not empty, it is evaluated after the evaluation of the code and the catch commands. If an error occurs during the evaluation of the finally command, it becomes the result of the try_eval command. Otherwise, the result of either code or catch is preserved, as described above.

Debugging and Development Commands

This section contains information on commands and procedures that are useful for developing and debugging Tcl scripts.

cmdtrace level | on ?noeval? ?notruncate? ?procs? ?fileid? ?com- mand cmd?

Print a trace statement for all commands executed at depth of level or below (1 is the top level). If on is specified, all commands at any level are traced. The following options are available:

noeval Causes arguments to be printed unevaluated. If noeval is specified, the arguments are printed before evaluation. Otherwise, they are printed afterwards.

If the command line is longer than 60 characters, it is truncated to 60 and a «...» is postpended to indicate that there was more output than was displayed. If an evaluated argument contains a space, the entire argument will be enclosed inside of braces (`{}') to allow the reader to visually separate the arguments from each other.

notruncate
Disables the truncation of commands and evaluated arguments.

procs Enables the tracing of procedure calls only. Commands that aren't procedure calls (i.e. calls to commands that are written in C, C++ or some object-compatible language) are not traced if the procs option is specified. This option is particularly useful for greatly reducing the output of cmdtrace while debugging.

fileid This is a file id as returned by the open command. If specified, then the trace output will be written to the file rather than stdout. A stdio buffer flush is done after every line is written so that the trace may be monitored externally or provide useful information for debugging problems that cause core dumps.

command cmd

Call the specified command cmd on when each command is executed instead of tracing to a file. See the description of the functionally below. This option may not be specified with a fileid.

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

cmdtrace on [open cmd.log w]

The command option causes a user specified trace command to be called for each command executed. The command will have the following arguments appended to it before evaluation:

command
A string containing the text of the command, before any argument substitution.

argv A list of the final argument information that will be passed to the command after command, variable, and backslash substitution.

evalLevel
The Tcl_Eval call level.

procLevel
The procedure call level.

The command should be constructed in such a manner that it will work if additional arguments are added in the future. It is suggested that the command be a proc with the final argument being args.

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

If an error occurs during the execution of command, an error message is dumped to stderr and the tracing is disabled. The underlying mechanism that this functionality is built on does not support returning an error to the interpreter.

cmdtrace off
Turn off all tracing.

cmdtrace depth
Returns the current maximum trace level, or zero if trace is disabled.

edprocs ?proc...?
This procedure writes the named procedures, or all currently defined procedures, to a temporary file, then calls an editor on it (as specified by the EDITOR environment variable, or vi if none is specified), then sources the file back in if it was changed.

profile ?-commands? ?-eval? on

profile off arrayVar
This command is used to collect a performance profile of a Tcl script. It collects data at the Tcl procedure level. The number of calls to a procedure, and the amount of real and CPU time is collected. Time is also collected for the global context. The procedure data is collected by bucketing it based on the procedure call stack, this allows determination of how much time is spent in a particular procedure in each of it's calling contexts.

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

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

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

A Tcl procedure profrep is supplied for reducing the data and producing a report.

On Windows 95/NT, profile command only reports elasped real time, CPU time is not available and is reported as zero.

profrep profDataVar sortKey ?outFile? ?userTitle? This procedure generates a report from data collect from the profile command. ProfDataVar is the name of the array containing the data returned by the profile command. SortKey indicates which data value to sort by. It should be one of «calls", «cpu» or «real". OutFile is the name of file to write the report to. If omitted, stdout is assumed. UserTitle is an optional title line to add to output.

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

saveprocs fileName ?proc...?
This procedure saves the definition of the named procedure, or all currently defined procedures if none is specified, to the named file.

UNIX Access Commands

These commands provide access to many basic Unix facilities, including process handling, date and time processing, signal handling and the executing commands via the shell.

alarm seconds
Instructs the system to send a SIGALRM signal in the specified number of seconds. This is a floating point number, so fractions of a section may be specified. If seconds is 0.0, any previous alarm request is canceled. Only one alarm at a time may be active; the command returns the number of seconds left in the previous alarm. On systems without the setitimer system call, seconds is rounded up to an integer number of seconds.

The alarm command is not available on Windows 95/NT.

execl ?-argv0 argv0? prog ?arglist?
Do an execl, replacing the current program (either Extended Tcl or an application with Extended Tcl embedded into it) with prog and passing the arguments in the list arglist.

The -argv0 options specifies that argv0 is to be passed to the program as argv [0] rather than prog.

Note: If you are using execl in a Tk application and it fails, you may not do anything that accesses the X server or you will receive a BadWindow error from the X server. This includes executing the Tk version of the exit command. We suggest using the following command to abort Tk applications after an execl failure:

kill [id process]

On Windows 95/NT, where the fork command is not available, execl starts a new process and returns the process id.

chroot dirname
Change root directory to dirname, by invoking the POSIX chroot(2) system call. This command only succeeds if running as root.

fork Fork the current Tcl process. Fork returns zero to the child process and the process number of the child to the parent process. If the fork fails, a Tcl error is generated.

If an execl is not going to be performed before the child process does output, or if a close and dup sequence is going to be performed on stdout or stderr, then a flush should be issued against stdout, stderr and any other open output file before doing the fork. Otherwise characters from the parent process pending in the buffers will be output by both the parent and child processes.

Note: If you are forking in a Tk based apllication you must execl before doing any window operations in the child or you will receive a BadWindow error from the X server.

The fork command is not available on Windows 95/NT.

id options

This command provides a means of getting, setting and converting user, group and process ids. The id command has the following options:

id user ?name?

id userid ?uid?
Set the real and effective user ID to name or uid, if the name (or uid) is valid and permissions allow it. If the name (or uid) is not specified, the current name (or uid) is returned.

id convert userid uid

id convert user name
Convert a user ID number to a user name, or vice versa.

id group ?name?

id groupid ?gid?
Set the real and effective group ID to name or gid, if the name (or gid) is valid and permissions allow it. If the group name (or gid) is not specified, the current group name (or gid) is returned.

id groups

id groupids
Return the current group access list of the process. The option groups returns group names and groupids returns id numbers.

id convert groupid gid id convert group name
Convert a group ID number to a group name, or vice versa.

id effective user

id effective userid
Return the effective user name, or effective user ID number, respectively.

id effective group

id effective groupid
Return the effective group name, or effective group ID number, respectively.

id effective groupids
Return all of the groupids the user is a member of.

id host
Return the hostname of the system the program is running on.

id process
Return the process ID of the current process.

id process parent
Return the process ID of the parent of the current process.

id process group
Return the process group ID of the current process.

id process group set
Set the process group ID of the current process to its process ID.

id host
Returns the standard host name of the machine the process is executing on.

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

kill ?-pgroup ?signal? idlist

Send a signal to the each process in the list idlist, if permitted. Signal, if present, is the signal number or the symbolic name of the signal, see the signal system call manual page. The leading ``SIG'' is optional when the signal is specified by its symbolic name. The default for signo is 15, SIGTERM.

If -pgroup is specified, the numbers in idlist are take as process group ids and the signal is sent to all of the process in that process group. A process group id of 0 specifies the current process group.

The kill command is not available on Windows 95/NT.

link ?-sym? srcpath destpath

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

The link command is not available on Windows 95/NT.

nice ?priorityincr?

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

Negative priorityincr values cumulatively increase the program's priority down to a system defined minimum (normally -19); increasing priority with negative niceness values will only work for the superuser.

The new priority is returned.

The nice command is not available on Windows 95/NT.

readdir ?-hidden? dirPath

Returns a list containing the contents of the directory dirPath. The directory entries «.» and «..» are not returned.

On Windows 95/NT, -hidden maybe specified to include hidden files in the result. This flag is ignored on Unix systems.

signal ?-restart? action siglist ?command?

Warning: If signals are being used as an event source (a trap action), rather than generating an error to terminate a task; one must use the -restart option. This causes a blocked system call, such as read or waitpid to be restarted rather than generate an error. Failure to do this may results in unexpected errors when a signal arrives while in one of these system calls. When available, the -restart option can prevent this problem.

If -restart is specified, restart blocking system calls rather than generating an error. The signal will be handled once the Tcl command that issued the system call completes. The -restart options is not available on all operating systems and its use will generate an error when it is not supported. Use infox have_signal_restart to check for availability.

Specify the action to take when a Unix signal is received by Extended Tcl, or a program that embeds it. Siglist is a list of either the symbolic or numeric Unix signal (the SIG prefix is optional). Action is one of the following actions to be performed on receipt of the signal. To specify all modifiable signals, use `*' (this will not include SIGKILL and SIGSTOP, as they can not be modified).

default
Perform system default action when signal is received (see signal system call documentation).

ignore Ignore the signal.

error Generate a catchable Tcl error. It will be as if the command that was running returned an error. The error code will be in the form:
POSIX SIG signame
For the death of child signal, signame will always be SIGCHLD, rather than SIGCLD, to allow writing portable code.

trap When the signal occurs, execute command and continue execution if an error is not returned by command. The command will be executed in the global context. The command will be edited before execution, replacing occurrences of «%S» with the signal name. Occurrences of «%%» result in a single «%". This editing occurs just before the trap command is evaluated. If an error is returned, then follow the standard Tcl error mechanism. Often command will just do an exit.

get
Retrieve the current settings of the specified signals. A keyed list will be returned were the keys are one of the specified signals and the values are a list consisting of the action associated with the signal, a 0 if the signal may be delivered (not block) and a 1 if it is blocked and a flag indicating if restarting of system calls is specified. The actions maybe one of `default',`ignore', `error' or `trap'. If the action is trap, the third element is the command associated with the action. The signal handler has been associated with the signal.
set
Set signals from a keyed list in the format returned by the get. For this action, siglist is the keyed list of signal state. Signals with an action of `unknown' are not modified.

block Block the specified signals from being received. (Posix systems only).

unblock
Allow the specified signal to be received. Pending signals will not occur. (Posix systems only).

The signal action will remain enabled after the specified signal has occurred. The exception to this is SIGCHLD on systems without Posix signals. For these systems, SIGCHLD is not be automatically reenabled. After a SIGCHLD signal is received, a call to wait must be performed to retrieve the exit status of the child process before issuing another signal SIGCHLD ... command. For code that is to be portable between both types of systems, use this approach.

Signals are not processed until after the completion of the Tcl command that is executing when the signal is received. If an interactive Tcl shell is running, then the SIGINT will be set to error, noninteractive Tcl sessions leave SIGINT unchanged from when the process started (normally default for foreground processes and ignore for processes in the background).

sleep seconds
Sleep the Extended Tcl process for seconds seconds. SecondsFR, if specified as a decimal number, is truncated to an integer value.

system cmdstr1 ?cmdstr2...?
Concatenates cmdstr1, cmdstr2 etc with space separators (see the concat command) into a single command and then evaluates the command using the standard system shell. On Unix systems, this is /bin/sh and om Windows its command.com. The exit code of the command is returned.

This command differs from the exec command in that system doesn't return the executed command's standard output as the result string, and system goes through the Unix shell to provide wildcard expansion, redirection, etc, as is normal from an sh command line.

sync ?fileId?

If fileId is not specified, or if it is and this system does not support the fsync system call, issues a sync system call to flush all pending disk output. If fileId is specified and the system does support the fsync system call, issues an fsync on the file corresponding to the specified Tcl fileId to force all pending output to that file out to the disk.

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

The infox have_fsync command can be used to determine if «sync fileId» will do a sync or a fsync.

times
Return a list containing the process and child execution times in the form:
utime stime cutime cstime
Also see the times(2) system call manual page. The values are in milliseconds.

umask ?octalmask?
Sets file-creation mode mask to the octal value of octalmask. If octalmask is omitted, the current mask is returned.

wait ?-nohang? ?-untraced? ?-pgroup? ?pid? Waits for a process created with the execl command to terminate, either due to an untrapped signal or call to exit system call. If the process id pid is specified, they wait on that process, otherwise wait on any child process to terminate.

If -nohang is specified, then don't block waiting on a process to terminate. If no process is immediately available, return an empty list. If -untraced is specified then the status of child processes that are stopped, and whose status has not yet been reported since they stopped, are also returned. If -pgroup is specified and pid is not specified, then wait on any child process whose process groupd ID is they same as the calling process. If pid is specified with -pgroup, then it is take as a process group ID, waiting on any process in that process group to terminate.

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

Note that it is possible to wait on processes to terminate that were create in the background with the exec command. However, if any other exec command is executed after the process terminates, then the process status will be reaped by the exec command and will not be available to the wait command.

On systems without the waitpid system call, the -nohang, -untraced and -pgroup options are not available. The infox have_waitpid command maybe use to determine if this functionality is available.

File Commands

These commands provide extended file access and manipulation. This includes searching ASCII-sorted data files, copying files, duplicating file descriptors, control of file access options, retrieving open file status, and creating pipes with the pipe system call. Also linking files, setting file, process, and user attributes and truncating files. An interface to the select system call is available on Unix systems that support it.

It should be noted that Tcl file I/O is implemented on top of the stdio library. By default, the file is buffered. When communicating to a process through a pipe, a flush command should be issued to force the data out. Alternatively, the fcntl command may be used to set the buffering mode of a file to line-buffered or unbuffered.

bsearch fileId key ?retvar? ?compare_proc? Search an opened file fileId containing lines of text sorted into ascending order for a match. Key contains the string to match. If retvar is specified, then the line from the file is returned in retvar, and the command returns 1 if key was found, and 0 if it wasn't. If retvar is not specified or is a null name, then the command returns the line that was found, or an empty string if key wasn't found.

By default, the key is matched against the first white-space separated field in each line. The field is treated as an ASCII string. If com_pare_proc is specified, then it defines the name of a Tcl procedure to evaluate against each line read from the sorted file during the execution of the bsearch command. Compare_proc takes two arguments, the key and a line extracted from the file. The compare routine should return a number less than zero if the key is less than the line, zero if the key matches the line, or greater than zero if the key is greater than the line. The file must be sorted in ascending order according to the same criteria compare_proc uses to compare the key with the line, or erroneous results will occur.

This command does not work on files containing binary data (bytes of zero).

chmod [-fileid] mode filelist
Set permissions of each of the files in the list filelist to mode, where mode is an absolute numeric mode or symbolic permissions as in the UNIX chmod(1) command. To specify a mode as octal, it should be prefixed with a «0» (e.g. 0622).

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

The chmod command is not available on Windows 95/NT.

chown [-fileid] owner | {owner group} filelist Set owner of each file in the list filelist to owner, which can be a user name or numeric user id. If the first parameter is a list, then the owner is set to the first element of the list and the group is set to the second element. Group can be a group name or numeric group id. If group is {}, then the file group will be set to the login group of the specified user.

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

The chown command is not available on Windows 95/NT.

chgrp [-fileid] group filelist
Set the group id of each file in the list filelist to group, which can be either a group name or a numeric group id.

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

The chgrp command is not available on Windows 95/NT.

dup fileId ?targetFileId?
Duplicate an open file. A new file id is opened that addresses the same file as fileId.

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

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

On Windows 95/NT, only stdin, stdout, or stderr or a non-socket file handle number maybe specified for targetFileId. The dup command does not work on sockets on Windows 95/NT.

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

RDONLY The file is opened for reading only. (Get only)

WRONLY The file is opened for writing only. (Get only)

RDWR The file is opened for reading and writing. (Get only)

READ
If the file is readable. (Get only).

WRITE If the file is writable. (Get only).

APPEND The file is opened for append-only writes. All writes will be forced to the end of the file. (Get or set).

NONBLOCK
The file is to be accessed with non-blocking I/O. See the read system call for a description of how it affects the behavior of file reads.
CLOEXEC
Close the file on an process exec. If the execl command or some other mechanism causes the process to do an exec, the file will be closed if this option is set.

NOBUF The file is not buffered. If set, then there no buffering for the file.

LINEBUF
Output the file will be line buffered. The buffer will be flushed when a newline is written, when the buffer is full, or when input is requested.
KEEPALIVE
Keep a socket connection alive. If SIGPIPE is enabled, then it is sent if connection is broken and data is written to the socket. If SIGPIPE is ignored, an error is returned on the write. This attribute is valid only on sockets. By default, SIGPIPE is ignored in Tcl.

The NONBLOCK, NOBUF and LINEBUF are provided for compatibility with older scripts. Thefconfigure command is preferred method of getting and setting these attributes.

The APPEND and CLOEXEC options are not available on Windows 95/NT.

flock options fileId ?start? ?length? ?origin?

This command places a lock on all or part of the file specified by fileId. The lock is either advisory or mandatory, depending on the mode bits of the file. The lock is placed beginning at relative byte offset start for length bytes. If start or length is omitted or empty, zero is assumed. If length is zero, then the lock always extents to end of file, even if the file grows. If origin is «start", then the offset is relative to the beginning of the file. If it is «current", it is relative to the current access position in the file. If it is «end", then it is relative to the end-offile (a negative is before the EOF, positive is after). If origin is omitted, start is assumed.

The following options are recognized:

-read
Place a read lock on the file. Multiple processes may be accessing the file with read-locks.
-write Place a write lock on the
file. Only one process may be accessing a file if there is a write lock.
-nowait
If specified, then the process will not block if the lock can not be obtained. With this option, the command returns 1 if the lock is obtained and 0 if it is not.

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

The flock command is not available on Windows 95. It is available on Windows NT.

for_file var filename code
This procedure implements a loop over the contents of a file. For each line in filename, it sets var to the line and executes code.

The break and continue commands work as with foreach.

For example, the command

for_file line /etc/passwd {echo $line}

would echo all the lines in the password file.

funlock fileId ?start? ?length? ?origin? Remove a locked from a file that was previously placed with the flock command. The arguments are the same as for the flock command, see that command for more details.

The funlock command is not available on Windows 95. It is available on Windows NT.

fstat fileId ?item? | ?stat arrayvar?

Obtain status information about an open file.

The following keys are used to identify data items:

atime The time of last access.

ctime The time of last file status change

dev
The device containing a directory for the file. This value uniquely identifies the file system that contains the file.
gid
The group ID of the file's group.
ino
The inode number. This field uniquely identifies the file in a given file system.

mode The mode of the file (see the mknod system call).

mtime Time when the data in the file was last modified.

nlink The number of links to the file.

size
The file size in bytes.
tty
If the file is associated with a terminal, then 1 otherwise 0.
type
The type of the file in symbolic form, which is one of the following values: file, directory, characterSpecial, blockSpecial, fifo, link, or socket.
uid
The user ID of the file's owner.

If one of these keys is specified as item, then that data item is returned.

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

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

The following values may be returned only if explicitly asked for, it will not be returned with the array or keyed list forms:

remotehost
If fileId is a TCP/IP socket connection, then a list is returned with the first element being the remote host IP address. If the remote host name can be found, it is returned as the second element of the list. The remote host IP port number is the third element.

localhost
If fileId is a TCP/IP socket connection, then a list is returned with the first element being the local host IP address. If the local host name can be found, it is returned as the second element of the list. The local host IP port number is the third element.

ftruncate [-fileid] file newsize
Truncate a file to have a length of at most newsize bytes.

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

This command is not available or not fully functional if the underlying operating system support is not available. The command infox have_truncate will indicate if this command may truncate by file path. The command infox have_ftruncate will indicate if this command may truncate by file id.

The -fileid option is not available on Windows 95/NT.

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

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

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

The lgets command maybe used to read and write lists containing binary data, however translation must be set to lf or the data maybe corrupted.

If lgets is currently supported on non-blocking files.

pipe ?fileId_var_r fileId_var_w?
Create a pipe. If fileId_var_r and fileId_var_r are specified, then pipe will set the a variable named fileId_var_r to contain the fileId of the side of the pipe that was opened for reading, and fileId_var_w will contain the fileId of the side of the pipe that was opened for writing.

If the fileId variables are not specified, then a list containing the read and write fileIdw is returned as the result of the command.

read_file ?-nonewline? fileName

read_file fileName numBytes
This proecure reads the file fileName and returns the contents as a string. If -nonewline is specified, then the last character of the file is discarded if it is a newline. The second form specifies exactly how many bytes will be read and returned, unless there are fewer than numBytes bytes left in the file; in this case, all the remaining bytes are returned.

select readfileIds ?writefileIds? ?exceptfileIds? ?time_out? This command allows an Extended Tcl program to wait on zero or more files being ready for for reading, writing, have an exceptional condition pending, or for a timeout period to expire. readFileIds, writeFileIds, exceptFileIds are each lists of fileIds, as returned from open, to query. An empty list ({}) may be specified if a category is not used.

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

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

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

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

could return

{file3 file4} {file6} {}

or perhaps

file3 {} {}

On Windows 95/NT, only sockets can be used with the select command. Pipes, as returned by the open command, are not supported.

write_file fileName string ?string...?
This procedure writes the specified strings to the named file.

Network Programming Support

TclX provides functionality to complement the Tcl socket command. The host_info command is used to get information about a host by name or IP address. In addition, the fstat and fcntl commands provide options of querying and controlling connected sockets. To obtain the host name of the system the local system, use the id host command.

host_info addresses host

host_info official_name host

host_info aliases host
Obtain information about a internet host. The argument host can be either a host name or an IP address.

The following subcommands are recognized:

addresses
Return the list of IP addresses for host.

official_name
Return official name for host.

aliases
Return the list of aliases for host. (Note that these are IP number aliases, not DNS CNAME aliases. See ifconfig(2).)

File Scanning Commands

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

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

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

scancontext create
Create a new scan context. The scanmatch command is used to define patterns in the context. A contexthandle is returned, which the Tcl programmer uses to refer to the newly created scan context in calls to the Tcl file scanning commands.

scancontext delete contexthandle
Delete the scan context identified by contex_thandle, and free all of the match statements and compiled regular expressions associated with the specified context.

scancontext copyfile contexthandle ?filehandle? Set or return the file handle that unmatched lines are copied to. (See scanfile). If filehandle is omitted, the copy file handle is returned. If no copy file is associated with the context, {} is returned. If a file handle is specified, it becomes the copy file for this context. If file_handle is {}, then it removes any copy file specification for the context.

scanfile ?-copyfile copyFileId? contexthandle fileId Scan the file specified by fileId, starting from the current file position. Check all patterns in the scan context specified by contexthandle against it, executing the match commands corresponding to patterns matched.

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

This command does not work on files containing binary data (bytes of zero).

scanmatch ?-nocase? contexthandle ?regexp? commands

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

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

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

matchInfo is local to the top level of the match command unless declared global at that level by the Tcl global command. If it is to be used as a global, it must be declared global before scanfile is called (since scanfile sets the matchInfo before the match code is executed, a subsequent global will override the local variable). The following array entries are available:

matchInfo(line)
Contains the text of the line of the file that was matched.

matchInfo(offset)
The byte offset into the file of the first character of the line that was matched.

matchInfo(linenum)
The line number of the line that was matched. This is relative to the first line scanned, which is usually, but not necessarily, the first line of the file. The first line is line number one.

matchInfo(context)
The context handle of the context that this scan is associated with.

matchInfo(handle)
The file id (handle) of the file currently being scanned.

matchInfo(copyHandle)
The file id (handle) of the file specified by the -copyfile option. The element does not exist if -copyfile was not specified.

matchInfo(submatch0)
Will contain the characters matching the first parenthesized subexpression. The second will be contained in submatch1, etc.

matchInfo(subindex0)
Will contain the a list of the starting and ending indices of the string matching the first parenthesized subexpression. The second will be contained in subindex1, etc.

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

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

Math Commands

Several extended math commands commands make many additional math functions available in TclX. In addition, a set of procedures provide command access to the math functions supported by the expr command.

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

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

max num1 ?..numN?

expr max(num1, num2)
Returns the argument that has the highest numeric value. Each argument may be any integer or floating point value.

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

min num1 ?..numN?

expr min(num1, num2)
Returns the argument that has the lowest numeric value. Each argument may be any integer or floating point value.

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

random limit | seed ?seedval?
Generate a pseudorandom integer number greater than or equal to zero and less than limit. If seed is specified, then the command resets the random number generator to a starting point derived from the seedval. This allows one to reproduce pseudorandom number sequences for testing purposes. If seedval is omitted, then the seed is set to a value based on current system state and the current time, providing a reasonably interesting and ever-changing seed.

List Manipulation Commands

Extended Tcl provides additional list manipulation commands and procedures.

intersect lista listb
Procedure to return the logical intersection of two lists. The returned list will be sorted.

intersect3 lista listb
Procedure to intersects two lists, returning a list containing three lists: The first list returned is everything in lista that wasn't in listb. The second list contains the intersection of the two lists, and the third list contains all the elements that were in listb but weren't in lista. The returned lists will be sorted.

lassign list var ?var...?
Assign successive elements of a list to specified variables. If there are more variable names than fields, the remaining variables are set to the empty string. If there are more elements than variables, a list of the unassigned elements is returned.

For example,

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

Assigns name to ``dave'', uid to ``100'', gid to ``200'', and longName to ``Dave Foo''.

lcontain list element
Determine if the element is a list element of list. If the element is contained in the list, 1 is returned, otherwise, 0 is returned.

lempty list
Determine if the specified list is empty. If empty, 1 is returned, otherwise, 0 is returned. This command is an alternative to comparing a list to an empty string, however it checks for a string of all whitespaces, which is an empty list.

lmatch ?mode? list pattern

Search the elements of list, returning a list of all elements matching pattern. If none match, an empty list is returned.

The mode argument indicates how the elements of the list are to be matched against pattern and it must have one of the following values: -exact The list element must contain exactly the same string as pattern.

-glob
Pattern is a glob-style pattern which is matched against each list element using the same rules as the string match command.
-regexp
Pattern is treated as a regular expression and matched against each list element using the same rules as the regexp command.

If mode is omitted then it defaults to -glob.

Only the -exact comparison will work on binary data.

lrmdups list
Procedure to remove duplicate elements from a list. The returned list will be sorted.

lvarcat var string ?string...?
This command treats each string argument as a list and concatenates them to the end of the contents of var, forming a a single list. The list is stored back into var and also returned as the result. if var does not exist, it is created.

lvarpop var ?indexExpr? ?string?
The lvarpop command pops (deletes) the element indexed by the expression indexExpr from the list contained in the variable var. If index is omitted, then 0 is assumed. If string, is specified, then the deleted element is replaced by string. The replaced or deleted element is returned. Thus ``lvarpop argv 0'' returns the first element of argv, setting argv to contain the remainder of the string.

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

lvarpush var string ?indexExpr?
The lvarpush command pushes (inserts) string as an element in the list contained in the variable var. The element is inserted before position indexExpr in the list. If index is omitted, then 0 is assumed. If var does not exists, it is created.

If the expression indexExpr starts with the string end, then end is replaced with the index of the last element in the list. If the expression starts with len, then len is replaced with the length of the list. Note the a value of end means insert the string before the last element.

union lista listb
Procedure to return the logical union of the two specified lists. Any duplicate elements are removed.

Keyed Lists

Extended Tcl defines a special type of list referred to as keyed lists. These lists provided a structured data type built upon standard Tcl lists. This provides a functionality similar to structs in the C programming language.

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

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

If the variable person contained the above list, then keylget person NAME would return {Frank Zappa}. Executing the command:

keylset person ID 106

would make person contain

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

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

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

There is no limit to the recursive depth of subfields, allowing one to build complex data structures.

Keyed lists are constructed and accessed via a number of commands. All keyed list management commands take the name of the variable containing the keyed list as an argument (i.e. passed by reference), rather than passing the list directly.

keyldel listvar key
Delete the field specified by key from the keyed list in the variable listvar. This removes both the key and the value from the keyed list.

keylget listvar ?key? ?retvar | {}?
Return the value associated with key from the keyed list in the variable listvar. If retvar is not specified, then the value will be returned as the result of the command. In this case, if key is not found in the list, an error will result.

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

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

keylkeys listvar ?key?
Return the a list of the keys in the keyed list in the variable listvar. If keys is specified, then it is the name of a key field who's subfield keys are to be retrieve.

keylset listvar key value ?key2 value2 ...? Set the value associated with key, in the keyed list contained in the variable listvar, to value. If listvar does not exists, it is created. If key is not currently in the list, it will be added. If it already exists, value replaces the existing value. Multiple keywords and values may be specified, if desired.

String and Character Manipulation Commands

The commands provide additional functionality to classify characters, convert characters between character and numeric values, index into a string, determine the length of a string, extract a range of character from a string, replicate a string a number of times, and transliterate a string (similar to the Unix tr program).

ccollate ?-local? string1 string2
This command compares two strings. If returns -1 if string1 is less than string2, 0 if they are equal and 1 if string1 is greater than string2.

If -local is specified, the strings are compared according to the collation environment of the current locale.

This command does not work with binary or UTF data.

cconcat ?string1? ?string2? ?...?
Concatenate the arguments, returning the resulting string. While string concatenation is normally performed by the parser, it is occasionally useful to have a command that returns a string. The is generally useful when a command to evaluate is required. No separators are inserted between the strings.

This command is UTF-aware.

cequal string string
This command compares two strings for equality. It returns 1 if string1 and string2 are the identical and 0 if they are not. This command is a short-cut for string compare and avoids the problems with string expressions being treated unintentionally as numbers.

This command is UTF-aware and will also work on binary data.

cindex string indexExpr
Returns the character indexed by the expression indexExpr (zero based) from string.

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

This command is UTF-aware.

clength string
Returns the length of string in characters. This command is a shortcut for:
string length string

This command is UTF-aware.

crange string firstExpr lastExpr
Returns a range of characters from string starting at the character indexed by the expression first_E xpr (zero-based) until the character indexed by the expression lastExpr.

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

This command is UTF-aware.

csubstr string firstExpr lengthExpr
Returns a range of characters from string starting at the character indexed by the expression first_E xpr (zero-based) for lengthExpr characters.

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

This command is UTF-aware.

ctoken strvar separators
Parse a token out of a character string. The string to parse is contained in the variable named strvar. The string separators contains all of the valid separator characters for tokens in the string. All leading separators are skipped and the first token is returned. The variable strvar will be modified to contain the remainder of the string following the token.

This command does not work with binary data.

ctype ?-failindex var? class string
ctype determines whether all characters in string are of the specified class. It returns 1 if they are all of class, and 0 if they are not, or if the string is empty. This command also provides another method (besides format and scan) of converting between an ASCII character and its numeric value. The following ctype commands are available: ctype ?-failindex var? alnum string Tests that all characters are alphabetic or numeric characters as defined by the character set.

ctype ?-failindex var? alpha string Tests that all characters are alphabetic characters as defined by the character set.

ctype ?-failindex var? ascii string Tests that all characters are an ASCII character (a non-negative number less than 0200).

ctype char number
Converts the numeric value, string, to an ASCII character. Number must be in the range 0 through the maximum Unicode values.

ctype ?-failindex var? cntrl string Tests that all characters are ``control characters'' as defined by the character set.

ctype ?-failindex var? digit string Tests that all characters are valid decimal digits, i.e. 0 through 9.

ctype ?-failindex var? graph string Tests that all characters within are any character for which ctype print is true, except for space characters.

ctype ?-failindex var? lower string Tests that all characters are lowercase letters as defined by the character set.

ctype ord character
Convert a character into its decimal numeric value. The first character of the string is converted to its numeric Unicode value.

ctype ?-failindex var? space string Tests that all characters are either a space, horizontal-tab, carriage return, newline, vertical-tab, or form-feed.

ctype ?-failindex var? print string Tests that all characters are a space or any character for which ctype alnum or ctype punct is true or other ``printing character'' as defined by the character set.

ctype ?-failindex var? punct string Tests that all characters are made up of any of the characters other than the ones for which alnum, cntrl, or space is true.

ctype ?-failindex var? upper string Tests that all characters are uppercase letters as defined by the character set.

ctype ?-failindex var? xdigit string Tests that all characters are valid hexadecimal digits, that is 0 through 9, a through f or A through F.

If -failindex is specified, then the index into string of the first character that did not match the class is returned in var.

replicate string countExpr
Returns string, replicated the number of times indicated by the expression countExpr.

This command is UTF-aware and will work with binary data.

translit inrange outrange string
Translate characters in string, changing characters occurring in inrange to the corresponding character in outrange. Inrange and outrange may be list of characters or a range in the form `A-M'. For example: translit a-z A-Z foobar

This command currently only supports characters in ASCII range; UTF-8 characters out of this range will generate an error.

Xpg/3 Message Catalog Commands

These commands provide a Tcl interface to message catalogs that are compliant with the X/Open Portability Guide, Version 3 (XPG/3).

Tcl programmers can use message catalogs to create applications that are language-independent. Through the use of message catalogs, prompts, messages, menus and so forth can exist for any number of languages, and they can altered, and new languages added, without affecting any Tcl or C source code, greatly easing the maintenance difficulties incurred by supporting multiple languages.

A default text message is passed to the command that fetches entries from message catalogs. This allows the Tcl programmer to create message catalogs containing messages in various languages, but still have a set of default messages available regardless of the presence of any message catalogs, and allow the programs to press on without difficulty when no catalogs are present.

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

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

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

catopen ?-fail | -nofail? catname
Open the message catalog catname. This may be a relative path name, in which case the NLSPATH environment variable is searched to find an absolute path to the message catalog. A handle in the form msgcat N is returned. Normally, errors are ignored, and in the case of a failed call to catopen, a handle is returned to an unopened message catalog. (This handle may still be passed to catgets and catclose, causing catgets to simply return the default string, as described above. If the -fail option is specified, an error is returned if the open fails. The option -nofail specifies the default behavior of not returning an error when catopen fails to open a specified message catalog.

If the handle from a failed catopen is passed to catgets, the default string is returned.

catgets catHandle setnum msgnum defaultstr Retrieve a message form a message catalog. CatHandle should be a Tcl message catalog handle that was returned by catopen. Setnum is the message set number, and msgnum is the message number. If the message catalog was not opened, or the message set or message number cannot be found, then the default string, defaultstr, is returned.

catclose ?-fail | -nofail? cathandle
Close the message catalog specified by cathandle. Normally, errors are ignored. If -fail is specified, any errors closing the message catalog file are returned. The option -nofail specifies the default behavior of not returning an error. The use of -fail only makes sense if it was also specified in the call to catopen.

Extended Tcl Shell

tcl ?-qn? ?-f? script? | ?-c command? ?args?

The tcl starts the interactive TclX command interpreter. The TclX shell provides an environment for writing, debugging and executing Tcl scripts. The functionality of the TclX shell can be easily obtained by any application that includes TclX.

The tcl command, issued without any arguments, invokes an interactive Tcl shell, allowing the user to interact directly with Tcl, executing any Tcl commands at will and viewing their results.

If script is specified, then the script is executed noninteractively with any additional arguments, args, being supplied in the global Tcl variable `argv'. If command is supplied, then this command (or semicolon-separated series of commands) is executed, with `argv' containing any args.

The TclX shell is intended as an environment for Tcl program development and execution. While it is not a fullfeatured interactive shell, it provides a comfortable environment for the interactive development of Tcl code.

The following command line flags are recognized by the Tcl shell command line parser:

-q
Quick initialization flag. The Tcl initiaization file is not evaluated and the auto_path variable is not set. Tcl auto-load libraries will not be available.
-n
No procedure call stack dump. The procedure call stack will not be displayed when an error occurs, only the error message. Useful in the #! line of already debugged scripts.
-f
Takes the next argument as a script for Tcl to source, rather than entering interactive mode. The -f flag is optional. Normally the first argument that does not start with a `-' is taken as the script to execute unless the `-c' option is specified. Any following arguments are passed to the script via argv, thus any other Tcl shell commandline flags must precede this option.
-c
Take the next argument as a Tcl command to execute. It may contain series of commands to execute, separated by `;'. Any following arguments are passed in argv, thus, as with -f, any other Tcl shell flags must precede this option.
--
Mark the end of the arguments to the Tcl shell. All

arguments following this are passed in the Tcl variable argv. This is useful to pass arguments without attempting to execute a Tcl script.

The result string returned by a command executed from the Tcl shell command line is normally echoed back to the user. If an error occurs, then the string result is displayed, along with the error message. The error message will be preceded by the string ``Error:''.

The set command is a special case. If the command is called to set a variable (i.e. with two arguments), then the result will not be echoed. If only one argument, the name of a variable, is supplied to set, then the result will be echoed.

If an unknown Tcl command is entered from the command line, then the Unix command path, specified in the environment variable PATH, will be searched for a command of the same name. If the command is found, it will be executed with any arguments remaining on the Tcl command line being passed as arguments to the command. This feature is provided to enhance the interactive environment for developing Tcl scripts.

Automatic execution of programs in this manner is only supported from the command line, not in script files or in procedures, to reduce confusion and mistakes while programming in Tcl. Scripts should use the Tcl exec or system commands to run Unix commands.

The following variables are set and/or used by the Tcl shell.

argv0 Contains the name of the Tcl program specified on the command line or the name that the Tcl shell was invoked under if no program was specified. argc Contains a count of the number of argv arguments (0 if none). argv A list containing the arguments passed in from the command line, excluding arguments used by the Tcl shell. The first element is the first passed argument, not the program name.

tcl_interactive
Set to 1 if Tcl shell is invoked interactively, or 0 if the Tcl shell is directly executing a script. Normally checked by scripts so that they can function as a standalone application if specified on the command line, but merely load in and not execute if loaded during an interactive invocation of Tcl.

auto_path
Path to search to locate Tcl autoload libraries.

Used by the both the Tcl and TclX library autoloading facility.

tclx_library
Path to the TclX runtime library. If your running the TclX shell or an application based on it (like wishx). The TclX initialization file normally adds this to the auto_path.

tkx_library
Path to the TkX runtime library. This is set only if your application has called Tkx_Init. The TkX initialization file normally adds this to the auto_path.

tcl_prompt1
Contains code to run to output the prompt used when interactively prompting for commands.

tcl_prompt2
Contains code to run to output the prompt used when interactively prompting for continuation of an incomplete command.

TCLXENV
Array that contains information used internally by various Tcl procedures that are part of the TclX shell. Don't change this array unless you know what your doing. tclx_errorHandler message The tclx_errorHandler command doesn't exist as built-in part of TclX. Instead, individual applications or users can define a tclx_errorHandler command (e.g. as a Tcl procedure) if they wish to handle uncaught errors. The procedure will be passed a single argument of the error message, with errorCode and errorInfo having values reflecting the error that occurred.

The tclx_errorHandler command is called when an error that is not caught returns to the top level command evaluation in the TclX shell or wishx. The difference between tclx_errorHandler and bgerror is that tclx_errorHandler is called during the synchronous execution of a script while bgerror is called as a result of an uncaught error in an event handler. In a non-event oriented Tcl script tclx_errorHandler will be called on all errors that are not caught and bgerror is not used. In a wishx script or event oriented script executed with the TclX shell, tclx_errorHandler will be called on uncaught errors during the execution of the main script that set up the event oriented program. Once the event loop is entered, bgerror will be called on uncaught errors.

This procedure is not called in response to commands entered via an interactive command loop, only from the evaluation of scripts or Tcl commands passed via the command line. If the procedure returns normally, the program will just exit without any error being issued by the shell. Generally the procedure should exit with a non-zero exit code once the error has been processed. It is not possible to continue executing the code in which the error occurred. This is useful for logging errorInfo or e-mailing it to the maintainer.

mainloop
This procedure sets up a top-level event loop. Events are processed until there are no more active event sources, at which time the process exits. It is used to build event oriented programs using the TclX shell in a style similar to that used with wish. If the global variable tcl_interactive exists and has a true value an interactive command handler is started as well. If the command handler is terminated by an EOF, the process will be exited.

This commands is not useful in wishx, as it automatically enters an event loop after processing a script.

Help Facility

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

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

To run the Tk-based interactive help program:

tclhelp ?addpaths?

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

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

help
Help, without arguments, lists of all the help subjects and pages under the current help subject.

help subject
Displays all of help pages and lower level subjects (if any exist) under the subject subject.

help subject/helppage
Display the specified help page. The help output is passed through a simple pager if output exceeds 23 lines, pausing waiting for a return to be entered. If any other character is entered, the output is terminated.

helpcd ?subject?
Change the current subject, which is much like the Unix current directory. If subject is not specified, return to the top-level of the help tree. Help subject path names may also include ``..'' elements.

helppwd
Displays the current help subject.

help help | ?
Displays help on the help facility at any directory level.

apropos pattern
This command locates subjects by searching their one-line descriptions for a pattern. Apropos is useful when you can remember part of the name or description of a command, and want to search through the one-line summaries for matching lines. Full regular expressions may be specified (see the regexp command).

Tcl Loadable Libraries and Packages

Extended Tcl supports standard Tcl tclIndex libraries and package libraries. A package library file can contain multiple independent Tcl packages. A package is a named collection of related Tcl procedures and initialization code.

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

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

The start of a package is delimited by:

#@package: package_name proc1 ?..procN?

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

Care should be taken in defining package_name, as the first package found in the path by with a given name is loaded. This can be useful in developing new version of packages installed on the system.

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

#@package: directory_stack pushd popd dirs

says that the text lines following that line in the package file up to the next package line or the end of the file is a package named directory_stack and that an attempt to execute either pushd, popd or dirs when the routine is not already defined will cause the directory_stack portion of the package file to be loaded.

Package Library Management Commands

Several commands are available for building and managing package libraries. Commands that are extended versions of the standard Tcl library commands are listed here. All of the standard Tcl library management commands and variables are also supported.

auto_commands ?-loaders?
Lists the names of all known loadable procedures and commands procedures. If -loaders is specified, the command that will be executed to load the command will also be returned.

buildpackageindex libfilelist
Build index files for package libraries. The argument libfilelist is a list of package libraries. Each name must end with the suffix .tlib. A corresponding .tndx file will be built. The user must have write access to the directory containing each library.

convert_lib tclIndex packagelib ?ignore? Convert a Ousterhout style tclIndex index file and associate source files into a package library packagelib. If packagelib does not have a .tlib extension, one will be added. Any files specified in tclIndex that are in the list ignore will be skipped. Files listed in ignore should just be the base file names, not full paths.

loadlibindex libfile.tlib
Load the package library index of the library file libfile (which must have the suffix .tlib). Package library indexes along the auto_path are loaded automatically on the first demand_load; this command is provided to explicitly load libraries that are not in the path. If the index file (with a .tndx suffix) does not exists or is out of date, it will be rebuilt if the user has directory permissions to create it. If a package with the same name as a package in libfile.tlib has already been loaded, its definition will be overridden by the new package. However, if any procedure has actually been used from the previously defined package, the procedures from libfile.tlib will not be loaded.

auto_packages ?-location?
Returns a list of the names of all defined packages. If -location is specified, a list of pairs of package name and the .tlib path name, offset and length of the package within the library.

auto_load_file file
Source a file, as with the source command, except search auto_path for the file.

searchpath path file
Search all directories in the specified path, which is a Tcl list, for the specified file. Returns the full path name of the file, or an empty string if the requested file could not be found.

Table of Contents

  • Name
  • Synopsis
  • Introduction
  • General Commands
  • Debugging and Development Commands
  • UNIX Access Commands
  • File Commands
  • Network Programming Support
  • File Scanning Commands
  • Math Commands
  • List Manipulation Commands
  • Keyed Lists
  • String and Character Manipulation Commands
  • Xpg/3 Message Catalog Commands
  • Extended Tcl Shell
  • Help Facility
  • Tcl Loadable Libraries and Packages
  • Package Library Management Commands


TclX TclXInit

 Table of Contents

Name

Tclx_Init, Tclxcmd_Init, TclX_Main, Tkx_Init, TkX_Main Extended Tcl initialization.

Synopsis

-ltclx -ltcl

#include «tclExtend.h"

int
Tclx_Init (Tcl_Interp *interp);

int
Tclxcmd_Init (Tcl_Interp *interp);

int
void

TclX_Main (int
argc,
char
**argv, Tcl_AppInitProc *appInitProc);

int
Tkx_Init (Tcl_Interp *interp);

void

TkX_Main (int
argc,
char
**argv, Tcl_AppInitProc *appInitProc);

void

TclX_SetAppInfo (int
defaultValues, char *appName, char *appLongName, char *appVersion, int appPatchlevel);

Description

These functions are used to initialize Extended Tcl and applications based on Extended Tcl. This manual page also discusses various issues and approaches of integrating TclX into other applications.

Tclx_Init
Initializes Extended Tcl, adding the extended command set to the interpreter. This is called from Tcl_AppInit. This function must be called after the Tcl_Init function. In addition to the standard command set, it enables use of tlib packages libraries and makes the standard TclX library available.

Parameters
o interp - A pointer to the interpreter to add the commands to.

Returns:
TCL_OK if all is ok, TCL_ERROR if an error occurred.

Tclxcmd_Init
Add the TclX command set to the interpreter, with the exception of the TclX library management commands. This is normally called by Tclx_Init and should only be used if you don't want the TclX library handling.

Parameters
o interp - A pointer to the interpreter to add the commands to.

Returns:
TCL_OK if all is ok, TCL_ERROR if an error occurred.

TclX_Main
This function parses the command line according to the TclX shell specification (Unix shell compatible). It creates an interpreter and calls the specified function appInitProc to initialize any application specific commands. It then either evaluates the command of script specified on the command line or enters an interactive command loop. This procedure never returns, it exits the process when it's done. Using the TclX shell also gives you SIGINT handling in interactive shells.

Tkx_Init
Initializes Extended Tcl Tk environment. This is called from Tcl_AppInit after the Tk_Init function.

Parameters
o interp - A pointer to the interpreter to add the commands to.

Returns:
TCL_OK if all is ok, TCL_ERROR if an error occurred.

TkX_Main
This function parses the command line according to the wish shell specification. It creates an interpreter and calls the specified function appInitProc to initialize any application specific commands. It then either evaluates the command of script specified on the command line or enters an interactive command loop. This procedure never returns, it exits the process when it's done. Using the TclX wish shell gives you SIGINT handling in interactive shells, otherwise it is identical to standard wish.

TclX_SetAppInfo
Store the application information returned by infox.

Parameters
o defaultValues - If true, then the values are assigned only if they are not already defined (defaulted). If false, the values are always set.
o appName - Application symbolic name. o appLongName - Long, natural language application name. o appVersion - Version number of the application. o appPatchlevel - Patch level of the application. If less than zero, don't change.

String pointers are saved without copying, don't release the memory. If the arguments are NULL, don't change the values.

Dynamic Loading of Tclx

TclX can be dynamically loaded on systems that support shared libraries and the load command. This can be done using either the load or the package require commands. If package require is to be used, a pkgIndex,tcl must be constructed. The pkg_mkIndex does not generate a pkgIndex.tcl file that works with TclX. Instead a command similar to

package ifneeded Tclx 7.5.0 «load $dir/libtclx.so"

should be placed in the directory containing the TclX shared library. A prototype pkgIndex,tcl file is build by TclX and is installed in the run time directory under the name pkgIndex,proto. This file can't be used as-is, but should be renamed and copied or combined with an existing pkgIndex,tcl in the directory containing the shared library.

There is no need to dynamically load libtkx.so, since it only contains support for wishx.

Integrating Tclx with Other Extensions and Applications

The main aspects to integrating TclX with into an application is to decide if the application is based on the standard Tcl/Tk shells or the TclX shells. If the standard shells are desired, then all that is necessary is to call Tclx_Init after Tcl_Init and
Tkx_Init after Tk_Init. This functionality may also be dynamically loaded.

To get the TclX shell in a Tcl only application, with the tcl command functionality, call TclX_Main from the main function instead of Tcl_Main. This shell has arguments conforming to other Unix shells and SIGINT signal handling when interactive,.

To get the Tclx shell in a Tk application, with the wishx command functionality, call TkX_Main from the main function instead of Tk_Main. This shell has SIGINT signal handling when interactive,

Table of Contents

  • Name
  • Synopsis
  • Description
  • Dynamic Loading of Tclx
  • Integrating Tclx with Other Extensions and Applications


TclX Keylist

 Table of Contents

Name

TclX_NewKeyedListObj, TclX_KeyedListGet, TclX_KeyedListSet, TclX_KeyedListDelete, TclX_KeyedListGetKeys - Keyed list management routines.

Synopsis

#include <tclExtend.h>

Tcl_Obj *
TclX_NewKeyedListObj (void);

int
TclX_KeyedListGet (Tcl_Interp *interp,

Tcl_Obj
*keylPtr,
char
*key, Tcl_Obj **valuePtrPtr);

int
TclX_KeyedListSet (Tcl_Interp *interp,

Tcl_Obj
*keylPtr,
char
*key,
Tcl_Obj
*valuePtr);

int
TclX_KeyedListDelete (Tcl_Interp *interp,

Tcl_Obj
*keylPtr,
char
*key);

int
TclX_KeyedListGetKeys (Tcl_Interp *interp,

Tcl_Obj
*keylPtr,
char
*key, Tcl_Obj **listObjPtrPtr);

Description

These routines perform operations on keyed lists. See the Extended Tcl man page for a description of keyed lists.

TclX_NewKeyedListObj
Create and initialize a new keyed list object.

Returns:
A pointer to the object.

TclX_KeyedListGet
Retrieve a key value from a keyed list.

Parameters:
o interp - Error message will be return in result if there is an error.
o keylPtr - Keyed list object to get key from. o key - The name of the key to extract. Will recusively process sub-keys seperated by `.'.
o valueObjPtrPtr - If the key is found, a pointer to the key object
is returned here. NULL is returned if the key is not present.

Returns:
o TCL_OK - If the key value was returned. o TCL_BREAK - If the key was not found. o TCL_ERROR - If an error occured.

TclX_KeyedListSet
Set a key value in keyed list object.

Parameters:
o interp - Error message will be return in result object.
o keylPtr - Keyed list object to update. o key - The name of the key to extract. Will recusively process sub-key seperated by `.'.
o valueObjPtr - The value to set for the key.

Returns:
TCL_OK or TCL_ERROR.

TclX_KeyedListDelete
Delete a key value from keyed list.

Parameters:
o interp - Error message will be return in result if there is an error.
o keylPtr - Keyed list object to update. o key - The name of the key to extract. Will recusively process sub-key seperated by `.'.

Returns:
o TCL_OK - If the key was deleted. o TCL_BREAK - If the key was not found. o TCL_ERROR - If an error occured.

TclX_KeyedListGetKeys
Retrieve a list of keyed list keys.

Parameters:
o interp - Error message will be return in result if there is an error.
o keylPtr - Keyed list object to get key from. o key - The name of the key to get the sub keys for. NULL or empty to retrieve all top level keys. o listObjPtrPtr - List object is returned here with key as values.

Returns:
o TCL_OK - If the zero or more key where returned. o TCL_BREAK - If the key was not found. o TCL_ERROR - If an error occured.

Table of Contents

  • Name
  • Synopsis
  • Description


TclX Handles

 Table of Contents

Name

Tcl_HandleAlloc, Tcl_HandleFree, Tcl_HandleTblInit, Tcl_HandleTblRelease, Tcl_HandleTblUseCount Tcl_HandleWalk, Tcl_HandleXlate - Dynamic, handle addressable tables.

Synopsis

#include <tclExtend.h>

void_pt
Tcl_HandleTblInit (const char *handleBase,

int
entrySize,
int
initEntries);

int
Tcl_HandleTblUseCount (void_pt headerPtr,

int
amount);

void
Tcl_HandleTblRelease (void_pt headerPtr);

void_pt

Tcl_HandleAlloc (void_pt
headerPtr,
char
*handlePtr);

void_pt
Tcl_HandleXlate (Tcl_Interp *interp,

void_pt
headerPtr, const char *handle);

void_pt

Tcl_HandleWalk (void_pt
headerPtr,
int
*walkKeyPtr);

void

Tcl_WalkKeyToHandle (void_pt
headerPtr,
int
walkKey,
char
*handlePtr);

void
Tcl_HandleFree (void_pt headerPtr,
void_pt entryPtr);

Description

The Tcl handle facility provides a way to manage table entries that may be referenced by a textual handle from Tcl code. This is provided for applications that need to create data structures in one command, return a reference (i.e. pointer) to that particular data structure and then access that data structure in other commands. An example application is file handles.

A handle consists of a base name, which is some unique, meaningful name, such as `file' and a numeric value appended to the base name (e.g. `file3'). The handle facility is designed to provide a standard mechanism for building Tcl commands that allocate and access table entries based on an entry index. The tables are expanded when needed, consequently pointers to entries should not be kept, as they will become invalid when the table is expanded. If the table entries are large or pointers must be kept to the entries, then the the entries should be allocated separately and pointers kept in the handle table. A use count is kept on the table. This use count is intended to determine when a table shared by multiple commands is to be release.

Tcl_HandleTblInit
Create and initialize a Tcl dynamic handle table. The use count on the table is set to one.

Parameters:
o handleBase - The base name of the handle, the handle will be returned in the form «baseNN", where NN is the table entry number.
o entrySize - The size of an entry, in bytes. o initEntries - Initial size of the table, in entries.

Returns:
A pointer to the table header.

Tcl_HandleTblUseCount
Alter the handle table use count by the specified amount, which can be positive or negative. Amount may be zero to retrieve the use count.

Parameters:
o headerPtr - Pointer to the table header. o amount - The amount to alter the use count by.

Returns:
The resulting use count.

Tcl_HandleTblRelease
Decrement the use count on a Tcl dynamic handle table. If the count goes to zero or negative, then release the table.

Parameters:
o headerPtr - Pointer to the table header.

Tcl_HandleAlloc
Allocate an entry and associate a handle with it.

Parameters:
o headerPtr - A pointer to the table header. o handlePtr - Buffer to return handle in. It must be big enough to hold the name.

Returns:
A pointer to the allocated entry (user part).

Tcl_HandleXlate
Translate a handle to a entry pointer.

Parameters:
o interp - A error message may be returned in result. o headerPtr - A pointer to the table header.

o handle - The handle assigned to the entry.

Returns:
A pointer to the entry, or NULL if an error occurred.

Tcl_HandleWalk
Walk through and find every allocated entry in a table. Entries may be deallocated during a walk, but should not be allocated.

Parameters:
o headerPtr - A pointer to the table header. o walkKeyPtr - Pointer to a variable to use to keep track of the place in the table. The variable should be initialized to -1 before the first call. Returns:
A pointer to the next allocated entry, or NULL if there are not more.

Tcl_WalkKeyToHandle
Convert a walk key, as returned from a call to Tcl_HandleWalk into a handle. The Tcl_HandleWalk must have succeeded.

Parameters:
o headerPtr - A pointer to the table header. o walkKey - The walk key.
o handlePtr - Buffer to return handle in. It must be big enough to hold the name.

Tcl_HandleFree
Frees a handle table entry.

Parameters:
o headerPtr - A pointer to the table header. o entryPtr - Entry to free.

Table of Contents

  • Name
  • Synopsis
  • Description


TclX CmdWrite

 Table of Contents

Name

TclCommandWriting - Writing C language extensions to Tcl.

Overview

This document is intended to help the programmer who wishes to extend Tcl with C language routines. It should also be useful to someone wishing to add Tcl to an existing editor, communications program, window manager, etc. C programming information can also be found in the *.3 manual pages in the doc directory of the Berkeley distribution, and in the *.3 manpages in the man directory of Extended Tcl.

Writing Tcl Extensions in C

All C-based Tcl commands are called with four arguments: a client data pointer, an interpreter pointer, an argument count and a pointer to an array of pointers to character strings containing the Tcl arguments to the command.

A simple Tcl extension in C is now presented, and described below:

#include «tcl.h"

int App_EchoCmd(clientData, interp, argc, argv)

void
*clientData; Tcl_Interp *interp;
int
argc;
char
     **argv;
{
int i;

for (i = 1; i < argc; i++) {
printf("%s",argv[i]);
if (i < argc - 1) printf(» «);
}
printf("\n");
return TCL_OK;
}

The client data pointer will be described later.

The interpreter pointer is the ``key'' to an interpreter. It is returned by Tcl_CreateInterp and is used extensively within Tcl, and will be by your C extensions. The data structure pointed to by the interpreter pointer, and all of the subordinate structures that branch off of it, make up a Tcl interpreter, which includes all of the currently defined procedures, commands, variables, arrays and the execution state of that interpreter. (For more information on creating and deleting interpreters, please examine the CrtInterp(3) manpage in the Berkeley Tcl distribution. For information on creating interpreters that include the commands provided by Extended Tcl, check out the

TclX_Init(3) manpage of Extended Tcl. For a manual page describing the user-visible fields of a Tcl interpreter, please look at Interp(3) in Berkeley Tcl.)

The argument count and pointer to an array of pointers to textual arguments is handled by your C code in the same manner that you would use in writing a C main function -the argument count and array of pointers works the same as in a C main call; pointers to the arguments to the function are contained in the argv array. Similar to a C main, the first argument (argv[0]) is the name the routine was called as (in a main, the name the program was invoked as).

In the above example, all of the arguments are output with a space between each one by looping through argv from one to the argument count, argc, and a newline is output to terminate the line -- an ``echo'' command.

All arguments from a Tcl call to a Tcl C extension are passed as strings. If your C routine expects certain numeric arguments, your routine must first convert them using the Tcl_GetInt or Tcl_GetDouble function, Extended Tcl's Tcl_GetLong or Tcl_GetUnsigned, or some other method of your own devising. Likewise for converting boolean values, Tcl_GetBoolean should be used. These routines automatically leave an appropriate error message in the Tcl interpreter's result buffer and return TCL_ERROR if a conversion error occurs. (For more information on these routines, please look at the GetInt(3) manpage in the Berkeley Tcl distribution.)

Likewise, if you program produces a numeric result, it should return a string equivalent to that numeric value. A common way of doing this is something like...

sprintf(interp->result, «%ld", result);

Writing results directly into the interpreter's result buffer is only good for relatively short results. Tcl has a function, Tcl_SetResult, which provides the ability for your C extensions to return very large strings to Tcl, with the ability to tell the interpreter whether it ``owns'' the string (meaning that Tcl should delete the string when it's done with it), that the string is likely to be changed or overwritten soon (meaning that Tcl should make a copy of the string right away), or that the string won't change (so Tcl can use the string as is and not worry about it). Understanding how results are passed back to Tcl is essential to the C extension writer. Please study the SetResult(3) manual page in the Tcl distribution.

Sophisticated commands should verify their arguments whenever possible, both by examining the argument count, by verifying that numeric fields are really numeric, that values are in range (when their ranges are known), and so forth.

Tcl is designed to be as bullet-proof as possible, in the sense that no Tcl program should be able to cause Tcl to dump core. Please carry this notion forward with your C extensions by validating arguments as above.

Another C Extension - the Max Command

In the command below, two or more arguments are compared and the one with the maximum value is returned, if all goes well. It is an error if there are fewer than three arguments (the pointer to the ``max'' command text itself, argv[0], and pointers to at least two arguments to compare the values of).

This routine also shows the use of the programmer laborsaving Tcl_AppendResult routine. See the Tcl manual page, SetResult(3) , for details. Also examine the calls Tcl_AddErrorInfo, Tcl_SetErrorCode and Tcl_PosixError documented in the Tcl manual page AddErrInfo(3) .

int
Tcl_MaxCmd (clientData, interp, argc, argv)

char
*clientData; Tcl_Interp *interp;
int
argc;
char
     **argv;
{
int maxVal = MININT;
int maxIdx = 1;
int value, idx;

if (argc < 3) {
Tcl_AppendResult (interp, «bad # arg: «, argv[0],
« num1 num2 [..numN]", (char *)NULL);
return TCL_ERROR;
}

for (idx = 1; idx < argc; idx++) { if (Tcl_GetInt (argv[idx], 10, &Value) != TCL_OK) return TCL_ERROR;

if (value > maxVal) {
maxVal = value;
maxIdx = idx;
}
}
Tcl_SetResult (interp, argv [maxIdx], TCL_VOLATILE);
return TCL_OK;

}

When Tcl-callable functions complete, they should normally return TCL_OK or TCL_ERROR. TCL_OK is returned when the command succeeded and TCL_ERROR is returned when the command has failed in some abnormal way. TCL_ERROR should be returned for all syntax errors, non-numeric values (when numeric ones were expected), and so forth. Less clear in some cases is whether Tcl errors should be returned or whether a function should just return a status value. For example, end-of-file during a gets returns a status, but open returns an error if the open fails. Errors can be caught from Tcl programs using the catch command. (See Tcl's catch(n) and error(n) manual pages.)

Less common return values are TCL_RETURN, TCL_BREAK and TCL_CONTINUE. These are used if you are adding new control and/or looping structures to Tcl. To see these values in action, examine the source code to Tcl's while, for and if, and Extended Tcl's loop commands.

Note the call to Tcl_SetResult in the above command to set the return value to Tcl. TCL_VOLATILE is used because the memory containing the result will be freed upon the function's return.

Another C Extension - the Lreverse Command

In the command below, one list is passed as an argument, and a list containing all of the elements of the list in reverse order is returned. It is an error if anything other than two arguments are passed (the pointer to the ``lreverse'' command text itself, argv[0], and a pointer to the list to reverse.

Once lreverse has determined that it has received the correct number of arguments, Tcl_SplitList is called to break the list into an argc and argv array of pointers.

lreverse then operates on the array of pointers, swapping them from lowest to highest, second-lowest to second-highest, and so forth.

Finally Tcl_Merge is calleds to create a single new string containing the reversed list and it is set as the result via Tcl_SetResult. Note that TCL_DYNAMIC is used to tell Tcl_SetResult that it now owns the string and it is up to Tcl to free the string when it is done with it.

Note that it is safe to play around with the argv list like this, and that a single call to ckfree can be made to free all the data returned by Tcl_SplitList in this manner. int
Tcl_LreverseCmd(notUsed, interp, argc, argv)

ClientData notUsed;
/* Not used. */
Tcl_Interp *interp;
/* Current interpreter. */
int argc;
/* Number of arguments. */
char **argv;
             /* Argument strings. */
{
int listArgc, lowListIndex, hiListIndex;
char **listArgv;
char *temp, *resultList;

if (argc != 2) {
Tcl_AppendResult(interp, «wrong # args: should be « list
return TCL_ERROR;
}

if (Tcl_SplitList(interp, argv[1], &listArgc, &listArgv) != TCL_OK) {
return TCL_ERROR;
}
for (lowListIndex = 0, hiListIndex = listArgc;
--hiListIndex > lowListIndex; lowListIndex++) {
temp = listArgv[lowListIndex];
listArgv[lowListIndex] = listArgv[hiListIndex];
listArgv[hiListIndex] = temp;
}
resultList = Tcl_Merge (listArgc, listArgv);
ckfree (listArgv);
Tcl_SetResult (interp, resultList, TCL_DYNAMIC);
return TCL_OK;
}

Installing Your Command

To install your command into Tcl you must call Tcl_CreateCommand, passing it the pointer to the interpreter you want to install the command into, the name of the command, a pointer to the C function that implements the command, a client data pointer, and a pointer to an optional callback routine.

The client data pointer and the callback routine will be described later.

For example, for the max function above (which, incidentally, comes from TclX's tclXmath.c in the TclX7.4/src directory):

Tcl_CreateCommand (interp, «max", Tcl_MaxCmd, (ClientData)NULL, (void (*)())NULL);

In the above example, the max function is added to the specified interpreter. The client data pointer and callback function pointer are NULL. (For complete information on Tcl_CreateCommand and its companion routine, Tcl_CommandInfo, please examine the CrtCommand(3) command page in the Berkeley Tcl distribution.)

Dynamic Strings

Dynamic strings are an important abstraction that first became available with Tcl 7.0. Dynamic strings, or DStrings, provide a way to build up arbitrarily long strings through a repeated process of appending information to them. DStrings reduce the amount of allocating and copying required to add information to a string. Further, they simplify the process of doing so. For complete information on dynamic strings, please examine the DString(3) manual page in the Berkeley Tcl distribution.

Client Data

The client data pointer provides a means for Tcl commands to have data associated with them that is not global to the C program nor included in the Tcl core. Client data is essential in a multi-interpreter environment (where a single program has created and is making use of multiple Tcl interpreters) for the C routines to maintain any permanent data they need on a per-interpreter basis. Otherwise there would be reentrancy problems. Tcl solves this through the client data mechanism. When you are about to call Tcl_CreateCommand to add a new command to an interpreter, if that command needs to keep some read/write data across invocations, you should allocate the space, preferably using ckalloc, then pass the address of that space as the ClientData pointer to Tcl_CreateCommand.

When your command is called from Tcl, the ClientData pointer you gave to Tcl_CreateCommand when you added the command to that interpreter is passed to your C routine through the ClientData pointer calling argument.

Commands that need to share this data with one another can do so by using the same ClientData pointer when the commands are added.

It is important to note that the Tcl extensions in the tclX7.4/src directory have had all of their data set up in this way. Since release 6.2, Extended Tcl has supported multiple interpreters within one invocation of Tcl.

Theory of Handles

Sometimes you need to have a data element that isn't readily representable as a string within Tcl, for example a pointer to a complex C data structure. It is not a good idea to try to pass pointers around within Tcl as strings by converting them to and from hex or integer representations, for example. It is too easy to mess one up, and the likely outcome of doing that is a core dump.

Instead we have developed and made use of the concept of handles. Handles are identifiers a C extension can pass to, and accept from, Tcl to make the transition between what your C code knows something as and what name Tcl knows it by to be as safe and painless as possible. For example, the stdio package included in Tcl uses file handles. When you open a file from Tcl, a handle is returned of the form file n where n is a file number. When you pass the file handle back to puts, gets, seek, flush and so forth, they validate the file handle by checking the the file text is present, then converting the file number to an integer that they use to look into a data structure of pointers to Tcl open file structures, which contain a Unix file descriptor, flags indicating whether or not the file is currently open, whether the file is a file or a pipe and so forth.

Handles have proven so useful that, as of release 6.1a, general support has been added for them. If you need a similar capability, it would be best to use the handle routines, documented in Handles(3) in Extended Tcl. We recommend that you use a unique-to-your-package textual handle coupled with a specific identifier and let the handle management routines validate it when it's passed back. It is much easier to track down a bug with an implicated handle named something like file4 or bitmap6 than just 6.

Tracking Memory Corruption Problems

Occasionally you may write code that scribbles past the end of an allocated piece of memory. The memory debugging routines included in Tcl can help find these problems. See Memory(TCL) for details.

Installing Your Extensions into Extended Tcl

To add your extensions to Extended Tcl, you must compile them and cause them to be linked with TclX. For the routines to be linked into the tcl and wishx executables, they must be referenced (directly or indirectly) from TclX. For these extensions to be visible as Tcl commands, they must be installed into Tcl with Tcl_CreateCommand.

Application-specific startup is accomplished by creating or editing the Tcl_AppInit function. In Tcl_AppInit you should add a call to an application-specific init function which you create. This function should take the address of the interpreter it should install its commands into, and it should install those commands with Tcl_CreateCommand and do any other application-specific startup that is necessary.

The naming convention for application startup routines is App_Init, where App is the name of your application. For example, to add an application named cute one would create a Cute_Init routine that expected a Tcl_Interp pointer as an argument, and add the following code to Tcl_AppInit:

if (Cute_Init (interp) == TCL_ERROR) {
return TCL_ERROR;
}

As you can guess from the above example, if your init routine is unable to initialize, it should use Tcl_AppendResult to provide some kind of useful error message back to TclX, then return TCL_ERROR to indicate that an error occurred. If the routine executed successfully, it should return TCL_OK.

When you examine Tcl_AppInit, note that there is one call already there to install an application -- the call to TclX_Init installs Extended Tcl into the Tcl core.

Making Application Information Visible from Extended Tcl

TclX's infox command can return several pieces of information relevant to Extended Tcl, including the application's name, descriptive name, patch level and version. Your application's startup can set these variables to application-specific values. If it doesn't, they are given default values for Extended Tcl.

To set these values, first be sure that you include either tclExtend.h or tclExtdInt.h from the source file that defines your init routine. This will create external declarations for the variables. Then, set the variables in your init route, for example:

tclAppName = «cute";
tclAppLongName = «Call Unix/Tcl Environment";
tclAppVersion = «2.1";

Note that the default values are set by TclX_Init, so if you wish to override them, you must call your init routine in Tcl_AppInit after its call to TclX_Init.

Extended Tcl Exit

When Extended Tcl exits, Tcl_DeleteInterp may be called to free memory used by Tcl -- normally, this is only called if TCL_MEM_DEBUG was defined, since Unix will return all of the allocated memory back to the system, anyway. If TCL_MEM_DEBUG was defined, it is called so that any memory that was allocated without ever being freed can be detected. This greatly reduces the amount of work to detect and track down memory leaks, a situation where some piece of your code allocates memory repeatedly without ever freeing it, or without always freeing it.

It is often necessary for an application to perform special cleanup functions upon the deletion of an interpreter as well. To facilitate this activity, Tcl provides the ability to perform a function callback when an interpreter is deleted. To arrange for a C function to be called when the interpreter is deleted, call Tcl_CallWhenDeleted from your application initialization routine. For details on how to use this function, read the CallDel(3) manual page that ships with Berkeley Tcl.

Executing Tcl Code from Your C Extension

Suppose you are in the middle of coding a C extension and you realize that you need some operation performed, one that would be simple from Tcl but possibly excruciating to do directly in C. Tcl provides the Tcl_Eval, Tcl_VarEval, Tcl_EvalFile and Tcl_GlobalEval functions for the purpose of executing Tcl code from within a C extension. The results of the call will be in interp->result. For more information please consult the Eval(3) manual page within the Tcl distribution.

Accessing Tcl Variables and Arrays from Your C Extensions

Tcl variables and arrays can be read from a C extension through the Tcl_GetVar and Tcl_GetVar2 functions, and set from C extensions through the Tcl_SetVar and Tcl_SetVar2 functions. They can also be unset via the Tcl_UnsetVar and Tcl_UnsetVar2 functions. For complete information on these functions, please refer to the SetVar(3) manual page in the doc directory of the Berkeley Tcl distribution.

Linking Tcl Variables to C Variables

Tcl_LinkVar and Tcl_UnlinkVar can be used to automatically keep Tcl variables synchronized with corresponding C variables. Once a Tcl variable has been linked to a C variable with Tcl_LinkVar, anytime the Tcl variable is read the value of the C variable will be returned, and when the Tcl variable is written, the C variable will be updated with the new value.

Tcl_LinkVar uses variable traces to keep the Tcl variable named by varName in sync with the C variable at the address given by addr.

Whenever the Tcl variable is read the value of the C variable will be returned, and whenever the Tcl variable is written the C variable will be updated to have the same value.

Int, double, boolean and char * variables are supported. For more information, please examine the LinkVar(3) manual page in the Berkeley Tcl distribution.

Adding New Math Functions to Tcl

As of Tcl version 7.0, math functions such as sin, cos, etc, are directly supported within Tcl expressions. These obsolete the Extended Tcl commands that provided explicit calls for these functions for many releases.

New math functions can be added to Tcl, or existing math functions can be replaced, by calling Tcl_CreateMathFunc.

For more information on adding math functions, please examine the CrtMathFnc(3) manual page in the Berkeley Tcl distribution.

Performing Tilde Substitutions on Filenames

The Tcl_TildeSubst function is available to C extension writers to perform tilde substitutions on filenames. If the name starts with a ``~'' character, the function returns a new string where the name is replaced with the home directory of the given user. For more information please consult the TildeSubst(3) manual page in the Berkeley Tcl distribution.

Setting the Recursion Limit

Tcl has a preset recursion limit that limits the maximum allowable nesting depth of calls within an interpreter. This is useful for detecting infinite recursions before other limits such as the process memory limit or, worse, available swap space on the system, are exceeded.

The default limit is just a guess, however, and applications that make heavy use of recursion may need to call Tcl_SetRecursionLimit to raise this limit. For more information, please consult the SetRecLmt(3) manual page in the Berkeley Tcl distribution.

Handling Signals from Tcl Extensions

If an event such as a signal occurs while a Tcl script is being executed, it isn't safe to do much in the signal handling routine -- the Tcl environment cannot be safely manipulated at this point because it could be in the middle of some operation, such as updating pointers, leaving the interpreter in an unreliable state.

The only safe approach is to set a flag indicating that the event occurred, then handle the event later when the interpreter has returned to a safe state, such as after the current Tcl command completes.

The Tcl_AsyncCreate, Tcl_AsyncMark, Tcl_AsyncInvoke, and Tcl_AsyncDelete functions provide a safe mechanism for dealing with signals and other asynchronous events. For more information on how to use this capability, please refer to the Async(3) manual page in the Berkeley Tcl distribution.

Parsing Backslash Sequences

The Tcl_Backslash function is called to parse Tcl backslash sequences. These backslash sequences are the usual sort that you see in the C programming language, such as \n for newline, \r for return, and so forth. Tcl_Backslash parses a single backslash sequence and returns a single character corresponding to the backslash sequence.

For more info on this call, look at the Backslash(3) manual page in the Berkeley Tcl distribution. For information on the valid backslash sequences, consult the summary of Tcl language syntax, Tcl(n) in the same distribution.

Hash Tables

Hash tables provide Tcl with a high-performance facility for looking up and managing key-value pairs located and maintained in memory. Tcl uses hash tables internally to locate procedure definitions, Tcl variables, array elements, file handles and so forth. Tcl makes the hash table functions accessible to C extension writers as well.

Hash tables grow automatically to maintain efficiency, rather than exposing the table size to the programmer at allocation time, which would needlessly add complexity to Tcl and would be prone to inefficiency due to the need to guess the number of items that will go into the table, and the seemingly inevitable growth in amount of data processed per run over the life of the program.

For more information on hash tables, please consult the Hash(3) manual page in the Berkeley Tcl distribution.

Tracing Variable Accesses

The C extension writer can arrange to have a C routine called whenever a Tcl variable is read, written, or unset. Variable traces are the mechanism by which Tk toolkit widgets such as radio and checkbuttons, messages and so forth update without Tcl programmer intervention when their data variables are changed. They are also used by the routine that links Tcl and C variables, Tcl_LinkVar, described above.

Tcl_TraceVar is called to establish a variable trace. Entire arrays and individual array elements can be traced as well. If the programmer already has an array name in one string and a variable name in another, Tcl_TraceVar2 can be called. Calls are also available to request information about traces and to delete them.

For more information on variable traces, consult the TraceVar(3) manual page in the Berkeley Tcl distribution.

Tracing Execution

Tcl has the ability to call C routines for every command it executes, up to a specified depth of nesting levels. The command Tcl_CreateTrace creates an execution trace; Tcl_DeleteTrace deletes it.

Command tracing is used in Extended Tcl to implement the cmdtrace Tcl command, a useful command for debugging Tcl applications.

For complete information on execution tracing, please look at the CrtTrace(3) manual pages in the Berkeley Tcl distribution.

Evaluating Tcl Expressions from C

Tcl_ExprLong, Tcl_ExprDouble, Tcl_ExprBool, and Tcl_ExprString can be called to evaluate Tcl expressions from within a C routine. Depending on the routine called, the result is either a C long, a double, a boolean (int with a value of 0 or 1), or a char * (pointed to by interp->result).

For complete information on evaluating Tcl expressions from C, you are invited to examine the ExprLong(3) manpage in the Berkeley Tcl distribution.

Pattern Matching

The Tcl_StringMatch function can be called to see if a string matches a specified pattern. Tcl_StringMatch is called by the Tcl string match command, so the format for patterns is identical. The pattern format is similar to the one used by the C-shell; string(n) describes this format.

More information about Tcl_StringMatch is available in the StrMatch(3) manpage in the Berkeley Tcl distribution.

Regular Expression Pattern Matching

Tcl_RegExpMatch can be called to determine whether a string matches a regular expression. Tcl_RegExpMatch is used internally by the regexp Tcl command.

For more information on this function, please consult the RegExp(3) manpage in the Berkeley Tcl distribution.

Manipulating Tcl Lists from C Extensions

The C extension writer often needs to create, manipulate and decompose Tcl lists. Tcl_SplitList parses a list into an argv and argc like to the way command-line arguments are passed to a Tcl extension. Tcl_Merge, likewise, creates a single string (pointer to a char *) from an argv and argc.

Two routines, Tcl_ScanElement and Tcl_ConvertElement, do most of the work of Tcl_Merge, and may also be of use to the C programmer.

For more information on these commands, please consult the SplitList(3) manual page in the Berkeley Tcl distribution.

Concatenating Strings

Tcl_Concat concatenates zero or more strings into a single string. The strings are space-separated. Tcl_Concat works like Tcl_Merge, except that Tcl_Concat does not attempt to make the resulting string into a valid Tcl list.

Tcl_Concat is documented in the Concat(3) manpage in the Berkeley Tcl distribution.

Detecting Whether or Not You Have a Complete Command

C routines that collect data to form a command to be passed to Tcl_Eval often need a way to tell whether they have a complete command already or whether they need more data. (Programs that read typed-in Tcl input such as Tcl shells need this capability.) Tcl_CommandComplete can be used to tell whether or not you have a complete command.

For more information examine CmdCmplt(3) in the Berkeley Tcl distribution.

Recording Commands for Command History

Tcl has a history mechanism that is accessed from Tcl through the history command. To propagate commands into the command history, your extension should call Tcl_Recor_dAndEval. This command works just like Tcl_Eval, except that it records the command as well as executing it.

Tcl_RecordAndEval should only be called with user-entered top-level commands, since the history mechanism exists to allow the user to easily access, edit and reissue previously issued commands.

For complete information on this function, please examine the RecordEval.3 manual page in the Berkeley Tcl distribution.

Converting Floating Point Values to Strings

Tcl_PrintDouble converts a C double into an ASCII string. It ensures that the string output will continue to be interpreted as a floating point number, rather than an integer, by always putting a ``.'' or ``e'' into the string representing the number. The precision of the output string is controlled by the Tcl tcl_precision variable.

For complete information on Tcl_PrintDouble, examine PrintDbl(3) in the Berkeley Tcl distribution.

Creating Child Processes and Pipelines from C

Tcl_CreatePipeline is a useful procedure for spawning child processes. The child (or pipeline of children) can have its standard input, output and error redirected from files, variables or pipes. To understand the meaning of the redirection symbols understood by this function, look at the exec(n) Tcl command. For complete information on Tcl_CreatePipeline, please examine CrtPipelin(3) .

Accessing Tcl Filehandles from C

Files opened from your C code can be made visible to Tcl code via the Tcl_EnterFile function. Likewise, Tcl filehandles passed to your C extension can be translated to a Posix FILE * structure using the Tcl_GetOpenFile function.

For complete explanations of these commands, please look at EnterFile(3) in the Berkeley Tcl distribution.

Managing Background Process Termination and Cleanup

When a Posix system does a fork to create a new process, the process ID of the child is returned to the caller. After the child process exits, its process table entry (and some other data associated with the process) cannot be reclaimed by the operating system until a call to wait_pid, or one of a couple of other, similar system calls, has been made by the parent process.

The C extension writer who has created a subprocess, by whatever mechanism, can turn over responsibility for detecting the processes' termination and calling waitpid to obtain its exit status by calling Tcl_DetachPids.

Tcl_ReapDetachedProcs is the C routine that will detect the termination of any processes turned over to Tcl, permitting the processes to be fully reclaimed by the operating system.

For complete information on these routines, please look at DetachPids(3) in the Berkeley Tcl distribution.

for More Information

In addition to the documentation referenced above, you can learn a lot by studying the source code of the commands added by Tcl, Tk and Extended Tcl. The comp.lang.tcl Usenet newsgroup is read by tens of thousands of Tcl people, and is a good place to ask questions. Finally, if you have interactive Internet access, you can ftp to ftp.aud.alcatel.com, the site for contributed Tcl sources. This site contains quite a few extensions, applications, and so forth, including several object-oriented extension packages.

Authors

Extended Tcl was created by Karl Lehenbauer (karl@neosoft.com) and Mark Diekhans (markd@grizzly.com).

Table of Contents

  • Name
  • Overview
  • Writing Tcl Extensions in C
  • Another C Extension - the Max Command
  • Another C Extension - the Lreverse Command
  • Installing Your Command
  • Dynamic Strings
  • Client Data
  • Theory of Handles
  • Tracking Memory Corruption Problems
  • Installing Your Extensions into Extended Tcl
  • Making Application Information Visible from Extended Tcl
  • Extended Tcl Exit
  • Executing Tcl Code from Your C Extension
  • Accessing Tcl Variables and Arrays from Your C Extensions
  • Linking Tcl Variables to C Variables
  • Adding New Math Functions to Tcl
  • Performing Tilde Substitutions on Filenames
  • Setting the Recursion Limit
  • Handling Signals from Tcl Extensions
  • Parsing Backslash Sequences
  • Hash Tables
  • Tracing Variable Accesses
  • Tracing Execution
  • Evaluating Tcl Expressions from C
  • Pattern Matching
  • Regular Expression Pattern Matching
  • Manipulating Tcl Lists from C Extensions
  • Concatenating Strings
  • Detecting Whether or Not You Have a Complete Command
  • Recording Commands for Command History
  • Converting Floating Point Values to Strings
  • Creating Child Processes and Pipelines from C
  • Accessing Tcl Filehandles from C
  • Managing Background Process Termination and Cleanup
  • for More Information
  • Authors


TclX ObjCmdWrite

 Table of Contents

Name

TclCommandWriting - Writing C language extensions to Tcl.

Overview

This document is intended to help the programmer who wishes to extend Tcl with C language routines. It should also be useful to someone wishing to add Tcl to an existing editor, communications program, window manager, etc. Experienced extension writers may find this manual helpful in rewriting their applications to use the new Tcl object system. We assume you are already fluent in the C programming language and that you have built and installed Tcl on your machine.

Information on the available C interface routines to Tcl can be found in the *.3 manual pages in the doc directory of the baseline Tcl distribution, and in the *.3 manpages in the doc directory of Extended Tcl.

Tcl Object System

With the release of Tcl version 8, Tcl has a new system for managing Tcl values internally. To the Tcl programmer, the new objects look and act like strings, as before. But at the C level, these objects can now also hold cached internal representations of the strings in various native datatypes. For example, an object containing a string consisting of an integer, will now maintain a machine-code integer representation, if an integer representation has been needed. Using these objects is much more efficient than using the older-style Tcl strings, although the older style is still (currently) supported.

Although the object system has almost no effect at all on how the Tcl programmer uses Tcl, the object system's C interfaces to strings, integers, lists, etc., have changed considerably. While converting a package to use the new system can be a lot of work, the combination of the object system, which saves Tcl from having to constantly convert strings to integers and back, etc., and the on-the-fly bytecode compiler (which keeps Tcl from having to continually reparse code it is to execute) yield Tcl programs that routinely execute several times more quickly than with previous versions (Tcl 7 and before), and in some cases run as much as 2500 (!) times faster than before.

We have chosen, then, to rewrite the Command Writer's manpage, which has been shipping with Extended Tcl for a number of years, to produce this new version based on the new object system. The old manpage, based on the older string-oriented routines, will still be included in TclX releases for now, as it is still relevant to Tcl releases through version 7, and may be of use to those modifying/upgrading packages written for the old model. The old manual will be dropped from the release once we deem it unneeded; the old interfaces should now be considered legacy interfaces, and all new development should be done using the new object interfaces, unless backwards compatibility to pre-Tcl-8 releases is needed.

a Simple C Extension

All C-based Tcl commands are called with four arguments: a client data pointer, an interpreter pointer, an argument count and a pointer to an array of Tcl objects containing the arguments to the command.

A simple C extension to Tcl is now presented, and described below:

#include «tcl.h"

int App_DumpArgsObjCmd(clientData, interp, objc, objv)

void
*clientData;
Tcl_Interp
*interp;
int
objc;
Tcl_Obj
     **objv;
{
int i;
int stringLen;
char *stringPtr;

for (i = 1; i < objc; i++) {
stringPtr = Tcl_GetStringFromObj (objv [i], &stringLen);
printf("%s", stringPtr);
if (i < objc - 1) printf(» «);
}
printf("\n");
return TCL_OK;
}

The client data pointer will be described later.

Interpreters

The interpreter pointer is the ``key'' to an interpreter. It is returned by Tcl_CreateInterp and is used extensively within Tcl, and will be used by your C extensions. The data structure pointed to by the interpreter pointer, and all of the subordinate structures that branch off of it, make up a Tcl interpreter, which includes all of the currently defined procedures, commands, variables, arrays and the execution state of that interpreter. (For more information on creating and deleting interpreters, please examine the CrtInterp(3) manpage in the core Tcl distribution. For information on creating interpreters that include the commands provided by Extended Tcl, check out the TclX_Init(3) manpage of Extended Tcl. For a manual page describing the user-visible fields of a Tcl interpreter, please look at Interp(3) in core Tcl.)

Object Count and Arguments

The argument count, or object count (objc), and pointer to an array of pointers to Tcl objects of the command's arguments (objv) is handled by your C code, in a manner similar to the one you would use in writing a C main function -- an argument count and array of pointers works the same as in a C main call; pointers to the arguments to the function are contained in the objv array. Similar to a C main, the first argument (objv[0]) is an object containing the name the routine was called as (in a C main, the name the program was invoked as).

In Tcl, however, the array of pointers are not pointers to character strings (although they were in all version of Tcl before 8.0).

In the above example, all of the arguments are output with a space between each one by looping through elements of the objv array from one to the argument count, objc, and a newline is output to terminate the line -- a simple ``echo'' command. This example uses printf for simplicity. Of course in production code you would want to use the Tcl filesystem interfaces. See GetFile(3) and friends for more information.

All arguments from a Tcl call to a Tcl C extension are passed as Tcl Objects. If your C routine wants to look at one of those arguments as an integer, you need to make a call to a routine to fetch the representation of the object that you need. In the earlier example, for instance, Tcl_GetStringFromObj is called to obtain a textual representation of an object. Additional routines are available to fetch the representation of a data element as other data types. Tcl_GetBooleanFromObj, Tcl_GetDoubleFromObj, Tcl_GetIntFromObj, Tcl_GetLongFromObj, and Tcl_GetIndexFromObj, fetch object representations of Tcl strings as booleans, double-precision floating point, integer, long integer, and lists, among others.

These routines automatically leave an appropriate error message in the Tcl interpreter's result object and return TCL_ERROR if a conversion error occurs. (For more information on these routines, please look at the Object(3) manpage in the core Tcl distribution.)

Returning Results

As you might expect, the API for setting results from C extensions has changed significantly under the object system. The old technique of writing small results directory into the interpreter's result buffer is no longer used, for example. The notion of having to tell Tcl whether a result is static or dynamic is also a thing of the past. Under the object system, results are objects that are set up by your code, and objects are freed when their reference counts say they should be. More on this later.

If you program produces a numeric result, it should set the result object to contain that numeric value. A common way of doing this is something like...

Tcl_Obj *obj;

obj = Tcl_GetObjResult (interp); Tcl_SetIntObj (obj, value);

The above code obtains a pointer to the result object (an object made available to your routine that you're supposed to store your results into) and sets the integer value value into it.

Another way to do it would be to set up a new object and tell Tcl that this object contains the result...

Tcl_Obj *resultObj;

/* create a new object for use as a result */ resultObj = Tcl_NewObj ();

Tcl_SetIntObj (obj, value);
Tcl_SetObjResult (interp, resultObj);

Understanding how results are passed back to Tcl is essential to the C extension writer. Please study the SetObjResult(3) manual page in the Tcl distribution for more information.

Validating Arguments

It is a design goal of Tcl that no Tcl program be able to cause Tcl to dump core. It is important that the extension writers, likewise, use the avaiable methods and tools to make sure that their extensions do not allow unchecked input, for example, to cause the code to get some kind of runtime exception.

The object system has simplified, to some degree, the task of validating arguments, in that the object system automatically attempts type conversions as needed, and will return an error when a type conversion fails.

A simple, but important, check that every C extension should do is verify that it has the right number of arguments.

The act of trying to use, say, a string as an integer, implicitly performs the type conversion of the string and, if it doesn't work as an integer, returns TCL_ERROR. The developer should check for the TCL_ERROR return from all of the GetXxxFromObj commands, and handle them as appropriate. Usually this will mean propagating the error on back to the user, or to an intevening catch, as the case may be.

You should also check that values are in range (when their ranges are known), and so forth. When C data structures need to be handled in Tcl in some form or another, yet the contents of the data must remain opaque to Tcl, as is usually the case with binary data (although futures releases of Tcl are expected to have native abilities to read, write and manipulate binary data instrinsically), handles need to be used. Handles will be described and examples presented, later in this doc.

Another C Extension - the Max Command

In the command below, two or more arguments are compared, and the one with the maximum value is returned, if all goes well. It is an error if there are fewer than two arguments (the pointer to the ``max'' command text itself, objv[0], and a pointer to at least one object to compare the values of).

int
Tcl_MaxCmd (clientData, interp, objc, objv)

char
*clientData; Tcl_Interp *interp;
int
objc;
Tcl_Obj
    **objv;
{
int maxVal = MININT;
int value, idx;

if (objc < 3)
return TclX_WrongArgs (interp, objv[0], « num1 num2 [..numN]");

for (idx = 1; idx < objc; idx++) { if (Tcl_GetIntFromObj (interp, objv[idx], &value) != TCL_OK) return TCL_ERROR;

if (value > maxVal) {
maxVal = value;
}
}
Tcl_SetIntObj (Tcl_GetObjResult (interp), value);
return TCL_OK;
}

Here we introduce the Extended Tcl helper function TclX_WrongArgs. This routine makes it easy to create an error message and error return in response to the common mistake of being called with a wrong number.

Tcl_GetIntFromObj is used to fetch the integer values of the remaining arguments. If any fail to be converted, we return a Tcl error. If an interpreter is specified in the call to Tcl_GetIntFromObj, an appropriate error message about the conversion failure will be left in the result, so we do that here.

After examining all of the arguments to find the largest value, we set the result object to contain that value, and return TCL_OK.

Returning Results

When Tcl-callable functions complete, they should normally return TCL_OK or TCL_ERROR. TCL_OK is returned when the command succeeded, and TCL_ERROR is returned when the command has failed in some abnormal way. TCL_ERROR should be returned for all syntax errors, non-numeric values when numeric ones were expected, and so forth. Less clear in some cases is whether Tcl errors should be returned or whether a function should just return a status value. For example, end-of-file during a gets returns a status, but open returns an error if it fails. Errors can be caught from Tcl programs using the catch command. (See Tcl's catch(n) and error(n) manual pages.)

Less common return values are TCL_RETURN, TCL_BREAK and TCL_CONTINUE. These are used if you are adding new control and/or looping structures to Tcl. To see these values in action, examine the source code to Extended Tcl's loop commands. Tcl's while, for and if commands used to work in the just same manner, but are now compiled into bytecode by the bytecode for performance.

Another C Extension - the Lreverse Command

In the command below, a list is passed as an argument, and a list containing all of the elements of the list in reverse order is returned. It is an error if anything other than two arguments are passed (the pointer to the ``lreverse'' command text itself, objv[0], and a pointer to the list to reverse.

Once lreverse has determined that it has received the correct number of arguments, Tcl_ListObjGetElements is called to split the list into its own objc count of elements and objv array of pointers to the list's elements.

lreverse then operates on the array of pointers, swapping them from lowest to highest, second-lowest to second-highest, and so forth.

Tcl_ListObjAppendElement is called on successive list elements to build up the new list, which is finally returned as result of the command.

int
Tcl_LreverseObjCmd(notUsed, interp, objc, objv) ClientData notUsed; /* Not used. */ Tcl_Interp *interp; /* Current interpreter. */

int
          objc;            /* Number of arguments. */
Tcl_Obj     **obj;             /* Argument strings. */
{
int listObjc, lowListIndex, hiListIndex;
Tcl_Obj **listObjv;
char *temp, *resultList;
Tcl_Obj **newListObjv;

/* Verify argument count. Since we take only one argument, argument
* count must be 2 (command plus one argument).
*/
if (objc != 2)
return TclX_WrongArgs (interp, objv [0], «list");

/* Create an object to handle the new list we're creating */ newListObjv = Tcl_NewObj();

/* Crack the list at objv[1] into its own count and array of object
* pointers.
*/
if (Tcl_ListObjGetElements (interp, objv[1], &listObjc, &listObjv) != TCL_OK) {
return TCL_ERROR;
}

/* For each element in the source list from last to first, append an
* element to the new list.
*/
for (listIndex = listObjc - 1; listIndex >= 0; listIndex--) {
Tcl_ListObjAppendElement (interp, newListObjv, listObjv[listIndex]);
}
FIX: NEED TO RETURN THE LIST.
return TCL_OK;
}

Installing Your Command

To install your command into Tcl you must call Tcl_CreateObjCommand, passing it the pointer to the interpreter you want to install the command into, the name of the command, a pointer to the C function that implements the command, a client data pointer, and a pointer to an optional callback routine.

The client data pointer and the callback routine will be described later.

For example, for the max function above (which, incidentally, comes from TclX's tclXmath.c in the TclX7.4/src directory):

Tcl_CreateCommand (interp, «max", Tcl_MaxCmd, (ClientData)NULL, (void (*)())NULL);

In the above example, the max function is added to the specified interpreter. The client data pointer and callback function pointer are NULL. (For complete information on Tcl_CreateCommand and its companion routine, Tcl_CommandInfo, please examine the CrtCommand(3) command page in the core Tcl distribution.)

Dynamic Strings

Dynamic strings are an important abstraction that first became available with Tcl 7.0. Dynamic strings, or DStrings, provide a way to build up arbitrarily long strings through a repeated process of appending information to them. DStrings reduce the amount of allocating and copying required to add information to a string. Further, they simplify the process of doing so.

At first glance, it may seem that the object system supersedes DStrings. It does not, in that the performance improvements made possible by the lazy conversion of an object's representation from one datatype to another does not come into play much while constructing strings as the string representation is always available either without any type conversion or where type conversion would be necessary in any case as a string representation of the object is required when strings are being constructed by concatenation, etc.

It should be noted, however, that the C level string manipulation capabilites of objects, such as Tcl_AppendToObj and Tcl_AppendStringsToObj, are often plenty enough for what you need to do. For complete information on dynamic strings, please examine the DString(3) manual page in the core Tcl distribution. For more on Tcl object's string-oriented calls, seek Tcl_StringObj(3) in the same location.

Client Data

The client data pointer provides a means for Tcl commands to have data associated with them that is not global to the C program nor included in the Tcl core. Client data is essential in a multi-interpreter environment (where a single program has created and is making use of multiple Tcl interpreters) for the C routines to maintain any permanent data they need on a per-interpreter basis. If needed static data was simply declared static in C, you will probably have reentrancy problems when you work with multiple interpreters.

Tcl solves this through the client data mechanism. When you are about to call Tcl_CreateObjCommand to add a new command to an interpreter, if your command needs to keep some read/write data across invocations, you should allocate the space, preferably using Tcl_Alloc instead of malloc, then pass the address of that space as the ClientData pointer to Tcl_CreateObjCommand.

When your command is called from Tcl, the ClientData pointer you passed to Tcl_CreateObjCommand will be passed to your C routine through the ClientData pointer calling argument.

Commands that need to share this data with one another can do so by using the same ClientData pointer when the commands are added.

It is important to note that the Tcl extensions in the tclX8.0.0 directory have had all of their data set up in this way. Since release 6.2, Extended Tcl has supported multiple interpreters within one invocation of Tcl.

Theory of Handles

Sometimes you need to have a data element that isn't readily representable as a string within Tcl, for example a pointer to a complex C data structure. It is not a good idea to try to pass pointers around within Tcl as strings by converting them to and from hex or integer representations, for example. It is too easy to mess one up, and the likely outcome of doing that is a core dump.

Instead we have developed and made use of the concept of handles. Handles are identifiers a C extension can pass to, and accept from, Tcl to make the transition between what your C code knows something as and what name Tcl knows it by to be as safe and painless as possible. For example, the I/O system included in Tcl uses file handles. When you open a file from Tcl, a handle is returned of the form file n where n is a file number. When you pass the file handle back to puts, gets, seek, flush and so forth, they validate the file handle by checking the the file text is present, then converting the file number to an integer that they use to look into a data structure of pointers to Tcl open file structures, which contain a Unix file descriptor, flags indicating whether or not the file is currently open, whether the file is a file or a pipe and so forth.

Handles have proven so useful that, since TclX release 6.1a, general support has been available to help create and manipulate them. Many of these capabilities have migrated into baseline Tcl. If you have a similar need, you might like to use the handle routines documented in Handles(3) in Extended Tcl. We recommend that you use a unique-to-your-package textual handle coupled with a specific identifier and let the handle management routines validate it when it's passed back. It is much easier to track down a bug with an implicated handle named something like file4 or bitmap6 than just 6.

Note that Tcl's object offers another way for complex data structures to exist in parallel with and underneath Tcl strings. As of this writing (May 30, 1997) this is fairly new territory, but things are looking good for the prospects of using the Tcl object system in this manner, and for enhancements to the object system that allow even Tcl objects to have methods in a very straightforward and simple way.

Using Commands to Do the Same Thing, and More

Another handle-like technique, first popularized in the Tk toolkit, offers handle-like capabilities as well as some neat additional capabilities. That is to create a new Tcl command, from C, that uses ClientData to keep a «handle" on its complex underlying data structure. Then by having that command look at its second argument for what it is to do (its sub-functions), you get these nice methods, where you have several additional sub-commands that don't pollute the global namespace and only work on (and are available with) the objects (new commands) they are relevant to. For example, in Tk, creating a checkbutton (checkbutton .b) creates a new Tcl command (.b), that has methods to configure the button, select, deselect, toggle and flash it.

A lot of people think this is really the way to go, and I am pretty much leaning that way myself. If you use the incr tcl script-level object system for Tcl, objects that you define in Tcl will be highly compatible in terms of their command interfaces and configuration management with objects you create in C using the the command-and-ClientData technique described here. I believe Tk has some nice facilities for making this easy for the Tcl programmer. Itcl certainly does.

Tracking Memory Corruption Problems

Occasionally you may write code that scribbles past the end of an allocated piece of memory. This will usually result in a core dump or memory allocation failure sometime later in the program, often implicating code that is not actually responsible for the problem (as you start looking from the point where the error is detected, which is usually where the later routine has failed).

The memory debugging routines included in Tcl can help find these problems. Developed by Mark and Karl, the memory debugging routines are now part of baseline Tcl, and is to our knowledge the largest piece of TclX to drop into the core without being reengineered first. (You see, summer back in `91, John was sitting in his office in the CS building at UC Berkeley trying to find a memory leak somewhere in Tcl, when he was paid a visit by two long-hairedyet-polite programmers bearing gifts in the form of the technology grab-bag known as Extended Tcl. He saw that, using TclX's malloc routines, Tcl could be prompted to print the filename and line number of every single memory allocation that did not have a corresponding free. It was just what the doctor ordered ;-) See Memory(TCL) for details.

Installing Your Extensions into Tcl

To add your extensions to Tcl, you used to have to statically link them, together with any other extensions, into a single binary executable image. Today, although the statically linked executable is still an option, most operating systems, even Microsoft Windows, support shared libraries, and in most cases, Tcl can now make use of those shared libraries such that you extensions, and most others, can now be built a shared libraries that can be loaded in (using package require) by scripts that need them. Shared libraries can simplify a Tcl installation, because only one copy of Tcl is required, rather than a hodepodge of combinations of applications that you might have found at a big Tcl site in the previous era.

GNU Autoconf

While the build procedure for shared libraries varies from system to system, most Unix and Unix workalike systems will figure out the nuances of the compiler and linker arguments automatically when the configure script is run. If you are building a package that you plan to make generally available, we strongly recommend that you use GNU autoconf (ftp://prep.ai.mit.edu/pub/gnu) to set up an automatic configure script for it. Be forewarned that autoconf uses some pretty heavy duty shell and sed script magic to get the job done, and the learning curve can be pretty steep. Once done and shaken out, though, it's rewarding to know that your package can build and run on everything from a notebook to a Cray to a RISC SMP server.

Application-specific startup is accomplished by creating or editing the Tcl_AppInit function. In Tcl_AppInit you should add a call to an application-specific init function which you create. This function should take the address of the interpreter it should install its commands into, and it should install those commands with Tcl_CreateCommand and do any other application-specific startup that is necessary.

The naming convention for application startup routines is App_Init, where App is the name of your application. For example, to add an application named cute one would create a Cute_Init routine that expected a Tcl_Interp pointer as an argument, and add the following code to Tcl_AppInit:

if (Cute_Init (interp) == TCL_ERROR) {
return TCL_ERROR;
}

As you can guess from the above example, if your init routine is unable to initialize, it should use Tcl_AppendResult to provide some kind of useful error message back to TclX, then return TCL_ERROR to indicate that an error occurred. If the routine executed successfully, it should return TCL_OK.

When you examine Tcl_AppInit, note that there is one call already there to install an application -- the call to TclX_Init installs Extended Tcl into the Tcl core.

Making Application Information Visible from Extended Tcl

TclX's infox command can return several pieces of information relevant to Extended Tcl, including the application's name, descriptive name, patch level and version. Your application's startup can set these variables to application-specific values. If it doesn't, they are given default values for Extended Tcl.

To set these values, first be sure that you include either tclExtend.h or tclExtdInt.h from the source file that defines your init routine. This will create external declarations for the variables. Then, set the variables in your init route, for example:

tclAppName = «cute";
tclAppLongName = «Call Unix/Tcl Environment";
tclAppVersion = «2.1";

Note that the default values are set by TclX_Init, so if you wish to override them, you must call your init routine in Tcl_AppInit after its call to TclX_Init.

Extended Tcl Exit

When Extended Tcl exits, Tcl_DeleteInterp may be called to free memory used by Tcl -- normally, this is only called if TCL_MEM_DEBUG was defined, since Unix will return all of the allocated memory back to the system, anyway. If TCL_MEM_DEBUG was defined, it is called so that any memory that was allocated without ever being freed can be detected. This greatly reduces the amount of work to detect and track down memory leaks, a situation where some piece of your code allocates memory repeatedly without ever freeing it, or at least without always freeing it.

It is often necessary for an application to perform special cleanup functions upon the deletion of an interpreter as well. To facilitate this activity, Tcl provides the ability to perform a function callback when an interpreter is deleted. To arrange for a C function to be called when the interpreter is deleted, call Tcl_CallWhenDeleted from your application initialization routine. For details on how to use this function, read the CallDel(3) manual page that ships with core Tcl.

Executing Tcl Code from Your C Extension

Suppose you are in the middle of coding a C extension and you realize that you need some operation performed, one that would be simple from Tcl, but possibly excruciating to do directly in C. Tcl provides a number of C-level interfaces whereby you can cause Tcl code to be executeed. The old-style calls are Tcl_Eval, Tcl_VarEval, Tcl_EvalFile and Tcl_GlobalEval. The results of these calls can be dug out of the interpreter using Tcl_GetStringResult, if you want a string representation of the result, or Tcl_GetObjResult if you want the object. (The use of interp->result to access the result string has been deprecated.)

The Tcl object system adds Tcl_EvalObj and Tcl_GlobalEvalObj. The difference here is that we are evaluating an object, not just a string, and using these routines in preference to the aforementioned ones can result in a major performance improvement in your code, when the code is executed repeatedly (even if it only executes once but loops several times within itself), as these routines make it possible for the bytecode compiler to compile the code being evaluated and save the compiled code with the data structure, in an implementation-dependent manner.

For more information please consult the EvalObj(3) and Eval(3) manual pages within the Tcl distribution.

Accessing Tcl Variables and Arrays from Your C Extensions

In addition to the non-object-system ways of reading from and storing to Tcl variables, using routines such as Tcl_SetVar2 and Tcl_GetVar2, Tcl variables and arrays can be read from a C extension as Tcl objects by using the Tcl_ObjGetVar2 function, and set from C extensions through the Tcl_ObjSetVar2 function.

Please note that the object versions do not carry forward analogues to the one-variable-name-argument Tcl_GetVar,

Tcl_SetVar, and Tcl_UnsetVar. If you know you have a scalar, call the object variable get and set functions with a NULL second argument. If your variable name might contain an array reference via a self-contained embedded array index (i.e., I'm asking Tcl_ObjGetVar2 for «foo(5) " instead of «foo» «5"), add the TCL_PARSE_PART1 to the flags in your call.

While the fact that Tcl_ObjGetVar2 retrieves Tcl objects, rather than strings, is critical for the object system to be able to provide the performance boosts from «lazy» type conversion and the binary data capabilities, the arguments containing the variable name, or the array name and element name if they've been split out, also must be specified as Tcl objects rather than strings. While this is useful on occasion, those writing C extensions for Tcl in the post-object-system era usually have the names available as plain old char * variables, requiring conversion of the strings to objects before use and account for their possible destruction afterwards.

To simplify the task in those cases, TclX adds the TclX_ObjGetVar2S subroutine. It works just like Tcl_ObjGetVar2, except the one or two variable name arguments are specified as strings, and the routine takes care of making and disposing of object equivalents.

Tcl variables can be unset from C via the Tcl_UnsetVar and Tcl_UnsetVar2 functions. There are currently (as of 8.0) no object-system equivalents, so in the rare case where you have the name of the variable you want unset as an object instead of a string, you can call Tcl_GetStringFromObj to obtain the string representation first.

For complete information on these functions, please refer to the ObjSetVar(3) and SetVar(3) manual pages in the doc directory of the core Tcl distribution.

Linking Tcl Variables to C Variables

Tcl_LinkVar and Tcl_UnlinkVar can be used to automatically keep Tcl variables synchronized with corresponding C variables. Once a Tcl variable has been linked to a C variable with Tcl_LinkVar, anytime the Tcl variable is read, the value of the C variable is converted (if necessary) and returned, and when the Tcl variable is written, the C variable will be updated with the new value.

Tcl_LinkVar uses variable traces to keep the Tcl variable named by varName in sync with the C variable at the address given by addr.

Int, double, boolean and char * variables are supported. You can make your linked variables read only from the Tcl side, as well. Please note that the C variables must continually exist while they are linked, in other words, linking «automatic» C variables, those created on the stack while a routine is being executed and destroyed afterwards, will result in a malfunctioning program at best and a coredump or more at worst.

For more information, please examine the LinkVar(3) manual page in the core Tcl distribution.

Adding New Math Functions to Tcl

As of Tcl version 7.0, math functions such as sin, cos, etc, are directly supported within Tcl expressions. These obsolete the Extended Tcl commands that provided explicit commands for these functions for many, many releases, although procs equivalencing the old TclX commands to the new math functions are still provided for backwards compatibility.

New math functions can be added to Tcl, or existing math functions can be replaced, by calling Tcl_CreateMathFunc.

Accessing and Manipulating the Random Number Generator

Prior to Tcl version 8.0, the Tcl core did not provide access to a random number generator, but TclX did, through its random command. As of Tcl version 8.0, access to a random number generator is provided by baseline Tcl through the new math functions, rand and srand.

The TclX random command is still available -- it has some useful capabilities not directly provided by the new baseline functions.

For more information on adding your own math functions to Tcl, please study the CrtMathFnc(3) manual page in the core Tcl distribution.

Converting Filenames to Native Form and Performing Tilde Substitutions

The Tcl_TranslateFileName function is available to C extension writers to translate filenames to a form suitable for use by the local operating system. It converts network names to their native form, and if the name starts with a ``~'' character, the function returns a new string where the name is replaced with the home directory of the given user.

For more information please consult the Translate(3) manual page in the core Tcl distribution.

Setting the Recursion Limit

Tcl has a preset recursion limit that limits the maximum allowable nesting depth of calls within an interpreter. This is useful for detecting infinite recursions before other limits such as the process memory limit or, worse, available swap space on the system, run out.

The default limit is just a guess, however, and applications that make heavy use of recursion may need to call Tcl_SetRecursionLimit to raise this limit. For more information, please consult the SetRecLmt(3) manual page in the core Tcl distribution.

Handling Signals from Tcl Extensions

If an event such as a signal occurs while a Tcl script is being executed, it isn't safe to do much in the signal handling routine -- the Tcl environment cannot be safely manipulated at this point because it could be in the middle of some operation, such as updating pointers, leaving the interpreter in an unreliable state.

The only safe approach is to set a flag indicating that the event occurred, then handle the event later when the interpreter has returned to a safe state, such as after the current Tcl command completes.

The Tcl_AsyncCreate, Tcl_AsyncMark, Tcl_AsyncInvoke, and Tcl_AsyncDelete functions provide a safe mechanism for dealing with signals and other asynchronous events. For more information on how to use this capability, please refer to the Async(3) manual page in the core Tcl distribution.

Note that Extended Tcl provides built-in support for managing signals in numerous ways, including generating them with alarm(2) and kill(2) , ignoring them, trapping them, getting, setting, blocking and unblocking them. You can cause specific code to execute at a safe point after a signal occurs, or cause a Tcl error backtrace on one's occurrence. For more information, please examine the TclX documentation.

Parsing Backslash Sequences

The Tcl_Backslash function is called to parse Tcl backslash sequences. These backslash sequences are the usual sort that you see in the C programming language, such as \n for newline, \r for return, and so forth. Tcl_Backslash parses a single backslash sequence and returns a single character corresponding to the backslash sequence.

For more info on this call, look at the Backslash(3) manual page in the core Tcl distribution. For information on the valid backslash sequences, consult the summary of Tcl language syntax, Tcl(n) in the same distribution.

Hash Tables

Hash tables provide Tcl with a high-performance facility for looking up and managing key-value pairs located and maintained in memory. Tcl uses hash tables internally to locate procedure definitions, Tcl variables, array elements, file handles and so forth. Tcl makes the hash table functions accessible to C extension writers as well.

Hash tables grow automatically to maintain efficiency, rather than exposing the table size to the programmer at allocation time, which would needlessly add complexity to Tcl and would be prone to inefficiency due to the need to guess the number of items that will go into the table, and the seemingly inevitable growth in amount of data processed per run over the useful life of the program.

For more information on hash tables, please consult the Hash(3) manual page in the core Tcl distribution.

Tracing Variable Accesses

The C extension writer can arrange to have a C routine called whenever a Tcl variable is read, written, or unset. Variable traces are the mechanism by which Tk toolkit widgets such as radio and checkbuttons, messages and so forth update without Tcl programmer intervention when their data variables are changed. They are also used by the routine that links Tcl and C variables, Tcl_LinkVar, described above.

Tcl_TraceVar is called to establish a variable trace. Entire arrays and individual array elements can be traced as well. If the programmer already has an array name in one string and a variable name in another, Tcl_TraceVar2 can be called. Calls are also available to request information about traces and to delete them.

For more information on variable traces, consult the TraceVar(3) manual page in the core Tcl distribution.

Tracing Tcl Execution

Tcl has the ability to call C routines each time it executes a Tcl command, up to a specified depth of nesting levels. The command Tcl_CreateTrace creates an execution trace; Tcl_DeleteTrace deletes it.

Command tracing is used in Extended Tcl to implement the cmdtrace Tcl command, a useful command for debugging Tcl applications.

For complete information on execution tracing, please look at the CrtTrace(3) manual pages in the core Tcl distribution.

Evaluating Tcl Expressions from C

Tcl_ExprLong, Tcl_ExprDouble, Tcl_ExprBool, and Tcl_ExprString all take string arguments and, when called, evaluate those strings as Tcl expressions. Depending on the routine called, the result is either a C long, a dou_ble, a boolean (int with a value of 0 or 1), or a char * (obtainable through Tcl_GetResult).

To take advantage of the performance gains available through the bytecode compiler, Tcl_ExprLongObj, Tcl_ExprDoubleObj, Tcl_ExprBoolObj, and Tcl_ExprObj all take an object containing an expression to be evaluated (rather than a string.) The result is that bytecode-compiled version of the expression will be kept in the object, alongside the string representation. If the expression is evaluated again, without being changed, it does not have to be recompiled... a major performance win.

For complete information on evaluating Tcl expressions from C, you are invited to examine the ExprLong(3) and ExprLongObj(3) manpages in the core Tcl distribution.

Pattern Matching

The Tcl_StringMatch function can be called to see if a string matches a specified pattern. Tcl_StringMatch is called by the Tcl string match command, so the format for patterns is identical. The pattern format is similar to the one used by the C-shell; string(n) describes this format.

More information about Tcl_StringMatch is available in the StrMatch(3) manpage in the core Tcl distribution.

Regular Expression Pattern Matching

Tcl_RegExpMatch can be called to determine whether a string matches a regular expression. Tcl_RegExpMatch is used internally by the regexp Tcl command.

As regular expressions are typically «compiled» before use, a fairly involved process, Tcl also supports routines that separate the compilation of an expression from its use: Tcl_RegExpCompile, Tcl_RegExpExec, and Tcl_RegExpRange. If an expression is going to be matched many times, doing the compile once and caching the compiled regular expression result, then reusing the cached version by using Tcl_RegExpExec, can be a significant performance win.

For more information on this function, please consult the RegExp(3) manpage in the core Tcl distribution.

Manipulating Tcl Lists from C Extensions

The C extension writer often needs to create, manipulate and decompose Tcl lists. Tcl_SplitList and Tcl_Merge used to be the only way to parse strings into lists and vice versa. As of Tcl 8, lists can be parsed and assembled, object-style, using Tcl_ListObjGetElements and Tcl_SetListObj, and friends. Once again the «win» of using objectsystem-based list manipulation, instead of the previous string based routines, is that the parsing of a string in an object to a list is cached in the object structure, the same as with integers and floating point numbers, compiled procedures, etc. The next time this string needs to be looked at as a list, if the contents of the string have not changed, the string does not have to be parsed.

In the author's experience, working with an admittedly degenerate test whereby we iterated rather inefficiently across a 6,000-element list, a speedup factor of more than 2500 was obtained over the previous non-object-based version of Tcl.

For more information on these commands, please consult the ListObj(3) manual page in the core Tcl distribution.

Concatenating Strings

Tcl_ConcatObj concatenates the string representation of zero or more objects into a single new object. The elements of the new string are space-separated. Tcl_Concat does the same thing for strings, as Tcl_ConcatObj does for objects.

Concatenating strings is similar to constructing lists from them, except that Tcl_ConcatObj and Tcl_Concat do not attempt to make the resulting string into a valid Tcl list.

Tcl_Concat is documented in the Concat(3) manpage, and Tcl_ConcatObj in the tringObj manpage, both in the core Tcl distribution.

Detecting Whether or Not You Have a Complete Command

C routines that collect data to form a command to be passed to Tcl_Eval often need a way to tell whether they have a complete command already or whether they need more data. (Programs that read typed-in Tcl input such as Tcl

shells need this capability, for instance.)
Tcl_CommandComplete can be used to tell whether or not you have a complete command.

For more information examine CmdCmplt(3) in the core Tcl distribution.

Recording Commands for Command History

Tcl has a history mechanism that is accessed from Tcl through the history command. If you want your extension to propagate commands into the command history, you should call Tcl_RecordAndEvalObj (object system) or Tcl_RecordAn_dEval (old system),

These commands work like Tcl_EvalObj and Tcl_Eval, respectively, except that these versions record the command as well as executing it.

Tcl_RecordAndEval and Tcl_RecordAndEvlObj should only be called with user-entered top-level commands, since the history mechanism exists to allow the user to easily access, edit and reissue previously issued commands.

For complete information on these functions, please examine the RecordEval.3 and RecEvalObj.3 manual pages in the core Tcl distribution.

Converting Floating Point Values to Strings

The Tcl object system's Tcl_GetDoubleFromObj and Tcl_SetDoubleObj use Tcl objects, rather than the strings used by Tcl_PrintDouble, and convert, when necessary, an ASCII string to a double and back again.

These routines ensure that the string output will continue to be interpretable as a floating point number, rather than an integer, by always putting a ``.'' or ``e'' into the string representing the number.

The precision of the output string is controlled by the Tcl tcl_precision variable.

For complete information on these routines, please examine DoubleObj(3) and PrintDbl(3) in the core Tcl distribution.

Creating Child Processes and Pipelines from C

Tcl_OpenCommandChannel provides a C-level interface to the exec and open commands. The child (or pipeline of children) can have its standard input, output and error redirected from files, variables or pipes. To understand the meaning of the redirection symbols understood by this function, look at the exec(n) Tcl command. For complete information on Tcl_OpenCommandChannel, please examine OpenFileChnl(3) .

Accessing Tcl Filehandles from C

On Posix/Unix systems, Tcl filehandles passed to your C extension can be translated to a Posix FILE * structure using the Tcl_GetOpenFile function, documented in GetOpnFl.3.

Managing Background Process Termination and Cleanup

When a Posix system does a fork to create a new process, the process ID of the child is returned to the caller. After the child process exits, its process table entry (and some other data associated with the process) cannot be reclaimed by the operating system until a call to wait_pid, or one of a couple of other, similar system calls, has been made by the parent process.

The C extension writer who has created a subprocess, by whatever mechanism, can turn over responsibility for detecting the processes' termination and calling waitpid to obtain its exit status, by calling Tcl_DetachPids on it.

Tcl_ReapDetachedProcs is the C routine that will detect the termination of any processes turned over to Tcl, permitting the processes to be fully reclaimed by the operating system. It is usually not necessary to call Tcl_ReapDetachedProcs, as it is called automatically every time exec is performed.

For complete information on these routines, please look at DetachPids(3) in the core Tcl distribution.

for More Information

In addition to the documentation referenced above, you can learn a lot by studying the source code of the commands added by Tcl, Tk and Extended Tcl, etc. The comp.lang.tcl Usenet newsgroup is read by hundreds of thousands of Tcl people. A number of Frequently Asked Questions (FAQs) about Tcl are posted there periodically. The newsgroup is a good place to ask questions (after you've made sure they're not already answered in the FAQ ;-)

Finally, if you have interactive Internet access, you can ftp to ftp://ftp.neosoft.com/pub/tcl, the site for contributed Tcl sources. This site contains quite a few extensions, applications, and so forth, including several object-oriented extension packages.

If you have access via the world-wide web, check out the Sun Microsystems site (http://sunscript.sun.com), the contributed sources archive website (http://www.neosoft.com/tcl), and the homepage for Extended Tcl (http://www.neosoft.com/tclx).

Authors

Extended Tcl was created by Karl Lehenbauer (karl@neosoft.com) and Mark Diekhans (markd@grizzly.com).

Table of Contents

  • Name
  • Overview
  • Tcl Object System
  • a Simple C Extension
  • Interpreters
  • Object Count and Arguments
  • Returning Results
  • Validating Arguments
  • Another C Extension - the Max Command
  • Returning Results
  • Another C Extension - the Lreverse Command
  • Installing Your Command
  • Dynamic Strings
  • Client Data
  • Theory of Handles
  • Using Commands to Do the Same Thing, and More
  • Tracking Memory Corruption Problems
  • Installing Your Extensions into Tcl
  • GNU Autoconf
  • Making Application Information Visible from Extended Tcl
  • Extended Tcl Exit
  • Executing Tcl Code from Your C Extension
  • Accessing Tcl Variables and Arrays from Your C Extensions
  • Linking Tcl Variables to C Variables
  • Adding New Math Functions to Tcl
  • Accessing and Manipulating the Random Number Generator
  • Converting Filenames to Native Form and Performing Tilde Substitutions
  • Setting the Recursion Limit
  • Handling Signals from Tcl Extensions
  • Parsing Backslash Sequences
  • Hash Tables
  • Tracing Variable Accesses
  • Tracing Tcl Execution
  • Evaluating Tcl Expressions from C
  • Pattern Matching
  • Regular Expression Pattern Matching
  • Manipulating Tcl Lists from C Extensions
  • Concatenating Strings
  • Detecting Whether or Not You Have a Complete Command
  • Recording Commands for Command History
  • Converting Floating Point Values to Strings
  • Creating Child Processes and Pipelines from C
  • Accessing Tcl Filehandles from C
  • Managing Background Process Termination and Cleanup
  • for More Information
  • Authors


man page(1)

 Table of Contents

_________________________________________________________________

Name

table - Create and manipulate tables

Synopsis

table pathName ?options?

Standard Options

-anchor
-background -cursor
-exportselection
-font -foreground
-highlightbackground
-highlightcolor -highlightthickness
-insertbackground
-insertborderwidth-insertofftime -insertontime -insertwidth -invertselected
-relief
-takefocus -xscrollcommand -yscrollcommand

See the options manual entry for details on the standard options.

Widget-specific Options

Command-Line Name:-autoclear
Database Name: autoClear
Database Class: AutoClear

A boolean value which specifies whether the first keypress in a cell will delete whatever text was previously there. Defaults to 0.

Command-Line Name:-bordercursor
Database Name: borderCursor
Database Class: Cursor

Specifies the name of the cursor to show when over borders, a visual indication that interactive resizing is allowed (it is thus affect by the value of -resizeborders). Defaults to crosshair.

Command-Line Name:-borderwidth or -bd
Database Name: borderWidth
Database Class: BorderWidth

Specifies a non-negative pixel value or list of values indicating the width of the 3-D border to draw on interior table cells (if such a border is being drawn; the relief option typically determines this). If one value is specified, a rectangle of this width will be drawn. If two values are specified, then only the left and right edges of the cell will have borders. If four values are specified, then the values correspond to the {left right top bottom} edges. This can be overridden by the a tag's borderwidth option. It can also be affected by the defined -drawmode for the table. Each value in the list must have one of the forms acceptable to Tk_GetPixels.

Command-Line Name:-browsecommand or -browsecmd Database Name: browseCommand
Database Class: BrowseCommand

Specifies a command which will be evaluated anytime the active cell changes. It uses the %-substition model described in COMMAND SUBSTITUTION below.

Command-Line Name:-cache
Database Name: cache
Database Class: Cache

A boolean value that specifies whether an internal cache of the table contents should be kept. This greatly enhances speed performance when used with -command but uses extra memory. Can maintain state when both -command and -variable are empty. The cache is automatically flushed whenever the value of -cache or -variable changes, otherwise you have to explicitly call clear on it. Defaults to off.

Command-Line Name:-colorigin
Database Name: colOrigin
Database Class: Origin

Specifies what column index to interpret as the leftmost column in the table. This value is used for user indices in the table. Defaults to 0.

Command-Line Name:-cols
Database Name: cols
Database Class: Cols

Number of cols in the table. Defaults to 10.

Command-Line Name:-colseparator
Database Name: colSeparator
Database Class: Separator

Specifies a separator character that will be interpreted as the column separator when cutting or pasting data in a table. By default, columns are separated as elements of a tcl list.

Command-Line Name:-colstretchmode
Database Name: colStretchMode
Database Class: StretchMode

Specifies one of the following stretch modes for columns to fill extra allocated window space: none Columns will not stretch to fill the assigned window space. If the columns are too narrow, there will be a blank space at the right of the table. This is the default.

unset Only columns that do not have a specific width set will be stretched.

all
All columns will be stretched by the same number of pixels to fill the window space allocated to the table. This mode can interfere with interactive border resizing which tries to force column width.

last The last column will be stretched to fill the window space allocated to the table.

fill (only valid for -rowstretch currently) The table will get more or less columns according to the window space allocated to the table. This mode has numerous quirks and may disappear in the future.

Command-Line Name:-coltagcommand
Database Name: colTagCommand
Database Class: TagCommand

Provides the name of a procedure that will be evaluated by the widget to determine the tag to be used for a given column. When displaying a cell, the table widget will first check to see if a tag has been defined using the tag col widget method. If no tag is found, it will evaluate the named procedure passing the column number in question as the sole argument. The procedure is expected to return the name of a tag to use, or a null string. Errors occuring during the evaluation of the procedure, or the return of an invalid tag name are silently ignored.

Command-Line Name:-colwidth
Database Name: colWidth
Database Class: ColWidth

Default column width, interpreted as characters in the default font when the number is positive, or pixels if it is negative. Defaults to 10.

Command-Line Name:-command
Database Name: command
Database Class: Command

Specified a command to use as a procedural interface to cell values. If -usecommand is true, this command will be used instead of any reference to the -variable array. When retrieving cell values, the return value of the command is used as the value for the cell. It uses the %-substition model described in COMMAND SUBSTITUTION below.

Command-Line Name:-drawmode
Database Name: drawMode
Database Class: DrawMode

Sets the table drawing mode to one of the following options:

slow The table is drawn to an offscreen pixmap using the Tk bordering functions (doublebuffering). This means there will be no flashing, but this mode is slow for larger tables.

compatible
The table is drawn directly to the screen using the Tk border functions. It is faster, but the screen may flash on update. This is the default.

fast The table is drawn directly to the screen and the borders are done with fast X calls, so they are always one pixel wide only. As a side effect, it restricts -borderwidth to a range of 0 or 1. This mode provides best performance for large tables, but can flash on redraw and is not 100% Tk compatible on the border mode.

single The table is drawn to the screen as in fast mode, but only single pixel lines are drawn (not square borders).

Command-Line Name:-flashmode
Database Name: flashMode
Database Class: FlashMode

A boolean value which specifies whether cells should flash when their value changes. The table tag flash will be applied to these cells for the duration specified by -flashtime. Defaults to 0.

Command-Line Name:-flashtime
Database Name: flashTime
Database Class: FlashTime

The amount of time, in 1/4 second increments, for which a cell should flash when its value has changed. -flashmode must be on. Defaults to 2.

Command-Line Name:-height
Database Name: height
Database Class: Height

Specifies the desired height for the window, in rows. If zero or less, then the desired height for the window is made just large enough to hold all the rows in the table. The height can be further limited by -maxheight.

Command-Line Name:-invertselected
Database Name: invertSelected
Database Class: InvertSelected

Specifies whether the foreground and background of an item should simply have their values swapped instead of merging the sel tag options when the cell is selected. Defaults to 0 (merge sel tag).

Command-Line Name:-ipadx
Database Name: ipadX
Database Class: Pad

A pixel value specifying the internal offset X padding for text in a cell. This value does not grow the size of the cell, it just causes the text to be drawn further from the cell border. It only affects one side (depending on anchor). Defaults to 0. See -padx for an alternate padding style.

Command-Line Name:-ipady
Database Name: ipadY
Database Class: Pad

A pixel value specifying the internal offset Y padding for text in a cell. This value does not grow the size of the cell, it just causes the text to be drawn further from the cell border. It only affects one side (depending on anchor). Defaults to 0. See -pady for an alternate padding style.

Command-Line Name:-maxheight
Database Name: maxHeight
Database Class: MaxHeight

The max height in pixels that the window will request. Defaults to 600.

Command-Line Name:-maxwidth
Database Name: maxWidth
Database Class: MaxWidth

The max width in pixels that the window will request. Defaults to 800.

Command-Line Name:-multiline
Database Name: multiline
Database Class: Multiline

Specifies the default setting for the multiline tag option. Defaults to 1.

Command-Line Name:-padx
Database Name: padX
Database Class: Pad

A pixel value specifying the offset X padding for a cell. This value causes the default size of the cell to increase by two times the value (one for each side), unless a specific pixel size is chosen for the cell with the width command. This will force an empty area on the left and right of each cell edge. This padding affects all types of data in the cell. Defaults to 0. See -ipadx for an alternate padding style.

Command-Line Name:-pady
Database Name: padY
Database Class: Pad

A pixel value specifying the offset Y padding for a cell. This value causes the default size of the cell to increase by two times the value (one for each side), unless a specific pixel size is chosen for the cell with the height command. This will force an empty area on the top and bottom of each cell edge. This padding affects all types of data in the cell. Defaults to 0. See -ipadx for an alternate padding style.

Command-Line Name:-resizeborders
Database Name: resizeBorders
Database Class: ResizeBorders

Specifies what kind of interactive border resizing to allow, must be one of row, col, both (default) or none.

Command-Line Name:-rowheight
Database Name: rowHeight
Database Class: RowHeight

Default row height, interpreted as lines in the default font when the number is positive, or pixels if it is negative. Defaults to 1.

Command-Line Name:-roworigin
Database Name: rowOrigin
Database Class: Origin

Specifies what row index to interpret as the topmost row in the table. This value is used for user indices in the table. Defaults to 0.

Command-Line Name:-rows
Database Name: rows
Database Class: Rows

Number of rows in the table. Defaults to 10.

Command-Line Name:-rowseparator
Database Name: rowSeparator
Database Class: Separator

Specifies a separator character that will be interpreted as the row separator when cutting or pasting data in a table. By default, rows are separated as tcl lists.

Command-Line Name:-rowstretchmode
Database Name: rowStretchMode
Database Class: StretchMode

Specifies the stretch modes for rows to fill extra allocated window space. See -colstretchmode for valid options.

Command-Line Name:-rowtagcommand
Database Name: rowTagCommand
Database Class: TagCommand

Provides the name of a procedure that can evaluated by the widget to determine the tag to be used for a given row. The procedure must be defined by the user to accept a single argument (the row number), and return a tag name or null string. This operates in a similar manner as -coltagcommand, except that it applies to row tags.

Command-Line Name:-selectioncommand or -selcmd Database Name: selectionCommand
Database Class: SelectionCommand

Specifies a command to evaluate when the selection is retrieved from a table via the selection mechanism (ie: evaluating «selection get"). The return value from this command will become the string passed on by the selection mechanism. It uses the %-substition model described in COMMAND SUBSTITUTION below. If an error occurs, a Tcl background error is generated and nothing is returned.

Command-Line Name:-selectmode
Database Name: selectMode
Database Class: SelectMode

Specifies one of several styles for manipulating the selection. The value of the option may be arbitrary, but the default bindings expect it to be either single, browse, multiple, or extended; the default value is browse. These styles are like those for the Tk listbox, except expanded for 2 dimensions.

Command-Line Name:-selecttitle
Database Name: selectTitles
Database Class: SelectTitles

Specifies whether title cells should be allowed in the selection. Defaults to 0 (disallowed).

Command-Line Name:-selecttype
Database Name: selectType
Database Class: SelectType

Specifies one of several types of selection for the table. The value of the option may be one of row, col, cell, or both (meaning row && col); the default value is cell. These types define whether an entire row/col is affected when a cell's selection is changed (set or clear).

Command-Line Name:-sparsearray
Database Name: sparseArray
Database Class: SparseArray

A boolean value that specifies whether an associated Tcl array should be kept as a sparse array (1, the default) or as a full array (0). If true, then cell values that are empty will be deleted from the array (taking less memory). If false, then all values in the array will be maintained.

Command-Line Name:-state
Database Name: state
Database Class: State

Specifies one of two states for the entry:
normal or disabled. If the table is disabled then the value may not be changed using widget commands and no insertion cursor will be displayed, even if the input focus is in the widget. Also, all insert or delete methods will be ignored. Defaults to normal.

Command-Line Name:-titlecols
Database Name: titleCols
Database Class: TitleCols

Number of columns to use as a title area. Defaults to 0.

Command-Line Name:-titlerows
Database Name: titleRows
Database Class: TitleRows

Number of rows to use as a title area. Defaults to 0.

Command-Line Name:-usecommand
Database Name: useCommand
Database Class: UseCommand

A boolean value which specifies whether to use the command option. This value sets itself to zero if command is used and returns an error. Defaults to 1 (will use command if specified).

Command-Line Name:-validate
Database Name: validate
Database Class: Validate

A boolean specifying whether validation should occur for the active buffer. Defaults to 0.

Command-Line Name:-validatecommand or -vcmd Database Name: validateCommand
Database Class: ValidateCommand

Specifies a command to execute when the active cell is edited. This command is expected to return a Tcl boolean. If it returns true, then it is assumed the new value is OK, otherwise the new value is rejected (the edition will not take place). Errors in this command are handled in the background. It uses the %-substition model described in COMMAND SUBSTITUTION below.

Command-Line Name:-variable
Database Name: variable
Database Class: Variable

Global Tcl array variable to attach to the table's C array. It will be created if it doesn't already exist or is a simple variable. Keys used by the table in the array are of the form row,col for cells and the special key active which contains the value of the active cell buffer. The Tcl array is managed as a sparse array (the table doesn't require all valid indices have values). No stored value for an index is equivalent to the empty string, and clearing a cell will remove that index from the Tcl array, unless the -sparsearray options is set to 0.

Command-Line Name:-width
Database Name: width
Database Class: Width

Specifies the desired width for the window, in columns. If zero or less, then the desired width for the window is made just large enough to hold all the columns in the table. The width can be further limited by -maxwidth.

Command-Line Name:-wrap
Database Name: wrap
Database Class: Wrap

Specifies the default wrap value for tags. Defaults to 0.
_________________________________________________________________

Description

The table command creates a 2-dimensional grid of cells. The table can use a Tcl array variable or Tcl command for data storage and retrieval. The widget has an active cell, the contents of which can be edited (when the state is normal). The widget supports a default style for the cells and also multiple tags, which can be used to change the style of a row, column or cell (see TAGS for details). A cell flash can be set up so that changed cells will change color for a specified amount of time ("blink"). Cells can have embedded images or windows, as described in TAGS and «EMBEDDED WINDOWS» respectively.

One or more cells may be selected as described below. If a table is exporting its selection (see -exportselection option), then it will observe the standard X11 protocols for handling the selection. See THE SELECTION for details.

It is not necessary for all the cells to be displayed in the table window at once; commands described below may be used to change the view in the window. Tables allow scrolling in both directions using the standard -xscrollcommand and -yscrollcommand options. They also support scanning, as described below.

In order to obtain good performance, the table widget supports multiple drawing modes, two of which are fully Tk compatible.

Initialization

When the table command is loaded into an interpreter, a built-in Tcl command, tkTableInit, is evaluated. This will search for the appropriate table binding init file to load. The directories searched are those in $tcl_pkgPath, both with Tktable(version) appended and without, $tk_library and [pwd] (the current directory). You can also define an $env(TK_TABLE_LIBRARY) to head this search list. By default, the file searched for is called tkTable.tcl, but this can be overridden by setting $env(TK_TABLE_LIBRARY_FILE).

This entire init script can be overridden by providing your own tkTableInit procedure before the library is loaded. Otherwise, the aforementioned env(TK_TABLE_LIBRARY) variable will be set with the directory in which $env(TK_TABLE_LIBRARY_FILE) was found.

Indices

Many of the widget commands for tables take one or more indices as arguments. An index specifies a particular cell of the table, in any of the following ways:

number,number
Specifies the cell as a numerical index of row,col which corresponds to the index of the associated Tcl array, where -roworigin,-colorigin corresponds to the first cell in the table (0,0 by default).

active
Indicates the cell that has the location cursor. It is specified with the activate widget command.
anchor
Indicates the anchor point for the selection, which is set with the selection anchor widget command.

bottomright Indicates the bottom-rightmost cell visible in the table.

end
Indicates the bottom right cell of the table.
origin
Indicates the top-leftmost editable cell of the table, not necessarily in the display. This takes into account the user specified origin and title area.
topleft
Indicates the top-leftmost editable cell visible in the table (this excludes title cells).
@x,y
Indicates the cell that covers the point in the table window specified by x and y (in pixel coordinates). If no cell covers that point, then the closest cell to that point is used.

In the widget command descriptions below, arguments named index, first, and last always contain text indices in one of the above forms.

Tags

A tag is a textual string that is associated with zero or more rows, columns or cells in a table. Tags may contain arbitrary characters, but it is probably best to avoid using names which look like indices to reduce coding confusion. There may be any number of tags in a table, but each row, column or cell can only have one tag associated with it at a time. There are several permanent tags in each table that can be configured by the user and will determine the attributes for special cells:

active
This tag is given to the active cell
flash
If flash mode is on, this tag is given to any recently edited cells.
sel
This tag is given to any selected cells.
title
This tag is given to any cells in the title rows and columns. This tag has -state disabled by default.

Tags control the way cells are displayed on the screen. Where appropriate, the default for displaying cells is determined by the options for the table widget. However, display options may be associated with individual tags using the ``pathName tag configure'' widget command. If a cell, row or column has been tagged, then the display options associated with the tag override the default display style. The following options are currently supported for tags:

-anchor anchor
Anchor for item in the cell space.
-background or -bg color
Background color of the cell.
-borderwidth or -bd pixelList
Borderwidth of the cell, of the same format for the table, but may also be empty to inherit the default table borderwidth value (the default).
-font fontName
Font for text in the cell.
-foreground or -fg color
Foreground color of the cell.
-justify justify
How to justify multi-line text in a cell. It must be one of left, right, or center.
-image imageName
An image to display in the cell instead of text.
-multiline boolean
Whether to display text with newlines on multiple lines.
-relief relief
The relief for the cell.
-showtext boolean
Whether to show the text over an image.
-state state
The state of the cell, to allow for certain cells to be disabled. This prevents the cell from being edited by the insert or delete methods, but a direct set will not be prevented.
-wrap boolean
Whether characters should wrap in a cell that is not wide enough.

A priority order is defined among tags based on creation order (first created tag has highest default priority), and this order is used in implementing some of the tag-related functions described below. When a cell is displayed, its properties are determined by the tags which are assigned to it. The priority of a tag can be modified by the ``pathName tag lower'' and ``pathName tag raise'' widget commands.

If a cell has several tags associated with it that define the same display options (eg - a title cell with specific row and cell tags), then the options of the highest priority tag are used. If a particular display option hasn't been specified for a particular tag, or if it is specified as an empty string, then that option will not be used; the next-highest-priority tag's option will be used instead. If no tag specifies a particular display option, then the default style for the widget will be used.

Images are used for display purposes only. Editing in that cell will still be enabled and any querying of the cell will show the text value of the cell, regardless of the value of -showtext.

Embedded Windows

There may be any number of embedded windows in a table widget (one per cell), and any widget may be used as an embedded window (subject to the usual rules for geometry management, which require the table window to be the parent of the embedded window or a descendant of its parent). The embedded window's position on the screen will be updated as the table is modified or scrolled, and it will be mapped and unmapped as it moves into and out of the visible area of the table widget. Each embedded window occupies one cell's worth of space in the table widget, and it is referred to by the index of the cell in the table. Windows associated with the table widget are destroyed when the table widget is destroyed.

Windows are used for display purposes only. A value still exists for that cell, but will not be shown unless the window is deleted in some way. If the window is destroyed or lost by the table widget to another geometry manager, then any data associated with it is lost (the cell it occupied will no longer appear in window names).

When an embedded window is added to a table widget with the window configure widget command, several configuration options may be associated with it. These options may be modified with later calls to the window configure widget command. The following options are currently supported:

-create script
NOT CURRENTLY SUPPORTED. Specifies a Tcl script that may be evaluated to create the window for the annotation. If no -window option has been specified for this cell then this script will be evaluated when the cell is about to be displayed on the screen. Script must create a window for the cell and return the name of that window as its result. If the cell's window should ever be deleted, the script will be evaluated again the next time the cell is displayed.
-background or -bg color
Background color of the cell. If not specified, it uses the table's default background.
-borderwidth or -bd pixelList
Borderwidth of the cell, of the same format for the table, but may also be empty to inherit the default table borderwidth value (the default).
-padx pixels
As defined in the Tk options man page.
-pady pixels
As defined in the Tk options man page.
-relief relief
The relief to use for the cell in which the window lies. If not specified, it uses the table's default relief.
-sticky sticky
Stickiness of the window inside the cell, as defined by the grid command.
-window pathName
Specifies the name of a window to display in the annotation. It must exist before being specified here.

the Selection

Table selections are available as type STRING. By default, the value of the selection will be the values of the selected cells in nested Tcl list form where each row is a list and each column is an element of a row list. You can change the way this value is interpreted by setting the -rowseparator and -colseparator options. For example, default Excel format would be to set -rowseparator to «\n» and -colseparator to «\t". Changing these values affects both how the table sends out the selection and reads in pasted data, ensuring that the table should always be able to cut and paste to itself. It is possible to change how pastes are handled by editing the table library procedure tk_tablePasteHandler. This might be necessary if -selectioncommand is set.

Row/Col Spanning

Individual cells can span multiple rows and/or columns. This is done via the spans command (see below for exact arguments). Cells in the title area that span are not permitted to span beyond the title area, and will be constrained accordingly. If the title area shrinks during a configure, sanity checking will occur to ensure the above. You may set spans on regular cells that extend beyond the defined row/col area. These spans will not be constrained, so that when the defined row/col area expands, the span will expand with it.

When setting a span, checks are made as to whether the span would overlap an already spanning or hidden cell. This is an error and it not allowed. Spans can affect the overall speed of table drawing, although not significantly. If spans are not used, then there is no performance loss.

Cells hidden by spanning cells still have valid data. This will be seen during cut and paste operations that involve hidden cells, or through direct access by a command like get or set.

The drawing properties of spanning cells apply to only the visual area of the cell. For example, if a cell is center justified over 5 columns, then when viewing any portion of those columns, it will appear centered in the visible area. The non-visible column area will not be considered in the centering calculations.

Command Substitution

The various option based commands that the table supports all support the familiar Tk %-substitution model (see bind for more details). The following %-sequences are recognized and substituted by the table widget:

%c For SelectionCommand, it is the maximum number of columns in any row in the selection. Otherwise it is the column of the triggered cell.

%C
A convenience substitution for %r,%c.
%i
For SelectionCommand, it is the total number of cells in the selection. For Command, it is 0 for a read (get) and 1 for a write (set). Otherwise it is the current cursor position in the cell.
%r
For SelectionCommand, it is the number of rows in the selection. Otherwise it is the row of the triggered cell.

%s For ValidateCommand, it is the current value of the cell being validated. For SelectionCommand, it is the default value of the selection. For BrowseCommand, it is the index of the last active cell. For Command, it is empty for reads (get) and the current value of the cell for writes (set).

%S
For ValidateCommand, it is the potential new value of the cell being validated. For BrowseCommand, it is the index of the new active cell.

%W The pathname to the window for which the command was generated.

Widget Command

The table command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command.

The following commands are possible for table widgets:

pathName activate index
Sets the active cell to the one indicated by index.

pathName bbox first ?last?
It returns the bounding box for the specified cell (range) as a 4-tuple of x, y, width and height in pixels. It clips the box to the visible portion, if any, otherwise an empty string is returned.

pathName border option args
This command is a voodoo hack to implement border sizing for tables. This is normally called through bindings, with the following as valid options:

pathName border mark x y ?row|col? Records x and y and the row and/or column border under that point in the table window, if any; used in conjunction with later border dragto commands. Typically this command is associated with a mouse button press in the widget. If row or col is not specified, it returns a tuple of both border indices (an empty item means no border). Otherwise, just the specified item is returned.

pathName border dragto x y
This command computes the difference between its x and y arguments and the x and y arguments to the last border mark command for the widget. It then adjusts the previously marked border by the difference. This command is typically associated with mouse motion events in the widget, to produce the effect of interactive border resizing.

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the table command.

pathName clear option ?first? ?last?
This command is a convenience routine to clear certain state information managed by the table. first and last represent valid table indices. If neither are specified, then the command operates on the whole table. The following options are recognized:

pathName clear cache ?first? ?last? Clears the specified section of the cache, if the table has been keeping one.

pathName clear sizes ?first? ?last? Clears the specified row and column areas of specific height/width dimensions. When just one index is specified, for example 2,0, that is interpreted as row 2 and column 0.

pathName clear tags ?first? ?last? Clears the specified area of tags (all row, column and cell tags).

pathName clear all ?first? ?last? Performs all of the above clear functions on the specified area.

pathName configure ?option? ?value option value ...? Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for path_N ame (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the table command.

pathName curselection ?value?
With no arguments, it returns the sorted indices of the currently selected cells. Otherwise it sets all the selected cells to the given value. The set has no effect if there is no associated Tcl array or the state is disabled.

pathName curvalue ?value?
If no value is given, the value of the cell being edited (indexed by active) is returned, else it is set to the given value.

pathName delete option arg ?arg?
This command is used to delete various things in a table. It has several forms, depending on the option: pathName delete active index ?index? Deletes text from the active cell. If only one index is given, it deletes the character after that index, otherwise it deletes from the first index to the second. index can be a number, insert or end.

pathName delete cols ?switches? index ?count? Deletes count cols starting at (and including) col index. The index will be constrained to the limits of the tables. If count is negative, it deletes cols to the left. Otherwise it deletes cols to the right. count defaults to 1 (meaning just the column specified). At the moment, spans are not adjusted with this action. Optional switches are:

-holddimensions
Causes the table cols to be unaffected by the deletion (empty cols may appear). By default the dimensions are adjusted by count.
-holdselection
Causes the selection to be maintained on the absolute cells values. Otherwise, the selection will be cleared..
-holdtags
Causes the tags specified by the tag method to not move along with the data. Also prevents specific widths set by the width method from being adjusted. By default, these tags are properly adjusted.
-holdwindows
Causes the embedded windows created with the window method to not move along with the data. By default, these windows are properly adjusted.
-keeptitles
Prevents title area cells from being changed. Otherwise they are treated just like regular cells and will move as specified.
--
Signifies the end of the switches.

pathName delete rows ?switches? index ?count? Deletes count rows starting at (and including) row index. If count is negative, it deletes rows going up. Otherwise it deletes rows going down. The selection will be cleared. The switches are the same as those for column deletion.

pathName get first ?last?
Returns the value of the cells specified by the table indices first and (optionally) last in a list.

pathName height ?row? ?value row value ...? If no row is specified, returns a list describing all rows for which a height has been set. If row is specified with no value, it prints out the height of that row in characters (positive number) or pixels (negative number). If one or more row-value pairs are specified, then it sets each row to be that height in lines (positive number) or pixels (negative number). If value is default, then the row uses the default height, specified by -rowheight.

pathName hidden ?index? ?index ...?
When called without args, it returns all the hidden cells (those cells covered by a spanning cell). If one index is specified, it returns the spanning cell covering that index, if any. If multiple indices are specified, it returns 1 if all indices are hidden cells, 0 otherwise.

pathName icursor ?arg?
With no arguments, prints out the location of the insertion cursor in the active cell. With one argument, sets the cursor to that point in the string. 0 is before the first character, you can also use insert or end for the current insertion point or the end of the text. If there is no active cell, or the cell or table is disabled, this will return -1.

pathName index index ?row|col?
Returns the integer cell coordinate that corresponds to index in the form row,col. If row or col is specified, then only the row or column index is returned.

pathName insert option arg arg
This command is used to into various things into a table. It has several forms, depending on the option:

pathName insert active index value The value is a text string which is inserted at the index postion of the active cell. The cursor is then positioned after the new text. index can be a number, insert or end.

pathName insert cols ?switches? index ?count? Inserts count cols starting at col index. If count is negative, it inserts before the specified col. Otherwise it inserts after the specified col. The selection will be cleared. The switches are the same as those for column deletion.

pathName insert rows ?switches? index ?count? Inserts count rows starting at row index. If count is negative, it inserts before the specified row. Otherwise it inserts after the specified row. The selection will be cleared. The switches are the same as those for column deletion.

pathName reread
Rereads the old contents of the cell back into the editing buffer. Useful for a key binding when <Escape> is pressed to abort the edit (a default binding).

pathName scan option args
This command is used to implement scanning on tables. It has two forms, depending on option:

pathName scan mark x y
Records x and y and the current view in the table window; used in conjunction with later scan dragto commands. Typically this command is associated with a mouse button press in the widget. It returns an empty string.

pathName scan dragto x y.
This command computes the difference between its x and y arguments and the x and y arguments to the last scan mark command for the widget. It then adjusts the view by 5 times the difference in coordinates. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the list at high speed through the window. The return value is an empty string.

pathName see index
Adjust the view in the table so that the cell given by index is positioned as the cell one off from top left (excluding title rows and columns) if the cell is not currently visible on the screen. The actual cell may be different to keep the screen full.

pathName selection option arg
This command is used to adjust the selection within a table. It has several forms, depending on option:

pathName selection anchor index
Sets the selection anchor to the cell given by index. The selection anchor is the end of the selection that is fixed while dragging out a selection with the mouse. The index anchor may be used to refer to the anchor cell.

pathName selection clear first ?last? If any of the cells between first and last (inclusive) are selected, they are deselected. The selection state is not changed for cells outside this range. first may be specified as all to remove the selection from all cells.

pathName selection includes index Returns 1 if the cell indicated by index is currently selected, 0 if it isn't.

pathName selection set first ?last? Selects all of the cells in the range between first and last, inclusive, without affecting the selection state of cells outside that range.

pathName set ?row|col? index ?value? ?index value ...? Sets the specified index to the associated value. Table validation will not be triggered via this method. If row or col precedes the list of index/value pairs, then the value is assumed to be a Tcl list whose values will be split and set into the subsequent columns (if row is specified) or rows (for col). For example, set row 2,3 {2,3 2,4 2,5} will set 3 cells, from 2,3 to 2,5. The setting of cells is silently bounded by the known table dimensions.

pathName spans ?index? ?rows,cols index rows,cols ...? This command is used to manipulate row/col spans. When called with no arguments, all known spans are returned as a list of tuples of the form {index span}. When called with only the index, the span for that index only is returned, if any. Otherwise an even number of index rows,cols pairs are used to set spans. A span starts at the index and continues for the specified number of rows and cols. Negative spans are not supported. A span of 0,0 unsets any span on that cell. See EXAMPLES for more info.

pathName tag option ?arg arg ...?
This command is used to manipulate tags. The exact behavior of the command depends on the option argument that follows the tag argument. cget, cell, and row|col complain about unknown tag names. The following forms of the command are currently supported:

pathName tag cell tagName ?index ...? With no arguments, prints out the list of cells that use the tag. Otherwise it sets the specified cells to use the named tag, replacing any tag that may have been set using this method before. If tagName is {}, the cells are reset to the default tag. Tags added during -*tagcommand evaluation do not register here. If tagName does not exist, it will be created with the default options.

pathName tag cget tagName option This command returns the current value of the option named option associated with the tag given by tagName. Option may have any of the values accepted by the tag configure widget command.

pathName tag col tagName ?col ...? With no arguments, prints out the list of cols that use the tag. Otherwise it sets the specified columns to use the named tag, replacing any tag that may have been set using this method before. If tagName is {}, the cols are reset to the default tag. Tags added during -coltagcommand evaluation do not register here. If tagName does not exist, it will be created with the default options.

pathName tag configure tagName ?option? ?value? ?option value ...?
This command is similar to the configure widget command except that it modifies options associated with the tag given by tagName instead of modifying options for the overall table widget. If no option is specified, the command returns a list describing all of the available options for tagName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s) in tagName; in this case the command returns an empty string. See TAGS above for details on the options available for tags.

pathName tag delete tagName
Deletes a tag. No error if the tag does not exist.

pathName tag exists tagName
Returns 1 if the named tag exists, 0 otherwise.

pathName tag includes tagName index Returns 1 if the specified index has the named tag, 0 otherwise.

pathName tag lower tagName ?belowThis? Lower the priority of the named tag. If belowThis is not specified, then the tag's priority is lowered to the bottom, otherwise it is lowered to one below belowThis.

pathName tag names ?pattern?
If no pattern is specified, shows the names of all defined tags. Otherwise the pattern is used as a glob pattern to show only tags matching that pattern. Tag names are returned in priority order (highest priority tag first).

pathName tag raise tagName ?aboveThis? Raise the priority of the named tag. If aboveThis is not specified, then the tag's priority is raised to the top, otherwise it is raised to one above aboveThis.

pathName tag row tagName ?row ...? With no arguments, prints out the list of rows that use the tag. Otherwise it sets the specified columns to use the named tag, replacing any tag that may have been set using this method before. If tagName is {}, the rows are reset to use the default tag. Tags added during -rowtagcommand evaluation do not register here. If tagName does not exist, it will be created with the default options.

pathName validate index
Explicitly validates the specified index based on the current -validatecommand and returns 0 or 1 based on whether the cell was validated.

pathName width ?col? ?value col value ...? If no col is specified, returns a list describing all cols for which a width has been set. If col is specified with no value, it prints out the width of that col in characters (positive number) or pixels (negative number). If one or more col-value pairs are specified, then it sets each col to be that width in characters (positive number) or pixels (negative number). If value is default, then the col uses the default width, specified by -colwidth.

pathName window option ?arg arg ...?
This command is used to manipulate embedded windows. The exact behavior of the command depends on the option argument that follows the window argument. The following forms of the command are currently supported:

pathName window cget index option This command returns the current value of the option named option associated with the window given by index. Option may have any of the values accepted by the window configure widget command.

pathName window configure index ?option? ?value? ?option value ...?
This command is similar to the configure widget command except that it modifies options associated with the embedded window given by index instead of modifying options for the overall table widget. If no option is specified, the command returns a list describing all of the available options for index (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s) in index; in this case the command returns an empty string. See EMBEDDED WINDOWS above for details on the options available for windows.

pathName window delete index ?index ...? Deletes an embedded window from the table. The associated window will also be deleted.

pathName window move indexFrom indexTo Moves an embedded window from one cell to another. If a window already exists in the target cell, it will be deleted.

pathName window names ?pattern?
If no pattern is specified, shows the cells of all embedded windows. Otherwise the pat_tern is used as a glob pattern to show only cells matching that pattern.

pathName xview args
This command is used to query and change the horizontal position of the information in the widget's window. It can take any of the following forms:

pathName xview
Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the horizontal span that is visible in the window. For example, if the first element is .2 and the second element is .6, 20% of the table's text is off-screen to the left, the middle 40% is visible in the window, and 40% of the text is off-screen to the right. These are the same values passed to scrollbars via the -xscrollcommand option.

pathName xview index
Adjusts the view in the window so that the column given by index is displayed at the left edge of the window.

pathName xview moveto fraction
Adjusts the view in the window so that frac_tion of the total width of the table text is off-screen to the left. fraction must be a fraction between 0 and 1.

pathName xview scroll number what This command shifts the view in the window left or right according to number and what. Number must be an integer. What must be either units or pages or an abbreviation of one of these. If what is units, the view adjusts left or right by number character units (the width of the 0 character) on the display; if it is pages then the view adjusts by number screenfuls. If number is negative then characters farther to the left become visible; if it is positive then characters farther to the right become visible.

pathName yview ?args?
This command is used to query and change the vertical position of the text in the widget's window. It can take any of the following forms:

pathName yview
Returns a list containing two elements, both of which are real fractions between 0 and 1. The first element gives the position of the table element at the top of the window, relative to the table as a whole (0.5 means it is halfway through the table, for example). The second element gives the position of the table element just after the last one in the window, relative to the table as a whole. These are the same values passed to scrollbars via the -yscrollcommand option.

pathName yview index
Adjusts the view in the window so that the row given by index is displayed at the top of the window.

pathName yview moveto fraction
Adjusts the view in the window so that the element given by fraction appears at the top of the window. Fraction is a fraction between 0 and 1; 0 indicates the first element in the table, 0.33 indicates the element one-third the way through the table, and so on.

pathName yview scroll number what This command adjusts the view in the window up or down according to number and what. Number must be an integer. What must be either units or pages. If what is units, the view adjusts up or down by number lines; if it is pages then the view adjusts by num_ber screenfuls. If number is negative then earlier elements become visible; if it is positive then later elements become visible.

Default Bindings

The initialization creates class bindings that give the following default behaviour:

[1]
Clicking Button-1 in a cell activates that cell. Clicking into an already active cell moves the insertion cursor to the character nearest the mouse.
[2]
Moving the mouse while Button-1 is pressed will stroke out a selection area. Exiting while Button-1 is pressed causing scanning to occur on the table along with selection.
[3]
Moving the mouse while Button-2 is pressed causes scanning to occur without any selection.
[4]
Home moves the table to have the origin in view.
[5]
End moves the table to have the end cell in view.
[6]
Control-Home moves the table to the origin and activates that cell.
[7]
Control-End moves the table to the end and activates that cell.
[8]
Shift-Control-Home extends the selection to the origin.
[9]
Shift-Control-End extends the selection to the end.
[10]
The left, right, up and down arrows move the active cell.

[11] Shift-<arrow> extends the selection in that direction.

[12] Control-leftarrow and Control-rightarrow move the insertion cursor within the cell.

[13]
Control-slash selects all the cells.

[14] Control-backslash clears selection from all the cells.

[15] Backspace deletes the character before the insertion cursor in the active cell.

[16] Delete deletes the character after the insertion cursor in the active cell.

[17] Escape rereads the value of the active cell from the specified data source, discarding any edits that have may been performed on the cell.

[18] Control-a moves the insertion cursor to the beginning of the active cell.

[19] Control-e moves the insertion cursor to the end of the active cell.

[20] Control-minus and Control-equals decrease and increase the width of the column with the active cell in it.

[21] Moving the mouse while Button-3 (the right button on Windows) is pressed while you are over a border will cause interactive resizing of that row and/or column to occur, based on the value of -resizeborders.

Some bindings may have slightly different behavior dependent on the -selectionmode of the widget.

If the widget is disabled using the -state option, then its view can still be adjusted and cells can still be selected, but no insertion cursor will be displayed and no cell modifications will take place.

The behavior of tables can be changed by defining new bindings for individual widgets or by redefining the class bindings. The default bindings are either compiled in or read from a file expected to correspond to: «[lindex $tcl_pkgPath 0]/Tktable<version>/tkTable.tcl".

Performance Issues

The number of rows and columns or a table widget should not significantly affect the speed of redraw. Recalculation and redraw of table parameters and cells is restricted as much as possible.

The display cell with the insert cursor is redrawn each time the cursor blinks, which causes a steady stream of graphics traffic. Set the -insertofftime option to 0 avoid this. The use of a -command with the table without a cache can cause significant slow-down, as the command is called once for each request of a cell value.

Examples

Set the topleft title area to be one spanning cell. This overestimates both row and column span by one, but the command does all the constraining for us. $table span [$table cget -roworigin],[$table cget -colorigin] [$table cget -titlerows],[$table cget -titlecols] Force a table window refresh (useful for the slight chance that a bug in the table is not causing proper refresh): $table configure -padx [$table cget -padx]

Keywords

table, widget, extension

Table of Contents

  • Name
  • Synopsis
  • Standard Options
  • Widget-specific Options
  • Description
  • Initialization
  • Indices
  • Tags
  • Embedded Windows
  • the Selection
  • Row/Col Spanning
  • Command Substitution
  • Widget Command
  • Default Bindings
  • Performance Issues
  • Examples
  • Keywords


itcl Manual

itcl

itclsh

itcl Commands

body       code       delete     find       itcl_class itclvars   scope
class      configbody ensemble   itcl       itcl_info  local

itcl Library

[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - itclsh (1)

[incr\ Tcl]

NAME

itclsh - Simple shell for [incr Tcl]

SYNOPSIS

itclsh ?fileName arg arg ...?

DESCRIPTION

itclsh is a shell-like application that reads Tcl commands from its standard input, or from a file, and evaluates them. It is just like tclsh, but includes the [incrTcl] extensions for object-oriented programming.

See the tclsh man page for details concerning usage. See the itcl man page for an overview of [incrTcl].

KEYWORDS

Tcl, itcl, interpreter, script file, shell
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - body (n)

[incr\ Tcl]

NAME

body - change the body for a class method/proc

SYNOPSIS

body className::function args body

DESCRIPTION

The body command is used outside of an [incrTcl] class definition to define or redefine the body of a class method or proc. This facility allows a class definition to have separate "interface" and "implementation" parts. The "interface" part is a class command with declarations for methods, procs, instance variables and common variables. The "implementation" part is a series of body and configbody commands. If the "implementation" part is kept in a separate file, it can be sourced again and again as bugs are fixed, to support interactive development. When using the "tcl" mode in the emacs editor, the "interface" and "implementation" parts can be kept in the same file; as bugs are fixed, individual bodies can be highlighted and sent to the test application.

The name "className::function" identifies the method/proc being changed.

If an args list was specified when the function was defined in the class definition, the args list for the body command must match in meaning. Variable names can change, but the argument lists must have the same required arguments and the same default values for optional arguments. The special args argument acts as a wildcard when included in the args list in the class definition; it will match zero or more arguments of any type when the body is redefined.

If the body string starts with "@", it is treated as the symbolic name for a C procedure. The args list has little meaning for the C procedure, except to document the expected usage. (The C procedure is not guaranteed to use arguments in this manner.) If body does not start with "@", it is treated as a Tcl command script. When the function is invoked, command line arguments are matched against the args list, and local variables are created to represent each argument. This is the usual behavior for a Tcl-style proc.

Symbolic names for C procedures are established by registering procedures via Itcl_RegisterC(). This is usually done in the Tcl_AppInit() procedure, which is automatically called when the interpreter starts up. In the following example, the procedure My_FooCmd() is registered with the symbolic name "foo". This procedure can be referenced in the body command as "@foo".

int
Tcl_AppInit(interp)
    Tcl_Interp *interp;     /* Interpreter for application. */
{
    if (Itcl_Init(interp) == TCL_ERROR) {
        return TCL_ERROR;
    }

    if (Itcl_RegisterC(interp, "foo", My_FooCmd) != TCL_OK) {
        return TCL_ERROR;
    }
}

EXAMPLE

In the following example, a "File" class is defined to represent open files. The method bodies are included below the class definition via the body command. Note that the bodies of the constructor/destructor must be included in the class definition, but they can be redefined via the body command as well.
class File {
    private variable fid ""
    constructor {name access} {
        set fid [open $name $access]
    }
    destructor {
        close $fid
    }

    method get {}
    method put {line}
    method eof {}
}

body File::get {} {
    return [gets $fid]
}
body File::put {line} {
    puts $fid $line
}
body File::eof {} {
    return [::eof $fid]
}

#
# See the File class in action:
#
File x /etc/passwd "r"
while {![x eof]} {
    puts "=> [x get]"
}
delete object x

KEYWORDS

class, object, procedure
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - code (n)

[incr\ Tcl]

NAME

code - capture the namespace context for a code fragment

SYNOPSIS

code ?-namespace name? command ?arg arg ...?

DESCRIPTION

Creates a scoped value for the specified command and its associated arg arguments. A scoped value is a list with three elements: the "@scope" keyword, a namespace context, and a value string. For example, the command

namespace foo {
    code puts "Hello World!"
}
produces the scoped value:
@scope ::foo {puts {Hello World!}}
Note that the code command captures the current namespace context. If the -namespace flag is specified, then the current context is ignored, and the name string is used as the namespace context.

Extensions like Tk execute ordinary code fragments in the global namespace. A scoped value captures a code fragment together with its namespace context in a way that allows it to be executed properly later. It is needed, for example, to wrap up code fragments when a Tk widget is used within a namespace:

namespace foo {
    private proc report {mesg} {
        puts "click: $mesg"
    }

    button .b1 -text "Push Me"
        -command [code report "Hello World!"]
    pack .b1
}
The code fragment associated with button .b1 only makes sense in the context of namespace "foo". Furthermore, the "report" procedure is private, and can only be accessed within that namespace. The code command wraps up the code fragment in a way that allows it to be executed properly when the button is pressed.

Also, note that the code command preserves the integrity of arguments on the command line. This makes it a natural replacement for the list command, which is often used to format Tcl code fragments. In other words, instead of using the list command like this:

after 1000 [list puts "Hello $name!"]
use the code command like this:
after 1000 [code puts "Hello $name!"]
This not only formats the command correctly, but also captures its namespace context.

Scoped commands can be invoked like ordinary code fragments, with or without the eval command. For example, the following statements work properly:

set cmd {@scope ::foo .b1}
$cmd configure -background red

set opts {-bg blue -fg white}
eval $cmd configure $opts
Note that scoped commands by-pass the usual protection mechanisms; the command:
@scope ::foo {report {Hello World!}}
can be used to access the "foo::report" proc from any namespace context, even though it is private.

KEYWORDS

scope, callback, namespace, public, protected, private
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - delete (n)

[incr\ Tcl]

NAME

delete - delete things in the interpreter

SYNOPSIS

delete option ?arg arg ...?

DESCRIPTION

The delete command is used to delete things in the interpreter. It is implemented as an ensemble, so extensions can add their own options and extend the behavior of this command. By default, the delete command handles the destruction of namespaces.

The option argument determines what action is carried out by the command. The legal options (which may be abbreviated) are:

delete class name ?name...?
Deletes one or more [incrTcl] classes called name. This deletes all objects in the class, and all derived classes as well.
If an error is encountered while destructing an object, it will prevent the destruction of the class and any remaining objects. To destroy the entire class without regard for errors, use the "delete namespace" command.
delete object name ?name...?
Deletes one or more [incrTcl] objects called name. An object is deleted by invoking all destructors in its class hierarchy, in order from most- to least-specific. If all destructors are successful, data associated with the object is deleted and the name is removed as a command from the interpreter.
If the access command for an object resides in another namespace, then its qualified name can be used:
delete object foo::bar::x
If an error is encountered while destructing an object, the delete command is aborted and the object remains alive. To destroy an object without regard for errors, use the "rename" command to destroy the object access command.
delete namespace name ?name...?
Deletes one or more namespaces called name. This deletes all commands and variables in the namespace, and deletes all child namespaces as well. When a namespace is deleted, it is automatically removed from the import lists of all other namespaces.

KEYWORDS

namespace, proc, variable, ensemble
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - find (n)

[incr\ Tcl]

NAME

find - search for classes and objects

SYNOPSIS

find option ?arg arg ...?

DESCRIPTION

The find command is used to find classes and objects that are available in the current interpreter. Classes and objects are reported first in the active namespace, then in all other namespaces in the interpreter.

The option argument determines what action is carried out by the command. The legal options (which may be abbreviated) are:

find classes ?pattern?
Returns a list of [incr Tcl] classes. Classes in the current namespace are listed first, followed by classes in all other namespaces in the interpreter. If the optional pattern is specified, then the reported names are compared using the rules of the "string match" command, and only matching names are reported.
If a class resides in the current namespace context, this command reports its simple name--without any qualifiers. However, if the pattern contains :: qualifiers, or if the class resides in another context, this command reports its fully-qualified name. Therefore, you can use the following command to obtain a list where all names are fully-qualified:
find classes ::*
find objects ?pattern? ?-class className? ?-isa className?
Returns a list of [incr Tcl] objects. Objects in the current namespace are listed first, followed by objects in all other namespaces in the interpreter. If the optional pattern is specified, then the reported names are compared using the rules of the "string match" command, and only matching names are reported. If the optional "-class" parameter is specified, this list is restricted to objects whose most-specific class is className. If the optional "-isa" parameter is specified, this list is further restricted to objects having the given className anywhere in their heritage.
If an object resides in the current namespace context, this command reports its simple name--without any qualifiers. However, if the pattern contains :: qualifiers, or if the object resides in another context, this command reports its fully-qualified name. Therefore, you can use the following command to obtain a list where all names are fully-qualified:
find objects ::*

KEYWORDS

class, object, search, import
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - itcl_class (n)

[incr\ Tcl]

NAME

itcl_class - create a class of objects (obsolete)

SYNOPSIS

itcl_class className {
inherit baseClass ?baseClass...?
constructor args ?init? body
destructor body
method name args body
proc name args body
public varName ?init? ?config?
protected varName ?init?
common varName ?init?
}
className objName ?args...?
className #auto ?args...?
className :: proc ?args...?
objName method ?args...?
Commands available within class methods/procs:
global varName ?varName...?
previous command ?args...?
virtual command ?args...?

DESCRIPTION

This command is considered obsolete, but is retained for backward-compatibility with earlier versions of [incrTcl]. It has been replaced by the class command, which should be used for any new development.

itcl_class className definition
Provides the definition for a class named className. If className is already defined, then this command returns an error. If the class definition is successfully parsed, className becomes a command in the current namespace context, handling the creation of objects and providing access to class scope. The class definition is evaluated as a series of Tcl statements that define elements within the class. In addition to the usual commands, the following class definition commands are recognized:
inherit baseClass ?baseClass...?
Declares one or more base classes, causing the current class to inherit their characteristics. Classes must have been defined by a previous itcl_class command, or must be available to the auto-loading facility (see "AUTO-LOADING" below). A single class definition can contain no more than one inherit command.

When the same member name appears in two or more base classes, the base class that appears first in the inherit list takes precedence. For example, if classes "Foo" and "Bar" both contain the member "x", then the "inherit" statement:

inherit Foo Bar
allows "Foo::x" to be accessed simply as "x" but forces "Bar::x" (and all other inherited members named "x") to be referenced with their explicit "class::member" name.
constructor args ?init? body
Declares the argument list and body used for the constructor, which is automatically invoked whenever an object is created. Before the body is executed, the optional init statement is used to invoke any base class constructors that require arguments. Variables in the args specification can be accessed in the init code fragment, and passed to base class constructors. After evaluating the init statement, any base class constructors that have not been executed are invoked without arguments. This ensures that all base classes are fully constructed before the constructor body is executed. If construction is successful, the constructor always returns the object name-regardless of how the body is defined-and the object name becomes a command in the current namespace context. If construction fails, an error message is returned.
destructor body
Declares the body used for the destructor, which is automatically invoked whenever an object is deleted. If the destructor is successful, the object data is destroyed and the object name is removed as a command from the interpreter. If destruction fails, an error message is returned and the object remains.

When an object is destroyed, all destructors in a class hierarchy are invoked in order from most- to least-specific. This is the order that the classes are reported by the "info heritage" command, and it is exactly the opposite of the default constructor order.

method name args body
Declares a method called name with an argument list args and a body of Tcl statements. A method is just like the usual Tcl "proc" except that it has transparent access to object-specific variables, as well as common variables. Within the class scope, a method can be invoked like any other command-simply by using its name. Outside of the class scope, the method name must be prefaced by an object name. Methods in a base class that are redefined in the current class or hidden by another base class can be explicitly scoped using the "class::method" syntax.
proc name args body
Declares a proc called name with an argument list args and a body of Tcl statements. A proc is similar to a method, except that it can be invoked without referring to a specific object, and therefore has access only to common variables-not to object-specific variables declared with the public and protected commands. Within the class scope, a proc can be invoked like any other command-simply by using its name. In any other namespace context, the proc is invoked using a qualified name like "className::proc". Procs in a base class that are redefined in the current class, or hidden by another base class, can also be accessed via their qualified name.
public varName ?init? ?config?
Declares a public variable named varName. Public variables are visible in methods within the scope of their class and any derived class. In addition, they can be modified outside of the class scope using the special "config" formal argument (see "ARGUMENT LISTS" above). If the optional init is specified, it is used as the initial value of the variable when a new object is created. If the optional config command is specified, it is invoked whenever a public variable is modified via the "config" formal argument; if the config command returns an error, the public variable is reset to its value before configuration, and the method handling the configuration returns an error.
protected varName ?init?
Declares a protected variable named varName. Protected variables are visible in methods within the scope of their class and any derived class, but cannot be modified outside of the class scope. If the optional init is specified, it is used as the initial value of the variable when a new object is created. Initialization forces the variable to be a simple scalar value; uninitialized variables, on the other hand, can be used as arrays. All objects have a built-in protected variable named "this" which is initialized to the instance name for the object.
common varName ?init?
Declares a common variable named varName. Common variables are shared among all objects in a class. They are visible in methods and procs in the scope of their class and any derived class, but cannot be modified outside of the class scope. If the optional init is specified, it is used as the initial value of the variable. Initialization forces the variable to be a simple scalar value; uninitialized variables, on the other hand, can be used as arrays.

Once a common variable has been declared, it can be configured using ordinary Tcl code within the class definition. This facility is particularly useful when the initialization of the variable is non-trivial-when the variable contains an array of values, for example:

itcl_class Foo {
     .
     .
    common boolean
    set boolean(true) 1
    set boolean(false) 0
}

CLASS USAGE

When a class definition has been loaded (or made available to the auto-loader), the class name can be used as a command.

className objName ?args...?
Creates a new object in class className with the name objName. Remaining arguments are passed to the constructor. If construction is successful, the object name is returned and this name becomes a command in the current namespace context. Otherwise, an error is returned.
className #auto ?args...?
Creates a new object in class className with an automatically generated name. Names are of the form className<number>, where the className part is modified to start with a lowercase letter. In class "Toaster", for example, the "#auto" specification would produce names toaster0, toaster1, etc. Remaining arguments are passed to the constructor. If construction is successful, the object name is returned and this name becomes a command in the current namespace context. Otherwise, an error is returned.
className :: proc ?args...?
Used outside of the class scope to invoke a class proc named proc. Class procs are like ordinary Tcl procs, except that they are executed in the scope of the class and therefore have transparent access to common data members.

Notice that, unlike any other scope qualifier in [incrTcl], the "::" shown above is surrounded by spaces. This is unnecessary with the new namespace facility, and is considered obsolete. The capability is still supported, however, to provide backward-compatibility with earlier versions.

OBJECT USAGE

objName method ?args...?
Invokes a method named method to operate on the specified object. Remaining arguments are passed to the method. The method name can be "constructor", "destructor", any method name appearing in the class definition, or any of the following built-in methods.

BUILT-IN METHODS

objName isa className
Returns non-zero if the given className can be found in the object's heritage, and zero otherwise.
objName delete
Invokes the destructor associated with an object. If the destructor is successful, data associated with the object is deleted and objName is removed as a command from the interpreter. Returns the empty string, regardless of the destructor body.

The built-in delete method has been replaced by the "delete object" command in the global namespace, and is considered obsolete. The capability is still supported, however, to provide backward-compatibility with earlier versions.

objName info option ?args...?
Returns information related to the class definition or to a particular object named objName. The option parameter includes the following things, as well as the options recognized by the usual Tcl "info" command:
objName info class
Returns the name of the most-specific class for object objName.
objName info inherit
Returns the list of base classes as they were defined in the "inherit" command, or an empty string if this class has no base classes.
objName info heritage
Returns the current class name and the entire list of base classes in the order that they are traversed for member lookup and object destruction.
objName info method ?methodName? ?-args? ?-body?
With no arguments, this command returns a list of all class methods. If methodName is specified, it returns information for a specific method. If neither of the optional -args or -body flags is specified, a complete method definition is returned as a list of three elements including the method name, argument list and body. Otherwise, the requested information is returned without the method name. If the methodName is not recognized, an empty string is returned.
objName info proc ?procName? ?-args? ?-body?
With no arguments, this command returns a list of all class procs. If procName is specified, it returns information for a specific proc. If neither of the optional -args or -body flags is specified, a complete proc definition is returned as a list of three elements including the proc name, argument list and body. Otherwise, the requested information is returned without the proc name. If the procName is not recognized, an empty string is returned.
objName info public ?varName? ?-init? ?-value? ?-config?
With no arguments, this command returns a list of all public variables. If varName is specified, it returns information for a specific public variable. If none of the optional -init, -value or -config flags are specified, all available information is returned as a list of four elements including the variable name, initial value, current value, and configuration commands. Otherwise, the requested information is returned without the variable name. If the varName is not recognized, an empty string is returned.
objName info protected ?varName? ?-init? ?-value?
With no arguments, this command returns a list of all protected variables. If varName is specified, it returns information for a specific protected variable. If neither of the optional -init or -value flags is specified, all available information is returned as a list of three elements including the variable name, initial value and current value. Otherwise, the requested information is returned without the variable name. If the varName is not recognized, an empty string is returned.
objName info common ?varName? ?-init? ?-value?
With no arguments, this command returns a list of all common variables. If varName is specified, it returns information for a specific common variable. If neither of the optional -init or -value flags is specified, all available information is returned as a list of three elements including the variable name, initial value and current value. Otherwise, the requested information is returned without the variable name. If the varName is not recognized, an empty string is returned.

OTHER BUILT-IN COMMANDS

The following commands are also available within the scope of each class. They cannot be accessed from outside of the class as proper methods or procs; rather, they are useful inside the class when implementing its functionality.
global varName ?varName...?
Creates a link to one or more global variables in the current namespace context. Global variables can also be accessed in other namespaces by including namespace qualifiers in varName. This is useful when communicating with Tk widgets that rely on global variables.
previous command ?args...?
Invokes command in the scope of the most immediate base class (i.e., the "previous" class) for the object. For classes using single inheritance, this facility can be used to avoid hard-wired base class references of the form "class::command", making code easier to maintain. For classes using multiple inheritance, the utility of this function is dubious. If the class at the relevant scope has no base class, an error is returned.
virtual command ?args...?
Invokes command in the scope of the most-specific class for the object. The methods within a class are automatically virtual; whenever an unqualified method name is used, it always refers to the most-specific implementation for that method. This function provides a way of evaluating code fragments in a base class that have access to the most-specific object information. It is useful, for example, for creating base classes that can capture and save an object's state. It inverts the usual notions of object-oriented programming, however, and should therefore be used sparingly.

AUTO-LOADING

Class definitions need not be loaded explicitly; they can be loaded as needed by the usual Tcl auto-loading facility. Each directory containing class definition files should have an accompanying "tclIndex" file. Each line in this file identifies a Tcl procedure or [incrTcl] class definition and the file where the definition can be found.

For example, suppose a directory contains the definitions for classes "Toaster" and "SmartToaster". Then the "tclIndex" file for this directory would look like:

# Tcl autoload index file, version 2.0 for [incr Tcl]
# This file is generated by the "auto_mkindex" command
# and sourced to set up indexing information for one or
# more commands.  Typically each line is a command that
# sets an element in the auto_index array, where the
# element name is the name of a command and the value is
# a script that loads the command.

set auto_index(::Toaster) "source $dir/Toaster.itcl"
set auto_index(::SmartToaster) "source $dir/SmartToaster.itcl"

The auto_mkindex command is used to automatically
generate "tclIndex" files.
The auto-loader must be made aware of this directory by appending the directory name to the "auto_path" variable. When this is in place, classes will be auto-loaded as needed when used in an application.

KEYWORDS

class, object, object-oriented
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - itclvars (n)

[incr\ Tcl]

NAME

itclvars - variables used by [incrTcl]

DESCRIPTION

The following global variables are created and managed automatically by the [incrTcl] library. Except where noted below, these variables should normally be treated as read-only by application-specific code and by users.

itcl::library
When an interpreter is created, [incrTcl] initializes this variable to hold the name of a directory containing the system library of [incrTcl] scripts. The initial value of itcl::library is set from the ITCL_LIBRARY environment variable if it exists, or from a compiled-in value otherwise.
itcl::patchLevel
When an interpreter is created, [incrTcl] initializes this variable to hold the current patch level for [incrTcl]. For example, the value "2.0p1" indicates [incrTcl] version 2.0 with the first set of patches applied.
itcl::purist
When an interpreter is created containing Tcl/Tk and the [incrTcl] namespace facility, this variable controls a "backward-compatibility" mode for widget access.
In vanilla Tcl/Tk, there is a single pool of commands, so the access command for a widget is the same as the window name. When a widget is created within a namespace, however, its access command is installed in that namespace, and should be accessed outside of the namespace using a qualified name. For example,
namespace foo {
    namespace bar {
        button .b -text "Testing"
    }
}
foo::bar::.b configure -background red
pack .b
Note that the window name ".b" is still used in conjunction with commands like pack and destroy. However, the access command for the widget (i.e., name that appears as the first argument on a command line) must be more specific.
The "winfo command" command can be used to query the fully-qualified access command for any widget, so one can write:
[winfo command .b] configure -background red
and this is good practice when writing library procedures. Also, in conjunction with the bind command, the "%q" field can be used in place of "%W" as the access command:
bind Button <Key-Return> {%q flash; %q invoke}
While this behavior makes sense from the standpoint of encapsulation, it causes problems with existing Tcl/Tk applications. Many existing applications are written with bindings that use "%W". Many library procedures assume that the window name is the access command.
The itcl::purist variable controls a backward-compatibility mode. By default, this variable is "0", and the window name can be used as an access command in any context. Whenever the unknown procedure stumbles across a widget name, it simply uses "winfo command" to determine the appropriate command name. If this variable is set to "1", this backward-compatibility mode is disabled. This gives better encapsulation, but using the window name as the access command may lead to "invalid command" errors.
itcl::version
When an interpreter is created, [incrTcl] initializes this variable to hold the version number of the form x.y. Changes to x represent major changes with probable incompatibilities and changes to y represent small enhancements and bug fixes that retain backward compatibility.

KEYWORDS

itcl, variables
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - scope (n)

[incr\ Tcl]

NAME

scope - capture the namespace context for a variable

SYNOPSIS

scope name

DESCRIPTION

Creates a scoped value for the specified name, which must be a variable name. If the name is an instance variable, then the scope command returns a string of the following form:

@itcl object varName
This is recognized in any context as an instance variable belonging to object. So with itcl3.0 and beyond, it is possible to use instance variables in conjunction with widgets. For example, if you have an object with a private variable x, and you can use x in conjunction with the -textvariable option of an entry widget. Before itcl3.0, only common variables could be used in this manner.

If the name is not an instance variable, then it must be a common variable or a global variable. In that case, the scope command returns the fully qualified name of the variable, e.g., ::foo::bar::x.

If the name is not recognized as a variable, the scope command returns an error.

Ordinary variable names refer to variables in the global namespace. A scoped value captures a variable name together with its namespace context in a way that allows it to be referenced properly later. It is needed, for example, to wrap up variable names when a Tk widget is used within a namespace:

namespace foo {
    private variable mode 1

    radiobutton .rb1 -text "Mode #1"
        -variable [scope mode] -value 1
    pack .rb1

    radiobutton .rb2 -text "Mode #2"
        -variable [scope mode] -value 2
    pack .rb2
}
Radiobuttons .rb1 and .rb2 interact via the variable "mode" contained in the namespace "foo". The scope command guarantees this by returning the fully qualified variable name ::foo::mode.

You should never use the @itcl syntax directly. For example, it is a bad idea to write code like this:

set {@itcl ::fred x} 3
puts "value = ${@itcl ::fred x}"
Instead, you should always use the scope command to generate the variable name dynamically. Then, you can pass that name to a widget or to any other bit of code in your program.

KEYWORDS

code, namespace, variable
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - class (n)

[incr\ Tcl]

NAME

class - create a class of objects

SYNOPSIS

class className {
inherit baseClass ?baseClass...?
constructor args ?init? body
destructor body
method name ?args? ?body?
proc name ?args? ?body?
variable varName ?init? ?config?
common varName ?init?
public command ?arg arg ...?
protected command ?arg arg ...?
private command ?arg arg ...?
set varName ?value?
array option ?arg arg ...?
}
className objName ?arg arg ...?
objName method ?arg arg ...?
className::proc ?arg arg ...?

DESCRIPTION

The fundamental construct in [incrTcl] is the class definition. Each class acts as a template for actual objects that can be created. The class itself is a namespace which contains things common to all objects. Each object has its own unique bundle of data which contains instances of the "variables" defined in the class definition. Each object also has a built-in variable named "this", which contains the name of the object. Classes can also have "common" data members that are shared by all objects in a class.

Two types of functions can be included in the class definition. "Methods" are functions which operate on a specific object, and therefore have access to both "variables" and "common" data members. "Procs" are ordinary procedures in the class namespace, and only have access to "common" data members.

If the body of any method or proc starts with "@", it is treated as the symbolic name for a C procedure. Otherwise, it is treated as a Tcl code script. See below for details on registering and using C procedures.

A class can only be defined once, although the bodies of class methods and procs can be defined again and again for interactive debugging. See the body and configbody commands for details.

Each namespace can have its own collection of objects and classes. The list of classes available in the current context can be queried using the "itcl::find classes" command, and the list of objects, with the "itcl::find objects" command.

A class can be deleted using the "delete class" command. Individual objects can be deleted using the "delete object" command.

CLASS DEFINITIONS

class className definition
Provides the definition for a class named className. If the class className already exists, or if a command called className exists in the current namespace context, this command returns an error. If the class definition is successfully parsed, className becomes a command in the current context, handling the creation of objects for this class.

The class definition is evaluated as a series of Tcl statements that define elements within the class. The following class definition commands are recognized:

inherit baseClass ?baseClass...?
Causes the current class to inherit characteristics from one or more base classes. Classes must have been defined by a previous class command, or must be available to the auto-loading facility (see "AUTO-LOADING" below). A single class definition can contain no more than one inherit command.
The order of baseClass names in the inherit list affects the name resolution for class members. When the same member name appears in two or more base classes, the base class that appears first in the inherit list takes precedence. For example, if classes "Foo" and "Bar" both contain the member "x", and if another class has the "inherit" statement:
inherit Foo Bar
then the name "x" means "Foo::x". Other inherited members named "x" must be referenced with their explicit name, like "Bar::x".
constructor args ?init? body
Declares the args argument list and body used for the constructor, which is automatically invoked whenever an object is created.
Before the body is executed, the optional init statement is used to invoke any base class constructors that require arguments. Variables in the args specification can be accessed in the init code fragment, and passed to base class constructors. After evaluating the init statement, any base class constructors that have not been executed are invoked automatically without arguments. This ensures that all base classes are fully constructed before the constructor body is executed. By default, this scheme causes constructors to be invoked in order from least- to most-specific. This is exactly the opposite of the order that classes are reported by the info heritage command.
If construction is successful, the constructor always returns the object name-regardless of how the body is defined-and the object name becomes a command in the current namespace context. If construction fails, an error message is returned.
destructor body
Declares the body used for the destructor, which is automatically invoked when an object is deleted. If the destructor is successful, the object data is destroyed and the object name is removed as a command from the interpreter. If destruction fails, an error message is returned and the object remains.
When an object is destroyed, all destructors in its class hierarchy are invoked in order from most- to least-specific. This is the order that the classes are reported by the "info heritage" command, and it is exactly the opposite of the default constructor order.
method name ?args? ?body?
Declares a method called name. When the method body is executed, it will have automatic access to object-specific variables and common data members.
If the args list is specified, it establishes the usage information for this method. The body command can be used to redefine the method body, but the args list must match this specification.
Within the body of another class method, a method can be invoked like any other command-simply by using its name. Outside of the class context, the method name must be prefaced an object name, which provides the context for the data that it manipulates. Methods in a base class that are redefined in the current class, or hidden by another base class, can be qualified using the "className::method" syntax.
proc name ?args? ?body?
Declares a proc called name. A proc is an ordinary procedure within the class namespace. Unlike a method, a proc is invoked without referring to a specific object. When the proc body is executed, it will have automatic access only to common data members.
If the args list is specified, it establishes the usage information for this proc. The body command can be used to redefine the proc body, but the args list must match this specification.
Within the body of another class method or proc, a proc can be invoked like any other command-simply by using its name. In any other namespace context, the proc is invoked using a qualified name like "className::proc". Procs in a base class that are redefined in the current class, or hidden by another base class, can also be accessed via their qualified name.
variable varName ?init? ?config?
Defines an object-specific variable named varName. All object-specific variables are automatically available in class methods. They need not be declared with anything like the global command.
If the optional init string is specified, it is used as the initial value of the variable when a new object is created. Initialization forces the variable to be a simple scalar value; uninitialized variables, on the other hand, can be set within the constructor and used as arrays.
The optional config script is only allowed for public variables. If specified, this code fragment is executed whenever a public variable is modified by the built-in "configure" method. The config script can also be specified outside of the class definition using the configbody command.
common varName ?init?
Declares a common variable named varName. Common variables reside in the class namespace and are shared by all objects belonging to the class. They are just like global variables, except that they need not be declared with the usual global command. They are automatically visible in all class methods and procs.
If the optional init string is specified, it is used as the initial value of the variable. Initialization forces the variable to be a simple scalar value; uninitialized variables, on the other hand, can be set with subsequent set and array commands and used as arrays.
Once a common data member has been defined, it can be set using set and array commands within the class definition. This allows common data members to be initialized as arrays. For example:
class Foo {
    common boolean
    set boolean(true) 1
    set boolean(false) 0
}
Note that if common data members are initialized within the constructor, they get initialized again and again whenever new objects are created.
public command ?arg arg ...?
protected command ?arg arg ...?
private command ?arg arg ...?
These commands are used to set the protection level for class members that are created when command is evaluated. The command is usually method, proc, variable orcommon, and the remaining arg's complete the member definition. However, command can also be a script containing many different member definitions, and the protection level will apply to all of the members that are created.

CLASS USAGE

Once a class has been defined, the class name can be used as a command to create new objects belonging to the class.

className objName ?args...?
Creates a new object in class className with the name objName. Remaining arguments are passed to the constructor of the most-specific class. This in turn passes arguments to base class constructors before invoking its own body of commands. If construction is successful, a command called objName is created in the current namespace context, and objName is returned as the result of this operation. If an error is encountered during construction, the destructors are automatically invoked to free any resources that have been allocated, the object is deleted, and an error is returned.
If objName contains the string "#auto", that string is replaced with an automatically generated name. Names have the form className<number>, where the className part is modified to start with a lowercase letter. In class "Toaster", for example, the "#auto" specification would produce names like toaster0, toaster1, etc. Note that "#auto" can be also be buried within an object name:
fileselectiondialog .foo.bar.#auto -background red
This would generate an object named ".foo.bar.fileselectiondialog0".

OBJECT USAGE

Once an object has been created, the object name can be used as a command to invoke methods that operate on the object.
objName method ?args...?
Invokes a method named method on an object named objName. Remaining arguments are passed to the argument list for the method. The method name can be "constructor", "destructor", any method name appearing in the class definition, or any of the following built-in methods.

BUILT-IN METHODS

objName cget option
Provides access to public variables as configuration options. This mimics the behavior of the usual "cget" operation for Tk widgets. The option argument is a string of the form "-varName", and this method returns the current value of the public variable varName.
objName configure ?option? ?value option value ...?
Provides access to public variables as configuration options. This mimics the behavior of the usual "configure" operation for Tk widgets. With no arguments, this method returns a list of lists describing all of the public variables. Each list has three elements: the variable name, its initial value and its current value.
If a single option of the form "-varName" is specified, then this method returns the information for that one variable.
Otherwise, the arguments are treated as option/value pairs assigning new values to public variables. Each variable is assigned its new value, and if it has any "config" code associated with it, it is executed in the context of the class where it was defined. If the "config" code generates an error, the variable is set back to its previous value, and the configure method returns an error.
objName isa className
Returns non-zero if the given className can be found in the object's heritage, and zero otherwise.
objName info option ?args...?
Returns information related to a particular object named objName, or to its class definition. The option parameter includes the following things, as well as the options recognized by the usual Tcl "info" command:
objName info class
Returns the name of the most-specific class for object objName.
objName info inherit
Returns the list of base classes as they were defined in the "inherit" command, or an empty string if this class has no base classes.
objName info heritage
Returns the current class name and the entire list of base classes in the order that they are traversed for member lookup and object destruction.
objName info function ?cmdName? ?-protection? ?-type? ?-name? ?-args? ?-body?
With no arguments, this command returns a list of all class methods and procs. If cmdName is specified, it returns information for a specific method or proc. If no flags are specified, this command returns a list with the following elements: the protection level, the type (method/proc), the qualified name, the argument list and the body. Flags can be used to request specific elements from this list.
objName info variable ?varName? ?-protection? ?-type? ?-name? ?-init? ?-value? ?-config?
With no arguments, this command returns a list of all object-specific variables and common data members. If varName is specified, it returns information for a specific data member. If no flags are specified, this command returns a list with the following elements: the protection level, the type (variable/common), the qualified name, the initial value, and the current value. If varName is a public variable, the "config" code is included on this list. Flags can be used to request specific elements from this list.

CHAINING METHODS/PROCS

Sometimes a base class has a method or proc that is redefined with the same name in a derived class. This is a way of making the derived class handle the same operations as the base class, but with its own specialized behavior. For example, suppose we have a Toaster class that looks like this:
class Toaster {
    variable crumbs 0
    method toast {nslices} {
        if {$crumbs > 50} {
            error "== FIRE! FIRE! =="
        }
        set crumbs [expr $crumbs+4*$nslices]
    }
    method clean {} {
        set crumbs 0
    }
}
We might create another class like SmartToaster that redefines the "toast" method. If we want to access the base class method, we can qualify it with the base class name, to avoid ambiguity:
class SmartToaster {
    inherit Toaster
    method toast {nslices} {
        if {$crumbs > 40} {
            clean
        }
        return [Toaster::toast $nslices]
    }
}
Instead of hard-coding the base class name, we can use the "chain" command like this:
class SmartToaster {
    inherit Toaster
    method toast {nslices} {
        if {$crumbs > 40} {
            clean
        }
        return [chain $nslices]
    }
}
The chain command searches through the class hierarchy for a slightly more generic (base class) implementation of a method or proc, and invokes it with the specified arguments. It starts at the current class context and searches through base classes in the order that they are reported by the "info heritage" command. If another implementation is not found, this command does nothing and returns the null string.

AUTO-LOADING

Class definitions need not be loaded explicitly; they can be loaded as needed by the usual Tcl auto-loading facility. Each directory containing class definition files should have an accompanying "tclIndex" file. Each line in this file identifies a Tcl procedure or [incrTcl] class definition and the file where the definition can be found.

For example, suppose a directory contains the definitions for classes "Toaster" and "SmartToaster". Then the "tclIndex" file for this directory would look like:

# Tcl autoload index file, version 2.0 for [incr Tcl]
# This file is generated by the "auto_mkindex" command
# and sourced to set up indexing information for one or
# more commands.  Typically each line is a command that
# sets an element in the auto_index array, where the
# element name is the name of a command and the value is
# a script that loads the command.

set auto_index(::Toaster) "source $dir/Toaster.itcl"
set auto_index(::SmartToaster) "source $dir/SmartToaster.itcl"

The auto_mkindex command is used to automatically
generate "tclIndex" files.
The auto-loader must be made aware of this directory by appending the directory name to the "auto_path" variable. When this is in place, classes will be auto-loaded as needed when used in an application.

C PROCEDURES

C procedures can be integrated into an [incrTcl] class definition to implement methods, procs, and the "config" code for public variables. Any body that starts with "@" is treated as the symbolic name for a C procedure.

Symbolic names are established by registering procedures via Itcl_RegisterC(). This is usually done in the Tcl_AppInit() procedure, which is automatically called when the interpreter starts up. In the following example, the procedure My_FooCmd() is registered with the symbolic name "foo". This procedure can be referenced in the body command as "@foo".

int
Tcl_AppInit(interp)
    Tcl_Interp *interp;     /* Interpreter for application. */
{
    if (Itcl_Init(interp) == TCL_ERROR) {
        return TCL_ERROR;
    }

    if (Itcl_RegisterC(interp, "foo", My_FooCmd) != TCL_OK) {
        return TCL_ERROR;
    }
}
C procedures are implemented just like ordinary Tcl commands. See the CrtCommand man page for details. Within the procedure, class data members can be accessed like ordinary variables using Tcl_SetVar(), Tcl_GetVar(), Tcl_TraceVar(), etc. Class methods and procs can be executed like ordinary commands using Tcl_Eval(). [incrTcl] makes this possible by automatically setting up the context before executing the C procedure.

This scheme provides a natural migration path for code development. Classes can be developed quickly using Tcl code to implement the bodies. An entire application can be built and tested. When necessary, individual bodies can be implemented with C code to improve performance.

KEYWORDS

class, object, object-oriented
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - configbody (n)

[incr\ Tcl]

NAME

configbody - change the "config" code for a public variable

SYNOPSIS

configbody className::varName body

DESCRIPTION

The configbody command is used outside of an [incrTcl] class definition to define or redefine the configuration code associated with a public variable. Public variables act like configuration options for an object. They can be modified outside the class scope using the built-in configure method. Each variable can have a bit of "config" code associate with it that is automatically executed when the variable is configured. The configbody command can be used to define or redefine this body of code.

Like the body command, this facility allows a class definition to have separate "interface" and "implementation" parts. The "interface" part is a class command with declarations for methods, procs, instance variables and common variables. The "implementation" part is a series of body and configbody commands. If the "implementation" part is kept in a separate file, it can be sourced again and again as bugs are fixed, to support interactive development. When using the "tcl" mode in the emacs editor, the "interface" and "implementation" parts can be kept in the same file; as bugs are fixed, individual bodies can be highlighted and sent to the test application.

The name "className::varName" identifies the public variable being updated. If the body string starts with "@", it is treated as the symbolic name for a C procedure. Otherwise, it is treated as a Tcl command script.

Symbolic names for C procedures are established by registering procedures via Itcl_RegisterC(). This is usually done in the Tcl_AppInit() procedure, which is automatically called when the interpreter starts up. In the following example, the procedure My_FooCmd() is registered with the symbolic name "foo". This procedure can be referenced in the configbody command as "@foo".

int
Tcl_AppInit(interp)
    Tcl_Interp *interp;     /* Interpreter for application. */
{
    if (Itcl_Init(interp) == TCL_ERROR) {
        return TCL_ERROR;
    }

    if (Itcl_RegisterC(interp, "foo", My_FooCmd) != TCL_OK) {
        return TCL_ERROR;
    }
}

EXAMPLE

In the following example, a "File" class is defined to represent open files. Whenever the "-name" option is configured, the existing file is closed, and a new file is opened. Note that the "config" code for a public variable is optional. The "-access" option, for example, does not have it.
class File {
    private variable fid ""

    public variable name ""
    public variable access "r"

    constructor {args} {
        eval configure $args
    }
    destructor {
        if {$fid != ""} {
            close $fid
        }
    }

    method get {}
    method put {line}
    method eof {}
}

body File::get {} {
    return [gets $fid]
}
body File::put {line} {
    puts $fid $line
}
body File::eof {} {
    return [::eof $fid]
}

configbody File::name {
    if {$fid != ""} {
        close $fid
    }
    set fid [open $name $access]
}

#
# See the File class in action:
#
File x

x configure -name /etc/passwd
while {![x eof]} {
    puts "=> [x get]"
}
delete object x

KEYWORDS

class, object, variable, configure
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - ensemble (n)

[incr\ Tcl]

NAME

ensemble - create or modify a composite command

SYNOPSIS

ensemble ensName ?command arg arg...?
or
ensemble ensName {
part partName args body
...
ensemble partName {
part subPartName args body
part subPartName args body
... }
}

DESCRIPTION

The ensemble command is used to create or modify a composite command. See the section WHAT IS AN ENSEMBLE? below for a brief overview of ensembles.

If the ensemble command finds an existing ensemble called ensName, it updates that ensemble. Otherwise, it creates an ensemble called ensName. If the ensName is a simple name like "foo", then an ensemble command named "foo" is added to the current namespace context. If a command named "foo" already exists in that context, then it is deleted. If the ensName contains namespace qualifiers like "a::b::foo", then the namespace path is resolved, and the ensemble command is added that namespace context. Parent namespaces like "a" and "b" are created automatically, as needed.

If the ensName contains spaces like "a::b::foo bar baz", then additional words like "bar" and "baz" are treated as sub-ensembles. Sub-ensembles are merely parts within an ensemble; they do not have a Tcl command associated with them. An ensemble like "foo" can have a sub-ensemble called "foo bar", which in turn can have a sub-ensemble called "foo bar baz". In this case, the sub-ensemble "foo bar" must be created before the sub-ensemble "foo bar baz" that resides within it.

If there are any arguments following ensName, then they are treated as commands, and they are executed to update the ensemble. The following commands are recognized in this context: part and ensemble.

The part command defines a new part for the ensemble. Its syntax is identical to the usual proc command, but it defines a part within an ensemble, instead of a Tcl command. If a part called partName already exists within the ensemble, then the part command returns an error.

The ensemble command can be nested inside another ensemble command to define a sub-ensemble.

WHAT IS AN ENSEMBLE?

The usual "info" command is a composite command--the command name info must be followed by a sub-command like body or globals. We will refer to a command like info as an ensemble, and to sub-commands like body or globals as its parts.

Ensembles can be nested. For example, the info command has an ensemble info namespace within it. This ensemble has parts like info namespace all and info namespace children.

With ensembles, composite commands can be created and extended in an automatic way. Any package can find an existing ensemble and add new parts to it. So extension writers can add their own parts, for example, to the info command.

The ensemble facility manages all of the part names and keeps track of unique abbreviations. Normally, you can abbreviate info complete to info comp. But if an extension adds the part info complexity, the minimum abbreviation for info complete becomes info complet.

The ensemble facility not only automates the construction of composite commands, but it automates the error handling as well. If you invoke an ensemble command without specifying a part name, you get an automatically generated error message that summarizes the usage information. For example, when the info command is invoked without any arguments, it produces the following error message:

wrong # args: should be one of...
  info args procname
  info body procname
  info cmdcount
  info commands ?pattern?
  info complete command
  info context
  info default procname arg varname
  info exists varName
  info globals ?pattern?
  info level ?number?
  info library
  info locals ?pattern?
  info namespace option ?arg arg ...?
  info patchlevel
  info procs ?pattern?
  info protection ?-command? ?-variable? name
  info script
  info tclversion
  info vars ?pattern?
  info which ?-command? ?-variable? ?-namespace? name
You can also customize the way an ensemble responds to errors. When an ensemble encounters an unspecified or ambiguous part name, it looks for a part called @error. If it exists, then it is used to handle the error. This part will receive all of the arguments on the command line starting with the offending part name. It can find another way of resolving the command, or generate its own error message.

EXAMPLE

We could use an ensemble to clean up the syntax of the various "wait" commands in Tcl/Tk. Instead of using a series of strange commands like this:
vwait x
tkwait visibility .top
tkwait window .
we could use commands with a uniform syntax, like this:
wait variable x
wait visibility .top
wait window .
The Tcl package could define the following ensemble:
ensemble wait part variable {name} {
    uplevel vwait $name
}
The Tk package could add some options to this ensemble, with a command like this:
ensemble wait {
    part visibility {name} {
        tkwait visibility $name
    }
    part window {name} {
        tkwait window $name
    }
}
Other extensions could add their own parts to the wait command too.

KEYWORDS

ensemble, part, info
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - itcl (n)

[incr\ Tcl]

NAME

itcl - object-oriented extensions to Tcl

DESCRIPTION

[incrTcl] provides object-oriented extensions to Tcl, much as C++ provides object-oriented extensions to C. The emphasis of this work, however, is not to create a whiz-bang object-oriented programming environment. Rather, it is to support more structured programming practices in Tcl without changing the flavor of the language. More than anything else, [incrTcl] provides a means of encapsulating related procedures together with their shared data in a namespace that is hidden from the outside world. It encourages better programming by promoting the object-oriented "library" mindset. It also allows for code re-use through inheritance.

CLASSES

The fundamental construct in [incrTcl] is the class definition. Each class acts as a template for actual objects that can be created. Each object has its own unique bundle of data, which contains instances of the "variables" defined in the class. Special procedures called "methods" are used to manipulate individual objects. Methods are just like the operations that are used to manipulate Tk widgets. The "button" widget, for example, has methods such as "flash" and "invoke" that cause a particular button to blink and invoke its command.

Within the body of a method, the "variables" defined in the class are automatically available. They need not be declared with anything like the global command. Within another class method, a method can be invoked like any other command-simply by using its name. From any other context, the method name must be prefaced by an object name, which provides a context for the data that the method can access.

Each class has its own namespace containing things that are common to all objects which belong to the class. For example, "common" data members are shared by all objects in the class. They are global variables that exist in the class namespace, but since they are included in the class definition, they need not be declared using the global command; they are automatically available to any code executing in the class context. A class can also create ordinary global variables, but these must be declared using the global command each time they are used.

Classes can also have ordinary procedures declared as "procs". Within another class method or proc, a proc can be invoked like any other command-simply by using its name. From any other context, the procedure name should be qualified with the class namespace like "className::proc". Class procs execute in the class context, and therefore have automatic access to all "common" data members. However, they cannot access object-specific "variables", since they are invoked without reference to any specific object. They are usually used to perform generic operations which affect all objects belonging to the class.

Each of the elements in a class can be declared "public", "protected" or "private". Public elements can be accessed by the class, by derived classes (other classes that inherit this class), and by external clients that use the class. Protected elements can be accessed by the class, and by derived classes. Private elements are only accessible in the class where they are defined.

The "public" elements within a class define its interface to the external world. Public methods define the operations that can be used to manipulate an object. Public variables are recognized as configuration options by the "configure" and "cget" methods that are built into each class. The public interface says what an object will do but not how it will do it. Protected and private members, along with the bodies of class methods and procs, provide the implementation details. Insulating the application developer from these details leaves the class designer free to change them at any time, without warning, and without affecting programs that rely on the class. It is precisely this encapsulation that makes object-oriented programs easier to understand and maintain.

The fact that [incrTcl] objects look like Tk widgets is no accident. [incrTcl] was designed this way, to blend naturally into a Tcl/Tk application. But [incrTcl] extends the Tk paradigm from being merely object-based to being fully object-oriented. An object-oriented system supports inheritance, allowing classes to share common behaviors by inheriting them from an ancestor or base class. Having a base class as a common abstraction allows a programmer to treat related classes in a similar manner. For example, a toaster and a blender perform different (specialized) functions, but both share the abstraction of being appliances. By abstracting common behaviors into a base class, code can be shared rather than copied. The resulting application is easier to understand and maintain, and derived classes (e.g., specialized appliances) can be added or removed more easily.

This description was merely a brief overview of object-oriented programming and [incrTcl]. A more tutorial introduction is presented in the paper included with this distribution. See the class command for more details on creating and using classes.

NAMESPACES

[incrTcl] now includes a complete namespace facility. A namespace is a collection of commands and global variables that is kept apart from the usual global scope. This allows Tcl code libraries to be packaged in a well-defined manner, and prevents unwanted interactions with other libraries. A namespace can also have child namespaces within it, so one library can contain its own private copy of many other libraries. A namespace can also be used to wrap up a group of related classes. The global scope (named "::") is the root namespace for an interpreter; all other namespaces are contained within it.

See the namespace command for details on creating and using namespaces.

MEGA-WIDGETS

Mega-widgets are high-level widgets that are constructed using Tk widgets as component parts, usually without any C code. A fileselectionbox, for example, may have a few listboxes, some entry widgets and some control buttons. These individual widgets are put together in a way that makes them act like one big widget.

[incrTk] is a framework for building mega-widgets. It uses [incrTcl] to support the object paradigm, and adds base classes which provide default widget behaviors. See the itk man page for more details.

[incrWidgets] is a library of mega-widgets built using [incrTk]. It contains more than 30 different widget classes that can be used right out of the box to build Tcl/Tk applications. Each widget class has its own man page describing the features available.

KEYWORDS

class, object, object-oriented, namespace, mega-widget
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - itcl_info (n)

[incr\ Tcl]

NAME

itcl_info - query info regarding classes and objects (obsolete)

SYNOPSIS

itcl_info classes ?pattern?
itcl_info objects ?pattern? ?-class className? ?-isa className?

DESCRIPTION

This command is considered obsolete, but is retained for backward-compatibility with earlier versions of [incrTcl]. It has been replaced by the "find classes" and "find objects" commands, which should be used for any new development.

The following commands are available in the global namespace to query information about classes and objects that have been created.

itcl_info classes ?pattern?
Returns a list of classes available in the current namespace context. If a class belongs to the current namespace context, its simple name is reported; otherwise, if a class is imported from another namespace, its fully-qualified name is reported.
If the optional pattern is specified, then the reported names are compared using the rules of the "string match" command, and only matching names are reported.
itcl_info objects ?pattern? ?-class className? ?-isa className?
Returns a list of objects available in the current namespace context. If an object belongs to the current namespace context, its simple name is reported; otherwise, if an object is imported from another namespace, its fully-qualified access command is reported.
If the optional pattern is specified, then the reported names are compared using the rules of the "string match" command, and only matching names are reported. If the optional "-class" parameter is specified, this list is restricted to objects whose most-specific class is className. If the optional "-isa" parameter is specified, this list is further restricted to objects having the given className anywhere in their heritage.

KEYWORDS

class, object, object-oriented
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itcl - local (n)

[incr\ Tcl]

NAME

local - create an object local to a procedure

SYNOPSIS

local className objName ?arg arg ...?

DESCRIPTION

The local command creates an [incrTcl] object that is local to the current call frame. When the call frame goes away, the object is automatically deleted. This command is useful for creating objects that are local to a procedure.

As a side effect, this command creates a variable named "itcl-local-xxx", where xxx is the name of the object that is created. This variable detects when the call frame is destroyed and automatically deletes the associated object.

EXAMPLE

In the following example, a simple "counter" object is used within the procedure "test". The counter is created as a local object, so it is automatically deleted each time the procedure exits. The puts statements included in the constructor/destructor show the object coming and going as the procedure is called.
class counter {
    private variable count 0
    constructor {} {
        puts "created: $this"
    }
    destructor {
        puts "deleted: $this"
    }

    method bump {{by 1}} {
        incr count $by
    }
    method get {} {
        return $count
    }
}

proc test {val} {
    local counter x
    for {set i 0} {$i < $val} {incr i} {
        x bump
    }
    return [x get]
}

set result [test 5]
puts "test: $result"

set result [test 10]
puts "test: $result"

puts "objects: [info objects]"

KEYWORDS

class, object, procedure
[ itcl ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itk Manual

itk

itkwish

itk Commands

Archetype Toplevel  Widget    itk       itkvars   usual

itk Library

[ itk ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itk - itkwish (1)

[incr\ Tk]

NAME

itkwish - Simple windowing shell for [incrTcl] / [incrTk]

SYNOPSIS

itkwish ?fileName arg arg ...?

OPTIONS

-display display
Display (and screen) on which to display window.
-geometry geometry
Initial geometry to use for window. If this option is specified, its value is stored in the geometry global variable of the application's Tcl interpreter.
-name name
Use name as the title to be displayed in the window, and as the name of the interpreter for send commands.
-sync
Execute all X server commands synchronously, so that errors are reported immediately. This will result in much slower execution, but it is useful for debugging.
--
Pass all remaining arguments through to the script's argv variable without interpreting them. This provides a mechanism for passing arguments such as -name to a script instead of having itkwish interpret them.

DESCRIPTION

itkwish is a simple program consisting of the Tcl command language, the Tk toolkit, the [incrTcl] extension for object-oriented programming, and the [incrTk] extension for building mega-widgets. The main program creates an interpreter, creates a main window, and then processes Tcl commands from standard input or from a file.

itkwish is just like wish, but includes the [incrTcl] / [incrTk] extensions.

See the wish man page for details concerning usage. See the itcl and itk man pages for an overview of [incrTcl] / [incrTk].

KEYWORDS

Tcl, Tk, itcl, itk, interpreter, shell, toolkit
[ itk ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itk - Archetype (n)

[incr\ Tk]

NAME

Archetype - base class for all [incrTk] mega-widgets

INHERITANCE

none

WIDGET-SPECIFIC OPTIONS

Name:clientData
Class:ClientData
Command-Line Switch:-clientdata

  • This does not affect the widget operation in any way. It is simply a hook that clients can use to store a bit of data with each widget. This can come in handy when using widgets to build applications.

DESCRIPTION

The Archetype class is the basis for all [incrTk] mega-widgets. It keeps track of component widgets and provides methods like "configure" and "cget" that are used to access the composite configuration options. Each component widget must be registered with the Archetype base class using the "itk_component add" method. When the component is registered, its configuration options are integrated into the composite option list. Configuring a composite option like "-background" causes all of the internal components to change their background color.

It is not used as a widget by itself, but is used as a base class for more specialized widgets. The Widget base class inherits from Archetype, and adds a Tk frame which acts as the "hull" for the mega-widget. The Toplevel base class inherits from Archetype, but adds a Tk toplevel which acts as the "hull".

Each derived class must invoke the itk_initialize method within its constructor, so that all options are properly integrated and initialized in the composite list.

PUBLIC METHODS

The following methods are provided to support the public interface of the mega-widget.

pathName cget option
Returns the current value of the configuration option given by option.
In this case, option refers to a composite configuration option for the mega-widget. Individual components integrate their own configuration options onto the composite list when they are registered by the "itk_component add" method.
pathName component ?name? ?command arg arg ...?
Used to query or access component widgets within a mega-widget. With no arguments, this returns a list of symbolic names for component widgets that are accessible in the current scope. The symbolic name for a component is established when it is registered by the "itk_component add" method. Note that component widgets obey any public/protected/private access restriction that is in force when the component is created.
If a symbolic name is specified, this method returns the window path name for that component.
Otherwise, the command and any remaining arg arguments are invoked as a method on the component with the symbolic name name. This provides a well-defined way of accessing internal components without relying on specific window path names, which are really details of the implementation.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string.
In this case, the options refer to composite configuration options for the mega-widget. Individual components integrate their own configuration options onto the composite list when they are registered by the "itk_component add" method.

PROTECTED METHODS

The following methods are used in derived classes as part of the implementation for a mega-widget.

itk_component add ?-protected? ?-private? ?--? name createCmds ?optionCmds?
Creates a component widget by executing the createCmds argument and registers the new component with the symbolic name name. The -protected and -private options can be used to keep the component hidden from the outside world. These options have a similar effect on component visibility as they have on class members.
The createCmds code can contain any number of commands, but it must return the window path name for the new component widget.
The optionCmds script contains commands that describe how the configuration options for the new component should be integrated into the composite list for the mega-widget. It can contain any of the following commands:
ignore option ?option option ...?
Removes one or more configuration options from the composite list. All options are ignored by default, so the ignore command is only used to negate the effect of a previous keep or rename command. This is useful, for example, when the some of the options added by the usual command should not apply to a particular component, and need to be ignored.
keep option ?option option ...?
Integrates one or more configuration options into the composite list, keeping the name the same. Whenever the mega-widget option is configured, the new value is also applied to the current component. Options like "-background" and "-cursor" are commonly found on the keep list.
rename option switchName resourceName resourceClass
Integrates the configuration option into the composite list with a different name. The option will be called switchName on the composite list. It will also be modified by setting values for resourceName and resourceClass in the X11 resource database. The "-highlightbackground" option is commonly renamed to "-background", so that when the mega-widget background changes, the background of the focus ring will change as well.
usual ?tag?
Finds the usual option-handling commands for the specified tag name and executes them. If the tag is not specified, then the widget class name is used as the tag name. The "usual" option-handling commands are registered via the usual command.

If the optionCmds script is not specified, the usual option-handling commands associated with the class of the component widget are used by default.
itk_component delete name ?name name ...?
Removes the component widget with the symbolic name name from the mega-widget. The component widget will still exist, but it will no longer be accessible as a component of the mega-widget. Also, any options associated with the component are removed from the composite option list.
Note that you can destroy a component using the destroy command, just as you would destroy any Tk widget. Components automatically detach themselves from their mega-widget parent when destroyed, so "itk_component delete" is rarely used.
itk_initialize ?option value option value...?
This method must be invoked within the constructor for each class in a mega-widget hierarchy. It makes sure that all options are properly integrated into the composite option list, and synchronizes all components to the initial option values. It is usually invoked near the bottom of the constructor, after all component widgets have been added.
If any option/value pairs are specified, they override settings determined from the X11 resource database. The arguments to the constructor are usually passed along to this method as follows:
class MyWidget {
    inherit Widget

    constructor {args} {
        .
        .
        .
        eval itk_initialize $args
    }
}
itk_option add optName ?optName optName ...?
Adds one or more options to the composite option list for a mega-widget. Here, optName can have one of the following forms:
component.option
Accesses an option belonging to a component with the symbolic name component. The option name is specified without a leading "-" sign.
className::option
Accesses an option defined by the "itk_option define" command in class className. The option name is specified without a leading "-" sign.

Options are normally integrated into the composite option list when a component widget is first created. This method can be used to add options at a later time. For example, the Widget and Toplevel base classes keep only the bare minimum options for their "hull" component: -background and -cursor. A derived class can override this decision, and add options that control the border of the "hull" component as well:

class MyWidget {
    inherit Widget

    constructor {args} {
        itk_option add hull.borderwidth hull.relief

        itk_component add label {
            label $itk_interior.l1 -text "Hello World!"
        }
        pack $itk_component(label)

        eval itk_initialize $args
    }
}
itk_option define switchName resourceName resourceClass init ?config?
This command is used at the level of the class definition to define a synthetic mega-widget option. Within the configure and cget methods, this option is referenced by switchName, which must start with a "-" sign. It can also be modified by setting values for resourceName and resourceClass in the X11 resource database. The init value string is used as a last resort to initialize the option if no other value can be used from an existing option, or queried from the X11 resource database. If any config code is specified, it is executed whenever the option is modified via the configure method. The config code can also be specified outside of the class definition via the configbody command.
In the following example, a synthetic "-background" option is added to the class, so that whenever the background changes, the new value is reported to standard output. Note that this synthetic option is integrated with the rest of the "-background" options that have been kept from component widgets:
class MyWidget {
    inherit Widget
    constructor {args} {
        itk_component add label {
            label $itk_interior.l1 -text "Hello World!"
        }
        pack $itk_component(label)

        eval itk_initialize $args
    }
    itk_option define -background background Background #d9d9d9 {
        puts "new background: $itk_option(-background)"
    }
}
itk_option remove optName ?optName optName ...?
Removes one or more options from the composite option list for a mega-widget. Here, optName can have one of the forms described above for the "itk_option add" command.
Options are normally integrated into the composite option list when a component widget is first created. This method can be used to remove options at a later time. For example, a derived class can override an option defined in a base class by removing and redefining the option:
class Base {
    inherit Widget
    constructor {args} {
        eval itk_initialize $args
    }

    itk_option define -foo foo Foo "" {
        puts "Base: $itk_option(-foo)"
    }
}

class Derived {
    inherit Base

    constructor {args} {
        itk_option remove Base::foo
        eval itk_initialize $args
    }
    itk_option define -foo foo Foo "" {
        puts "Derived: $itk_option(-foo)"
    }
}
Without the "itk_option remove" command, the code fragments for both of the "-foo" options would be executed each time the composite "-foo" option is configured. In the example above, the Base::foo option is suppressed in all Derived class widgets, so only the Derived::foo option remains.

PROTECTED VARIABLES

Derived classes can find useful information in the following protected variables.
itk_component(name)
The "itk_component" array returns the real window path name for a component widget with the symbolic name name. The same information can be queried using the component method, but accessing this array is faster and more convenient.
itk_interior
This variable contains the name of the window that acts as a parent for internal components. It is initialized to the name of the "hull" component provided by the Widget and Toplevel classes. Derived classes can override the initial setting to point to another interior window to be used for further-derived classes.
itk_option(option)
The "itk_option" array returns the current option value for the composite widget option named option. Here, the option name should include a leading "-" sign. The same information can be queried using the cget method, but accessing this array is faster and more convenient.

KEYWORDS

itk, Widget, Toplevel, mega-widget
[ itk ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itk - Toplevel (n)

[incr\ Tk]

NAME

Toplevel - base class for mega-widgets in a top-level window

INHERITANCE

itk::Archetype <- itk::Toplevel

STANDARD OPTIONS

backgroundcursor

See the "options" manual entry for details on the standard options.

WIDGET-SPECIFIC OPTIONS

Name: title
Class: Title
Command-Line Switch: -title

  • Sets the title that the window manager displays in the title bar above the window. The default title is the null string.

DESCRIPTION

The Toplevel class inherits everything from the Archetype class, and adds a Tk toplevel called the "hull" component to represent the body of the mega-widget. The window class name for the hull is set to the most-specific class name for the mega-widget. The protected variable itk_interior contains the window path name for the "hull" component. Derived classes specialize this widget by packing other widget components into the hull.

Since the hull for the Toplevel class is implemented with a Tk toplevel, mega-widgets in the Toplevel class have their own toplevel window. This class is used to create dialog boxes and other pop-up windows.

COMPONENTS

Name:hull
Class:Toplevel

  • The "hull" component acts as the body for the entire mega-widget. Other components are packed into the hull to further specialize the widget.

EXAMPLE

The following example implements a MessageInfo mega-widget. It creates a pop-up message that the user can dismiss by pushing the "Dismiss" button.

option add *MessageInfo.title "Notice" widgetDefault

class MessageInfo {
    inherit itk::Toplevel

    constructor {args} {
        itk_component add dismiss {
            button $itk_interior.dismiss -text "Dismiss"
                -command "destroy $itk_component(hull)"
        }
        pack $itk_component(dismiss) -side bottom -pady 4

        itk_component add separator {
            frame $itk_interior.sep -height 2 -borderwidth 1 -relief sunken
        }
        pack $itk_component(separator) -side bottom -fill x -padx 4

        itk_component add icon {
            label $itk_interior.icon -bitmap info
        }
        pack $itk_component(icon) -side left -padx 8 -pady 8

        itk_component add infoFrame {
            frame $itk_interior.info
        }
        pack $itk_component(infoFrame) -side left -expand yes
            -fill both -padx 4 -pady 4

        itk_component add message {
            label $itk_interior.mesg -width 20
        } {
            usual
            rename -text -message message Text
        }
        pack $itk_component(message) -expand yes -fill both

        eval itk_initialize $args

        after idle [code $this centerOnScreen]
    }

    protected method centerOnScreen {} {
        update idletasks
        set wd [winfo reqwidth $itk_component(hull)]
        set ht [winfo reqheight $itk_component(hull)]
        set x [expr ([winfo screenwidth $itk_component(hull)]-$wd)/2]
        set y [expr ([winfo screenheight $itk_component(hull)]-$ht)/2]
        wm geometry $itk_component(hull) +$x+$y
    }
}

usual MessageInfo {
    keep -background -cursor -foreground -font
    keep -activebackground -activeforeground -disabledforeground
    keep -highlightcolor -highlightthickness
}

#
# EXAMPLE:  Create a notice window:
#
MessageInfo .m -message "File not found:n/usr/local/bin/foo"

KEYWORDS

itk, Archetype, Widget, mega-widget
[ itk ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itk - Widget (n)

[incr\ Tk]

NAME

Widget - base class for mega-widgets within a frame

INHERITANCE

itk::Archetype <- itk::Widget

STANDARD OPTIONS

backgroundcursor

See the "options" manual entry for details on the standard options.

DESCRIPTION

The Widget class inherits everything from the Archetype class, and adds a Tk frame called the "hull" component to represent the body of the mega-widget. The window class name for the hull is set to the most-specific class name for the mega-widget. The protected variable itk_interior contains the window path name for the "hull" component. Derived classes specialize this widget by packing other widget components into the hull.

Since the hull for the Widget class is implemented with a Tk frame, mega-widgets in the Widget class can be packed into other frames and toplevels.

COMPONENTS

Name:hull
Class:Frame

  • The "hull" component acts as the body for the entire mega-widget. Other components are packed into the hull to further specialize the widget.

EXAMPLE

The following example implements a simple TextDisplay mega-widget. It creates a read-only display of text with a text widget and a scrollbar.

option add *TextDisplay.wrap none widgetDefault
option add *TextDisplay.textBackground ivory widgetDefault
option add *TextDisplay.width 40 widgetDefault
option add *TextDisplay.height 10 widgetDefault

class TextDisplay {
    inherit itk::Widget

    constructor {args} {
        itk_component add text {
            text $itk_interior.info -state disabled
                -yscrollcommand [code $itk_interior.sbar set]
        } {
            usual
            keep -tabs -wrap -width -height
            rename -background -textbackground textBackground Background
        }
        pack $itk_component(text) -side left -expand yes -fill both

        itk_component add scrollbar {
            scrollbar $itk_interior.sbar
                -command [code $itk_interior.info yview]
        }
        pack $itk_component(scrollbar) -side right -fill y

        eval itk_initialize $args
    }

    public method display {info}
    public method append {info}
}

body TextDisplay::display {info} {
    $itk_component(text) configure -state normal
    $itk_component(text) delete 1.0 end
    $itk_component(text) insert 1.0 $info
    $itk_component(text) configure -state disabled
}

body TextDisplay::append {info} {
    $itk_component(text) configure -state normal
    $itk_component(text) insert end $info
    $itk_component(text) configure -state disabled
}

usual TextDisplay {
    keep -background -cursor -foreground -font
    keep -activebackground -activerelief
    keep -highlightcolor -highlightthickness
    keep -insertbackground -insertborderwidth -insertwidth
    keep -insertontime -insertofftime
    keep -selectbackground -selectborderwidth -selectforeground
    keep -textbackground -troughcolor
}

#
# EXAMPLE:  Display the /etc/passwd file
#
TextDisplay .file -background red
pack .file

.file display [exec cat /etc/passwd]

KEYWORDS

itk, Archetype, Widget, mega-widget
[ itk ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itk - itk (n)

[incr\ Tk]

NAME

itk - framework for building mega-widgets in Tcl/Tk

DESCRIPTION

Mega-widgets are high-level widgets that are constructed using Tk widgets as component parts, usually without any C code. A fileselectionbox, for example, may have a few listboxes, some entry widgets and some control buttons. These individual widgets are put together in a way that makes them act like one big widget. A fileselectionbox mega-widget can be created with a command like:

fileselectionbox .fsb -background blue -foreground white
Once it has been created, it can be reconfigured with a command like:
.fsb configure -background green -foreground black
and all of its internal components will change color. Each mega-widget has a set of methods that can be used to manipulate it. For example, the current selection can be queried from a fileselectionbox like this:
set fileName [.fsb get]
In effect, a mega-widget looks and acts exactly like a Tk widget, but is considerably easier to implement.

[incrTk] is a framework for building mega-widgets. It uses [incrTcl] to support the object paradigm, and adds base classes which provide default widget behaviors.

All [incrTk] widgets are derived from the Archetype base class. This class manages internal component widgets, and provides methods like "configure" and "cget" to access configuration options.

The Widget base class inherits everything from Archetype, and adds a Tk frame which acts as a container for the mega-widget. It is used to build mega-widgets that sit inside of other frames and toplevels. Derived classes create other internal components and pack them into the "hull" frame created by the Widget base class.

The Toplevel base class inherits everything from Archetype, but adds a Tk toplevel which acts as a container for the mega-widget. It is used to build mega-widgets, such as dialog boxes, that have their own toplevel window. Derived classes create other internal components and pack them into the "hull" toplevel created by the Toplevel base class.

[incr Widgets] LIBRARY

[incrWidgets] is a mega-widget library built using [incrTk]. It can be used right out of the box, and contains more than 30 different widget classes, including:

  1. fileselectiondialog
  2. tabnotebook
  3. panedwindow
  4. combobox
  5. optionmenu
  6. scrolledlistbox
  7. scrolledframe
  8. messagedialog
  9. and many others...

The catalog demo in the "iwidgets/demos" directory shows all of the available widgets in action. Each widget class has its own man page describing the features available.

KEYWORDS

class, object, object-oriented, mega-widget
[ itk ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itk - itkvars (n)

[incr\ Tk]

NAME

itkvars - variables used by [incrTk]

DESCRIPTION

The following global variables are created and managed automatically by the [incrTk] library. Except where noted below, these variables should normally be treated as read-only by application-specific code and by users.

itk::library
When an interpreter is created, [incrTk] initializes this variable to hold the name of a directory containing the system library of [incrTk] scripts. The initial value of itk::library is set from the ITK_LIBRARY environment variable if it exists, or from a compiled-in value otherwise.
When [incrTk] is added to an interpreter, it executes the script "init.itk" in this directory. This script, in turn, looks for other script files with the name "init.xxx". Mega-widget libraries will be automatically initialized if they install a script named "init.xxx" in this directory, where "xxx" is the name of the mega-widget library. For example, the [incrWidgets] library installs the script "init.iwidgets" in this directory. This script establishes the "iwidgets" namespace, and sets up autoloading for all [incrWidgets] commands.

KEYWORDS

itcl, itk, variables
[ itk ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


itk - usual (n)

[incr\ Tk]

NAME

usual - access default option-handling commands
for a mega-widget component

SYNOPSIS

usual ?tag? ?commands?

DESCRIPTION

The usual command is used outside of an [incrTcl] class definition to define the usual set of option-handling commands for a component widget. Option-handling commands are used when a component is registered with the Archetype base class via the "itk_component add" method. They specify how the component's configuration options should be integrated into the composite option list for the mega-widget. Options can be kept, renamed, or ignored, as described in the Archetype man page.

It is tedious to include the same declarations again and again whenever components are added. The usual command allows a standard code fragment to be registered for each widget class, which is used by default to handle the options. All of the standard Tk widgets have usual declarations defined in the [incrTk] library. Similar usual declarations should be created whenever a new mega-widget class is conceived. Only the most-generic options should be included in the usual declaration.

The tag name is usually the name of a widget class, which starts with a capital letter; however, any string registered here can be used later with the usual command described on the Archetype man page.

If the commands argument is specified, it is associated with the tag string, and can be accessed later via itk_component add.

If only the tag argument is specified, this command looks for an existing tag name and returns the commands associated with it. If there are no commands associated with tag, this command returns the null string.

If no arguments are specified, this command returns a list of all tag names previously registered.

EXAMPLE

Following is the usual declaration for the standard Tk button widget:
usual Button {
    keep -background -cursor -foreground -font
    keep -activebackground -activeforeground -disabledforeground
    keep -highlightcolor -highlightthickness
    rename -highlightbackground -background background Background
}
Only the options that would be common to all buttons in a single mega-widget are kept or renamed. Options like "-text" that would be unique to a particular button are ignored.

KEYWORDS

itk, Archetype, component, mega-widget
[ itk ]
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


iwidgets Manual

Iwidget

Classes

buttonbox | Create and manipulate a manager widget for buttons
calendar | Create and manipulate a monthly calendar
canvasprintbox | Create and manipulate a canvas print box widget
canvasprintdialog | Create and manipulate a canvas print dialog widget
checkbox | Create and manipulate a checkbox widget
combobox | Create and manipulate combination box widgets
dateentry | Create and manipulate a dateentry widget
datefield | Create and manipulate a date field widget
dialog | Create and manipulate a dialog widget
dialogshell | Create and manipulate a dialog shell widget
disjointlistbox | Create and manipulate a disjointlistbox widget
entryfield | Create and manipulate a entry field widget
extbutton | Extends the behavior of the Tk button by allowing
extfileselectionbox | Create and manipulate a file selection box widget
extfileselectiondialog | Create and manipulate a file selection dialog widget
feedback | Create and manipulate a feedback widget to display feedback on
fileselectionbox | Create and manipulate a file selection box widget
fileselectiondialog | Create and manipulate a file selection dialog widget
finddialog | Create and manipulate a find dialog widget
hierarchy | Create and manipulate a hierarchy widget
hyperhelp | Create and manipulate a hyperhelp widget
labeledframe | Create and manipulate a labeled frame widget
labeledwidget | Create and manipulate a labeled widget
mainwindow | Create and manipulate a mainwindow widget
menubar | Create and manipulate menubar menu widgets
messagebox | Create and manipulate a messagebox text widget
messagedialog | Create and manipulate a message dialog widget
notebook | create and manipulate notebook widgets
optionmenu | Create and manipulate a option menu widget
panedwindow | Create and manipulate a paned window widget
promptdialog | Create and manipulate a prompt dialog widget
pushbutton | Create and manipulate a push button widget
radiobox | Create and manipulate a radiobox widget
scopedobject | Create and manipulate a scoped \[incr Tcl\] class object.
scrolledcanvas | Create and manipulate scrolled canvas widgets
scrolledframe | Create and manipulate scrolled frame widgets
scrolledhtml | Create and manipulate a scrolled text widget with the capability
scrolledlistbox | Create and manipulate scrolled listbox widgets
scrolledtext | Create and manipulate a scrolled text widget
selectionbox | Create and manipulate a selection box widget
selectiondialog | Create and manipulate a selection dialog widget
shell | Create and manipulate a shell widget
spindate | Create and manipulate time spinner widgets
spinint | Create and manipulate a integer spinner widget
spinner | Create and manipulate a spinner widget
spintime | Create and manipulate time spinner widgets
tabnotebook | create and manipulate tabnotebook widgets
tabset | create and manipulate tabs as as set
timeentry | Create and manipulate a timeentry widget
timefield | Create and manipulate a time field widget
toolbar | Create and manipulate a tool bar
watch | Create and manipulate time with a watch widgets

iwidgets

[ iwidgets ]
Copyright © 2001 ActiveState.


IWidgets buttonbox

 Table of Contents

iwidgets::buttonbox - Create and manipulate a manager widget for buttons

Synopsis

iwidgets::buttonbox pathName ?options?

Inheritance

itk::Widget <- iwidgets::buttonbox

Standard Options

background
cursor

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: orient

Class: Orient

Command-Line Switch: -orient

Orientation of the button box: horizontal or vertical. The

default is horizontal.

Name: padX

Class: PadX

Command-Line Switch: -padx

Specifies a non-negative padding distance to leave between the

button group and the outer edge of the button box in the x direc- tion. The value may be given in any of the forms acceptable to

Tk_GetPixels. The default is 5 pixels.

Name: padY

Class: PadY

Command-Line Switch: -pady

Specifies a non-negative padding distance to leave between the

button group and the outer edge of the button box in the y direc- tion. The value may be given in any of the forms acceptable to

Tk_GetPixels. The default is 5 pixels.

_________________________________________________________________

Description

The iwidgets::buttonbox command creates a manager widget for con-

trolling buttons. The button box also supports the display and invocation of a default button. The button box can be configured either horizontally or vertically.

Methods

The iwidgets::buttonbox command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

Many of the widget commands for the buttonbox take as one argu-

ment an indicator of which button of the button box to operate on. These indicators are called indexes and allow reference and manipulation of buttons regardless of their current map state. buttonbox indexes may be specified in any of the following forms:

number
Specifies the button numerically, where 0 corresponds to the left/top-most button of the button box.
end
Indicates the right/bottom-most button of the button box.
default
Indicates the current default button of the button box. This is the button with the default ring displayed.
pattern
If the index doesn't satisfy one of the above forms then this form is used. Pattern is pattern-matched against the tag of each button in the button box, in order from left/top to right/left, until a matching entry is found. The rules of Tcl_StringMatch are used.

Widget-specific Methods

pathName add tag args

Add a button distinguished by tag to the end of the button box.

If additional arguments are present they specify options to be

applied to the button. See PushButton for information on the options available.
pathName buttonconfigure index ?options?

This command is similar to the configure command, except that it

applies to the options for an individual button, whereas config- ure applies to the options for the button box as a whole.

Options may have any of the values accepted by the PushButton

command. If options are specified, options are modified as indi- cated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for entry index (see Tk_ConfigureInfo for information on the format of this list).
pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::buttonbox command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::buttonbox command. pathName default index

Sets the default button to the button given by index. This

causes the default ring to appear arround the specified button. pathName delete index

Deletes the button given by index from the button box.

pathName hide index

Hides the button denoted by index. This doesn't remove the but-

ton permanently, just inhibits its display.
pathName index index

Returns the numerical index corresponding to index.

pathName insert index tag ?option value option value ...?

Same as the add command except that it inserts the new button

just before the one given by index, instead of appending to the end of the button box. The option, and value arguments have the same interpretation as for the add widget command. pathName invoke ?index?

Invoke the command associated with a button. If no arguments are

given then the current default button is invoked, otherwise the argument is expected to be a button index.
pathName show index

Display a previously hidden button denoted by index.

Example

package require Iwidgets 4.0
iwidgets::buttonbox .bb

.bb add Yes -text Yes -command «puts Yes"
.bb add No -text No -command «puts No"
.bb add Maybe -text Maybe -command «puts Maybe" .bb default Yes

pack .bb -expand yes -fill both

Author

Bret A. Schuhmacher

Mark L. Ulferts

Keywords

buttonbox, pushbutton, button, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: orient
  • Class: Orient
  • Command-Line Switch: -orient
  • Orientation of the button box: horizontal or vertical. The
  • Name: padX
  • Class: PadX
  • Command-Line Switch: -padx
  • Specifies a non-negative padding distance to leave between the
  • Tk_GetPixels. The default is 5 pixels.
  • Name: padY
  • Class: PadY
  • Command-Line Switch: -pady
  • Specifies a non-negative padding distance to leave between the
  • Tk_GetPixels. The default is 5 pixels.
  • Description
  • The iwidgets::buttonbox command creates a manager widget for con-
  • Methods
  • The iwidgets::buttonbox command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • Many of the widget commands for the buttonbox take as one argu-
  • Widget-specific Methods
  • Add a button distinguished by tag to the end of the button box.
  • If additional arguments are present they specify options to be
  • This command is similar to the configure command, except that it
  • Options may have any of the values accepted by the PushButton
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Sets the default button to the button given by index. This
  • Deletes the button given by index from the button box.
  • Hides the button denoted by index. This doesn't remove the but-
  • Returns the numerical index corresponding to index.
  • Same as the add command except that it inserts the new button
  • Invoke the command associated with a button. If no arguments are
  • Display a previously hidden button denoted by index.
  • Example
  • Author
  • Bret A. Schuhmacher
  • Mark L. Ulferts
  • Keywords


IWidgets calendar

 Table of Contents

iwidgets::calendar - Create and manipulate a monthly calendar

Synopsis

iwidgets::calendar pathName ?options?

Inheritance

itk::Widget <- iwidgets::calendar

Standard Options

background cursor foreground

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: backwardImage

Class: Image

Command-Line Switch: -backwardimage

Specifies a image to be displayed on the backwards calendar but-

ton. This image must have been created previously with the image create command. If none is specified, a default is provided.

Name: buttonForeground

Class: Foreground

Command-Line Switch: -buttonforeground

Specifies the foreground color of the forward and backward but-

tons in any of the forms acceptable to Tk_GetColor. The default color is blue.

Name: command

Class: Command

Command-Line Switch: -command

Specifies a Tcl script to executed upon selection of a date in

the calendar. If the command script contains any % characters, then the script will not be executed directly. Instead, a new script will be generated by replacing each %, and the character following it, with information from the calendar. The replace- ment depends on the character following the %, as defined in the list below.
%d

Replaced with the date selected in the format mm/dd/yyyy.

Name: currentDateFont

Class: Font

Command-Line Switch: -currentdatefont

Specifies the font used for the current date text in any of the

forms acceptable to Tk_GetFont.

Name: dateFont

Class: Font

Command-Line Switch: -datefont

Specifies the font used for the days of the month text in any of

the forms acceptable to Tk_GetFont.

Name: dayFont

Class: Font

Command-Line Switch: -dayfont

Specifies the font used for the days of the week text in any of

the forms acceptable to Tk_GetFont.

Name: days

Class: days

Command-Line Switch: -days

Specifies a list of values to be used for the days of the week

text to displayed above the days of the month. The default value is {Su Mo Tu We Th Fr Sa}.

Name: forewardImage

Class: Image

Command-Line Switch: -forewardimage

Specifies a image to be displayed on the forewards calendar but-

ton. This image must have been created previously with the image create command. If none is specified, a default is provided.

Name: height

Class: Height

Command-Line Switch: -height

Specifies a desired window height that the calendar widget should

request from its geometry manager. The value may be specified in any of the forms acceptable to Tk_GetPixels. The default height is 165 pixels.

Name: outline

Class: Outline

Command-Line Switch: -outline

Specifies the outline color used to surround the days of the

month text in any of the forms acceptable to Tk_GetColor. The default is the same color as the background.

Name: selectColor

Class: Foreground

Command-Line Switch: -selectcolor

Specifies the color of the ring displayed that distinguishes the

currently selected date in any of the forms acceptable to Tk_Get-

Color. The default is red.

Name: selectThickness

Class: SelectThickness

Command-Line Switch: -selectthickness

Specifies the thickness of the ring displayed that distinguishes

the currently selected date. The default is 3 pixels.

Name: startday

Class: Day

Command-Line Switch: -startday

Specifies the starting day for the week: sunday, monday, tuesday,

wednesday, thursday, friday, or saturday. The default is sunday.

Name: titleFont

Class: Font

Command-Line Switch: -titlefont

Specifies the font used for the title text which consists of the

month and year. The font may be given in any of the forms acceptable to Tk_GetFont.

Name: weekdayBackground

Class: Background

Command-Line Switch: -weekdaybackground

Specifies the background color for the weekdays which allows it

to be visually distinguished from the weekend. The color may be given in any of the forms acceptable to Tk_GetColor. The default is the same as the background.

Name: weekendBackground

Class: Background

Command-Line Switch: -weekendbackground

Specifies the background color for the weekends which allows it

to be visually distinguished from the weekdays. The color may be given in any of the forms acceptable to Tk_GetColor. The default is the same as the background.

Name: width

Class: Width

Command-Line Switch: -width

Specifies a desired window width that the calendar widget should

request from its geometry manager. The value may be specified in any of the forms acceptable to Tk_GetPixels. The default width is 200 pixels.
_________________________________________________________________

Description

The iwidgets::calendar command creates a calendar widget for the

selection of a date, displaying a single month at a time. But- tons exist on the top to change the month in effect turning the pages of a calendar. As a page is turned, the dates for the month are modified. Selection of a date visually marks that date. The selected value can be monitored via the -command option or just retrieved using the get command.

Methods

The iwidgets::calendar command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for calendar widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::calendar command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::calendar command. pathName get ?format?

Returns the currently selected date in a format of string or as

an integer clock value using the -string and -clicks format options respectively. The default is by string. Reference the clock command for more information on obtaining dates and their formats.
pathName select date

Changes the currently selected date to the value specified which

must be in the form of a date string, an integer clock value or as the keyword «now". Reference the clock command for more information on obtaining dates and their formats. Note that selecting a date does not change the month being shown to that of the date given. This chore is left to the show command. pathName show date

Changes the currently displayed date to be that of the date argu-

ment which must be in the form of a date string, an integer clock value or as the keyword «now". Reference the clock command for more information on obtaining dates and their formats.

Components

Name: forward

Class: Button

The forward component provides the button on the upper right of

the calendar that changes the month to be the next. See the «button» widget manual entry for details on the forward component item.

Name: page

Class: Canvas

The page component provides the canvas on which the title, days

of the week, and days of the month appear. See the «canvas» wid- get manual entry for details on the page component item.

Name: backward

Class: Button

The backward component provides the button on the upper right of

the
calendar that changes the month to be the next. See the «button" widget manual entry for details on the backward component item.

Example

package require Iwidgets 4.0
proc selectCmd {date} {
puts $date
}

iwidgets::calendar .c -command {selectCmd %d} \ -weekendbackground mistyrose \
-weekdaybackground ghostwhite -outline black \ -startday wednesday -days {We Th Fr Sa Su Mo Tu} pack .c

Author

Mark L. Ulferts

Michael J. McLennan

Keywords

calendar, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: backwardImage
  • Class: Image
  • Command-Line Switch: -backwardimage
  • Specifies a image to be displayed on the backwards calendar but-
  • Name: buttonForeground
  • Class: Foreground
  • Command-Line Switch: -buttonforeground
  • Specifies the foreground color of the forward and backward but-
  • Name: command
  • Class: Command
  • Command-Line Switch: -command
  • Specifies a Tcl script to executed upon selection of a date in
  • Replaced with the date selected in the format mm/dd/yyyy.
  • Name: currentDateFont
  • Class: Font
  • Command-Line Switch: -currentdatefont
  • Specifies the font used for the current date text in any of the
  • Name: dateFont
  • Class: Font
  • Command-Line Switch: -datefont
  • Specifies the font used for the days of the month text in any of
  • Name: dayFont
  • Class: Font
  • Command-Line Switch: -dayfont
  • Specifies the font used for the days of the week text in any of
  • Name: days
  • Class: days
  • Command-Line Switch: -days
  • Specifies a list of values to be used for the days of the week
  • Name: forewardImage
  • Class: Image
  • Command-Line Switch: -forewardimage
  • Specifies a image to be displayed on the forewards calendar but-
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies a desired window height that the calendar widget should
  • Name: outline
  • Class: Outline
  • Command-Line Switch: -outline
  • Specifies the outline color used to surround the days of the
  • Name: selectColor
  • Class: Foreground
  • Command-Line Switch: -selectcolor
  • Specifies the color of the ring displayed that distinguishes the
  • Color. The default is red.
  • Name: selectThickness
  • Class: SelectThickness
  • Command-Line Switch: -selectthickness
  • Specifies the thickness of the ring displayed that distinguishes
  • Name: startday
  • Class: Day
  • Command-Line Switch: -startday
  • Specifies the starting day for the week: sunday, monday, tuesday,
  • Name: titleFont
  • Class: Font
  • Command-Line Switch: -titlefont
  • Specifies the font used for the title text which consists of the
  • Name: weekdayBackground
  • Class: Background
  • Command-Line Switch: -weekdaybackground
  • Specifies the background color for the weekdays which allows it
  • Name: weekendBackground
  • Class: Background
  • Command-Line Switch: -weekendbackground
  • Specifies the background color for the weekends which allows it
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies a desired window width that the calendar widget should
  • Description
  • The iwidgets::calendar command creates a calendar widget for the
  • Methods
  • The iwidgets::calendar command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for calendar widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Returns the currently selected date in a format of string or as
  • Changes the currently selected date to the value specified which
  • Changes the currently displayed date to be that of the date argu-
  • Components
  • Name: forward
  • Class: Button
  • The forward component provides the button on the upper right of
  • Name: page
  • Class: Canvas
  • The page component provides the canvas on which the title, days
  • Name: backward
  • Class: Button
  • The backward component provides the button on the upper right of
  • Example
  • Author
  • Mark L. Ulferts
  • Michael J. McLennan
  • Keywords


IWidgets canvasprintbox

 Table of Contents

iwidgets::canvasprintbox - Create and manipulate a canvas print box widget

Synopsis

iwidgets::canvasprintbox pathName ?options?

Inheritance

itk::Widget <- iwidgets::Canvasprintbox

Standard Options

activeBackground background borderWidth cursor

foreground
highlightBackground highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth relief repeatDelay repeatInterval selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

Widget-specific Options

Name: filename

Class: FileName

Command-Line Switch: -filename

The file to write the postscript output to (Only when output is

set to «file"). If posterizing is turned on and hpagecnt and/or vpagecnt is more than 1, x.y is appended to the filename where x is the horizontal page number and y the vertical page number.

Name: hpagecnt

Class: PageCnt

Command-Line Switch: -hpagecnt

Is used in combination with posterize to determine over how many

pages the output should be distributed. This attribute specifies how many pages should be used horizontaly. Any change to this attribute will automatically update the «stamp". Defaults to 1.

Name: orient

Class: Orient

Command-Line Switch: -orient

Determines the orientation of the output to the printer (or

file). It can take the value «portrait» or «landscape" (default). Changes to this attribute will be reflected immedi- ately in the «stamp". Defaults to «landscape» but will be changed automaticaly to the value deemed appropiate for the cur- rent canvas. Setting this attribute when the canvasprintbox is first constructed (instead of using the «configure» method) will turn off the auto adjustment of this attribute.

Name: output

Class: Output

Command-Line Switch: -output

Specifies where the postscript output should go: to the printer

or to a file. Can take on the values «printer» or «file". The corresponding entry-widget will reflect the contents of either the printcmd attribute or the filename attribute. Defaults to «printer".

Name: pageSize

Class: PageSize

Command-Line Switch: -pagesize

The pagesize the printer supports. Changes to this attribute will

be reflected immediately in the «stamp". Defaults to «a4".

Name: posterize

Class: Posterize

Command-Line Switch: -posterize

Indicates if posterizing is turned on or not. Posterizing the

output means that it is possible to distribute the output over more than one page. This way it is possible to print a can- vas/region which is larger than the specified pagesize without stretching. If used in combination with stretching it can be used to «blow up» the contents of a canvas to as large as size as you want (See attributes: hpagecnt and vpagecnt). Any change to this attribute will automatically update the «stamp". Defaults to 0.

Name: printCmd

Class: PrintCmd

Command-Line Switch: -printcmd

The command to execute when printing the postscript output. The

command will get the postscript directed to its standard input (Only when output is set to «printer"). Defaults to «lpr".

Name: printRegion

Class: PrintRegion

Command-Line Switch: -printregion

A list of four coordinates specifying which part of the canvas to

print. An empty list means that the canvas' entire scrollregion should be printed. Any change to this attribute will automati- cally update the «stamp". Defaults to an empty list.

Name: stretch

Class: Stretch

Command-Line Switch: -stretch

Determines if the output should be stretched to fill the page (as

defined by the attribute pagesize) as large as possible. The aspect-ratio of the output will be retained and the output will never fall outside of the boundaries of the page. Defaults to 0 but will be changed automaticaly to the value deemed appropiate for the current canvas. Setting this attribute when the can- vasprintbox is first constructed (instead of using the «config- ure» method) will turn off the auto adjustment of this attribute.

Name: vPageCnt

Class: PageCnt

Command-Line Switch: -vpagecnt

Is used in combination with «posterize» to determine over how

many pages the output should be distributed. This attribute spec- ifies how many pages should be used verticaly. Any change to this attribute will automatically update the «stamp". Defaults to 1.
_________________________________________________________________

Description

Implements a print box for printing the contents of a canvas wid-

get to a printer or a file. It is possible to specify page orien- tation, the number of pages to print the image on and if the out- put should be stretched to fit the page. Options exist to control the appearance and actions of the widget.

Methods

The iwidgets::canvasprintbox command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for canvasprintbox widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::canvasprintbox command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::canvasprintbox command. pathName getoutput

Returns the value of the printercmd or filename option depending

on the current setting of output.
pathName print

Perfrom the actual printing of the canvas using the current set-

tings of all the attributes. Returns a boolean indicating wether the printing was successful or not.
pathName refresh

Retrieves the current value for all edit fields and updates the

stamp accordingly. Is useful for Apply-buttons. pathName setcanvas canvas

This is used to set the canvas that has to be printed. A stamp-

sized copy will automatically be drawn to show how the output would look with the current settings.
pathName stop

Stops the drawing of the «stamp". I'm currently unable to detect

when a Canvasprintbox gets destroyed or withdrawn. It's therefore advised that you perform a stop before you do something like that.

Components

Name: prtflentry

Class: Entry

The prtflentry component is the entry field for user input of the

filename or printer command (depending on the value of output).

Name: hpcnt

Class: Entry

The hpcnt component is the entry field for user input of the num-

ber of pages to use horizontaly when posterize is turned on.

Name: vpcnt

Class: Entry

The vpcnt component is the entry field for user input of the num-

ber of pages to use verticaly when posterize is turned on.

Example

package require Iwidgets 4.0
iwidgets::canvasprintbox .fsb -orient landscape -stretch 1 pack .fsb -padx 10 -pady 10 -fill both -expand yes

Author

Tako Schotanus

Tako.Schotanus@bouw.tno.nl

Keywords

canvasprintbox, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • Widget-specific Options
  • Name: filename
  • Class: FileName
  • Command-Line Switch: -filename
  • The file to write the postscript output to (Only when output is
  • Name: hpagecnt
  • Class: PageCnt
  • Command-Line Switch: -hpagecnt
  • Is used in combination with posterize to determine over how many
  • Name: orient
  • Class: Orient
  • Command-Line Switch: -orient
  • Determines the orientation of the output to the printer (or
  • Name: output
  • Class: Output
  • Command-Line Switch: -output
  • Specifies where the postscript output should go: to the printer
  • Name: pageSize
  • Class: PageSize
  • Command-Line Switch: -pagesize
  • The pagesize the printer supports. Changes to this attribute will
  • Name: posterize
  • Class: Posterize
  • Command-Line Switch: -posterize
  • Indicates if posterizing is turned on or not. Posterizing the
  • Name: printCmd
  • Class: PrintCmd
  • Command-Line Switch: -printcmd
  • The command to execute when printing the postscript output. The
  • Name: printRegion
  • Class: PrintRegion
  • Command-Line Switch: -printregion
  • A list of four coordinates specifying which part of the canvas to
  • Name: stretch
  • Class: Stretch
  • Command-Line Switch: -stretch
  • Determines if the output should be stretched to fill the page (as
  • Name: vPageCnt
  • Class: PageCnt
  • Command-Line Switch: -vpagecnt
  • Is used in combination with "posterize" to determine over how
  • Description
  • Implements a print box for printing the contents of a canvas wid-
  • Methods
  • The iwidgets::canvasprintbox command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for canvasprintbox widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Returns the value of the printercmd or filename option depending
  • Perfrom the actual printing of the canvas using the current set-
  • Retrieves the current value for all edit fields and updates the
  • This is used to set the canvas that has to be printed. A stamp-
  • Stops the drawing of the "stamp". I'm currently unable to detect
  • Components
  • Name: prtflentry
  • Class: Entry
  • The prtflentry component is the entry field for user input of the
  • Name: hpcnt
  • Class: Entry
  • The hpcnt component is the entry field for user input of the num-
  • Name: vpcnt
  • Class: Entry
  • The vpcnt component is the entry field for user input of the num-
  • Example
  • Author
  • Tako Schotanus
  • Tako.Schotanus@bouw.tno.nl
  • Keywords


IWidgets canvasprintdialog

 Table of Contents

iwidgets::canvasprintdialog - Create and manipulate a canvas print dialog widget

Synopsis

iwidgets::canvasprintdialog pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Dialogshell <- iwidgets::Dialog <- iwidgets::Canvasprintdialog

Standard Options

activeBackground background borderWidth cursor

foreground
highlightBackground highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth relief repeatDelay repeatInterval selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

filename hpagecnt orient output pagesize posterize printcmd printregion vpagecnt

See the «canvasprintbox» widget manual entry for details on the

above associated options.

Inherited Options

buttonBoxPadX buttonBoxPadY buttonBoxPos padX

padY
separator thickness

See the «dialogshell» widget manual entry for details on the

above inherited options.

master
modality

See the «shell» widget manual entry for details on the above

inherited options.
title

See the «Toplevel» widget manual entry for details on the above

inherited options.

Widget-specific Options

_________________________________________________________________

Description

The iwidgets::canvasprintdialog command creates a print dialog

for printing the contents of a canvas widget to a printer or a file. It is possible to specify page orientation, the number of pages to print the image on and if the output should be stretched to fit the page.

Methods

The iwidgets::canvasprintdialog command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for canvasprintdialog wid-

gets:

Associated Methods

getoutput setcanvas refresh print

See the «canvasprintbox» class manual entry for details on the

associated methods.

Inherited Methods

add buttonconfigure defaulthide insert invoke show

See the «buttonbox» widget manual entry for details on the above

inherited methods.

activate
deactivate

See the «dialogshell» widget manual entry for details on the

above inherited methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::canvasprintdialog command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::canvasprintdialog command.

Components

Name: cpb

Class: Canvasprintbox

The cpb component is the canvas print box for the canvas print

dialog. See the «canvasprintbox» widget manual entry for details on the cpb component item.

Example

package require Iwidgets 4.0
iwidgets::canvasprintdialog .cpb
.cpb activate

Author

Tako Schotanus

Tako.Schotanus@bouw.tno.nl

Keywords

canvasprintdialog, canvasprintbox, dialog, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "canvasprintbox" widget manual entry for details on the
  • Inherited Options
  • See the "dialogshell" widget manual entry for details on the
  • See the "shell" widget manual entry for details on the above
  • See the "Toplevel" widget manual entry for details on the above
  • Widget-specific Options
  • Description
  • The iwidgets::canvasprintdialog command creates a print dialog
  • Methods
  • The iwidgets::canvasprintdialog command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for canvasprintdialog wid-
  • Associated Methods
  • See the "canvasprintbox" class manual entry for details on the
  • Inherited Methods
  • See the "buttonbox" widget manual entry for details on the above
  • See the "dialogshell" widget manual entry for details on the
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: cpb
  • Class: Canvasprintbox
  • The cpb component is the canvas print box for the canvas print
  • Example
  • Author
  • Tako Schotanus
  • Tako.Schotanus@bouw.tno.nl
  • Keywords


IWidgets checkbox

 Table of Contents

iwidgets::checkbox - Create and manipulate a checkbox widget

Synopsis

iwidgets::checkbox pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledframe <- iwidgets::Checkbox

Standard Options

background borderWidth cursor disabledForeground foreground relief selectColor

See the «options» manual entry for details on the standard

options.

Inherited Options

labelBitmap labelFont labelImage labelMargin

labelPos
labelText labelVariable

See the «labeledframe» class manual entry for details on the

inherited options.

Widget-specific Options

Name: command

Class: Command

Command-Line Switch: -command

Specifies a Tcl command procedure to be evaluated following a

change in the current check box selection.

Name: orient

Class: Orient

Command-Line Switch: -orient

Default Value: vertical

Specifies the orientation of the checkbuttons within the check-

box. Valid values are either «horizontal» or «vertical". _________________________________________________________________

Description

The iwidgets::checkbox command creates a check button box widget

capable of adding, inserting, deleting, selecting, and configur- ing checkbuttons as well as obtaining the currently selected but- ton.

Methods

The iwidgets::checkbox command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

Many of the widget commands for the checkbox take as one argument

an indicator of which checkbutton of the checkbox to operate on.

These indicators are called indexes and allow reference and

manipulation of checkbuttons. Checkbox indexes may be specified in any of the following forms:

number
Specifies the checkbutton numerically, where 0 corresponds to the top checkbutton of the checkbox.
end
Indicates the last checkbutton of the checkbox.
pattern
If the index doesn't satisfy one of the above forms then this form is used. Pattern is pattern-matched against the tag of each checkbutton in the checkbox, in order from top to bottom, until a matching entry is found. The rules of Tcl_StringMatch are used.

Widget-specific Methods

pathName add tag ?option value option value?

Adds a new checkbutton to the checkbuttond window on the bottom.

The command takes additional options which are passed on to the

checkbutton as construction arguments. These include the stan- dard Tk checkbutton options. The tag is returned.

pathName buttonconfigure index ?options?

This command is similar to the configure command, except that it

applies to the options for an individual checkbutton, whereas configureapplies to the options for the checkbox as a whole.

Options may have any of the values accepted by the add widget

command. If options are specified, options are modified as indi- cated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for entry index (see Tk_ConfigureInfo for information on the format of this list).
pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::checkbox command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::checkbox command. pathName delete index

Deletes a specified checkbutton given an index.

pathName deselect index

Deselects a specified checkbutton given an index.

pathName flash index

Flashes a specified checkbutton given an index.

pathName get ?index?

Returns the tags of the currently selected checkbuttons or the

selection status of specific checkbutton when given an index. pathName index index

Returns the numerical index corresponding to index.

pathName insert index tag ?option value option value ...?

Same as the add command except that it inserts the new checkbut-

ton just before the one given by index, instead of appending to the end of the checkbox. The option, and value arguments have the same interpretation as for the add widget command. pathName select index

Selects a specified checkbutton given an index.

Example

package require Iwidgets 4.0
iwidgets::checkbox .cb -labeltext Styles
.cb add bold -text Bold
.cb add italic -text Italic
.cb add underline -text Underline
.cb select underline

pack .cb -padx 10 -pady 10 -fill both -expand yes

Author

John A. Tucker

Keywords

checkbox, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "labeledframe" class manual entry for details on the
  • Widget-specific Options
  • Name: command
  • Class: Command
  • Command-Line Switch: -command
  • Specifies a Tcl command procedure to be evaluated following a
  • Name: orient
  • Class: Orient
  • Command-Line Switch: -orient
  • Default Value: vertical
  • Specifies the orientation of the checkbuttons within the check-
  • Description
  • The iwidgets::checkbox command creates a check button box widget
  • Methods
  • The iwidgets::checkbox command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • Many of the widget commands for the checkbox take as one argument
  • These indicators are called indexes and allow reference and
  • Widget-specific Methods
  • Adds a new checkbutton to the checkbuttond window on the bottom.
  • The command takes additional options which are passed on to the
  • This command is similar to the configure command, except that it
  • Options may have any of the values accepted by the add widget
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Deletes a specified checkbutton given an index.
  • Deselects a specified checkbutton given an index.
  • Flashes a specified checkbutton given an index.
  • Returns the tags of the currently selected checkbuttons or the
  • Returns the numerical index corresponding to index.
  • Same as the add command except that it inserts the new checkbut-
  • Selects a specified checkbutton given an index.
  • Example
  • Author
  • John A. Tucker
  • Keywords


IWidgets combobox

 Table of Contents

iwidgets::combobox - Create and manipulate combination box wid- gets

Synopsis

iwidgets::combobox pathName ?options?

Inheritance

itk::Widget <- iwidgets::LabeledWidget <- iwidgets::Entryfield <- iwidgets::Combobox

Standard Options

background borderWidth cursor justify exportSelection foreground highlightColor highlightThickness

insertWidth
insertBackground insertOffTime insertOnTime insertWidth insertBorderWidth relief selectForeground selectBackground selectBorderWidth textVariable width

See the «options» manual entry for details on the standard

options.

Associated Options

hscrollmode textBackground textFont vscrollmode

See the «scrolledlistbox» manual entry for details on the above

inherited options.
show

See the «entry» manual entry for details on the above inherited

option.

Inherited Options

childSitePos command fixed focusCommand

invalid
textBackground textFont validate

See the «entryfield» class manual entry for details on the inher-

ited options.
labelBitmap labelFont labelImage labelMargin

labelPos
labelText labelVariable sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: arrowRelief

Class: Relief

Command-Line Switch: -arrowrelief

Specifies the relief style to use for a dropdown Combobox's arrow

button in a normal (not depressed) state. Acceptable values are raised, sunken, flat, ridge, and groove. Sunken is discouraged as this is the relief used to indicate a depressed state. This option has no effect on simple Comboboxes. The default is raised.

Name: completion

Class: Completion

Command-Line Switch: -completion

Boolean given in any of the forms acceptable to Tcl_GetBoolean

which determines whether insertions into the entry field, whether from the keyboard or programmatically via the insert method, are automatically completed with the first matching item from the listbox. The default is true.

Name: dropdown

Class: Dropdown

Command-Line Switch: -dropdown

Boolean describing the Combobox layout style given in any of the

forms acceptable to Tcl_GetBoolean. If true, the Combobox will be a dropdown style widget which displays an entry field and an arrow button which when activated will pop up a scrollable list of items. If false, a simple Combobox style will be used which has an entry field and a scrollable list beneath it which is always visible. Both styles allow an optional label for the entry field area. The default is true.

Name: editable

Class: Editable

Command-Line Switch: -editable

Boolean describing whether or not the text entry area is editable

by the user. If true the user can add items to the combobox by entering text into the entry area and then pressing Return. If false, the list of items is non-editable and can only be changed by calling the insert or delete methods. (The value in the entry field can still be modified by selecting from the list.) Given in any of the forms acceptable to Tcl_GetBoolean. The default is true.

Name: grab

Class: Grab

Command-Line Switch: -grab

This option sets the grab scope for the appearance of the listbox

in drop-down comboboxes. It can be either global or local. The default is local.

Name: listHeight

Class: Height

Command-Line Switch: -listheight

Height of the listbox specified in any of the forms acceptable to

Tk_GetPixels. The default is 150 pixels.

Name: margin

Class: Margin

Command-Line Switch: -margin

Specifies the width in pixels between the entry component and the

arrow button for a dropdown Combobox given in any of the forms acceptable to Tk_GetPixels. This option has no effect on a simple

Combobox. The default is 1.

Name: popupCursor

Class: Cursor

Command-Line Switch: -popupcursor

Specifies the cursor to be used for dropdown style listboxes. The

value may have any of the forms acceptable to Tk_GetCursor. The default is arrow.

Name: selectionCommand

Class: SelectionCommand

Command-Line Switch: -selectioncommand

Specifies a Tcl command procedure which is called when an item in

the listbox area is selected. The item will be selected in the list, the listbox will be removed if it is a dropdown Combobox, and the selected item's text will be inserted into the entry field before the -selectioncommand proc is called. The default is {}.

Name: state

Class: State

Command-Line Switch: -state

Specifies the overall state of the Combobox megawidget. Can be

either normal or disabled. If the Combobox is disabled, no text can be entered into the entry field, no selection can be made in the listbox, and the arrowBtn component is disabled. The default is normal.

Name: unique

Class: Unique

Command-Line Switch: -unique

Boolean describing whether or not duplicate items are allowed in

the combobox list. If true, then duplicates are not allowed to be inserted. If false, a duplicate entry causes selection of the item. Given in any of the forms acceptable to Tcl_GetBoolean. The default is true.
_________________________________________________________________

Description

The iwidgets::combobox command creates an enhanced entry field

widget with an optional associated label and a scrollable list.

When an item is selected in the list area of a Combobox, its

value is then displayed in the entry field text area. Function- ally similar to an Optionmenu, the Combobox adds (optional) list scrolling and (optional) item editing and inserting capabilities.

There are two basic styles of Comboboxes (determined by the

-dropdown option): dropdown and simple. The dropdown style adds an arrow button to the right of the entry field which when acti- vated will pop up (and down) the scrolled listbox beneath the entry field. The simple (non-dropdown) Combobox permanently dis- plays the listbox beneath the entry field and has no arrow but- ton. Either style allows an optional entry field label.

Methods

The iwidgets::combobox command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for Combobox widgets:

Associated Methods

icursor
scan

See the «entry» manual entries for details on the above associ-

ated methods.
curselection index see size

xview
yview

See the «listbox» manual entries for details on the above associ-

ated methods.

getcurselection justify
sort

See the «scrolledlistbox» manual entries for details on the above

associated methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::combobox command.
pathName clear ?component?

Clears the contents from one or both components. Valid component

values are list, or entry. With no component specified, both are cleared.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::combobox command. pathName delete component first ?last?

Delete one or more elements from a given component, list or

entry. If a list item to be removed is currently selected (dis- played in the entry field area), the entry field will be cleared. pathName get ?index?

With no arguments, returns the contents currently in the entry

field area. With a single argument, returns the contents of the listbox item at the indicated index.
pathName insert component index element ?element element ...?

Insert one or more new elements into the given component, list or

entry, just before the element given by index. pathName selection option first ?last?

Adjust the selection within the listbox component and updates the

contents of the entry field component to the value of the selected item. See the «listbox» manual entry for more details on parameter options.

Components

Name: entry

Class: Entry

Text entry area where the current selection is displayed. If the

Combobox is editable and its state is normal, the user can edit

the contents of this item.

Name: list

Class: Scrolledlistbox

Scrollable list which stores all the items which the user can

select from. For dropdown Comboboxes, this component is hidden until the user pops it up by pressing on the arrow button to the right of the entry component. For simple Comboboxes this compo- nent is always visible just beneath the entry component.

Default Bindings

The Combobox generally has the same bindings as its primary com-

ponent items - the Scrolledlistbox and Entryfield. However it also adds these:
[1] Button-1 mouse press on the arrow key of a dropdown Combobox causes the list to be popped up. If the combobox is non-editable, a Button-1 press on the entry field area will also pop up the list.
[2] Button-1 mouse press anywhere on the display removes a drop- down listbox which has been popped up, unless the keypress is upon one of the Combobox scrollbars which scrolls the list. If it is pressed upon an item in the list area, that item will be selected before the list is removed.
[3] Button-3 mouse press on the arrow key of a dropdown Combobox causes the next item to be selected. Shift-Button-3 causes the previous item to be selected.
[4] Escape keypress removes a dropdown list which has been popped up.
[5] The <space> and <Return> keystrokes select the current item.

They also remove the popped up list for dropdown comboboxes.

[6] Up and Down arrow keypresses from the entry field and arrow button component cause the previous and next items in the listbox to be selected respectively. Ctl-P and Ctl-N are similarly mapped for emacs emulation.
[7] Entry field and arrow button component Shift-Up and Shift-

Down arrow keys pop up and down the listbox of a dropdown Com-

bobox. The arrow button component also maps <Return> and <space> similarly.

Example

package require Iwidgets 4.0
proc selectCmd {} {
puts stdout «[.cb2 getcurselection]"
}

#
# Non-editable Dropdown Combobox
#
iwidgets::combobox .cb1 -labeltext Month: \
-selectioncommand {puts «selected: [.cb1 getcurselection]"} \ -editable false -listheight 185 -popupcursor hand1 .cb1 insert list end Jan Feb Mar Apr May June Jul Aug Sept Oct Nov Dec

#
# Editable Dropdown Combobox
#
iwidgets::combobox .cb2 -labeltext «Operating System:» -selectioncommand selectCmd .cb2 insert list end Linux HP-UX SunOS Solaris Irix .cb2 insert entry end L

pack .cb1 -padx 10 -pady 10 -fill x
pack .cb2 -padx 10 -pady 10 -fill x

Original Author

John S. Sigler

Current Maintainer

Mitch Gorman (logain@erols.com)

Keywords

combobox, entryfield, scrolledlistbox, itk::Widget, entry, list- box, widget, iwidgets

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "scrolledlistbox" manual entry for details on the above
  • See the "entry" manual entry for details on the above inherited
  • Inherited Options
  • See the "entryfield" class manual entry for details on the inher-
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: arrowRelief
  • Class: Relief
  • Command-Line Switch: -arrowrelief
  • Specifies the relief style to use for a dropdown Combobox's arrow
  • Name: completion
  • Class: Completion
  • Command-Line Switch: -completion
  • Boolean given in any of the forms acceptable to Tcl_GetBoolean
  • Name: dropdown
  • Class: Dropdown
  • Command-Line Switch: -dropdown
  • Boolean describing the Combobox layout style given in any of the
  • Name: editable
  • Class: Editable
  • Command-Line Switch: -editable
  • Boolean describing whether or not the text entry area is editable
  • Name: grab
  • Class: Grab
  • Command-Line Switch: -grab
  • This option sets the grab scope for the appearance of the listbox
  • Name: listHeight
  • Class: Height
  • Command-Line Switch: -listheight
  • Height of the listbox specified in any of the forms acceptable to
  • Tk_GetPixels. The default is 150 pixels.
  • Name: margin
  • Class: Margin
  • Command-Line Switch: -margin
  • Specifies the width in pixels between the entry component and the
  • Combobox. The default is 1.
  • Name: popupCursor
  • Class: Cursor
  • Command-Line Switch: -popupcursor
  • Specifies the cursor to be used for dropdown style listboxes. The
  • Name: selectionCommand
  • Class: SelectionCommand
  • Command-Line Switch: -selectioncommand
  • Specifies a Tcl command procedure which is called when an item in
  • Name: state
  • Class: State
  • Command-Line Switch: -state
  • Specifies the overall state of the Combobox megawidget. Can be
  • Name: unique
  • Class: Unique
  • Command-Line Switch: -unique
  • Boolean describing whether or not duplicate items are allowed in
  • Description
  • The iwidgets::combobox command creates an enhanced entry field
  • When an item is selected in the list area of a Combobox, its
  • There are two basic styles of Comboboxes (determined by the
  • Methods
  • The iwidgets::combobox command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for Combobox widgets:
  • Associated Methods
  • See the "entry" manual entries for details on the above associ-
  • See the "listbox" manual entries for details on the above associ-
  • See the "scrolledlistbox" manual entries for details on the above
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Clears the contents from one or both components. Valid component
  • Query or modify the configuration options of the widget. If no
  • Delete one or more elements from a given component, list or
  • With no arguments, returns the contents currently in the entry
  • Insert one or more new elements into the given component, list or
  • Adjust the selection within the listbox component and updates the
  • Components
  • Name: entry
  • Class: Entry
  • Text entry area where the current selection is displayed. If the
  • Combobox is editable and its state is normal, the user can edit
  • Name: list
  • Class: Scrolledlistbox
  • Scrollable list which stores all the items which the user can
  • Default Bindings
  • The Combobox generally has the same bindings as its primary com-
  • They also remove the popped up list for dropdown comboboxes.
  • Down arrow keys pop up and down the listbox of a dropdown Com-
  • Example
  • Original Author
  • John S. Sigler
  • Current Maintainer
  • Mitch Gorman (logain@erols.com)
  • Keywords


IWidgets dateentry

 Table of Contents

iwidgets::dateentry - Create and manipulate a dateentry widget

Synopsis

iwidgets::dateentry pathName ?options?

Inheritance

itk::Widget <- iwidgets::LabeledWidget <- iwidgets::Datefield <- iwidgets::Dateentry

Standard Options

background borderWidth cursor exportSelection foreground highlightColor highlightThickness insertBackground

justify
relief

See the «options» manual entry for details on the standard

options.

Inherited Options

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable
state
sticky

See the «labeledwidget» class manual entry for details on these

inherited options.
command iq state textBackground textFont

See the «datefield» class manual entry for details on these

inherited options.

Associated Options

backwardImage buttonForeground commandcurrentDateFont dateFont dayFont days forwardImage

outline
selectColor selectThickness startDay titleFont weekdayBackground weekendBackground

See the «calendar» manual entry for details on the associated

options.

Widget-specific Options

Name: grab

Class: Grab

Command-Line Switch: -grab

Specifies the grab level, local or global, to be obtained before

bringing up the popup calendar. The default is global. For more information concerning grab levels, consult the documentation for

Tk's grab command.

Name: icon

Class: Icon

Command-Line Switch: -icon

Specifies the calendar icon image to be used in the dateentry.

This image must have been created previously with the image cre-

ate command. Should one not be provided, then one will be gener- ated, pixmap if possible, bitmap otherwise.
_________________________________________________________________

Description

The iwidgets::dateentry command creates a quicken style date

entry field with a popup calendar by combining the datefield and calendar widgets together. This allows a user to enter the date via the keyboard or by using the mouse and selecting the calendar icon which brings up a popup calendar.

Methods

The iwidgets::dateentry command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

Option and the args determine the exact behavior of the command.

The following commands are possible for dateentry widgets:

Inherited Methods

get
isvalid show

See the «datefield» manual entry for details on the associated

methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::dateentry command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::dateentry command.

Components

Name: label

Class: Label

The label component provides a label component to used to iden-

tify the date. See the «label» widget manual entry for details on the label component item.

Name: iconbutton

Class: Label

The iconbutton component provides a labelbutton component to act

as a lightweight button displaying the calendar icon. Upon pressing the labelbutton, the calendar appears. See the «label" widget manual entry for details on the labelbutton component item.

Name: date

Class: Entry

The date component provides the entry field for date input and

display. See the «entry» widget manual entry for details on the date component item.

Example

package require Iwidgets 4.0
iwidgets::dateentry .de
pack .de

Author

Mark L. Ulferts

Keywords

dateentry, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "labeledwidget" class manual entry for details on these
  • See the "datefield" class manual entry for details on these
  • Associated Options
  • See the "calendar" manual entry for details on the associated
  • Widget-specific Options
  • Name: grab
  • Class: Grab
  • Command-Line Switch: -grab
  • Specifies the grab level, local or global, to be obtained before
  • Tk's grab command.
  • Name: icon
  • Class: Icon
  • Command-Line Switch: -icon
  • Specifies the calendar icon image to be used in the dateentry.
  • This image must have been created previously with the image cre-
  • Description
  • The iwidgets::dateentry command creates a quicken style date
  • Methods
  • The iwidgets::dateentry command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for dateentry widgets:
  • Inherited Methods
  • See the "datefield" manual entry for details on the associated
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: label
  • Class: Label
  • The label component provides a label component to used to iden-
  • Name: iconbutton
  • Class: Label
  • The iconbutton component provides a labelbutton component to act
  • Name: date
  • Class: Entry
  • The date component provides the entry field for date input and
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets datefield

 Table of Contents

iwidgets::datefield - Create and manipulate a date field widget

Synopsis

iwidgets::datefield pathName ?options?

Inheritance

itk::Widget <- iwidgets::LabeledWidget <- iwidgets::Datefield

Standard Options

background borderWidth cursor exportSelection foreground highlightColor highlightThickness insertBackground

justify
relief

See the «options» manual entry for details on the standard

options.

Inherited Options

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable
state
sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: childSitePos

Class: Position

Command-Line Switch: -childsitepos

Specifies the position of the child site in the date field: n, s,

e, or w. The default is e.

Name: command

Class: Command

Command-Line Switch: -command

Specifies a Tcl command to be executed upon detection of a Return

key press event.

Name: gmt

Class: Gmt

Command-Line Switch: -gmt

Determines whether the date is calculated relative to Greenwich

Mean Time. Accepts a boolean value. The default is no.

Name: iq

Class: Iq

Command-Line Switch: -iq

Specifies the level of intelligence to be shown in the actions

taken by the datefield during the processing of keypress events.

Valid settings include high, average, and low. With a high

iq,the date prevents the user from typing in an invalid date.

For example, if the current date is 05/31/1997 and the user

changes the month to 04, then the day will be instantly modified for them to be 30. In addition, leap years are fully taken into account. With average iq, the month is limited to the values of 01-12, but it is possible to type in an invalid day. A setting of low iq instructs the widget to do no validity checking at all during date entry. With both average and low iq levels, it is assumed that the validity will be determined at a later time using the date's isvalid command.

Name: state

Class: State

Command-Line Switch: -state

Specifies one of two states for the datefield: normal or dis-

abled. If the datefield is disabled then input is not accepted.

The default is normal.

Name: textBackground

Class: Background

Command-Line Switch: -textbackground

Background color for inside textual portion of the entry field.

The value may be given in any of the forms acceptable to Tk_Get-

Color.

Name: textFont

Class: Font

Command-Line Switch: -textfont

Name of font to use for display of text in datefield. The value

may be given in any of the forms acceptable to Tk_GetFont. _________________________________________________________________

Description

The iwidgets::datefield command creates an enhanced text entry

widget for the purpose of date entry with various degrees of built-in intelligence.

Methods

The iwidgets::datefield command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for datefield widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::datefield command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::datefield command. pathName get ?format?

Returns the current contents of the datefield in a format of

string or as an integer clock value using the -string and -clicks format options respectively. The default is by string. Refer- ence the clock command for more information on obtaining dates and their formats.
pathName isvalid

Returns a boolean indication of the validity of the currently

displayed date value. For example, 03/03/1960 is valid whereas 02/29/1997 is invalid.
pathName show date

Changes the currently displayed date to be that of the date argu-

ment. The date may be specified either as a string, an integer clock value or the keyword «now". Reference the clock command for more information on obtaining dates and their formats.

Components

Name: date

Class: Entry

The date component provides the entry field for date input and

display. See the «entry» widget manual entry for details on the date component item.

Example

package require Iwidgets 4.0
proc returnCmd {} {
puts [.df get]
}

iwidgets::datefield .df -command returnCmd
pack .df -fill x -expand yes -padx 10 -pady 10

Author

Mark L. Ulferts

Keywords

datefield, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: childSitePos
  • Class: Position
  • Command-Line Switch: -childsitepos
  • Specifies the position of the child site in the date field: n, s,
  • Name: command
  • Class: Command
  • Command-Line Switch: -command
  • Specifies a Tcl command to be executed upon detection of a Return
  • Name: gmt
  • Class: Gmt
  • Command-Line Switch: -gmt
  • Determines whether the date is calculated relative to Greenwich
  • Mean Time. Accepts a boolean value. The default is no.
  • Name: iq
  • Class: Iq
  • Command-Line Switch: -iq
  • Specifies the level of intelligence to be shown in the actions
  • Valid settings include high, average, and low. With a high
  • For example, if the current date is 05/31/1997 and the user
  • Name: state
  • Class: State
  • Command-Line Switch: -state
  • Specifies one of two states for the datefield: normal or dis-
  • The default is normal.
  • Name: textBackground
  • Class: Background
  • Command-Line Switch: -textbackground
  • Background color for inside textual portion of the entry field.
  • The value may be given in any of the forms acceptable to Tk_Get-
  • Color.
  • Name: textFont
  • Class: Font
  • Command-Line Switch: -textfont
  • Name of font to use for display of text in datefield. The value
  • Description
  • The iwidgets::datefield command creates an enhanced text entry
  • Methods
  • The iwidgets::datefield command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for datefield widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Returns the current contents of the datefield in a format of
  • Returns a boolean indication of the validity of the currently
  • Changes the currently displayed date to be that of the date argu-
  • Components
  • Name: date
  • Class: Entry
  • The date component provides the entry field for date input and
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets dialog

 Table of Contents

iwidgets::dialog - Create and manipulate a dialog widget

Synopsis

iwidgets::dialog pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Shell <- iwidgets::Dialogshell <- iwidgets::Dialog

Standard Options

background cursor foreground

See the «options» manual entry for details on the standard

options.

Inherited Options

buttonBoxPadX buttonBoxPadY buttonBoxPos padX

padY
separator thickness

See the «dialogshell» manual entry for details on the above

inherited options.
height master modality width

See the «shell» manual entry for details on the above inherited

options.
title

See the «Toplevel» manual entry for details on the above inher-

ited options.
_________________________________________________________________

Description

The iwidgets::dialog command creates a dialog box providing stan-

dard buttons and a child site for use in derived classes. The buttons include ok, apply, cancel, and help. Methods and Options exist to configure the buttons and their containing box.

Methods

The iwidgets::dialog command creates a new Tcl command whose name

is pathName. This command may be used to invoke various opera- tions on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for dialog widgets:

Inherited Methods

add buttonconfigure defaulthide index insert invoke show

See the «buttonbox» manual entry for details on the above inher-

ited methods.
childsite

See the «dialogshell» manual entry for details on the above

inherited methods.
activate center deactivate

See the «shell» manual entry for details on the above inherited

methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::dialog command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::dialog command.

Example

package require Iwidgets 4.0
iwidgets::dialog .d -modality global
.d buttonconfigure OK -command {puts OK; .d deactivate 1}
.d buttonconfigure Apply -command {puts Apply}
.d buttonconfigure Cancel -command {puts Cancel; .d deactivate 0}
.d buttonconfigure Help -command {puts Help}

listbox [.d childsite].lb -relief sunken
pack [.d childsite].lb -expand yes -fill both

if {[.d activate]} {
puts «Exit via OK button"
} else {
puts «Exit via Cancel button"
}

Author

Mark L. Ulferts

Bret A. Schuhmacher

Keywords

dialog, dialogshell, shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "dialogshell" manual entry for details on the above
  • See the "shell" manual entry for details on the above inherited
  • See the "Toplevel" manual entry for details on the above inher-
  • Description
  • The iwidgets::dialog command creates a dialog box providing stan-
  • Methods
  • The iwidgets::dialog command creates a new Tcl command whose name
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for dialog widgets:
  • Inherited Methods
  • See the "buttonbox" manual entry for details on the above inher-
  • See the "dialogshell" manual entry for details on the above
  • See the "shell" manual entry for details on the above inherited
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Example
  • Author
  • Mark L. Ulferts
  • Bret A. Schuhmacher
  • Keywords


IWidgets dialogshell

 Table of Contents

iwidgets::dialogshell - Create and manipulate a dialog shell wid- get

Synopsis

iwidgets::dialogshell pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Shell <- iwidgets::Dialogshell

Standard Options

background cursor foreground

See the «options» manual entry for details on the standard

options.

Inherited Options

height master modality width

See the «shell» manual entry for details on the above inherited

options.
title

See the «Toplevel» manual entry for details on the above inher-

ited options.

Widget-specific Options

Name: buttonBoxPadX

Class: Pad

Command-Line Switch: -buttonboxpadx

Specifies a non-negative padding distance to leave between the

button group and the outer edge of the button box in the x direc- tion. The value may be given in any of the forms accpetable to

Tk_GetPixels. The default is 5 pixels.

Name: buttonBoxPadY

Class: Pad

Command-Line Switch: -buttonboxpady

Specifies a non-negative padding distance to leave between the

button group and the outer edge of the button box in the y direc- tion. The value may be given in any of the forms accpetable to

Tk_GetPixels. The default is 5 pixels.

Name: buttonBoxPos

Class: Position

Command-Line Switch: -buttonboxpos

Attaches buttons to the given side of the dialog: n, s, e or w.

The default is s.

Name: padX

Class: Pad

Command-Line Switch: -padx

Specifies a padding distance for the childsite in the X-direction

in any of the forms acceptable to Tk_GetPixels. The default is 10.

Name: padY

Class: Pad

Command-Line Switch: -pady

Specifies a padding distance for the childsite in the Y-direction

in any of the forms acceptable to Tk_GetPixels. The default is 10.

Name: separator

Class: Separator

Command-Line Switch: -separator

Specifies whether a line is drawn to separate the buttons from

the dialog box contents in any of the forms acceptable to

Tcl_GetBoolean. The default is true.

Name: thickness

Class: Thickness

Command-Line Switch: -thickness

Specifies the thickness of the separator in any of the forms

acceptable to Tk_GetPixels. The default is 3 pixels. _________________________________________________________________

Description

The iwidgets::dialogshell command creates a dialog shell which is

a top level widget composed of a button box, separator, and child site area. The class also has methods to control button con- struction.

Methods

The iwidgets::dialogshell command create a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for dialogshell widgets:

Inherited Methods

activate center deactivate

See the «shell» manual entry for details on the above inherited

methods.

Associated Methods

add buttonconfigure defaultdelete

hide
index insert invoke show

See the «buttonbox» manual entry for details on the associated

methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::dialogshell command.
pathName childsite

Returns the pathname of the child site widget.

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::dialogshell command.

Components

Name: dschildsite

Class: frame

The dschildsite component is the user child site for the dialog

shell. See the «frame» widget manual entry for details on the dschildsite component item.

Name: separator

Class: frame

The separator component devides the area between the user child

site and the button box. See the «frame» widget manual entry for details on the separator component item.

Name: bbox

Class: ButtonBox

The bbox component is the button box containing the buttons for

the dialog shell. See the «ButtonBox» widget manual entry for details on the bbox component item.

Example

package require Iwidgets 4.0
iwidgets::dialogshell .ds -modality none

.ds add OK -text «OK"
.ds add Cancel -text «Cancel"
.ds default OK

.ds activate

Author

Mark L. Ulferts

Keywords

dialogshell, dialog, shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "shell" manual entry for details on the above inherited
  • See the "Toplevel" manual entry for details on the above inher-
  • Widget-specific Options
  • Name: buttonBoxPadX
  • Class: Pad
  • Command-Line Switch: -buttonboxpadx
  • Specifies a non-negative padding distance to leave between the
  • Tk_GetPixels. The default is 5 pixels.
  • Name: buttonBoxPadY
  • Class: Pad
  • Command-Line Switch: -buttonboxpady
  • Specifies a non-negative padding distance to leave between the
  • Tk_GetPixels. The default is 5 pixels.
  • Name: buttonBoxPos
  • Class: Position
  • Command-Line Switch: -buttonboxpos
  • Attaches buttons to the given side of the dialog: n, s, e or w.
  • The default is s.
  • Name: padX
  • Class: Pad
  • Command-Line Switch: -padx
  • Specifies a padding distance for the childsite in the X-direction
  • Name: padY
  • Class: Pad
  • Command-Line Switch: -pady
  • Specifies a padding distance for the childsite in the Y-direction
  • Name: separator
  • Class: Separator
  • Command-Line Switch: -separator
  • Specifies whether a line is drawn to separate the buttons from
  • Tcl_GetBoolean. The default is true.
  • Name: thickness
  • Class: Thickness
  • Command-Line Switch: -thickness
  • Specifies the thickness of the separator in any of the forms
  • Description
  • The iwidgets::dialogshell command creates a dialog shell which is
  • Methods
  • The iwidgets::dialogshell command create a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for dialogshell widgets:
  • Inherited Methods
  • See the "shell" manual entry for details on the above inherited
  • Associated Methods
  • See the "buttonbox" manual entry for details on the associated
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Returns the pathname of the child site widget.
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: dschildsite
  • Class: frame
  • The dschildsite component is the user child site for the dialog
  • Name: separator
  • Class: frame
  • The separator component devides the area between the user child
  • Name: bbox
  • Class: ButtonBox
  • The bbox component is the button box containing the buttons for
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets disjointlistbox

 Table of Contents

iwidgets::disjointlistbox - Create and manipulate a disjointlist- box widget

Synopsis

iwidgets::disjointlistbox pathName ?options?

Inheritance

itk::Widget <- iwidgets::Disjointlistbox

Standard Options

activeBackground selectBorderWidth selectForeground activeForeground activeRelief background

borderWidth
buttonPlacement clientData
cursor
foreground highlightColor highlightThickness disabledForeground elementBorderWidth

See the «options» manual entry for details on the standard

options.

Associated Options

lhsButtonLabel rhsButtonLabel

See the «button» widget manual entry for details on the above

associated options.
labelFont lhsLabelText rhsLabelText

See the «label» widget manual entry for details on the above

associated options.
jump troughColor

See the «scrollbar» widget class manual entry for details on the

above associated options.
textBackground textFont
lhsItems rhsItems

See the «scrolledlistbox» widget manual entry for details on the

above associated options.

Widget-specific Options

Name: buttonPlacement

Class: ButtonPlacement

Command-Line Switch: -buttonplacement

Specifies the placement of the insertion and removal buttons rel-

ative to the scrolledlistbox widgetsn, bottom, or center. The default is bottom.

Name: lhsLabelText

Class: LabelText

Command-Line Switch: -lhslabeltext

Specifies the text for the label of the lhs scrolledlistbox. The

default is «Available".

Name: rhsLabelText

Class: LabelText

Command-Line Switch: -rhslabeltext

Specifies the text for the label of the rhs scrolledlistbox. The

default is «Available".

Name: lhsButtonLabel

Class: LabelText

Command-Line Switch: -lhsbuttonlabel

Specifies the text for the button of the lhs scrolledlistbox.

The default is «Insert >>".

Name: rhsButtonLabel

Class: LabelText

Command-Line Switch: -rhsbuttonlabel

Specifies the text for the button of the rhs scrolledlistbox.

The default is «<< Remove".

_________________________________________________________________

Description

The iwidgets::disjointlistbox command creates a disjoint pair of

listboxs similar to the OSF/Motif «Book» printing dialog of the «FrameMaker» program. It is implementation constists of a two

Scrolledlistboxs, 2 buttons, and 2 labels.

given instance of a Disjointlistbox will never exist, without the aid of a hack magician, which has Scrolledlistbox widgets with items in common. That means the relationship between the two is maintained similar to that of disjoint sets.

Users may transfer items between the two Listbox widgets using

the the two buttons.

Options exists which include the ability to configure the «items"

displayed by the 2 Scrolledlistboxes and to control the placement of the insertion and removal buttons.

Methods

The iwidgets::disjointlistbox command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for disjointlistbox widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::disjointlistbox command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::disjointlistbox command. pathName setlhs

Set the current contents of the left-most Scrolledlistbox with

the input list of items. Removes all (if any) items from the right-most Scrolledlistbox which exist in the input list option to maintain the disjoint property between the two pathName setrhs

Set the current contents of the right-most Scrolledlistbox with

the input list of items. Removes all (if any) items from the left-most Scrolledlistbox which exist in the input list option to maintain the disjoint property between the two pathName getlhs

Returns the current contents of the left-most Scrolledlistbox

pathName getrhs

Returns the current contents of the right-most Scrolledlistbox

pathName insertlhs

Add the input list of items to the current contents of the left-

most Scrolledlistbox. Removes all (if any) items from the right- most Scrolledlistbox which exist in the input list option to maintain the disjoint property between the two pathName insertrhs

Add the input list of items to the current contents of the right-

most Scrolledlistbox. Removes all (if any) items from the left- most Scrolledlistbox which exist in the input list option to maintain the disjoint property between the two.

Components

Name: lhs

Class: Scrolledlistbox

The lhs component is the scrolledlistbox for the rhs button. See

the «scrolledlistbox» widget manual entry for details on the lhs component item.

Name: rhs

Class: Scrolledlistbox

The rhs component is the scrolledlistbox for the rhs button. See

the «scrolledlistbox» widget manual entry for details on the rhs component item.

Name: lhsbutton

Class: utton

The lhsbutton component is the button for users to remove

selected items from the lhs Scrolledlistbox. See the «button" widget manual entry for details on the lhs button component.

Name: rhsbutton

Class: Button

The rhsbutton component is the button for users to remove

selected items from the rhs Scrolledlistbox. See the «button" widget manual entry for details on the rhs button component.

Name: lhsCount

Class: Label

The lhsCount component is the label for displaying a count of the

current items in the Scrolledlistbox. See the «Label» widget manual entry for details on the lhsCount label component.

Name: rhsCount

Class: Label

The rhsCount component is the label for displaying a count of the

current items in the Scrolledlistbox. See the «Label» widget manual entry for details on the rhsCount label component.

Example

package require Iwidgets 4.0
iwidgets::disjointlistbox .dlb
pack .dlb -padx 10 -pady 10 -fill both -expand yes

Author(s)

John A. Tucker

Anthony Parent

Keywords

disjointlistbox, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "button" widget manual entry for details on the above
  • See the "label" widget manual entry for details on the above
  • See the "scrollbar" widget class manual entry for details on the
  • See the "scrolledlistbox" widget manual entry for details on the
  • Widget-specific Options
  • Name: buttonPlacement
  • Class: ButtonPlacement
  • Command-Line Switch: -buttonplacement
  • Specifies the placement of the insertion and removal buttons rel-
  • Name: lhsLabelText
  • Class: LabelText
  • Command-Line Switch: -lhslabeltext
  • Specifies the text for the label of the lhs scrolledlistbox. The
  • Name: rhsLabelText
  • Class: LabelText
  • Command-Line Switch: -rhslabeltext
  • Specifies the text for the label of the rhs scrolledlistbox. The
  • Name: lhsButtonLabel
  • Class: LabelText
  • Command-Line Switch: -lhsbuttonlabel
  • Specifies the text for the button of the lhs scrolledlistbox.
  • The default is "Insert >>".
  • Name: rhsButtonLabel
  • Class: LabelText
  • Command-Line Switch: -rhsbuttonlabel
  • Specifies the text for the button of the rhs scrolledlistbox.
  • The default is "<< Remove".
  • Description
  • The iwidgets::disjointlistbox command creates a disjoint pair of
  • Scrolledlistboxs, 2 buttons, and 2 labels.
  • Users may transfer items between the two Listbox widgets using
  • Options exists which include the ability to configure the "items"
  • Methods
  • The iwidgets::disjointlistbox command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for disjointlistbox widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Set the current contents of the left-most Scrolledlistbox with
  • Set the current contents of the right-most Scrolledlistbox with
  • Returns the current contents of the left-most Scrolledlistbox
  • Returns the current contents of the right-most Scrolledlistbox
  • Add the input list of items to the current contents of the left-
  • Add the input list of items to the current contents of the right-
  • Components
  • Name: lhs
  • Class: Scrolledlistbox
  • The lhs component is the scrolledlistbox for the rhs button. See
  • Name: rhs
  • Class: Scrolledlistbox
  • The rhs component is the scrolledlistbox for the rhs button. See
  • Name: lhsbutton
  • Class: utton
  • The lhsbutton component is the button for users to remove
  • Name: rhsbutton
  • Class: Button
  • The rhsbutton component is the button for users to remove
  • Name: lhsCount
  • Class: Label
  • The lhsCount component is the label for displaying a count of the
  • Name: rhsCount
  • Class: Label
  • The rhsCount component is the label for displaying a count of the
  • Example
  • Author(s)
  • John A. Tucker
  • Anthony Parent
  • Keywords


IWidgets entryfield

 Table of Contents

iwidgets::entryfield - Create and manipulate a entry field widget

Synopsis

iwidgets::entryfield pathName ?options?

Inheritance

itk::Widget <- iwidgets::LabeledWidget <- iwidgets::Entryfield

Standard Options

background borderWidth cursor exportSelection

foreground
highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth
justify
relief selectBackground selectBorderWidth selectForeground textVariable width

See the «options» manual entry for details on the standard

options.

Associated Options

show
state

See the «entry» manual entry for details on the associated

options.

Inherited Options

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable
state
sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: childSitePos

Class: Position

Command-Line Switch: -childsitepos

Specifies the position of the child site in the entry field: n,

s, e, or w. The default is e.

Name: command

Class: Command

Command-Line Switch: -command

Specifies a Tcl command to be executed upon detection of a Return

key press event.

Name: fixed

Class: Fixed

Command-Line Switch: -fixed

Restrict entry to the specified number of chars. A value of 0,

which is the default, denotes no limit. The value is the maximum number of chars the user may type into the field, regardles of field width. For example, if the field width is set to 20 and the fixed value is 10, the user will only be able to type 10 characters into the field which is 20 characters long.

Name: focusCommand

Class: Command

Command-Line Switch: -focuscommand

Specifies a Tcl command to be executed upon reception of focus.

Name: invalid

Class: Command

Command-Line Switch: -invalid

Specifies a Tcl command to be executed upon determination of

invalid input. The default is bell.

Name: textBackground

Class: Background

Command-Line Switch: -textbackground

Background color for inside textual portion of the entry field.

The value may be given in any of the forms acceptable to Tk_Get-

Color.

Name: textFont

Class: Font

Command-Line Switch: -textfont

Name of font to use for display of text in entryfield. The value

may be given in any of the forms acceptable to Tk_GetFont.

Name: pasting

Class: Behavior

Command-Line Switch: -pasting

Option to enable/disable pasting into the entry component of the

entryfield. Valid values are 0 (disabled) or 1 (enabled).

Defaults to 1.

Name: validate

Class: Command

Command-Line Switch: -validate

The validate option allows specification of a validation mecha-

nism. Standard character validation such as numeric, alphabetic, integer, hexidecimal, real, and alphanumeric can be handled through the use of keywords. Should more extensive validation be necessary, the value may contain the name of a command script.

The script should return a boolean value. True for valid, false

for invalid. If false is returned, then the procedure associated with the invalid option will be invoked. If the validation script contains any % characters, then the script will not be executed directly. Instead, a new script will be generated by replacing each %, and the character following it, with informa- tion from the entryfield. The replacement depends on the charac- ter following the %, as defined in the list below. %c

Replaced with the current input character.

%P

Replaced with the contents of the entryfield modified to include

the latest keystoke. This is equivalent to peeking at the future contents, enabling rejection prior to the update. %S

Replaced with the current contents of the entryfield prior to the

latest keystroke being added.
%W

Replaced with the entryfield widget pathname.

_________________________________________________________________

Description

The iwidgets::entryfield command creates an enhanced text entry

widget with an optional associated label. Addtional options sup- port validation and establishing a upper limit on the number of characters which may be entered in the field.

Methods

The iwidgets::entryfield command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for entryfield widgets:

Associated Methods

delete get icursor index insert scan selection xview

See the «entry» manual entry for details on the associated meth-

ods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::entryfield command.
pathName childsite

Returns the path name of the child site.

pathName clear

Clear entry widget

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::entryfield command.

Components

Name: efchildsite

Class: frame

The efchildsite component is the user child site for the entry

field. See the «frame» widget manual entry for details on the efchildsite component item.

Name: entry

Class: entry

The entry component provides the entry field for user text input

and display. See the «entry» widget manual entry for details on the entry component item.

Example

package require Iwidgets 4.0
option add *textBackground white

proc returnCmd {} {
puts stdout «Return Pressed"
}

proc invalidCmd {} {
puts stdout «Alphabetic contents invalid" }

iwidgets::entryfield .ef -command returnCmd

iwidgets::entryfield .fef -labeltext «Fixed:» -fixed 10 -width 12

iwidgets::entryfield .nef -labeltext «Numeric:» -validate numeric -width 12

iwidgets::entryfield .aef -labeltext «Alphabetic:» \ -validate alphabetic -width 12 -invalid invalidCmd

iwidgets::entryfield .pef -labeltext «Password:» \ -show 267 -width 12 -command returnCmd

iwidgets::Labeledwidget::alignlabels .ef .fef .nef .aef .pef

pack .ef -fill x -expand yes -padx 10 -pady 5 pack .fef -fill x -expand yes -padx 10 -pady 5 pack .nef -fill x -expand yes -padx 10 -pady 5 pack .aef -fill x -expand yes -padx 10 -pady 5 pack .pef -fill x -expand yes -padx 10 -pady 5

Author

Sue Yockey

Mark L. Ulferts

Keywords

entryfield, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "entry" manual entry for details on the associated
  • Inherited Options
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: childSitePos
  • Class: Position
  • Command-Line Switch: -childsitepos
  • Specifies the position of the child site in the entry field: n,
  • Name: command
  • Class: Command
  • Command-Line Switch: -command
  • Specifies a Tcl command to be executed upon detection of a Return
  • Name: fixed
  • Class: Fixed
  • Command-Line Switch: -fixed
  • Restrict entry to the specified number of chars. A value of 0,
  • Name: focusCommand
  • Class: Command
  • Command-Line Switch: -focuscommand
  • Specifies a Tcl command to be executed upon reception of focus.
  • Name: invalid
  • Class: Command
  • Command-Line Switch: -invalid
  • Specifies a Tcl command to be executed upon determination of
  • Name: textBackground
  • Class: Background
  • Command-Line Switch: -textbackground
  • Background color for inside textual portion of the entry field.
  • The value may be given in any of the forms acceptable to Tk_Get-
  • Color.
  • Name: textFont
  • Class: Font
  • Command-Line Switch: -textfont
  • Name of font to use for display of text in entryfield. The value
  • Name: pasting
  • Class: Behavior
  • Command-Line Switch: -pasting
  • Option to enable/disable pasting into the entry component of the
  • Defaults to 1.
  • Name: validate
  • Class: Command
  • Command-Line Switch: -validate
  • The validate option allows specification of a validation mecha-
  • The script should return a boolean value. True for valid, false
  • Replaced with the current input character.
  • Replaced with the contents of the entryfield modified to include
  • Replaced with the current contents of the entryfield prior to the
  • Replaced with the entryfield widget pathname.
  • Description
  • The iwidgets::entryfield command creates an enhanced text entry
  • Methods
  • The iwidgets::entryfield command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for entryfield widgets:
  • Associated Methods
  • See the "entry" manual entry for details on the associated meth-
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Returns the path name of the child site.
  • Clear entry widget
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: efchildsite
  • Class: frame
  • The efchildsite component is the user child site for the entry
  • Name: entry
  • Class: entry
  • The entry component provides the entry field for user text input
  • Example
  • Author
  • Sue Yockey
  • Mark L. Ulferts
  • Keywords


IWidgets extbutton

 Table of Contents

iwidgets::extbutton - Extends the behavior of the Tk button by allowing a bitmap or image to coexist with text.

Synopsis

iwidgets::extbutton pathName ?options?

Inheritance

itk::Widget <- iwidgets::Extbutton

Standard Options

activebackground
activeforeground bitmap background bd cursor disabledforeground font foreground
image
justify relief text

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: bitmapforeground

Class: Foreground

Command-Line Switch: -bitmapforeground

Configures the foreground color of the bitmap.

Name: command

Class: Command

Command-Line Switch: -command

Associate a command with the extbutton. Simulates a Tk button's

-command option. Invoked by either <1> events or by explicitly calling the public invoke() method.

Name: defaultring

Class: DefaultRing

Command-Line Switch: -defaultring

Boolean describing whether the extbutton displays its default

ring given in any of the forms acceptable to Tcl_GetBoolean. The default is false.

Name: defaultringpad

Class: Pad

Command-Line Switch: -defaultringpad

Specifies the amount of space to be allocated to the indentation

of the default ring ring given in any of the forms acceptable to

Tcl_GetPixels. The option has no effect if the defaultring

option is set to false. The default is 4 pixels.

Name: imagePos

Class: Position

Command-Line Switch: -imagepos

Specifies the image position relative to the message text: n, ne,

nw, s, se, sw, w, wn, ws, e, en, or es. The default is w.

Name: ringBackground

Class: Background

Command-Line Switch: -ringbackground

Configures the background color of the default ring frame (if

-defaultring is set to boolean true).
_________________________________________________________________

Description

The extbutton extends the behavior of the atomic Tk button by

allowing text and an image or bitmap to coexist. The user may use the -image or -bitmap options to specify an image as well as the -imagepos option to specify image position relative to the text.

Note that the extbutton is not intended to be used without an

image/bitmap. There will be an emtpy space next to the text if no image/bitmap is specified.

Methods

The iwidgets::extbutton command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

Inherited Methods

Each of the following methods are inherited from itk::Archetype.

See that man page for details.

pathName cget
pathName component
pathName config
pathName configure

Widget-specific Methods

pathName invoke

Evaluates the command fragment associated with the -command

option.
pathName flash

Simulates the Tk button's flash command.

Examples

package require Iwidgets 4.0
iwidgets::extbutton .eb -text «Bitmap example» -bitmap info \ -background bisque -activeforeground red -bitmapforeground blue \ -defaultring 1 -command {puts «Bisque is beautiful"} pack .eb -expand 1

iwidgets::extbutton .eb -text «Image example» -relief ridge -image \ [image create photo -file $itk::library/../iwidgets/demos/images/clear.gif] \ -font 9x15bold -background lightgreen -imagepos e \ -activebackground lightyellow
pack .eb -expand 1

Author

Chad Smith

Keywords

button, pushbutton

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: bitmapforeground
  • Class: Foreground
  • Command-Line Switch: -bitmapforeground
  • Configures the foreground color of the bitmap.
  • Name: command
  • Class: Command
  • Command-Line Switch: -command
  • Associate a command with the extbutton. Simulates a Tk button's
  • Name: defaultring
  • Class: DefaultRing
  • Command-Line Switch: -defaultring
  • Boolean describing whether the extbutton displays its default
  • Name: defaultringpad
  • Class: Pad
  • Command-Line Switch: -defaultringpad
  • Specifies the amount of space to be allocated to the indentation
  • Tcl_GetPixels. The option has no effect if the defaultring
  • Name: imagePos
  • Class: Position
  • Command-Line Switch: -imagepos
  • Specifies the image position relative to the message text: n, ne,
  • Name: ringBackground
  • Class: Background
  • Command-Line Switch: -ringbackground
  • Configures the background color of the default ring frame (if
  • Description
  • The extbutton extends the behavior of the atomic Tk button by
  • Note that the extbutton is not intended to be used without an
  • Methods
  • The iwidgets::extbutton command creates a new Tcl command whose
  • Inherited Methods
  • Each of the following methods are inherited from itk::Archetype.
  • See that man page for details.
  • Widget-specific Methods
  • Evaluates the command fragment associated with the -command
  • Simulates the Tk button's flash command.
  • Examples
  • Author
  • Chad Smith
  • Keywords


IWidgets extfileselectionbox

 Table of Contents

iwidgets::extfileselectionbox - Create and manipulate a file selection box widget

Synopsis

iwidgets::extfileselectionbox pathName ?options?

Inheritance

itk::Widget <- iwidgets::Extfileselectionbox

Standard Options

activeBackground background borderWidth cursor

foreground
highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

popupCursor
textBackground textFont

See the «combobox» widget manual entry for details on the above

associated options.
labelFont

See the «labeledwidget» widget manual entry for details on the

above associated options.
sashCursor

See the «panedwindow» widget manual entry for details on the

above associated options.
activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget class manual entry for details on the

above associated options.
textBackground textFont

See the «scrolledlistbox» widget manual entry for details on the

above associated options.

Widget-specific Options

Name: automount

Class: Automount

Command-Line Switch: -automount

Specifies a list of directory prefixes to ignore. Typically, this

option would be used as follows:
-automount {export tmp_mnt}

Name: childSitePos

Class: Position

Command-Line Switch: -childsitepos

Specifies the position of the child site in the extended filese-

lection box: n, s, e, w, top, or bottom. The default is s.

Name: directory

Class: Directory

Command-Line Switch: -directory

Specifies the initial default directory. The default is the pre-

sent working directory.

Name: dirSearchCommand

Class: Command

Command-Line Switch: -dirsearchcommand

Specifies a Tcl command to be executed to perform a directory

search. The command will receive the current working directory and filter mask as arguments. The command should return a list of files which will be placed into the directory list.

Name: dirsLabel

Class: Text

Command-Line Switch: -dirslabel

Specifies the text of the label for the directory list. The

default is «Directories".

Name: dirsOn

Class: DirsOn

Command-Line Switch: -dirson

Specifies whether or not to display the directory list. The

value may be given in any of the forms acceptable to Tcl_Get-

Boolean. The default is true.

Name: fileSearchCommand

Class: Command

Command-Line Switch: -filesearchcommand

Specifies a Tcl command to be executed to perform a file search.

The command will receive the current working directory and filter

mask as arguments. The command should return a list of files which will be placed into the file list.

Name: filesLabel

Class: Text

Command-Line Switch: -fileslabel

Specifies the text of the label for the files list. The default

is «Files".

Name: filesOn

Class: FilesOn

Command-Line Switch: -fileson

Specifies whether or not to display the files list. The value

may be given in any of the forms acceptable to Tcl_GetBoolean.

The default is true.

Name: fileType

Class: FileType

Command-Line Switch: -filetype

Specify the type of files which may appear in the file list: reg-

ular, directory, or any. The default is regular.

Name: filterCommand

Class: Command

Command-Line Switch: -filtercommand

Specifies a Tcl command to be executed upon hitting the Return

key in the filter combobox widget.

Name: filterLabel

Class: Text

Command-Line Switch: -filterlabel

Specifies the text of the label for the filter combobox. The

default is «Filter".

Name: filterOn

Class: FilterOn

Command-Line Switch: -filteron

Specifies whether or not to display the filter combobox. The

value may be given in any of the forms acceptable to Tcl_Get-

Boolean. The default is true.

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the selection box. The value may be

specified in any of the forms acceptable to Tk_GetPixels. The default is 300 pixels.

Name: invalid

Class: Command

Command-Line Switch: -invalid

Command to be executed should the filter contents be proven

invalid. The default is {bell}.

Name: mask

Class: Mask

Command-Line Switch: -mask

Specifies the initial file mask string. The default is «*".

Name: noMatchString

Class: NoMatchString

Command-Line Switch: -nomatchstring

Specifies the string to be displayed in the files list should no

files match the mask. The default is «".

Name: selectDirCommand

Class: Command

Command-Line Switch: -selectdirommand

Specifies a Tcl command to be executed following selection of a

directory in the directory list.

Name: selectFileCommand

Class: Command

Command-Line Switch: -selectfileommand

Specifies a Tcl command to be executed following selection of a

file in the files list.

Name: selectionCommand

Class: Command

Command-Line Switch: -selectioncommand

Specifies a Tcl command to be executed upon hitting the Return

key in the selection combobox widget.

Name: selectionLabel

Class: Text

Command-Line Switch: -selectionlabel

Specifies the text of the label for the selection combobox. The

default is «Selection".

Name: selectionOn

Class: SelectionOn

Command-Line Switch: -selectionon

Specifies whether or not to display the selection combobox. The

value may be given in any of the forms acceptable to Tcl_Get-

Boolean. The default is true.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the selection box. The value may be spec-

ified in any of the forms acceptable to Tk_GetPixels. The default is 350 pixels.
_________________________________________________________________

Description

The iwidgets::extfileselectionbox command creates an extended

file selection box which is slightly different than the filese- lectionbox widget. The differences are mostly cosmetic in that the listboxes are within a panedwindow and the entryfields for the filter and selection have been replaced by comboboxes. Other than that the interface is practically the same.

Methods

The iwidgets::extfileselectionbox command creates a new Tcl com-

mand whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for extfileselectionbox wid-

gets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::extfileselectionbox command.
pathName childsite

Returns the child site widget path name.

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::extfileselectionbox command. pathName filter

Update the current contents of the extended file selection box

based on the current filter combobox value.
pathName get

Returns the current value of the selection combobox widget.

Components

Name: dirs

Class: Scrolledlistbox

The dirs component is the directory list box for the extended

fileselection box. See the «scrolledlistbox» widget manual entry for details on the dirs component item.

Name: files

Class: Scrolledlistbox

The files component is the file list box for the extended filese-

lection box. See the «scrolledlistbox» widget manual entry for details on the files component item.

Name: filter

Class: Combobox

The filter component is the field for user input of the filter

value. See the «combobox» widget manual entry for details on the filter component item.

Name: selection

Class: Combobox

The selection component is the field for user input of the cur-

rently selected file value. See the «combobox» widget manual entry for details on the selection component item.

Example

package require Iwidgets 4.0
iwidgets::extfileselectionbox .fsb
pack .fsb -padx 10 -pady 10 -fill both -expand yes

Author(s)

Mark L. Ulferts

Anthony Parent

Keywords

extfileselectionbox, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "combobox" widget manual entry for details on the above
  • See the "labeledwidget" widget manual entry for details on the
  • See the "panedwindow" widget manual entry for details on the
  • See the "scrollbar" widget class manual entry for details on the
  • See the "scrolledlistbox" widget manual entry for details on the
  • Widget-specific Options
  • Name: automount
  • Class: Automount
  • Command-Line Switch: -automount
  • Specifies a list of directory prefixes to ignore. Typically, this
  • Name: childSitePos
  • Class: Position
  • Command-Line Switch: -childsitepos
  • Specifies the position of the child site in the extended filese-
  • Name: directory
  • Class: Directory
  • Command-Line Switch: -directory
  • Specifies the initial default directory. The default is the pre-
  • Name: dirSearchCommand
  • Class: Command
  • Command-Line Switch: -dirsearchcommand
  • Specifies a Tcl command to be executed to perform a directory
  • Name: dirsLabel
  • Class: Text
  • Command-Line Switch: -dirslabel
  • Specifies the text of the label for the directory list. The
  • Name: dirsOn
  • Class: DirsOn
  • Command-Line Switch: -dirson
  • Specifies whether or not to display the directory list. The
  • Boolean. The default is true.
  • Name: fileSearchCommand
  • Class: Command
  • Command-Line Switch: -filesearchcommand
  • Specifies a Tcl command to be executed to perform a file search.
  • The command will receive the current working directory and filter
  • Name: filesLabel
  • Class: Text
  • Command-Line Switch: -fileslabel
  • Specifies the text of the label for the files list. The default
  • Name: filesOn
  • Class: FilesOn
  • Command-Line Switch: -fileson
  • Specifies whether or not to display the files list. The value
  • The default is true.
  • Name: fileType
  • Class: FileType
  • Command-Line Switch: -filetype
  • Specify the type of files which may appear in the file list: reg-
  • Name: filterCommand
  • Class: Command
  • Command-Line Switch: -filtercommand
  • Specifies a Tcl command to be executed upon hitting the Return
  • Name: filterLabel
  • Class: Text
  • Command-Line Switch: -filterlabel
  • Specifies the text of the label for the filter combobox. The
  • Name: filterOn
  • Class: FilterOn
  • Command-Line Switch: -filteron
  • Specifies whether or not to display the filter combobox. The
  • Boolean. The default is true.
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the selection box. The value may be
  • Name: invalid
  • Class: Command
  • Command-Line Switch: -invalid
  • Command to be executed should the filter contents be proven
  • Name: mask
  • Class: Mask
  • Command-Line Switch: -mask
  • Specifies the initial file mask string. The default is "*".
  • Name: noMatchString
  • Class: NoMatchString
  • Command-Line Switch: -nomatchstring
  • Specifies the string to be displayed in the files list should no
  • Name: selectDirCommand
  • Class: Command
  • Command-Line Switch: -selectdirommand
  • Specifies a Tcl command to be executed following selection of a
  • Name: selectFileCommand
  • Class: Command
  • Command-Line Switch: -selectfileommand
  • Specifies a Tcl command to be executed following selection of a
  • Name: selectionCommand
  • Class: Command
  • Command-Line Switch: -selectioncommand
  • Specifies a Tcl command to be executed upon hitting the Return
  • Name: selectionLabel
  • Class: Text
  • Command-Line Switch: -selectionlabel
  • Specifies the text of the label for the selection combobox. The
  • Name: selectionOn
  • Class: SelectionOn
  • Command-Line Switch: -selectionon
  • Specifies whether or not to display the selection combobox. The
  • Boolean. The default is true.
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the selection box. The value may be spec-
  • Description
  • The iwidgets::extfileselectionbox command creates an extended
  • Methods
  • The iwidgets::extfileselectionbox command creates a new Tcl com-
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for extfileselectionbox wid-
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Returns the child site widget path name.
  • Query or modify the configuration options of the widget. If no
  • Update the current contents of the extended file selection box
  • Returns the current value of the selection combobox widget.
  • Components
  • Name: dirs
  • Class: Scrolledlistbox
  • The dirs component is the directory list box for the extended
  • Name: files
  • Class: Scrolledlistbox
  • The files component is the file list box for the extended filese-
  • Name: filter
  • Class: Combobox
  • The filter component is the field for user input of the filter
  • Name: selection
  • Class: Combobox
  • The selection component is the field for user input of the cur-
  • Example
  • Author(s)
  • Mark L. Ulferts
  • Anthony Parent
  • Keywords


IWidgets extfileselectiondialog

 Table of Contents

iwidgets::extfileselectiondialog - Create and manipulate a file selection dialog widget

Synopsis

iwidgets::extfileselectiondialog pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Shell <- iwidgets::Dialogshell <- iwidgets::Dialog <- iwidgets::Extfileselectiondialog

Standard Options

activeBackground background borderWidth cursor

foreground
highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

popupCursor
textBackground textFont

See the «combobox» widget manual entry for details on the above

associated options.
childSitePos directory dirsLabel dirSearchCommand

dirsOn
filesLabel filesLabelOn fileSearchCommand
filesOn
fileType filterLabel filterOn
invalid
mask noMatchString selectionLabel selectionOn

See the «extfileselectionbox» widget manual entry for details on

the above associated options.
labelFont

See the «labeledwidget» widget manual entry for details on the

above associated options.
sashCursor

See the «panedwindow» widget manual entry for details on the

above associated options.
labelFont

See the «labeledwidget» widget manual entry for details on the

above associated options.
activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget class manual entry for details on the

above associated options.
textBackground textFont

See the «scrolledlistbox» widget manual entry for details on the

above associated options.

Inherited Options

buttonBoxPadX buttonBoxPadY buttonBoxPos padX

padY
separator thickness

See the «dialogshell» widget manual entry for details on the

above inherited options.
height master modality width

See the «shell» widget manual entry for details on the above

inherited options.
title

See the «Toplevel» widget manual entry for details on the above

inherited options.
_________________________________________________________________

Description

The iwidgets::extfileselectiondialog command creates an extended

file selection dialog which is slightly different than the files- electiondialog widget. The differences are mostly cosmetic in that the listboxes are within a panedwindow and the entryfields for the filter and selection have been replaced by comboboxes.

Other than that the interface is practically the same.

Methods

The iwidgets::extfileselectiondialog command creates a new Tcl

command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for extfileselectiondialog

widgets:

Associated Methods

get
childsite filter

See the «fileselectionbox» class manual entry for details on the

associated methods.

Inherited Methods

add buttonconfigure defaulthide insert invoke show

See the «buttonbox» widget manual entry for details on the above

inherited methods.
activate center deactivate

See the «shell» widget manual entry for details on the above

inherited methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::extfileselectiondialog command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::extfileselectiondialog command.

Components

Name: fsb

Class: Fileselectionbox

The fsb component is the extfileselectionbox for the extfilese-

lectiondialog. See the «extfileselectionbox» widget manual entry for details on the fsb component item.

Example

package require Iwidgets 4.0
#
# Non-modal example
#
proc okCallback {} {
puts «You selected [.nmfsd get]"
.nmfsd deactivate
}

iwidgets::extfileselectiondialog .nmfsd -title Non-Modal .nmfsd buttonconfigure OK -command okCallback

.nmfsd activate

#
# Modal example
#
iwidgets::extfileselectiondialog .mfsd -modality application .mfsd center

if {[.mfsd activate]} {
puts «You selected [.mfsd get]"
} else {
puts «You cancelled the dialog"
}

Author

Mark L. Ulferts

Anthony L. Parent

Keywords

extfileselectiondialog, extfileselectionbox, dialog, dialogshell, shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "combobox" widget manual entry for details on the above
  • See the "extfileselectionbox" widget manual entry for details on
  • See the "labeledwidget" widget manual entry for details on the
  • See the "panedwindow" widget manual entry for details on the
  • See the "labeledwidget" widget manual entry for details on the
  • See the "scrollbar" widget class manual entry for details on the
  • See the "scrolledlistbox" widget manual entry for details on the
  • Inherited Options
  • See the "dialogshell" widget manual entry for details on the
  • See the "shell" widget manual entry for details on the above
  • See the "Toplevel" widget manual entry for details on the above
  • Description
  • The iwidgets::extfileselectiondialog command creates an extended
  • Other than that the interface is practically the same.
  • Methods
  • The iwidgets::extfileselectiondialog command creates a new Tcl
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for extfileselectiondialog
  • Associated Methods
  • See the "fileselectionbox" class manual entry for details on the
  • Inherited Methods
  • See the "buttonbox" widget manual entry for details on the above
  • See the "shell" widget manual entry for details on the above
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: fsb
  • Class: Fileselectionbox
  • The fsb component is the extfileselectionbox for the extfilese-
  • Example
  • Author
  • Mark L. Ulferts
  • Anthony L. Parent
  • Keywords


IWidgets feedback

 Table of Contents

iwidgets::feedback - Create and manipulate a feedback widget to display feedback on the current status of an ongoing operation to the user.

Synopsis

iwidgets::feedback pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Feedback

Standard Options

background cursor foreground highlightColor highlightThickness

See the «options» manual entry for details on the standard

options.

Inherited Options

labelBitmap labelFont labelImage labelMargin

labelPos
labelText labelVariable sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: barcolor

Class: BarColor

Command-Line Switch: -barcolor

Specifies the color of the status bar, in any of the forms

acceptable to Tk_GetColor. The default is DodgerBlue.

Name: barheight

Class: BarHeight

Command-Line Switch: -barheight

Specifies the height of the status bar, in any of the forms

acceptable to Tk_GetPixels. The default is 20.

Name: troughColor

Class: TroughColor

Command-Line Switch: -troughcolor

Specifies the color of the frame in which the status bar sits, in

any of the forms acceptable to Tk_GetColor. The default is white.

Name: steps

Class: Steps

Command-Line Switch: -steps

Specifies the total number of steps for the status bar. The

default is 10.

Description

The iwidgets::feedback command creates a widget to display feed-

back on the current status of an ongoing operation to the user.

Display is given as a percentage and as a thermometer type bar.

Options exist for adding a label and controlling its position.

Methods

The iwidgets::feedback command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for scrolledtext widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the scrolledhtml command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for informa- tion on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::feedback command. pathName reset

Reset the current number of steps completed to 0, and configures

the percentage complete label text to 0%
pathName step ?inc?

Increase the current number of steps completed by the amount

specified by inc. Inc defaults to 1.

Example

package require Iwidgets 4.0
iwidgets::feedback .fb -labeltext «Status» -steps 20 pack .fb -padx 10 -pady 10 -fill both -expand yes

for {set i 0} {$i < 20} {incr i} {
.fb step
after 500
}

Acknowledgements

Sam Shen

This code is based largely on his feedback.tcl code from tk

inspect. The original feedback code is copyright 1995 Lawrence

Berkeley Laboratory.

Author

Kris Raney

Keywords

feedback, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: barcolor
  • Class: BarColor
  • Command-Line Switch: -barcolor
  • Specifies the color of the status bar, in any of the forms
  • Name: barheight
  • Class: BarHeight
  • Command-Line Switch: -barheight
  • Specifies the height of the status bar, in any of the forms
  • Name: troughColor
  • Class: TroughColor
  • Command-Line Switch: -troughcolor
  • Specifies the color of the frame in which the status bar sits, in
  • Name: steps
  • Class: Steps
  • Command-Line Switch: -steps
  • Specifies the total number of steps for the status bar. The
  • Description
  • The iwidgets::feedback command creates a widget to display feed-
  • Display is given as a percentage and as a thermometer type bar.
  • Options exist for adding a label and controlling its position.
  • Methods
  • The iwidgets::feedback command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for scrolledtext widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Reset the current number of steps completed to 0, and configures
  • Increase the current number of steps completed by the amount
  • Example
  • Acknowledgements
  • Sam Shen
  • This code is based largely on his feedback.tcl code from tk
  • Berkeley Laboratory.
  • Author
  • Kris Raney
  • Keywords


IWidgets fileselectionbox

 Table of Contents

iwidgets::fileselectionbox - Create and manipulate a file selec- tion box widget

Synopsis

iwidgets::fileselectionbox pathName ?options?

Inheritance

itk::Widget <- iwidgets::Fileselectionbox

Standard Options

activeBackground background borderWidth cursor

foreground
highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

textBackground textFont

See the «entryfield» widget manual entry for details on the above

associated options.
labelFont

See the «labeledwidget» widget manual entry for details on the

above associated options.
activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget class manual entry for details on the

above associated options.
textBackground textFont

See the «scrolledlistbox» widget manual entry for details on the

above associated options.

Widget-specific Options

Name: automount

Class: Automount

Command-Line Switch: -automount

Specifies a list of directory prefixes to ignore. Typically, this

option would be used as follows:
-automount {export tmp_mnt}

Name: childSitePos

Class: Position

Command-Line Switch: -childsitepos

Specifies the position of the child site in the selection box: n,

s, e, w, top, bottom, or center. The default is s.

Specifies a Tcl command procedure which is called when an file

list item is double clicked. Typically this occurs when mouse button 1 is double clicked over a file name.

Name: directory

Class: Directory

Command-Line Switch: -directory

Specifies the initial default directory. The default is the pre-

sent working directory.

Name: dirSearchCommand

Class: Command

Command-Line Switch: -dirsearchcommand

Specifies a Tcl command to be executed to perform a directory

search. The command will receive the current working directory and filter mask as arguments. The command should return a list of files which will be placed into the directory list.

Name: dirsLabel

Class: Text

Command-Line Switch: -dirslabel

Specifies the text of the label for the directory list. The

default is «Directories".

Name: dirsOn

Class: DirsOn

Command-Line Switch: -dirson

Specifies whether or not to display the directory list. The

value may be given in any of the forms acceptable to Tcl_Get-

Boolean. The default is true.

Name: fileSearchCommand

Class: Command

Command-Line Switch: -filesearchcommand

Specifies a Tcl command to be executed to perform a file search.

The command will receive the current working directory and filter

mask as arguments. The command should return a list of files which will be placed into the file list.

Name: filesLabel

Class: Text

Command-Line Switch: -fileslabel

Specifies the text of the label for the files list. The default

is «Files".

Name: filesOn

Class: FilesOn

Command-Line Switch: -fileson

Specifies whether or not to display the files list. The value

may be given in any of the forms acceptable to Tcl_GetBoolean.

The default is true.

Name: fileType

Class: FileType

Command-Line Switch: -filetype

Specify the type of files which may appear in the file list: reg-

ular, directory, or any. The default is regular.

Name: filterCommand

Class: Command

Command-Line Switch: -filtercommand

Specifies a Tcl command to be executed upon hitting the Return

key in the filter entry widget.

Name: filterLabel

Class: Text

Command-Line Switch: -filterlabel

Specifies the text of the label for the filter entry field. The

default is «Filter".

Name: filterOn

Class: FilterOn

Command-Line Switch: -filteron

Specifies whether or not to display the filter entry. The value

may be given in any of the forms acceptable to Tcl_GetBoolean.

The default is true.

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the selection box. The value may be

specified in any of the forms acceptable to Tk_GetPixels. The default is 360 pixels.

Name: invalid

Class: Command

Command-Line Switch: -invalid

Command to be executed should the filter contents be proven

invalid. The default is {bell}.

Name: mask

Class: Mask

Command-Line Switch: -mask

Specifies the initial file mask string. The default is «*".

Name: noMatchString

Class: NoMatchString

Command-Line Switch: -nomatchstring

Specifies the string to be displayed in the files list should no

files match the mask. The default is «".

Name: selectDirCommand

Class: Command

Command-Line Switch: -selectdirommand

Specifies a Tcl command to be executed following selection of a

directory in the directory list.

Name: selectFileCommand

Class: Command

Command-Line Switch: -selectfileommand

Specifies a Tcl command to be executed following selection of a

file in the files list.

Name: selectionCommand

Class: Command

Command-Line Switch: -selectioncommand

Specifies a Tcl command to be executed upon hitting the Return

key in the selection entry widget.

Name: selectionLabel

Class: Text

Command-Line Switch: -selectionlabel

Specifies the text of the label for the selection entry field.

The default is «Selection".

Name: selectionOn

Class: SelectionOn

Command-Line Switch: -selectionon

Specifies whether or not to display the selection entry. The

value may be given in any of the forms acceptable to Tcl_Get-

Boolean. The default is true.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the selection box. The value may be spec-

ified in any of the forms acceptable to Tk_GetPixels. The default is 470 pixels.
_________________________________________________________________

Description

The iwidgets::fileselectionbox command creates a file selection

box similar to the OSF/Motif standard Xmfileselectionbox compos- ite widget. The fileselectionbox is composed of directory and file scrolled lists as well as filter and selection entry fields.

Bindings are in place such that selection of a directory list

item loads the filter entry field and selection of a file list item loads the selection entry field. Options exist to control the appearance and actions of the widget.

Methods

The iwidgets::fileselectionbox command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for fileselectionbox widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::fileselectionbox command.
pathName childsite

Returns the child site widget path name.

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::fileselectionbox command. pathName filter

Update the current contents of the file selection box based on

the current filter entry field value.
pathName get

Returns the current value of the selection entry widget.

Components

Name: dirs

Class: Scrolledlistbox

The dirs component is the directory list box for the file selec-

tion box. See the «scrolledlistbox» widget manual entry for details on the dirs component item.

Name: files

Class: Scrolledlistbox

The files component is the file list box for the file selection

box. See the «scrolledlistbox» widget manual entry for details on the files component item.

Name: filter

Class: Entryfield

The filter component is the entry field for user input of the

filter value. See the «entryfield» widget manual entry for details on the filter component item.

Name: selection

Class: Entryfield

The selection component is the entry field for user input of the

currently selected file value. See the «entryfield» widget man- ual entry for details on the selection component item.

Example

package require Iwidgets 4.0
iwidgets::fileselectionbox .fsb
pack .fsb -padx 10 -pady 10 -fill both -expand yes

Author(s)

Mark L. Ulferts

Keywords

fileselectionbox, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "entryfield" widget manual entry for details on the above
  • See the "labeledwidget" widget manual entry for details on the
  • See the "scrollbar" widget class manual entry for details on the
  • See the "scrolledlistbox" widget manual entry for details on the
  • Widget-specific Options
  • Name: automount
  • Class: Automount
  • Command-Line Switch: -automount
  • Specifies a list of directory prefixes to ignore. Typically, this
  • Name: childSitePos
  • Class: Position
  • Command-Line Switch: -childsitepos
  • Specifies the position of the child site in the selection box: n,
  • Specifies a Tcl command procedure which is called when an file
  • Name: directory
  • Class: Directory
  • Command-Line Switch: -directory
  • Specifies the initial default directory. The default is the pre-
  • Name: dirSearchCommand
  • Class: Command
  • Command-Line Switch: -dirsearchcommand
  • Specifies a Tcl command to be executed to perform a directory
  • Name: dirsLabel
  • Class: Text
  • Command-Line Switch: -dirslabel
  • Specifies the text of the label for the directory list. The
  • Name: dirsOn
  • Class: DirsOn
  • Command-Line Switch: -dirson
  • Specifies whether or not to display the directory list. The
  • Boolean. The default is true.
  • Name: fileSearchCommand
  • Class: Command
  • Command-Line Switch: -filesearchcommand
  • Specifies a Tcl command to be executed to perform a file search.
  • The command will receive the current working directory and filter
  • Name: filesLabel
  • Class: Text
  • Command-Line Switch: -fileslabel
  • Specifies the text of the label for the files list. The default
  • Name: filesOn
  • Class: FilesOn
  • Command-Line Switch: -fileson
  • Specifies whether or not to display the files list. The value
  • The default is true.
  • Name: fileType
  • Class: FileType
  • Command-Line Switch: -filetype
  • Specify the type of files which may appear in the file list: reg-
  • Name: filterCommand
  • Class: Command
  • Command-Line Switch: -filtercommand
  • Specifies a Tcl command to be executed upon hitting the Return
  • Name: filterLabel
  • Class: Text
  • Command-Line Switch: -filterlabel
  • Specifies the text of the label for the filter entry field. The
  • Name: filterOn
  • Class: FilterOn
  • Command-Line Switch: -filteron
  • Specifies whether or not to display the filter entry. The value
  • The default is true.
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the selection box. The value may be
  • Name: invalid
  • Class: Command
  • Command-Line Switch: -invalid
  • Command to be executed should the filter contents be proven
  • Name: mask
  • Class: Mask
  • Command-Line Switch: -mask
  • Specifies the initial file mask string. The default is "*".
  • Name: noMatchString
  • Class: NoMatchString
  • Command-Line Switch: -nomatchstring
  • Specifies the string to be displayed in the files list should no
  • Name: selectDirCommand
  • Class: Command
  • Command-Line Switch: -selectdirommand
  • Specifies a Tcl command to be executed following selection of a
  • Name: selectFileCommand
  • Class: Command
  • Command-Line Switch: -selectfileommand
  • Specifies a Tcl command to be executed following selection of a
  • Name: selectionCommand
  • Class: Command
  • Command-Line Switch: -selectioncommand
  • Specifies a Tcl command to be executed upon hitting the Return
  • Name: selectionLabel
  • Class: Text
  • Command-Line Switch: -selectionlabel
  • Specifies the text of the label for the selection entry field.
  • The default is "Selection".
  • Name: selectionOn
  • Class: SelectionOn
  • Command-Line Switch: -selectionon
  • Specifies whether or not to display the selection entry. The
  • Boolean. The default is true.
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the selection box. The value may be spec-
  • Description
  • The iwidgets::fileselectionbox command creates a file selection
  • Bindings are in place such that selection of a directory list
  • Methods
  • The iwidgets::fileselectionbox command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for fileselectionbox widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Returns the child site widget path name.
  • Query or modify the configuration options of the widget. If no
  • Update the current contents of the file selection box based on
  • Returns the current value of the selection entry widget.
  • Components
  • Name: dirs
  • Class: Scrolledlistbox
  • The dirs component is the directory list box for the file selec-
  • Name: files
  • Class: Scrolledlistbox
  • The files component is the file list box for the file selection
  • Name: filter
  • Class: Entryfield
  • The filter component is the entry field for user input of the
  • Name: selection
  • Class: Entryfield
  • The selection component is the entry field for user input of the
  • Example
  • Author(s)
  • Mark L. Ulferts
  • Keywords


IWidgets fileselectiondialog

 Table of Contents

iwidgets::fileselectiondialog - Create and manipulate a file selection dialog widget

Synopsis

iwidgets::fileselectiondialog pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Shell <- iwidgets::Dialogshell <- iwidgets::Dialog <- iwidgets::Fileselectiondialog

Standard Options

activeBackground background borderWidth cursor

foreground
highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

textBackground textFont

See the «entryfield» widget manual entry for details on the above

associated options.
childSitePos directory dirsLabel dirSearchCommand

dirsOn
filesLabel filesLabelOn fileSearchCommand
filesOn
fileType filterLabel filterOn
invalid
mask noMatchString selectionLabel selectionOn

See the «fileselectionbox» widget manual entry for details on the

above associated options.
labelFont

See the «labeledwidget» widget manual entry for details on the

above associated options.
textBackground textFont

See the «scrolledlistbox» widget manual entry for details on the

above associated options.
activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget class manual entry for details on the

above associated options.

Inherited Options

buttonBoxPadX buttonBoxPadY buttonBoxPos padX

padY
separator thickness

See the «dialogshell» widget manual entry for details on the

above inherited options.
height master modality width

See the «shell» widget manual entry for details on the above

inherited options.
title

See the «Toplevel» widget manual entry for details on the above

inherited options.
_________________________________________________________________

Description

The iwidgets::fileselectiondialog command creates a file selec-

tion dialog similar to the OSF/Motif standard composite widget.

The fileselectiondialog is derived from the Dialog class and is

composed of a FileSelectionBox with attributes set to manipulate the dialog buttons.

Methods

The iwidgets::fileselectiondialog command creates a new Tcl com-

mand whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

Option and the args determine the exact behavior of the command.

The following commands are possible for fileselectiondialog wid-

gets:

Associated Methods

get
childsite filter

See the «fileselectionbox» class manual entry for details on the

associated methods.

Inherited Methods

add buttonconfigure defaulthide insert invoke show

See the «buttonbox» widget manual entry for details on the above

inherited methods.
activate center deactivate

See the «shell» widget manual entry for details on the above

inherited methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::fileselectiondialog command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::fileselectiondialog command.

Components

Name: fsb

Class: Fileselectionbox

The fsb component is the file selection box for the file selec-

tion dialog. See the «fileselectionbox» widget manual entry for details on the fsb component item.

Example

package require Iwidgets 4.0
#
# Non-modal example
#
proc okCallback {} {
puts «You selected [.nmfsd get]"
.nmfsd deactivate
}

iwidgets::fileselectiondialog .nmfsd -title Non-Modal .nmfsd buttonconfigure OK -command okCallback

.nmfsd activate

#
# Modal example
#
iwidgets::fileselectiondialog .mfsd -modality application .mfsd center

if {[.mfsd activate]} {
puts «You selected [.mfsd get]"
} else {
puts «You cancelled the dialog"
}

Author

Mark L. Ulferts

Keywords

fileselectiondialog, fileselectionbox, dialog, dialogshell, shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "entryfield" widget manual entry for details on the above
  • See the "fileselectionbox" widget manual entry for details on the
  • See the "labeledwidget" widget manual entry for details on the
  • See the "scrolledlistbox" widget manual entry for details on the
  • See the "scrollbar" widget class manual entry for details on the
  • Inherited Options
  • See the "dialogshell" widget manual entry for details on the
  • See the "shell" widget manual entry for details on the above
  • See the "Toplevel" widget manual entry for details on the above
  • Description
  • The iwidgets::fileselectiondialog command creates a file selec-
  • The fileselectiondialog is derived from the Dialog class and is
  • Methods
  • The iwidgets::fileselectiondialog command creates a new Tcl com-
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for fileselectiondialog wid-
  • Associated Methods
  • See the "fileselectionbox" class manual entry for details on the
  • Inherited Methods
  • See the "buttonbox" widget manual entry for details on the above
  • See the "shell" widget manual entry for details on the above
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: fsb
  • Class: Fileselectionbox
  • The fsb component is the file selection box for the file selec-
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets finddialog

 Table of Contents

iwidgets::finddialog - Create and manipulate a find dialog widget

Synopsis

iwidgets::finddialog pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Shell <- iwidgets::Dialogshell <- iwidgets::Finddialog

Standard Options

activeBackground activeForeground background borderWidth

cursor
disabledForeground font foreground
highlightColor
highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth selectBackground selectBorderWidth selectColor selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

selectColor

See the «checkbutton» widget manual entry for details on the

above associated options.
selectColor

See the «entryfield» widget manual entry for details on the above

associated options.
labelFont

See the «labeledwidget» widget manual entry for details on the

above associated options.

Inherited Options

buttonBoxPadX buttonBoxPadY buttonBoxPos padX

padY
separator thickness

See the «dialogshell» widget manual entry for details on the

above inherited options.
height master modality width

See the «shell» widget manual entry for details on the above

inherited options.
title

See the «Toplevel» widget manual entry for details on the above

inherited options.

Widget-specific Options

Name: clearCommand

Class: Command

Command-Line Switch: -clearcommand

Specifies a command to be invoked following a clear operation.

The option is meant to be used as means of notification that the

clear has taken place and allow other actions to take place such as disabling a find again menu.

Name: matchCommand

Class: Command

Command-Line Switch: -matchcommand

Specifies a command to be invoked following a find operation.

The command is called with a match point as an argument which

identifies where exactly where in the text or scrolledtext widget that the match is located. Should a match not be found the match point is {}. The option is meant to be used as a means of noti- fication that the find operation has completed and allow other actions to take place such as disabling a find again menu option if the match point was {}.

Name: patternBackground

Class: Background

Command-Line Switch: -patternbackground

Specifies the background color of the text matching the search

pattern. It may have any of the forms accepted by Tk_GetColor.

The default is gray44.

Name: patternForeground

Class: Background

Command-Line Switch: -patternforeground

Specifies the foreground color of the text matching the search

pattern. It may have any of the forms accepted by Tk_GetColor.

The default is white.

Name: searchBackground

Class: Background

Command-Line Switch: -searchbackground

Specifies the background color of the line containing the match-

ing the search pattern. It may have any of the forms accepted by

Tk_GetColor. The default is gray77.

Name: searchForeground

Class: Background

Command-Line Switch: -searchforeground

Specifies the foreground color of the line containing the match-

ing the search pattern. It may have any of the forms accepted by

Tk_GetColor. The default is black.

Name: textWidget

Class: TextWidget

Command-Line Switch: -textwidget

Specifies the text or scrolledtext widget to be searched.

_________________________________________________________________

Description

The iwidgets::finddialog command creates a find dialog that works

in conjunction with a text or scrolledtext widget to provide a means of performing search operations. The user is prompted for a text pattern to be found in the text or scrolledtext widget.

The search can be for all occurances, by regular expression, con-

siderate of the case, or backwards.

Methods

The iwidgets::finddialog command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for finddialog widgets:

Inherited Methods

add buttonconfigure defaulthide

invoke
show

See the «buttonbox» widget manual entry for details on the above

inherited methods.
activate center deactivate

See the «shell» widget manual entry for details on the above

inherited methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::finddialog command.
pathName clear

Clears the pattern in the entry field and the pattern matchin

indicators in the text or scrolledtext widget. pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::finddialog command.

pathName find

Search for a specific text string in the text widget given by the

-textwidget option. This method is the standard callback for the

Find button. It is made available such that it can be bound to a

find again action.

Components

Name: all

Class: Checkbutton

The all component specifies that all the matches of the pattern

should be found when performing the search. See the «checkbut- ton» widget manual entry for details on the all component item.

Name: backwards

Class: Checkbutton

The backwards component specifies that the search should continue

in a backwards direction towards the beginning of the text or scrolledtext widget. See the «checkbutton» widget manual entry for details on the backwards component item.

Name: case

Class: Checkbutton

The case component specifies that the case of the pattern should

be taken into consideration when performing the search. See the «checkbutton» widget manual entry for details on the case compo- nent item.

Name: pattern

Class: Entryfield

The pattern component provides the pattern entry field. See the

«entryfield» widget manual entry for details on the pattern com- ponent item.

Name: regexp

Class: Checkbutton

The regexp component specifies that the pattern is a regular

expression. See the «checkbutton» widget manual entry for details on the regexp component item.

Example

package require Iwidgets 4.0
iwidgets::scrolledtext .st
pack .st
.st insert end «Now is the time for all good men\n" .st insert end «to come to the aid of their country"

iwidgets::finddialog .fd -textwidget .st
.fd center .st
.fd activate

Author

Mark L. Ulferts

Keywords

finddialog, dialogshell, shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "checkbutton" widget manual entry for details on the
  • See the "entryfield" widget manual entry for details on the above
  • See the "labeledwidget" widget manual entry for details on the
  • Inherited Options
  • See the "dialogshell" widget manual entry for details on the
  • See the "shell" widget manual entry for details on the above
  • See the "Toplevel" widget manual entry for details on the above
  • Widget-specific Options
  • Name: clearCommand
  • Class: Command
  • Command-Line Switch: -clearcommand
  • Specifies a command to be invoked following a clear operation.
  • The option is meant to be used as means of notification that the
  • Name: matchCommand
  • Class: Command
  • Command-Line Switch: -matchcommand
  • Specifies a command to be invoked following a find operation.
  • The command is called with a match point as an argument which
  • Name: patternBackground
  • Class: Background
  • Command-Line Switch: -patternbackground
  • Specifies the background color of the text matching the search
  • The default is gray44.
  • Name: patternForeground
  • Class: Background
  • Command-Line Switch: -patternforeground
  • Specifies the foreground color of the text matching the search
  • The default is white.
  • Name: searchBackground
  • Class: Background
  • Command-Line Switch: -searchbackground
  • Specifies the background color of the line containing the match-
  • Tk_GetColor. The default is gray77.
  • Name: searchForeground
  • Class: Background
  • Command-Line Switch: -searchforeground
  • Specifies the foreground color of the line containing the match-
  • Tk_GetColor. The default is black.
  • Name: textWidget
  • Class: TextWidget
  • Command-Line Switch: -textwidget
  • Specifies the text or scrolledtext widget to be searched.
  • Description
  • The iwidgets::finddialog command creates a find dialog that works
  • The search can be for all occurances, by regular expression, con-
  • Methods
  • The iwidgets::finddialog command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for finddialog widgets:
  • Inherited Methods
  • See the "buttonbox" widget manual entry for details on the above
  • See the "shell" widget manual entry for details on the above
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Clears the pattern in the entry field and the pattern matchin
  • Query or modify the configuration options of the widget. If no
  • Search for a specific text string in the text widget given by the
  • Find button. It is made available such that it can be bound to a
  • Components
  • Name: all
  • Class: Checkbutton
  • The all component specifies that all the matches of the pattern
  • Name: backwards
  • Class: Checkbutton
  • The backwards component specifies that the search should continue
  • Name: case
  • Class: Checkbutton
  • The case component specifies that the case of the pattern should
  • Name: pattern
  • Class: Entryfield
  • The pattern component provides the pattern entry field. See the
  • Name: regexp
  • Class: Checkbutton
  • The regexp component specifies that the pattern is a regular
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets hierarchy

 Table of Contents

iwidgets::hierarchy - Create and manipulate a hierarchy widget

Synopsis

iwidgets::hierarchy pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Scrolledwid- get <- iwidgets::Hierarchy

Standard Options

activeBackground activeForeground background borderWidth

cursor
disabledForeground foreground highlightColor highlightThickness relief selectBackground selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget manual entry for details on the above

associated options.
spacing1 spacing2 spacing3 tabs

See the «text» widget manual entry for details on the above asso-

ciated options.

Inherited Options

labelBitmap labelFont labelImage labelMargin

labelPos
labelText labelVariable sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: alwaysQuery

Class: AlwaysQuery

Command-Line Switch: -alwaysquery

Boolean flag which tells the hierarchy widget weather or not each

refresh of the display should be via a new query using the com- mand value of the -querycommand option or use the values previous found the last time the query was made. The default is no.

Name: closedIcon

Class: Icon

Command-Line Switch: -closedicon

Specifies the name of an existing closed icon image to be used in

the hierarchy before those nodes that are collapsed. Should one not be provided, then a folder icon will be generated, pixmap if possible, bitmap otherwise.

Name: dblClickCommand

Class: Command

Command-Line Switch: -dblclickcommand

Specifies a command to be executed upon user double clicking via

mouse button one of the text label of an entry. If this command contains «%n", it is replaced with the name of the selected node.

Should it contain «%s» then a boolean indicator of the node's

current selection status is substituted.

Name: expanded

Class: Expanded

Command-Line Switch: -expanded

When true, the hierarchy will be completely expanded when it is

first displayed. A fresh display can be triggered by resetting the -querycommand option. The default is false.

Name: filter

Class: Filter

Command-Line Switch: -filter

When true only the branch nodes and selected items are displayed.

This gives a compact view of important items. The default is

false.

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the hierarchy as an entire unit. The

value may be specified in any of the forms acceptable to

Tk_GetPixels. Any additional space needed to display the other

components such as labels, margins, and scrollbars force the hierarchy to be compressed. A value of zero along with the same value for the width causes the value given for the visibleitems option to be applied which administers geometry constraints in a different manner. The default height is zero.

Name: iconCommand

Class: Command

Command-Line Switch: -iconcommand

Specifies a command to be executed upon user selection via mouse

button one of any additional icons given in the values returned by the command associated with the -querycommand option. If this command contains «%n", it is replaced with the name of the node the icon belongs to. Should it contain «%i» then the icon name is substituted.

Name: iconDblCommand

Class: Command

Command-Line Switch: -icondblcommand

Specifies a command to be executed upon user double clicking via

mouse button one of the icon of an entry. If this command con- tains «%n", it is replaced with the name of the node the icon belongs to. Should it contain «%i» then the icon name is substi- tuted.

Name: imageCommand

Class: Command

Command-Line Switch: -imagecommand

Specifies a command to be executed upon user selecting an image

of an entry. If this command contains «%n", it is replaced with the name of the selected node. Should it contain «%s» then a boolean indicator of the node's current selection status is sub- stituted.

Name: imageDblCommand

Class: Command

Command-Line Switch: -imagedblcommand

Specifies a command to be executed upon user double clicking via

mouse button one of the image of an entry. If this command con- tains «%n", it is replaced with the name of the node the icon belongs to. Should it contain «%i» then the icon name is substi- tuted.

Name: imageMenuLoadCommand

Class: Command

Command-Line Switch: -imagemenuloadcommand

Specifies a command to be executed upon user selection via mouse

button three, on the image or icon, that will dynamically load the itemMenu for the widget.

Name: markBackground

Class: Foreground

Command-Line Switch: -markbackground

Specifies the background color to use when displaying marked

nodes.

Name: markForeground

Class: Background

Command-Line Switch: -markforeground

Specifies the foreground color to use when displaying marked

nodes.

Name: menuCursor

Class: Cursor

Command-Line Switch: -menucursor

Specifies the mouse cursor to be used for the item and background

menus. The value may have any of the forms accept able to

Tk_GetCursor.

Name: nodeIcon

Class: Icon

Command-Line Switch: -nodeicon

Specifies the name of an existing node icon image to be used in

the hierarchy before those nodes that are leafs. Should one not be provided, then a dog-eared page icon will be generated, pixmap if possible, bitmap otherwise.

Name: openIcon

Class: Icon

Command-Line Switch: -openicon

Specifies the name of an existing open icon image to be used in

the hierarchy before those nodes that are expanded. Should one not be provided, then an open folder icon will be generated, pixmap if possible, bitmap otherwise.

Name: queryCommand

Class: Command

Command-Line Switch: -querycommand

Specifies the command executed to query the contents of each

node. If this command contains «%n", it is replaced with the name of the desired node. In its simpilest form it should return the children of the given node as a list which will be depicted in the display. Since the names of the children are used as tags in the underlying text widget, each child must be unique in the hierarchy. Due to the unique requirement, the nodes shall be reffered to as uids or uid in the singular sense. The format of returned list is
{uid [uid ...]}
where uid is a unique id and primary key for the hierarchy entry

Should the unique requirement pose a problem, the list returned

can take on another more extended form which enables the associa- tion of text to be displayed with the uids. The uid must still be unique, but the text does not have to obey the unique rule.

In addition, the format also allows the specification of addi-

tional tags to be used on the same entry in the hierarchy as the uid and additional icons to be displayed just before the node.

The tags and icons are considered to be the property of the user

in that the hierarchy widget will not depend on any of their val- ues. The extended format is
{{uid [text [tags [icons]]]} {uid [text [tags [icons]]]} ...} where uid is a unique id and primary key for the hierarchy entry
text is the text to be displayed for this uid tags is a list of user tags to be applied to the entry icons is a list of icons to be displayed in front of the text

The hierarchy widget does a look ahead from each node to deter-

mine if the node has a children. This can be cost some perfor- mace with large hierarchies. User's can avoid this by providing a hint in the user tags. A tag of «leaf» or «branch» tells the hierarchy widget the information it needs to know thereby avoid- ing the look ahead operation.

Name: hscrollMode

Class: ScrollMode

Command-Line Switch: -hscrollmode

Specifies the the display mode to be used for the horizontal

scrollbar: static, dynamic, or none. In static mode, the scroll bar is displayed at all times. Dynamic mode displays the scroll bar as required, and none disables the scroll bar display. The default is static.

Name: sbWidth

Class: Width

Command-Line Switch: -sbwidth

Specifies the width of the scrollbar in any of the forms accept-

able to Tk_GetPixels.

Name: scrollMargin

Class: Margin

Command-Line Switch: -scrollmargin

Specifies the distance between the text portion of the hierarchy

and the scrollbars in any of the forms acceptable to Tk_GetPix- els. The default is 3 pixels.

Name: selectCommand

Class: Command

Command-Line Switch: -selectcommand

Specifies a Tcl command to be evaluated when you select a node in

the hierarchy via left mouse click. If «%n» is included in the command, it is substituted with the node name. Similarly, «%s" is substituted with the node's current selection status: 1 for selected, 0 otherwise.

Name: textBackground Class: Background Com-

mand-Line Switch: -textbackground

Specifies the background color for the text portion of the hier-

archy in any of the forms acceptable to Tk_GetColor.

Name: textFont

Class: Font

Command-Line Switch: -textfont

Specifies the font to be used in the text portion of the hierar-

chy.

Name: textMenuLoadCommand

Class: Command

Command-Line Switch: -textmenuloadcommand

Specifies a command to be executed upon user selection via mouse

button three, that will dynamically load the itemMenu for the widget.

Name: visibleitems

Class: VisibleItems

Command-Line Switch: -visibleitems

Specifies the widthxheight in characters and lines for the hier-

archy. This option is only administered if the width and height options are both set to zero, otherwise they take precedence.

The default value is 80x24. With the visibleitems option

engaged, geometry constraints are maintained only on the text portion of the hierarchy. The size of the other components such as labels, margins, and scroll bars, are additive and indepen- dent, effecting the overall size of the hierarchy. In contrast, should the width and height options have non zero values, they are applied to the hierarchy as a whole. The hierarchy is com- pressed or expanded to maintain the geometry constraints.

Name: vscrollMode

Class: ScrollMode

Command-Line Switch: -vscrollmode

Specifies the the display mode to be used for the vertical

scrollbar: static, dynamic, or none. In static mode, the scroll bar is displayed at all times. Dynamic mode displays the scroll bar as required, and none disables the scroll bar display. The default is static.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the hierarchy as an entire unit. The

value may be specified in any of the forms acceptable to Tk_Get-

Pixels. Any additional space needed to display the other compo-

nents such as labels, margins, and scrollbars force the text por- tion of the hierarchy to be compressed. A value of zero along with the same value for the height causes the value given for the visibleitems option to be applied which administers geometry con- straints in a different manner. The default width is zero.

_________________________________________________________________

Description

The iwidgets::hierarchy command creates a hierarchical data view

widget. It allows the graphical management of a a list of nodes that can be expanded or collapsed. Individual nodes can be high- lighted. Clicking with the right mouse button on any item brings up a special item menu. Clicking on the background area brings up a different popup menu. Options exist to provide user control over the loading of the nodes and actions associated with node selection. Since the hierarchy is based on the scrolledtext wid- get, it includes options to control the method in which the scrollbars are displayed, i.e. statically or dynamically.

Options also exist for adding a label to the hierarchy and con-

trolling its position.

Methods

The iwidgets::hierarchy command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for hierarchy widgets:

Associated Methods

bbox
compare debug delete dlineinfo dump get index insert scan search see
tag
window xview yview

See the «text» manual entry for details on the standard methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::hierarchy command.
pathName clear

Removes all items from the hierarchy display including all tags

and icons. The display will remain empty until the -filter or -querycommand options are set.
pathName collapse uid

Collapses the hierarchy beneath the node with the specified

unique id by one level. Since this can take a moment for large hierarchies, the cursor will be changed to a watch during the collapse. Also, if any of the nodes beneath the node being col- lapsed are selected, their status is changed to unselected. pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::hierarchy command. pathName current

Returns the tags for the node that was most recently selected by

the right mouse button when the item menu was posted. Usually used by the code in the item menu to figure out what item is being manipulated.
pathName draw ?when?

Performs a complete redraw of the entire hierarchy. When may be

either -now or -eventually where the latter means the draw can be performed after idle.
pathName expand uid

Expands the hierarchy beneath the node with the specified unique

id by one level. Since this can take a moment for large hierar- chies, the cursor will be changed to a watch during the expan- sion.

pathName expanded uid

Returns the current state of expansion for the node with the

specified unique id.
pathName expState

Returns a list of all expanded nodes in the tree.

pathName mark option ?arg arg ...?

This command is used to manipulate marks which is quite similar

to selection, adding a secondary means of hilighting an item in the hierarchy. The exact behavior of the command depends on the option argument that follows the mark argument. The following forms of the command are currently supported: pathName mark clear

Clears all the currently marked nodes in the hierarchy.

pathName mark add uid ?uid uid ...?

Marks the nodes with the specified uids in the hierarchy using

the -markbackground and -markforeground options and without affecting the mark state of any other nodes that were already marked.
pathName mark remove uid ?uid uid ...?

Unmarks the nodes with the specified uids in the hierarchy with-

out affecting the mark state of any other nodes that were already marked.
pathName mark get

Returns a list of the unique ids that are currently marked.

pathName refresh uid

Performs a redraw of a specific node that has the given uid. If

the node is not currently visible or in other words already drawn on the text, then no action is taken.
pathName prune uid

Removes the node specified by the given uid from the hierarchy.

Should the node have children, then all of its children will be

removed as well.
pathName selection option ?arg arg ...?

This command is used to manipulate the selection of nodes in the

hierarchy. The exact behavior of the command depends on the option argument that follows the selection argument. The follow- ing forms of the command are currently supported: pathName selection clear

Clears all the currently selected nodes in the hierarchy.

pathName selection add uid ?uid uid ...?

Selects the nodes with the specified uids in the hierarchy using

the -selectionbackground and -selectionforeground options and without affecting the selection state of any other nodes that were already selected.
pathName selection remove uid ?uid uid ...?

Deselects the nodes with the specified uids in the hierarchy

without affecting the selection state of any other nodes that were already selected.
pathName selection get

Returns a list of the unique ids that are currently selected.

A nodes selection status is also dependent on it being visible.

If a node is selected and its parent is then collapsed making the

selected node not visible, then its selection status is changed to unselected.
pathName toggle uid

Toggles the hierarchy beneath the node with the specified unique

id. If the hierarchy is currently expanded, then it is col- lapsed, and vice-versa.

Components

Name: list

Class: Text

The list component is the text widget in which the hierarchy is

displayed. See the «text» widget manual entry for details on the text component item.

Name: bgMenu

Class: Menu

The bgMenu component is the popup menu which is displayed upon

pressing the right mouse button in the background, i.e. not over a specific node. Menu items can be added along with their com- mands via the component command. See the «menu» widget manual entry for details on the bgMenu component item.

Name: horizsb

Class: Scrollbar

The horizsb component is the horizontal scroll bar. See the

«scrollbar» widget manual entry for details on the horizsb compo- nent item.

Name: itemMenu

Class: Menu

The itemMenu component is the popup menu which is displayed upon

selection of a hierarchy node with the right mouse button. Menu items can be added along with their commands via the component command. See the «menu» widget manual entry for details on the itemMenu component item.

Name: vertsb

Class: Scrollbar

The vertsb component is the vertical scroll bar. See the

«scrollbar» widget manual entry for details on the vertsb compo- nent item.

Example

package require Iwidgets 4.0
proc get_files {file} {
global env

if {$file == «"} {
set dir $env(HOME)
} else {
set dir $file
}

if {[catch {cd $dir}] != 0} {
return «"
}

set rlist «"

foreach file [lsort [glob -nocomplain *]] { lappend rlist [list [file join $dir $file] $file] }

return $rlist
}

iwidgets::hierarchy .h -querycommand «get_files %n» -visibleitems 30x15 -labeltext $env(HOME) pack .h -side left -expand yes -fill both

Author

Mark L. Ulferts

Michael J. McLennan

Keywords

hierarchy, text, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "scrollbar" widget manual entry for details on the above
  • See the "text" widget manual entry for details on the above asso-
  • Inherited Options
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: alwaysQuery
  • Class: AlwaysQuery
  • Command-Line Switch: -alwaysquery
  • Boolean flag which tells the hierarchy widget weather or not each
  • Name: closedIcon
  • Class: Icon
  • Command-Line Switch: -closedicon
  • Specifies the name of an existing closed icon image to be used in
  • Name: dblClickCommand
  • Class: Command
  • Command-Line Switch: -dblclickcommand
  • Specifies a command to be executed upon user double clicking via
  • Should it contain "%s" then a boolean indicator of the node's
  • Name: expanded
  • Class: Expanded
  • Command-Line Switch: -expanded
  • When true, the hierarchy will be completely expanded when it is
  • Name: filter
  • Class: Filter
  • Command-Line Switch: -filter
  • When true only the branch nodes and selected items are displayed.
  • This gives a compact view of important items. The default is
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the hierarchy as an entire unit. The
  • Tk_GetPixels. Any additional space needed to display the other
  • Name: iconCommand
  • Class: Command
  • Command-Line Switch: -iconcommand
  • Specifies a command to be executed upon user selection via mouse
  • Name: iconDblCommand
  • Class: Command
  • Command-Line Switch: -icondblcommand
  • Specifies a command to be executed upon user double clicking via
  • Name: imageCommand
  • Class: Command
  • Command-Line Switch: -imagecommand
  • Specifies a command to be executed upon user selecting an image
  • Name: imageDblCommand
  • Class: Command
  • Command-Line Switch: -imagedblcommand
  • Specifies a command to be executed upon user double clicking via
  • Name: imageMenuLoadCommand
  • Class: Command
  • Command-Line Switch: -imagemenuloadcommand
  • Specifies a command to be executed upon user selection via mouse
  • Name: markBackground
  • Class: Foreground
  • Command-Line Switch: -markbackground
  • Specifies the background color to use when displaying marked
  • Name: markForeground
  • Class: Background
  • Command-Line Switch: -markforeground
  • Specifies the foreground color to use when displaying marked
  • Name: menuCursor
  • Class: Cursor
  • Command-Line Switch: -menucursor
  • Specifies the mouse cursor to be used for the item and background
  • Tk_GetCursor.
  • Name: nodeIcon
  • Class: Icon
  • Command-Line Switch: -nodeicon
  • Specifies the name of an existing node icon image to be used in
  • Name: openIcon
  • Class: Icon
  • Command-Line Switch: -openicon
  • Specifies the name of an existing open icon image to be used in
  • Name: queryCommand
  • Class: Command
  • Command-Line Switch: -querycommand
  • Specifies the command executed to query the contents of each
  • Should the unique requirement pose a problem, the list returned
  • In addition, the format also allows the specification of addi-
  • The tags and icons are considered to be the property of the user
  • The hierarchy widget does a look ahead from each node to deter-
  • Name: hscrollMode
  • Class: ScrollMode
  • Command-Line Switch: -hscrollmode
  • Specifies the the display mode to be used for the horizontal
  • Name: sbWidth
  • Class: Width
  • Command-Line Switch: -sbwidth
  • Specifies the width of the scrollbar in any of the forms accept-
  • Name: scrollMargin
  • Class: Margin
  • Command-Line Switch: -scrollmargin
  • Specifies the distance between the text portion of the hierarchy
  • Name: selectCommand
  • Class: Command
  • Command-Line Switch: -selectcommand
  • Specifies a Tcl command to be evaluated when you select a node in
  • Name: textBackground Class: Background Com-
  • Specifies the background color for the text portion of the hier-
  • Name: textFont
  • Class: Font
  • Command-Line Switch: -textfont
  • Specifies the font to be used in the text portion of the hierar-
  • Name: textMenuLoadCommand
  • Class: Command
  • Command-Line Switch: -textmenuloadcommand
  • Specifies a command to be executed upon user selection via mouse
  • Name: visibleitems
  • Class: VisibleItems
  • Command-Line Switch: -visibleitems
  • Specifies the widthxheight in characters and lines for the hier-
  • The default value is 80x24. With the visibleitems option
  • Name: vscrollMode
  • Class: ScrollMode
  • Command-Line Switch: -vscrollmode
  • Specifies the the display mode to be used for the vertical
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the hierarchy as an entire unit. The
  • Pixels. Any additional space needed to display the other compo-
  • Description
  • The iwidgets::hierarchy command creates a hierarchical data view
  • Options also exist for adding a label to the hierarchy and con-
  • Methods
  • The iwidgets::hierarchy command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for hierarchy widgets:
  • Associated Methods
  • See the "text" manual entry for details on the standard methods.
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Removes all items from the hierarchy display including all tags
  • Collapses the hierarchy beneath the node with the specified
  • Query or modify the configuration options of the widget. If no
  • Returns the tags for the node that was most recently selected by
  • Performs a complete redraw of the entire hierarchy. When may be
  • Expands the hierarchy beneath the node with the specified unique
  • Returns the current state of expansion for the node with the
  • Returns a list of all expanded nodes in the tree.
  • This command is used to manipulate marks which is quite similar
  • Clears all the currently marked nodes in the hierarchy.
  • Marks the nodes with the specified uids in the hierarchy using
  • Unmarks the nodes with the specified uids in the hierarchy with-
  • Returns a list of the unique ids that are currently marked.
  • Performs a redraw of a specific node that has the given uid. If
  • Removes the node specified by the given uid from the hierarchy.
  • Should the node have children, then all of its children will be
  • This command is used to manipulate the selection of nodes in the
  • Clears all the currently selected nodes in the hierarchy.
  • Selects the nodes with the specified uids in the hierarchy using
  • Deselects the nodes with the specified uids in the hierarchy
  • Returns a list of the unique ids that are currently selected.
  • A nodes selection status is also dependent on it being visible.
  • If a node is selected and its parent is then collapsed making the
  • Toggles the hierarchy beneath the node with the specified unique
  • Components
  • Name: list
  • Class: Text
  • The list component is the text widget in which the hierarchy is
  • Name: bgMenu
  • Class: Menu
  • The bgMenu component is the popup menu which is displayed upon
  • Name: horizsb
  • Class: Scrollbar
  • The horizsb component is the horizontal scroll bar. See the
  • Name: itemMenu
  • Class: Menu
  • The itemMenu component is the popup menu which is displayed upon
  • Name: vertsb
  • Class: Scrollbar
  • The vertsb component is the vertical scroll bar. See the
  • Example
  • Author
  • Mark L. Ulferts
  • Michael J. McLennan
  • Keywords


IWidgets hyperhelp

 Table of Contents

iwidgets::hyperhelp - Create and manipulate a hyperhelp widget

Synopsis

iwidgets::hyperhelp pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Shell <- iwidgets::Hyperhelp

Standard Options

activeBackground background borderWidth closecmd cursor exportSelection

foreground
highlightColor highlightThickness
insertBackground
insertBorderWidth insertOffTime insertOnTime insertWidth padX
padY
relief repeatDelay
repeatInterval
selectBackground selectBorderWidth
selectForeground
setGrid

See the «options» manual entry for details on the standard

options.

Associated Options

hscrollmode
vscrollmode textbackground fontname fontsize fixedfont link linkhighlight width height state wrap unknownimage

See the «scrolledhtml» widget manual entry for details on the

above associated options.

Inherited Options

modality
title

See the «shell» manual entry for details on the above inherited

options.

Widget-specific Options

Name: topics

Class: Topics

Command-Line Switch: -topics

Specifies a list of help topics in the form {?topic? ... }. Topic

may either be a topic name, in which case the document associated with the topic should be in the file helpdir/topic.html, or it may be of the form {name file}. In the latter case, name is dis- played in the topic menu, and selecting the name loads file. If file has a relative path, it is assumed to be relative to helpdir.

Name: helpdir

Class: Directory

Command-Line Switch: -helpdir

Specifies the directory where help files are located.

Name: closeCmd

Class: CloseCmd

Command-Line Switch: -closecmd

Specifies the tcl command to be executed when the close option is

selected from the topics menu.

Name: maxHistory

Class: MaxHistory

Command-Line Switch: -maxhistory

Specifies the maximum number of entries stored in the history

list

Name: beforelink

Class: BeforeLink

Command-Line Switch: -beforelink

Specifies a command to be eval'ed before a new link is displayed.

The path of the link to be displayed is appended before evaling

the command. A suggested use might be to busy the widget while a new page is being displayed.

Name: afterlink

Class: AfterLink

Command-Line Switch: -afterlink

Specifies a command to be eval'ed after a new link is completely

displayed. The path of the link that was displayed is appended before evaling the command.
_________________________________________________________________

Description

The iwidgets::hyperhelp command creates a shell window with a

pulldown menu showing a list of topics. The topics are displayed by importing a HTML formatted file named helpdir/topic.html. For a list of supported HTML tags, see scrolledhtml(n) .

Methods

The iwidgets::hyperhelp command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for dialog widgets:

Inherited Methods

activate center childsite deactivate

See the «shell» manual entry for details on the above inherited

methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::hyperhelp command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::hyperhelp command. pathName showtopic topic

Display html file helpdir/topic.html. Topic may optionally be of

the form topicname#anchorname. In this form, either topicname or anchorname or both may be empty. If topicname is empty, the cur- rent topic is assumed. If anchorname is empty, the top of the document is assumed
pathName followlink href

Display html file href. Href may be optionally be of the form

filename#anchorname. In this form, either filename or anchorname or both may be empty. If filename is empty, the current document is assumed. If anchorname is empty, the top of the document is assumed.
pathName forward

Display html file one forward in history list, if applicable.

pathName back

Display html file one back in history list, if applicable.

Example

package require Iwidgets 4.0
iwidgets::hyperhelp .h -topics { Intro Help } -helpdir ~/help .h showtopic Intro

Author

Kris Raney

Keywords

hyperhelp, html, help, shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "scrolledhtml" widget manual entry for details on the
  • Inherited Options
  • See the "shell" manual entry for details on the above inherited
  • Widget-specific Options
  • Name: topics
  • Class: Topics
  • Command-Line Switch: -topics
  • Specifies a list of help topics in the form {?topic? ... }. Topic
  • Name: helpdir
  • Class: Directory
  • Command-Line Switch: -helpdir
  • Specifies the directory where help files are located.
  • Name: closeCmd
  • Class: CloseCmd
  • Command-Line Switch: -closecmd
  • Specifies the tcl command to be executed when the close option is
  • Name: maxHistory
  • Class: MaxHistory
  • Command-Line Switch: -maxhistory
  • Specifies the maximum number of entries stored in the history
  • Name: beforelink
  • Class: BeforeLink
  • Command-Line Switch: -beforelink
  • Specifies a command to be eval'ed before a new link is displayed.
  • The path of the link to be displayed is appended before evaling
  • Name: afterlink
  • Class: AfterLink
  • Command-Line Switch: -afterlink
  • Specifies a command to be eval'ed after a new link is completely
  • Description
  • The iwidgets::hyperhelp command creates a shell window with a
  • Methods
  • The iwidgets::hyperhelp command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for dialog widgets:
  • Inherited Methods
  • See the "shell" manual entry for details on the above inherited
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Display html file helpdir/topic.html. Topic may optionally be of
  • Display html file href. Href may be optionally be of the form
  • Display html file one forward in history list, if applicable.
  • Display html file one back in history list, if applicable.
  • Example
  • Author
  • Kris Raney
  • Keywords


IWidgets labeledframe

 Table of Contents

iwidgets::labeledframe - Create and manipulate a labeled frame widget

Synopsis

iwidgets::labeledframe pathName ?options?

Inheritance

itk::Archetype <- iwidgets::Labeledframe

Standard Options

background
borderwidth cursor
foreground
relief

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: iPadX

Class: IPad

Command-Line Switch: -ipadx

Specifies horizontal padding space between the border and the

childsite. The value may have any of the forms acceptable to

Tk_GetPixels. The default is 0.

Name: iPadY

Class: IPad

Command-Line Switch: -ipady

Specifies vertical padding space between the border and the

childsite. The value may have any of the forms acceptable to

Tk_GetPixels. The default is 0.

Name: labelBitmap

Class: Bitmap

Command-Line Switch: -labelbitmap

Specifies a bitmap to display in the label, in any of the forms

acceptable to Tk_GetBitmap. This option overrides the labeltext option.

Name: labelImage

Class: Image

Command-Line Switch: -labelimage

Specifies a image to be used as the label. The image may be any

of the values created by the image create command. This option overrides both the labelbitmap and labeletext options.

Name: labelMargin

Class: Margin

Command-Line Switch: -labelmargin

Specifies the distance between the inner ede of the hull frames

relief, and the label in any of the forms acceptable to Tk_Get-

Pixels. The default is 10 pixels.

Name: labelText

Class: Text

Command-Line Switch: -labeltext

Specifies the text of the label around the childsite.

Name: labelVariable

Class: Variable

Command-Line Switch: -labelvariable

Specifies the text variable of the label around the childsite.

Name: labelFont

Class: Font

Command-Line Switch: -labelfont

Specifies the font of the label around the childsite.

Name: labelPos

Class: Position

Command-Line Switch: -labelpos

Specifies the position of the label within the grooved relief of

the hull widget.
ne, n, nw, se, s, sw, en, e, es, wn, w, ws Default is n. _________________________________________________________________

Description

The iwidgets::labeledframe command creates a hull frame with a

grooved relief, a label positioned within the grooved relief of the hull frame, and a frame childsite. The frame childsite can filled with any widget via a derived class or though the use of the childsite method. This class was designed to be a general purpose base class for supporting the combination of labeled frame and a childsite. The options include the ability to posi- tion the label at configurable locations within the grooved relief of the hull frame, and control the display of the label.

Methods

The iwidgets::labeledframe command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for labeledframe widgets:

Widget-specific Methods

pathName childsite

Return the path name of the child site.

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::labeledframe command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::labeledframe command.

Components

Name: label

Class: label

The label component provides the label for the labeled widget.

See the «label» widget manual entry for details on the label com-

ponent item.

Example

The labeledframe was primarily meant to be a base class. The

Radiobox is a good example of a derived classe of the labeled-

frame class. In order to provide equal support for composite classes, the `childsite' methods also exists. The following is an example of `childsite' method usage.

package require Iwidgets 4.0
iwidgets::labeledframe .lw -labeltext «Entry Frame» -labelpos n pack .lw -fill both -expand yes -padx 10 -pady 10 set cs [.lw childsite]

pack [iwidgets::entryfield $cs.entry1 -labeltext «Name:"] -side top -fill x pack [iwidgets::spinint $cs.entry2 -labeltext «Number:"] -side top -fill x pack [iwidgets::pushbutton $cs.entry3 -text «Details:"] -side top -fill x

Author

John A. Tucker

Keywords

labeledframe, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: iPadX
  • Class: IPad
  • Command-Line Switch: -ipadx
  • Specifies horizontal padding space between the border and the
  • Tk_GetPixels. The default is 0.
  • Name: iPadY
  • Class: IPad
  • Command-Line Switch: -ipady
  • Specifies vertical padding space between the border and the
  • Tk_GetPixels. The default is 0.
  • Name: labelBitmap
  • Class: Bitmap
  • Command-Line Switch: -labelbitmap
  • Specifies a bitmap to display in the label, in any of the forms
  • Name: labelImage
  • Class: Image
  • Command-Line Switch: -labelimage
  • Specifies a image to be used as the label. The image may be any
  • Name: labelMargin
  • Class: Margin
  • Command-Line Switch: -labelmargin
  • Specifies the distance between the inner ede of the hull frames
  • Pixels. The default is 10 pixels.
  • Name: labelText
  • Class: Text
  • Command-Line Switch: -labeltext
  • Specifies the text of the label around the childsite.
  • Name: labelVariable
  • Class: Variable
  • Command-Line Switch: -labelvariable
  • Specifies the text variable of the label around the childsite.
  • Name: labelFont
  • Class: Font
  • Command-Line Switch: -labelfont
  • Specifies the font of the label around the childsite.
  • Name: labelPos
  • Class: Position
  • Command-Line Switch: -labelpos
  • Specifies the position of the label within the grooved relief of
  • Description
  • The iwidgets::labeledframe command creates a hull frame with a
  • Methods
  • The iwidgets::labeledframe command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for labeledframe widgets:
  • Widget-specific Methods
  • Return the path name of the child site.
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: label
  • Class: label
  • The label component provides the label for the labeled widget.
  • See the "label" widget manual entry for details on the label com-
  • Example
  • The labeledframe was primarily meant to be a base class. The
  • Radiobox is a good example of a derived classe of the labeled-
  • Author
  • John A. Tucker
  • Keywords


IWidgets labeledwidget

 Table of Contents

iwidgets::labeledwidget - Create and manipulate a labeled widget

Synopsis

iwidgets::labeledwidget pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget

Standard Options

background cursor foreground

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: disabledForeground

Class: DisabledForeground

Command-Line Switch: -disabledforeground

Specifies the foreground to be used when the state is disabled.

Name: labelBitmap

Class: Bitmap

Command-Line Switch: -labelbitmap

Specifies a bitmap to display in the widget, in any of the forms

acceptable to Tk_GetBitmap. This option overrides the labeltext option.

Name: labelFont

Class: Font

Command-Line Switch: -labelfont

Specifies the font to be used for the label.

Name: labelImage

Class: Image

Command-Line Switch: -labelimage

Specifies a image to be used as the label. The image may be any

of the values created by the image create command. This option overrides both the labelbitmap and labeletext options.

Name: labelMargin

Class: Margin

Command-Line Switch: -labelmargin

Specifies the distance between the childsite and label in any of

the forms acceptable to Tk_GetPixels. The default is 2 pixel.

Name: labelPos

Class: Position

Command-Line Switch: -labelpos

Specifies the position of the label along the side of the child-

site: nw, n, ne, sw, s, se, en, e, es, wn, w, or ws. The default is w.

Name: labelText

Class: Text

Command-Line Switch: -labeltext

Specifies the text of the label around the childsite.

Name: labelVariable

Class: Variable

Command-Line Switch: -labelvariable

Specifies the text variable of the label around the childsite.

Name: state

Class: State

Command-Line Switch: -state

Specifies one of two states for the label: normal or disabled.

If the label is disabled then it is displayed in a disabled fore-

ground color. The default is normal.

Name: sticky

Class: Sticky

Command-Line Switch: -sticky

Specifies the «sticky-ness» of the childsite. The default value

is nsew, which is the the same behavior of the labeledwidget before this option was added.
_________________________________________________________________

Description

The iwidgets::labeledwidget command creates a labeled widget

which contains a label and child site. The child site is a frame which can filled with any widget via a derived class or though the use of the childsite method. This class was designed to be a general purpose base class for supporting the combination of label widget and a childsite. The options include the ability to position the label around the childsite widget, modify the font and margin, and control the display of the labels.

Methods

The iwidgets::labeledwidget command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for labeledwidget widgets:

Widget-specific Methods

pathName childsite

Return the path name of the child site.

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::labeledwidget command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::labeledwidget command.

Static Methods

iwidgets::Labeledwidget::alignlabels widget ?widget ...?

The alignlabels procedure takes a list of widgets derived from

the Labeledwidget class and uses the label margin to make each widget have the same total space for the combination of label and margin. The net effect is to left align the labels. Generally, this method is only useful with a label position of w, which is the default.

Components

Name: label

Class: label

The label component provides the label for the labeled widget.

See the «label» widget manual entry for details on the label com-

ponent item.

Name: lwchildsite

Class: frame

The lwchildsite component is the user child site for the labeled

widget. See the «frame» widget manual entry for details on the lwchildsite component item.

Example

The labeledwidget was primarily meant to be a base class. The

ScrolledListBox and EntryField are good examples of derived

classes of the labeledwidget class. In order to provide equal support for composite classes, the `childsite' methods also exists. The following is an example of `childsite' method usage.

package require Iwidgets 4.0
iwidgets::labeledwidget .lw -labeltext «Canvas Widget» -labelpos s pack .lw -fill both -expand yes -padx 10 -pady 10

set cw [canvas [.lw childsite].c -relief raised -width 200 -height 200] pack $cw -padx 10 -pady 10

Author

Mark L. Ulferts

Keywords

labeledwidget, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: disabledForeground
  • Class: DisabledForeground
  • Command-Line Switch: -disabledforeground
  • Specifies the foreground to be used when the state is disabled.
  • Name: labelBitmap
  • Class: Bitmap
  • Command-Line Switch: -labelbitmap
  • Specifies a bitmap to display in the widget, in any of the forms
  • Name: labelFont
  • Class: Font
  • Command-Line Switch: -labelfont
  • Specifies the font to be used for the label.
  • Name: labelImage
  • Class: Image
  • Command-Line Switch: -labelimage
  • Specifies a image to be used as the label. The image may be any
  • Name: labelMargin
  • Class: Margin
  • Command-Line Switch: -labelmargin
  • Specifies the distance between the childsite and label in any of
  • Name: labelPos
  • Class: Position
  • Command-Line Switch: -labelpos
  • Specifies the position of the label along the side of the child-
  • Name: labelText
  • Class: Text
  • Command-Line Switch: -labeltext
  • Specifies the text of the label around the childsite.
  • Name: labelVariable
  • Class: Variable
  • Command-Line Switch: -labelvariable
  • Specifies the text variable of the label around the childsite.
  • Name: state
  • Class: State
  • Command-Line Switch: -state
  • Specifies one of two states for the label: normal or disabled.
  • If the label is disabled then it is displayed in a disabled fore-
  • Name: sticky
  • Class: Sticky
  • Command-Line Switch: -sticky
  • Specifies the "sticky-ness" of the childsite. The default value
  • Description
  • The iwidgets::labeledwidget command creates a labeled widget
  • Methods
  • The iwidgets::labeledwidget command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for labeledwidget widgets:
  • Widget-specific Methods
  • Return the path name of the child site.
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Static Methods
  • The alignlabels procedure takes a list of widgets derived from
  • Components
  • Name: label
  • Class: label
  • The label component provides the label for the labeled widget.
  • See the "label" widget manual entry for details on the label com-
  • Name: lwchildsite
  • Class: frame
  • The lwchildsite component is the user child site for the labeled
  • Example
  • The labeledwidget was primarily meant to be a base class. The
  • ScrolledListBox and EntryField are good examples of derived
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets mainwindow

 Table of Contents

iwidgets::mainwindow - Create and manipulate a mainwindow widget

Synopsis

iwidgets::mainwindow pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Shell <- iwidgets::Mainwindow

Standard Options

background cursor disabledForeground font foreground highlightBackground highlightColor highlightThickness

See the «options» manual entry for details on the standard

options.

Associated Options

balloonBackground
balloonDelay1 balloonDelay2ballonFont balloonForeground

See the «toolbar» manual entry for details on the above associ-

ated options.

Inherited Options

title

See the «Toplevel» manual entry for details on the above inher-

ited options.
height master modality padX

padY
width

See the «shell» manual entry for details on the above inherited

options.

Widget-specific Options

Name: helpLine

Class: HelpLine

Command-Line Switch: -helpline

Specifies whether or not to display the help line. The value may

be given in any of the forms acceptable to Tk_GetBoolean. The default is yes.

Name: menuBarBackground

Class: Background

Command-Line Switch: -menubarbackground

Specifies the normal background color for the menubar.

Name: menuBarFont

Class: Font

Command-Line Switch: -menubarfont

Specifies the font to use when drawing text inside the menubar.

Name: menuBarForeround

Class: Foreground

Command-Line Switch: -menubarforeground

Specifies the normal foreground color for the menubar.

Name: statusLine

Class: StatusLine

Command-Line Switch: -statusline

Specifies whether or not to display the status line. The value

may be given in any of the forms acceptable to Tk_GetBoolean.

The default is yes.

Name: toolBarBackground

Class: Background

Command-Line Switch: -toolbarbackground

Specifies the normal background color for the toolbar.

Name: toolBarFont

Class: Font

Command-Line Switch: -toolbarfont

Specifies the font to use when drawing text inside the toolbar.

Name: toolBarForeround

Class: Foreground

Command-Line Switch: -toolbarforeground

Specifies the normal foreground color for the toolbar.

_________________________________________________________________

Description

The iwidgets::mainwindow command creates a mainwindow shell which

contains a menubar, toolbar, mousebar, childsite, status line, and help line. Each item may be filled and configured to suit individual needs.

Methods

The iwidgets::mainwindow command create a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for mainwindow widgets:

Inherited Methods

activate center deactivate

See the «shell» manual entry for details on the above inherited

methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::mainwindow command.
pathName childsite

Returns the pathname of the child site widget.

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::mainwindow command. pathName menubar ?args?

The menubar method provides access to the menubar. Invoked with

no arguments it returns the pathname of the menubar. With argu- ments, they are evaluated against the menubar which in effect provides access to the entire API of the menubar. See the «menubar» manual entry for details on the commands available in the menubar.
pathName mousebar ?args?

The mousebar method provides access to the mousebar which is a

vertical toolbar. Invoked with no arguments it returns the path- name of the mousebar. With arguments, they are evaluated against the mousebar which in effect provides access to the entire API of the underlying toolbar. See the «toolbar» manual entry for details on the commands available in the mousebar. pathName msgd ?args?

The msgd method provides access to the messagedialog contained in

the mainwindow. Invoked with no arguments it returns the path- name of the messagedialog. With arguments, they are evaluated against the messagedialog which in effect provides access to the entire API of the messagedialog. See the «messagedialog» manual entry for details on the commands available in the messagedialog. pathName toolbar ?args?

The toolbar method provides access to the toolbar. Invoked with

no arguments it returns the pathname of the toolbar. With argu- ments, they are evaluated against the toolbar which in effect provides access to the entire API of the toolbar. See the «tool- bar» manual entry for details on the commands available in the toolbar.

Components

Name: help

Class: Label

The help component provides a location for displaying any help

strings provided in the menubar, toolbar, or mousebar. See the «label» widget manual entry for details on the help component item.

Name: menubar

Class: Menubar

The menubar component is the menubar located at the top of the

window. See the «menubar» widget manual entry for details on the menubar component item.

Name: mousebar

Class: Toolbar

The mousebar component is the vertical toolbar located on the

right side of the window. See the «toolbar» widget manual entry for details on the mousebar component item.

Name: msgd

Class: Messagedialog

The msgd component is a messagedialog which may be reconfigured

as needed and used repeatedly throughout the application. See the «messagedialog» widget manual entry for details on the mes- sagedialog component item.

Name: status

Class: Label

The status component provides a location for displaying applica-

tion status information. See the «label» widget manual entry for details on the status component item.

Name: toolbar

Class: Toolbar

The toolbar component is the horizontal toolbar located on the

top of the window. See the «toolbar» widget manual entry for details on the toolbar component item.

Example

package require Iwidgets 4.0
iwidgets::mainwindow .mw

#
# Add a File menubutton
#
.mw menubar add menubutton file -text «File» -underline 0 -padx 8 -pady 2 \ -menu {options -tearoff no
command new -label «New» -underline 0 \ -helpstr «Create a new file" command open -label «Open ...» -underline 0 \ -helpstr «Open an existing file" command save -label «Save» -underline 0 \ -helpstr «Save the current file" command saveas -label «Save As ...» -underline 5 \ -helpstr «Save the file as a differnet name" command print -label «Print» -underline 0 \ -helpstr «Print the file" separator sep1
command close -label «Close» -underline 0 \ -helpstr «Close the file" separator sep2
command exit -label «Exit» -underline 1 \ -helpstr «Exit this application" }

#
# Install a scrolledtext widget in the childsite. #
iwidgets::scrolledtext [.mw childsite].st
pack [.mw childsite].st -fill both -expand yes

#
# Activate the main window.
#
.mw activate

Author

Mark L. Ulferts

John A. Tucker

Keywords

mainwindow, shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "toolbar" manual entry for details on the above associ-
  • Inherited Options
  • See the "Toplevel" manual entry for details on the above inher-
  • See the "shell" manual entry for details on the above inherited
  • Widget-specific Options
  • Name: helpLine
  • Class: HelpLine
  • Command-Line Switch: -helpline
  • Specifies whether or not to display the help line. The value may
  • Name: menuBarBackground
  • Class: Background
  • Command-Line Switch: -menubarbackground
  • Specifies the normal background color for the menubar.
  • Name: menuBarFont
  • Class: Font
  • Command-Line Switch: -menubarfont
  • Specifies the font to use when drawing text inside the menubar.
  • Name: menuBarForeround
  • Class: Foreground
  • Command-Line Switch: -menubarforeground
  • Specifies the normal foreground color for the menubar.
  • Name: statusLine
  • Class: StatusLine
  • Command-Line Switch: -statusline
  • Specifies whether or not to display the status line. The value
  • The default is yes.
  • Name: toolBarBackground
  • Class: Background
  • Command-Line Switch: -toolbarbackground
  • Specifies the normal background color for the toolbar.
  • Name: toolBarFont
  • Class: Font
  • Command-Line Switch: -toolbarfont
  • Specifies the font to use when drawing text inside the toolbar.
  • Name: toolBarForeround
  • Class: Foreground
  • Command-Line Switch: -toolbarforeground
  • Specifies the normal foreground color for the toolbar.
  • Description
  • The iwidgets::mainwindow command creates a mainwindow shell which
  • Methods
  • The iwidgets::mainwindow command create a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for mainwindow widgets:
  • Inherited Methods
  • See the "shell" manual entry for details on the above inherited
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Returns the pathname of the child site widget.
  • Query or modify the configuration options of the widget. If no
  • The menubar method provides access to the menubar. Invoked with
  • The mousebar method provides access to the mousebar which is a
  • The msgd method provides access to the messagedialog contained in
  • The toolbar method provides access to the toolbar. Invoked with
  • Components
  • Name: help
  • Class: Label
  • The help component provides a location for displaying any help
  • Name: menubar
  • Class: Menubar
  • The menubar component is the menubar located at the top of the
  • Name: mousebar
  • Class: Toolbar
  • The mousebar component is the vertical toolbar located on the
  • Name: msgd
  • Class: Messagedialog
  • The msgd component is a messagedialog which may be reconfigured
  • Name: status
  • Class: Label
  • The status component provides a location for displaying applica-
  • Name: toolbar
  • Class: Toolbar
  • The toolbar component is the horizontal toolbar located on the
  • Example
  • Author
  • Mark L. Ulferts
  • John A. Tucker
  • Keywords


IWidgets menubar

 Table of Contents

iwidgets::menubar - Create and manipulate menubar menu widgets

Synopsis

iwidgets::menubar pathName ?options?

Inheritance

itk::Widget <- iwidgets::Menubar

Standard Options

activeBackground activeBorderWidth activeForeground

anchor
background borderWidth
cursor
disabledForeground font
foreground
highlightBackground hightlightColor highligthThickness justify relief padX padY wrapLength

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: helpVariable

Class: HelpVariable

Command-Line Switch: -helpvariable

Specifies the global variable to update whenever the mouse is in

motion over a menu entry. This global variable is updated with the current value of the active menu entry's helpStr. Other wid- gets can «watch» this variable with the trace command, or as is the case with entry or label widgets, they can set their textVariable to the same global variable. This allows for a sim- ple implementation of a help status bar. Whenever the mouse leaves a menu entry, the helpVariable is set to the empty string {}. The mainwindow(1) associates its helpstatus and its menubar in this fashion.

Name: menuButtons

Class: MenuButtons

Command-Line Switch: -menubuttons

The menuButton option is a string which specifies the arrangement

of menubuttons on the menubar frame. Each menubutton entry is delimited by the newline character.
iwidgets::menubar .mb -menubuttons {
menubutton file -text File
menubutton edit -text Edit
menubutton options -text Options
}
specifies that three menubuttons will be added to the menubar (file, edit, options). Each entry is translated into an add com- mand call.

The menuButtons option can accept embedded variables, commands,

and backslash quoting. Embedded variables and commands must be enclosed in curly braces ({}) to ensure proper parsing of the substituted values.
_________________________________________________________________

Description

The iwidgets::menubar command creates a new window (given by the

pathName argument) and makes it into a menubar menu widget. Addi- tional options, described above may be specified on the command line or in the option database to configure aspects of the menubar such as its colors and font. The iwidgets::menubar com- mand returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but path-

Name's parent must exist.

A menubar is a widget that simplifies the task of creating menu

hierarchies. It encapsulates a frame widget, as well as menubut- tons, menus, and menu entries. The menubar allows menus to be specified and referenced in a more consistent manner than using

Tk to build menus directly.

list of menubuttons to be added to the menubar. In turn, each menubutton accepts a menu option that specifies a list of menu entries to be added to the menubutton's menu. Cascade entries also accept the menu option for specifying a list of menu entries to be added to the cascade's menu.

Additionally, the menubar allows each component of the menubar

system to be referenced by a simple menuPathName syntax. The menubar also extends the set of options for menu entries to include a helpStr option.

Menu Path Names

A menuPathName is a series of component names separated by the

`.' character. Each menubar component can be referenced via these menuPathNames. menuPathNames are similar to widget pathNames in

Tk. Some correspond directly to a widget pathName (components of

type menu or menubutton), others correspond to a menu entry type.

Every widget and entry in a menubar can be referenced with the

menuPathName naming convention. A menubar can have four types of components:
frame. A menubar holds exactly one frame which manages menubut- tons. The frame is always signified by the `.' character as the path name.
menubutton. A menubutton corresponds directly to a Tk menubutton.

See menubutton(n) .

menu. A menu is attached to a menubutton and corresponds directly to Tk's menu widget. A menu is always signified by the menuPath-

Name ending with the keyword menu. See menu(n) .

entry. An entry corresponds directly to Tk's menu widget entries.

Menus consist of a column of one line entries. Entries may be of

type: command, checkbutton, radiobutton, separator, or cascade.

For a complete description of these types see the discussion on

ENTRIES in menu(n) .

The suffix of a menuPathName may have the form of:

tkWidgetName Specifies the name of the component, either a frame, menubutton, menu, or an entry. This is the normal naming of widgets. For example, .file references a menubutton named file.

The menuPathName is a series of segment names, each separated by

the `.' character. Segment names may be one of the following forms:

number
Specifies the index of the the component. For menubuttons, 0 corresponds to the left-most menubutton of the menu bar frame. As an example, .1 would correspond to the second menubutton on the menu bar frame. For entries, 0 corresponds to the top-most entry of the menu. For example, .file.0 would correspond to the first entry on the menu attached to the menubutton named file.
end
Specifes the last component. For menubuttons, it specifies the right-most entry of the menu bar frame. For menu entries, it specifies the bottommost entry of the menu.
last
Same as end.

Finally, menu components always end with the menu keyword. These

components are automatically created via the -menu option on menubuttons and cascades or via the add or insert commands.

menu
Specifes the menu pane that is associated with the given menubutton prefix. For example, .file.menu specifies the menu pane attached to the .file menubutton.

For example, the path .file.new specifies the entry named new on

the menu associated with the file menubutton located on the menu bar. The path .file.menu specifies the menu pane associated with the menubutton .file. The path .last specifies the last menu on the menu bar. The path .0.last would specify the first menu (file) and the last entry on that menu (quit), yielding .file.quit.

As a restriction, the last name segment of menuPathName cannot be

one of the keywords last, menu, end, nor may it be a numeric value (integer).

Widget-specific Methods

The iwidgets::menubar command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

option and the args determine the exact behavior of the command.

In addition, many of the widget commands for menubar take as one

argument a path name to a menu component. These path names are called menuPathNames. See the discussion on MENUBAR PATH NAMES above.

The following commands are possible for menubar widgets:

pathName add type menuPathName ?option value option value?

Adds either a menu to the menu bar or a menu entry to a menu

pane.

If additional arguments are present, they specify options avail-

able to component type entry. See the man pages for menu(1) in the section on ENTRIES.

If type is one of cascade, checkbutton, command, radiobutton, or

separator it adds a new entry to the bottom of the menu denoted by the prefix of menuPathName. If additonal arguments are pre- sent, they specify options available to menu entry widgets. In addition, the helpStr option is added by the menubar widget to all components of type entry.
-helpstr value

Specifes the string to associate with the entry. When the mouse

moves over the associated entry, the variable denoted by help-

Variable is set. Another widget can bind to the helpVariable and

thus display status help.

If the type of the component added is menubutton or cascade, a

menubutton or cascade is added to the menubar. If additional arguments are present, they specify options available to menubut- ton or cascade widgets. In addition, the menu option is added by the menubar widget to all menubutton and cascade widgets. -menu menuSpec

This is only valid for menuPathNames of type menubutton or cas-

cade. Specifes an option set and/or a set of entries to place on a menu and associate with the menubutton or cascade. The option keyword allows the menu widget to be configured. Each item in the menuSpec is treated as add commands (each with the possibility of having other -menu options). In this way a menu can be recur- sively built.

The last segment of menuPathName cannot be one of the keywords

last, menu, end. Additionally, it may not be a number. However the menuPathName may be referenced in this manner (see discussion of COMPONENT PATH NAMES).

Note that the same curly brace quoting rules apply to -menu

option strings as did to -menubuttons option strings. See the earlier discussion on umenubuttons in the «WIDGET-SPECIFIC

OPTIONS» section.

pathName cget option

Returns the current value of the configuration option given by

option.
pathName configure ?options value option value?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string.
pathName delete menuPathName ?menuPathName2?

If menuPathName is of component type Menubutton or Menu, delete

operates on menus. If menuPathName is of component type Entry, delete operates on menu entries.

This command deletes all components between menuPathName and

menuPathName2 inclusive. If menuPathName2 is omitted then it defaults to menuPathName. Returns an empty string.

If menuPathName is of type menubar, then all menus and the menu

bar frame will be destroyed. In this case menuPathName2 is ignored.
pathName index menuPathName

If menuPathName is of type menubutton or menu, it returns the

position of the menu/menubutton on the menubar frame.

If menuPathName is of type command, separator, radiobutton,

checkbutton, or cascade, it returns the menu widget's numerical index for the entry corresponding to menuPathName. If path is not found or the path is equal to «.", a value of -1 is returned. pathName insert menuPathName type name ?option value?

Insert a new component named name before the component specified

by menuPathName.

If menuPathName is of type Menubutton or Menu, the new component

inserted is of type Menu and given the name name. In this case valid option value pairs are those accepted by menubuttons.

If menuPathName is of type Entry, the new component inserted is

of type entry and given the name name. In this case, valid option value pairs are those accepted by menu entries. Name cannot be one of the keywords last, menu, end. Additionally, it may not be a number. However the menuPathName may be referenced in this man- ner (see discussion of COMPONENT PATH NAMES). pathName invoke menuPathName

Invoke the action of the menu entry denoted by menuPathName. See

the sections on the individual entries in the menu(1) man pages.

If the menu entry is disabled then nothing happens. If the entry

has a command associated with it then the result of that command is returned as the result of the invoke widget command. Otherwise the result is an empty string.

If menuPathName is not a menu entry, an error is issued.

pathName menucget menuPathName option

Returns the current value of the configuration option given by

option. The component type of menuPathName determines the valid available options.
pathName menuconfigure menuPathName ?option value?

Query or modify the configuration options of the componet of the

menubar specified by menuPathName. If no option is specified, returns a list describing all of the available options for menu-

PathName (see Tk_ConfigureInfo for information on the format of

this list). If option is specified with no value, then the com- mand returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. The component type of menuPathName determines the valid available options.
pathName path ?mode? pattern

Returns a fully formed menuPathName that matches pattern. If no

match is found it returns -1. The mode argument indicates how the search is to be matched against pattern and it must have one of the following values:
-glob

Pattern is a glob-style pattern which is matched against each

component path using the same rules as the string match command. -regexp

Pattern is treated as a regular expression and matched against

each component of the menuPathName using the same rules as the regexp command. The default mode is -glob.
pathName type menuPathName

Returns the type of the component specified by menuPathName. For

menu entries, this is the type argument passed to the add/insert widget command when the entry was created, such as command or separator. Othewise it is either a menubutton or a menu. pathName yposition menuPathName

Returns a decimal string giving the y-coordinate within the menu

window of the topmost pixel in the entry specified by menuPath-

Name. If the menuPathName is not an entry, an error is issued.

Example One: Using Grammar

The following example creates a menubar with «File", «Edit",

«Options» menubuttons. Each of these menubuttons has an associ- ated menu. In turn the File menu has menu entries, as well as the Edit menu and the Options menu. The Options menu is a tearoff menu with selectColor (for radiobuttons) set to blue. In addi- tion, the Options menu has a cascade titled More, with several menu entries attached to it as well. An entry widget is provided to display help status.

package require Iwidgets 4.0
iwidgets::menubar .mb -helpvariable helpVar -menubuttons { menubutton file -text File -menu {
options -tearoff false
command new -label New \
-helpstr «Open new document» \
-command {puts NEW}
command close -label Close \
-helpstr «Close current document» \ -command {puts CLOSE}
separator sep1
command exit -label Exit -command {exit} \ -helpstr «Exit application"
}
menubutton edit -text Edit -menu {
options -tearoff false
command undo -label Undo -underline 0 \ -helpstr «Undo last command» \
-command {puts UNDO}
separator sep2
command cut -label Cut -underline 1 \ -helpstr «Cut selection to clipboard» \ -command {puts CUT}
command copy -label Copy -underline 1 \ -helpstr «Copy selection to clipboard» \ -command {puts COPY}
command paste -label Paste -underline 0 \ -helpstr «Paste clipboard contents» \ -command {puts PASTE}
}
menubutton options -text Options -menu {
options -tearoff false -selectcolor blue radiobutton byName -variable viewMode \ -value NAME -label «by Name» \
-helpstr «View files by name order» \ -command {puts NAME}
radiobutton byDate -variable viewMode \ -value DATE -label «by Date» \
-helpstr «View files by date order» \ -command {puts DATE}
cascade prefs -label Preferences -menu { command colors -label Colors... \
-helpstr «Change text colors» \ -command {puts COLORS}
command fonts -label Fonts... \
-helpstr «Change text font» \
-command {puts FONT}
}
}

}
frame .fr -width 300 -height 300
entry .ef -textvariable helpVar
pack .mb -anchor nw -fill x -expand yes
pack .fr -fill both -expand yes
pack .ef -anchor sw -fill x -expand yes

Example Two: Using Methods

Alternatively the same menu could be created by using the add and

configure methods:

package require Iwidgets 4.0
iwidgets::menubar .mb
.mb configure -menubuttons {
menubutton file -text File -menu {
command new -label New
command close -label Close
separator sep1

command
quit -label Quit } menubutton edit -text Edit } .mb add command .edit.undo -label Undo -underline 0 .mb add separator .edit.sep2 .mb add command .edit.cut -label Cut -underline 1 .mb add command .edit.copy -label Copy -underline 1 .mb add command .edit.paste -label Paste -underline 0

.mb add menubutton .options -text Options -menu { radiobutton byName -variable viewMode \ -value NAME -label «by Name"
radiobutton byDate -variable viewMode \ -value DATE -label «by Date"
}

.mb add cascade .options.prefs -label Preferences -menu { command colors -label Colors... command fonts -label Fonts...
}
pack .mb -side left -anchor nw -fill x -expand yes

Caveats

The -menubuttons option as well as the -menu option is evaluated

by menubar with the subst command. The positive side of this is that the option string may contain variables, commands, and/or backslash substitutions. However, substitutions might expand into more than a single word. These expansions can be protected by enclosing candidate substitutions in curly braces ({}). This ensures, for example, a value for an option will still be treated as a single value and not multiple values. The following example illustrates this case:
set fileMenuName «File Menu"
set var {}
iwidgets::menubar .mb -menubuttons {
menubutton file -text {$fileMenuName}
menubutton edit -text Edit -menu {
checkbutton check \
-label Check \
-variable {[scope var]} \ -onvalue 1 \
-offvalue 0
}
menubutton options -text Options
}

The variable fileMenuName will expand to «File Menu» when the

subst command is used on the menubutton specification. In addi- tion, the [scope...] command will expand to @scope :: var. By enclosing these inside {} they stay as a single value. Note that only {} work for this. [list...], «» etc. will not protect these from the subst command.

Acknowledgments

Bret Schumaker

1994 - Early work on a menubar widget.

Mark Ulferts, Mark Harrison, John Sigler

Invaluable feedback on grammar and usability of the menubar wid-

get

Author

Bill W. Scott

Keywords

frame, menu, menubutton, entries, help

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: helpVariable
  • Class: HelpVariable
  • Command-Line Switch: -helpvariable
  • Specifies the global variable to update whenever the mouse is in
  • Name: menuButtons
  • Class: MenuButtons
  • Command-Line Switch: -menubuttons
  • The menuButton option is a string which specifies the arrangement
  • The menuButtons option can accept embedded variables, commands,
  • Description
  • The iwidgets::menubar command creates a new window (given by the
  • Name's parent must exist.
  • A menubar is a widget that simplifies the task of creating menu
  • Tk to build menus directly.
  • Additionally, the menubar allows each component of the menubar
  • Menu Path Names
  • A menuPathName is a series of component names separated by the
  • Tk. Some correspond directly to a widget pathName (components of
  • Every widget and entry in a menubar can be referenced with the
  • See menubutton(n).
  • Name ending with the keyword menu. See menu(n).
  • Menus consist of a column of one line entries. Entries may be of
  • For a complete description of these types see the discussion on
  • ENTRIES in menu(n).
  • The suffix of a menuPathName may have the form of:
  • The menuPathName is a series of segment names, each separated by
  • Finally, menu components always end with the menu keyword. These
  • For example, the path .file.new specifies the entry named new on
  • As a restriction, the last name segment of menuPathName cannot be
  • Widget-specific Methods
  • The iwidgets::menubar command creates a new Tcl command whose
  • In addition, many of the widget commands for menubar take as one
  • The following commands are possible for menubar widgets:
  • Adds either a menu to the menu bar or a menu entry to a menu
  • If additional arguments are present, they specify options avail-
  • If type is one of cascade, checkbutton, command, radiobutton, or
  • Specifes the string to associate with the entry. When the mouse
  • Variable is set. Another widget can bind to the helpVariable and
  • If the type of the component added is menubutton or cascade, a
  • This is only valid for menuPathNames of type menubutton or cas-
  • The last segment of menuPathName cannot be one of the keywords
  • Note that the same curly brace quoting rules apply to -menu
  • OPTIONS" section.
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • If menuPathName is of component type Menubutton or Menu, delete
  • This command deletes all components between menuPathName and
  • If menuPathName is of type menubar, then all menus and the menu
  • If menuPathName is of type menubutton or menu, it returns the
  • If menuPathName is of type command, separator, radiobutton,
  • Insert a new component named name before the component specified
  • If menuPathName is of type Menubutton or Menu, the new component
  • If menuPathName is of type Entry, the new component inserted is
  • Invoke the action of the menu entry denoted by menuPathName. See
  • If the menu entry is disabled then nothing happens. If the entry
  • If menuPathName is not a menu entry, an error is issued.
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the componet of the
  • PathName (see Tk_ConfigureInfo for information on the format of
  • Returns a fully formed menuPathName that matches pattern. If no
  • Pattern is a glob-style pattern which is matched against each
  • Pattern is treated as a regular expression and matched against
  • Returns the type of the component specified by menuPathName. For
  • Returns a decimal string giving the y-coordinate within the menu
  • Name. If the menuPathName is not an entry, an error is issued.
  • Example One: Using Grammar
  • The following example creates a menubar with "File", "Edit",
  • Example Two: Using Methods
  • Alternatively the same menu could be created by using the add and
  • Caveats
  • The -menubuttons option as well as the -menu option is evaluated
  • The variable fileMenuName will expand to "File Menu" when the
  • Acknowledgments
  • Bret Schumaker
  • Mark Ulferts, Mark Harrison, John Sigler
  • Invaluable feedback on grammar and usability of the menubar wid-
  • Author
  • Bill W. Scott
  • Keywords


IWidgets messagebox

 Table of Contents

iwidgets::messagebox - Create and manipulate a messagebox text widget

Synopsis

iwidgets::messagebox pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Scrolledwid- get <- iwidgets::Messagebox

Standard Options

activeBackground activeForeground background borderWidth

cursor
exportSelection font foreground highlightColor highlightThickness padX padY
relief
setGrid

See the «options» manual entry for details on the standard

options.

Associated Options

labelBitmap labelFont labelImage labelMargin

labelPos
labelText labelVariable

See the «labeledwidget» class manual entry for details on the

above associated options.
activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget manual entry for details on the above

associated options.

height
hscrollMode sbWidth scrollMargin textBackground visibleItems vscrollMode width

See the «scrolledtext» widget manual entry for details on the

above associated options.
spacing1 spacing2 spacing3

See the «text» widget manual entry for details on the above asso-

ciated options.

Widget-specific Options

Name: fileName

Class: FileName

Command-Line Switch: -filename

Specifies the filename to be displayed in the file selection dia-

log when it pops up during a save of the messagebox contents operation.

Name: maxLines

Class: MaxLines

Command-Line Switch: -maxlines

Specifies the maximum number of lines allowed in the text area of

the messagebox. When this limit is reached, the oldest line will be deleted such that the total number of lines remains maxlines.

Name: saveDir

Class: SaveDir

Command-Line Switch: -savedir

Specifies the default directory to display when the file selec-

tion dialog pops up during a save of the messagebox contents operation. If this parameter is not specified, then the files in the current working directory are displayed.
_________________________________________________________________

Description

The iwidgets::messagebox command creates a scrolled information

messages area widget. Message types can be user defined and con- figured. Their options include foreground, background, font, bell, and their display mode of on or off. This allows message types to defined as needed, removed when no longer so, and modi- fied when necessary. An export method is provided for file I/O. removed. A popup menu which appears when the right mouse button has been pressed in the message area has been predefined. The contents of the popup menu by default support clearing the area and saving its contents to a file. Additional operations may be defined or existing operations removed by using the component command to access the popup menu.

Message Types

The display characteristics of messages issued to the messagebox

vary with the message type. Types are defined by the user and they may be added, removed, and configured. The options of the message type control the display include the following: -background color

Color specifies the background color to use for characters asso-

ciated with the message type. It may have any of the forms accepted by Tk_GetColor.
-bell boolean

Specifies whether or not to ring the bell whenenver a message of

this type is issued. Boolean may have any of the forms accepted by Tk_GetBoolean. The default is 0.
-font fontName

FontName is the name of a font to use for drawing characters. It

may have any of the forms accepted by Tk_GetFontStruct. -foreground color

Color specifies the foreground color to use for characters asso-

ciated with the message type. It may have any of the forms accepted by Tk_GetColor.
-show boolean

Specifies whether of not to display this message type when

issued. Boolean may have any of the forms accepted by Tk_Get-

Boolean. The default is 1.

Methods

The iwidgets::messagebox command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for messagebox widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::messagebox command.
pathName clear

Clear the messagebox of all messages.

pathName export filename

Write text to a file. If filename exists then contents are

replaced with text widget contents.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::messagebox command. pathName type option msgtype ?arg arg ...?

This command is used to manipulate message types. The behav-

ior of the command depends on the option argument that follows the type keyword. The following forms of the command are supported:

pathName type add msgtype ?option value ...?

Adds a new message type given by msgtype with the display proper-

ties defined by the option value pairs. See MESSAGE TYPES for information on the options that are supported. pathName type cget msgtype option

Returns the value of a configuration option for a message type.

Msgtype identifies the message type, and option specifies a par-

ticular configuration option, which must be one of the ones listed in the section MESSAGE TYPES.
pathName type configure msgtype ?option value ...?

Query or modify the configuration options for a message type. If

no option is specified, returns a list describing all of the available options for the message type msgtype. If option is specified with no value, then the command returns a list describ- ing the one named option. If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. See MESSAGE TYPES for information on the options that are supported. pathName type remove msgtype Removes an existing message type given by msgtype.
pathName issue string ?level? ?tags?

Print a string to the text area at the given level and with any

additional tags specified.

Components

Name: itemMenu

Class: Menu

This is the popup menu that gets displayed when you right-click

in the text area of the messagebox. Its contents may be modified via the component command.

Name: text

Class: Scrolledtext

The text component is the scrolledtext widget. See the

«scrolledtext» widget manual entry for details on the text compo- nent item.

Example

package require Iwidgets 4.0
iwidgets::messagebox .mb -hscrollmode dynamic \ -labeltext «Messages» -labelpos n \
-height 120 -width 550 -savedir «/tmp» -textbackground #d9d9d9

pack .mb -padx 5 -pady 5 -fill both -expand yes

.mb type add ERROR -background red -foreground white -bell 1 .mb type add WARNING -background yellow -foreground black .mb type add INFO -background white -foreground black

.mb issue «This is an error message in red with a beep» ERROR .mb issue «This warning message in yellow» WARNING .mb issue «This is an informational message» INFO

Author

Alfredo Jahn V

Mark L. Ulferts

Keywords

messagebox, scrolledtext, text, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "labeledwidget" class manual entry for details on the
  • See the "scrollbar" widget manual entry for details on the above
  • See the "scrolledtext" widget manual entry for details on the
  • See the "text" widget manual entry for details on the above asso-
  • Widget-specific Options
  • Name: fileName
  • Class: FileName
  • Command-Line Switch: -filename
  • Specifies the filename to be displayed in the file selection dia-
  • Name: maxLines
  • Class: MaxLines
  • Command-Line Switch: -maxlines
  • Specifies the maximum number of lines allowed in the text area of
  • Name: saveDir
  • Class: SaveDir
  • Command-Line Switch: -savedir
  • Specifies the default directory to display when the file selec-
  • Description
  • The iwidgets::messagebox command creates a scrolled information
  • Message Types
  • The display characteristics of messages issued to the messagebox
  • Color specifies the background color to use for characters asso-
  • Specifies whether or not to ring the bell whenenver a message of
  • FontName is the name of a font to use for drawing characters. It
  • Color specifies the foreground color to use for characters asso-
  • Specifies whether of not to display this message type when
  • Boolean. The default is 1.
  • Methods
  • The iwidgets::messagebox command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for messagebox widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Clear the messagebox of all messages.
  • Write text to a file. If filename exists then contents are
  • Query or modify the configuration options of the widget. If no
  • This command is used to manipulate message types. The behav-
  • Adds a new message type given by msgtype with the display proper-
  • Returns the value of a configuration option for a message type.
  • Msgtype identifies the message type, and option specifies a par-
  • Query or modify the configuration options for a message type. If
  • Print a string to the text area at the given level and with any
  • Components
  • Name: itemMenu
  • Class: Menu
  • This is the popup menu that gets displayed when you right-click
  • Name: text
  • Class: Scrolledtext
  • The text component is the scrolledtext widget. See the
  • Example
  • Author
  • Alfredo Jahn V
  • Mark L. Ulferts
  • Keywords


IWidgets messagedialog

 Table of Contents

iwidgets::messagedialog - Create and manipulate a message dialog widget

Synopsis

iwidgets::messagedialog pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Shell <- iwidgets::Dialogshell <- iwidgets::Dialog <- iwidgets::Messagedialog

Standard Options

background bitmap cursor font foreground image text

See the «options» manual entry for details on the standard

options.

Inherited Options

buttonBoxPadX buttonBoxPadY buttonBoxPos padX

padY
separator thickness

See the «dialogshell» widget manual entry for details on the

above inherited options.

master
modality

See the «shell» widget manual entry for details on the above

inherited options.
title

See the «Toplevel» widget manual entry for details on the above

inherited options.

Widget-specific Options

Name: imagePos

Class: Position

Command-Line Switch: -imagepos

Specifies the image position relative to the message text: n, s,

e, or w. The default is w.

Name: textPadX

Class: Pad

Command-Line Switch: -textpadx

Specifies a non-negative value indicating how much extra space to

request for the message text in the X direction. The value may have any of the forms acceptable to Tk_GetPixels.

Name: textPadY

Class: Pad

Command-Line Switch: -textpady

Specifies a non-negative value indicating how much extra space to

request for the message text in the X direction. The value may have any of the forms acceptable to Tk_GetPixels. _________________________________________________________________

Description

The iwidgets::messagedialog command creates a message dialog com-

posite widget. The messagedialog is derived from the Dialog class and is composed of an image and associated message text with commands to manipulate the dialog buttons.

Methods

The iwidgets::messagedialog command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for messagedialog widgets:

Inherited Methods

add buttonconfigure defaulthide insert invoke show

See the «buttonbox» widget manual entry for details on the above

inherited methods.
childsite

See the «dialogshell» widget manual entry for details on the

above inherited methods.
activate center deactivate

See the «dialogshell» widget manual entry for details on the

above inherited methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::messagedialog command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::messagedialog command.

Components

Name: image

Class: Label

The image component is the bitmap or image of the message dialog.

See the «label» widget manual entry for details on the image com-

ponent item.

Name: message

Class: Label

The message component provides the textual portion of the message

dialog. See the «label» widget manual entry for details on the message component item.

Example

package require Iwidgets 4.0
#
# Standard question message dialog used for confirmation. #
iwidgets::messagedialog .md -title «Message Dialog» -text «Are you sure ?» \ -bitmap questhead -modality global

.md buttonconfigure OK -text Yes
.md buttonconfigure Cancel -text No

if {[.md activate]} {
.md configure -text «Are you really sure ?" if {[.md activate]} {
puts stdout «Yes"
} else {
puts stdout «No"
}
} else {
puts stdout «No"
}

destroy .md

#
# Copyright notice with automatic deactivation. #
iwidgets::messagedialog .cr -title «Copyright» -bitmap @dsc.xbm -imagepos n \ -text «Copyright 1995 DSC Communications Corporation\n \ All rights reserved"

.cr hide Cancel

.cr activate
after 10000 «.cr deactivate"

Author

Mark L. Ulferts

Keywords

messagedialog, dialog, dialogshell, shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "dialogshell" widget manual entry for details on the
  • See the "shell" widget manual entry for details on the above
  • See the "Toplevel" widget manual entry for details on the above
  • Widget-specific Options
  • Name: imagePos
  • Class: Position
  • Command-Line Switch: -imagepos
  • Specifies the image position relative to the message text: n, s,
  • Name: textPadX
  • Class: Pad
  • Command-Line Switch: -textpadx
  • Specifies a non-negative value indicating how much extra space to
  • Name: textPadY
  • Class: Pad
  • Command-Line Switch: -textpady
  • Specifies a non-negative value indicating how much extra space to
  • Description
  • The iwidgets::messagedialog command creates a message dialog com-
  • Methods
  • The iwidgets::messagedialog command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for messagedialog widgets:
  • Inherited Methods
  • See the "buttonbox" widget manual entry for details on the above
  • See the "dialogshell" widget manual entry for details on the
  • See the "dialogshell" widget manual entry for details on the
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: image
  • Class: Label
  • The image component is the bitmap or image of the message dialog.
  • See the "label" widget manual entry for details on the image com-
  • Name: message
  • Class: Label
  • The message component provides the textual portion of the message
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets notebook

 Table of Contents

iwidgets::notebook - create and manipulate notebook widgets

Synopsis

iwidgets::notebook pathName ?options?

Inheritance

itk::Widget <- iwidgets::Notebook

Standard Options

background
foreground scrollCommand width
cursor
height

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: auto

Class: Auto

Command-Line Switch: -auto

Specifies whether to use the automatic packing/unpacking algo-

rithm of the notebook. A value of true indicates that page frames will be unpacked and packed acoording to the algorithm described in the select command. A value of false leaves the current page packed and subsequent selects, next, or previous commands do not switch pages automatically. In either case the page's associated command (see the add command's description of the command option) is invoked. The value may have any of the forms accepted by the

Tcl_GetBoolean, such as true, false, 0, 1, yes, or no.

For example, if a series of pages in a notebook simply change

certain display configurations of a graphical display, the -auto flag could be used. By setting it, the -command procs could do the appropriate reconfiguring of the page when the page is switched.
_________________________________________________________________

Description

The iwidgets::notebook command creates a new window (given by the

pathName argument) and makes it into a notebook widget. Addi- tional options, described above may be specified on the command line or in the option database to configure aspects of the note- book such as its colors, font, and text. The iwidgets::notebook command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A notebook is a widget that contains a set of pages. It displays

one page from the set as the selected page. When a page is selected, the page's contents are displayed in the page area.

When first created a notebook has no pages. Pages may be added or

deleted using widget commands described below.

Notebook Pages

A notebook's pages area contains a single child site frame. When

a new page is created it is a child of this frame. The page's child site frame serves as a geometry container for applications to pack widgets into. It is this frame that is automatically unpacked or packed when the auto option is true. This creates the effect of one page being visible at a time. When a new page is selected, the previously selected page's child site frame is automatically unpacked from the notebook's child site frame and the newly selected page's child site is packed into the note- book's child site frame.

However, sometimes it is desirable to handle page changes in a

different manner. By specifying the auto option as false, child site packing can be disabled and done differently. For example, all widgets might be packed into the first page's child site frame. Then when a new page is selected, the application can reconfigure the widgets and give the appearance that the page was flipped.

In both cases the command option for a page specifies a Tcl Com-

mand to execute when the page is selected. In the case of auto being true, it is called between the unpacking of the previously selected page and the packing of the newly selected page.

Widget-specific Methods

The iwidgets::notebookfR command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

option and the args determine the exact behavior of the command.

Many of the widget commands for a notebook take as one argument

an indicator of which page of the notebook to operate on. These indicators are called indexes and may be specified in any of the following forms:
number

Specifies the index of the the component. For menus, 0 corre-

sponds to the left-most menu of the menu bar. For entries, 0 cor- responds to the top-most entry of the menu. number Specifies the page numerically, where 0 corresponds to the first page in the notebook, 1 to the second, and so on.
select

Specifies the currently selected page's index. If no page is cur-

rently selected, the value -1 is returned.
end

Specifes the last page in the notebooks's index. If the notebook

is empty this will return -1.
pattern

If the index doesn't satisfy the form of a number, then this form

is used. Pattern is pattern-matched against the label of each page in the notebook, in order from the first to the last page, until a matching entry is found. The rules of Tcl_StringMatch are used.

The following commands are possible for notebook widgets:

pathName add ?option value?

Add a new page at the end of the notebook. A new child site frame

is created. Returns the child site pathName. If additional argu- ments are present, they specify any of the following options: -background value

Specifies a background color to use for displaying the child site

frame of this page. If this option is specified as an empty string (the default), then the background option for the overall notebook is used.
-command value

Specifies a Tcl command to be executed when this page is

selected. This allows the programmer a hook to reconfigure this page's widgets or any other page's widgets.

If the notebook has the auto option set to true, when a page is

selected this command will be called immediately after the previ- ously selected page is unpacked and immediately before this page is selected. The index value select is valid during this Tcl com- mand. `index select' will return this page's page number.

If the auto option is set to false, when a page is selected the

unpack and pack calls are bypassed. This Tcl command is still called.
-foreground value

Specifies a foreground color to use for displaying tab labels

when tabs are in their normal unselected state. If this option is specified as an empty string (the default), then the foreground option for the overall notebook is used.
-label value

Specifies a string to associate with this page. This label serves

as an additional identifier used to reference the page. This label may be used for the index value in widget commands. pathName childSite ?index?

If passed no arguments, returns a list of pathNames for all the

pages in the notebook. If the notebook is empty, an empty list is returned

If index is passed, it returns the pathName for the page's child

site frame specified by index. Widgets that are created with this pathName will be displayed when the associated page is selected.

If index is not a valid index, an empty string is returned.

pathName cget option

Returns the current value of the configuration option given by

option.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::notebook command. pathName delete index1 ?index2?

Delete all of the pages between index1 and index2 inclusive. If

index2 is omitted then it defaults to index1. Returns an empty string.
pathName index index

Returns the numerical index corresponding to index.

pathName insert index ?option value?

Insert a new page in the notebook before the page specified by

index. A new child site frame is created. See the add command for valid options. Returns the child site pathName. pathName next

Advances the selected page to the next page (order is determined

by insertion order). If the currently selected page is the last page in the notebook, the selection wraps around to the first page in the notebook.

For notebooks with auto set to true the current page's child site

is unpacked from the notebook's child site frame. Then the next page's child site is packed into the notebooks child site frame.

The Tcl command given with the command option will be invoked

between these two operations.

For notebooks with auto set to false the Tcl command given with

the command option will be invoked.
pathName pagecget index ?option?

Returns the current value of the configuration option given by

option for the page specified by index. The valid available options are the same as available to the add command. pathName pageconfigure index ?option? ?value option value ...?

This command is similar to the configure command, except that it

applies to the options for an individual page, whereas configure applies to the options for the notebook. Options may have any of the values accepted by the add widget command. If options are specified, options are modified as indicated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for page index (see

Tk_ConfigureInfo for information on the format of this list).

pathName prev

Moves the selected page to the previous page (order is determined

by insertion order). If the currently selected page is the first page in the notebook, the selection wraps around to the last page in the notebook.

For notebooks with auto set to true the current page's child site

is unpacked from the notebook's child site frame. Then the previous page's child site is packed into the notebooks child site frame. The Tcl command given with the command option will be invoked between these two operations.

For notebooks with auto set to false the Tcl command given with

the command option will be invoked.
pathName select index

Selects the page specified by index as the currently selected

page.

For notebooks with auto set to true the current page's child site

is unpacked from the notebook's child site frame. Then the index page's child site is packed into the notebooks child site frame.

The Tcl command given with the command option will be invoked

between these two operations.

For notebooks with auto set to false the Tcl command given with

the command option will be invoked.
pathName view

Returns the currently selected page. This command is for compati-

bility with the scrollbar widget.
pathName view index

Selects the page specified by index as the currently selected

page. This command is for compatibility with the scrollbar wid- get.
pathName view moveto fraction

Uses the fraction value to determine the corresponding page to

move to. This command is for compatibility with the scrollbar widget.
pathName view scroll num what

Uses the num value to determine how many pages to move forward or

backward (num can be negative or positive). The what argument is ignored. This command is for compatibility with the scrollbar widget.

Example

Following is an example that creates a notebook with two pages.

In this example, we use a scrollbar widget to control the note-

book widget.

package require Iwidgets 4.0
# Create the notebook widget and pack it.
iwidgets::notebook .nb -width 100 -height 100 pack .nb -anchor nw \
-fill both \
-expand yes \
-side left \
-padx 10 \
-pady 10
# Add two pages to the notebook, labelled
# «Page One» and «Page Two", respectively.
.nb add -label «Page One"
.nb add -label «Page Two"
# Get the child site frames of these two pages. set page1CS [.nb childsite 0]
set page2CS [.nb childsite «Page Two"]
# Create buttons on each page of the notebook button $page1CS.b -text «Button One"
pack $page1CS.b
button $page2CS.b -text «Button Two"
pack $page2CS.b
# Select the first page of the notebook
.nb select 0
# Create the scrollbar and associate teh scrollbar # and the notebook together, then pack the scrollbar scrollbar .scroll -command «.nb view"
.nb configure -scrollcommand «.scroll set"
pack .scroll -fill y -expand yes -pady 10

Author

Bill W. Scott

Keywords

notebook page

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: auto
  • Class: Auto
  • Command-Line Switch: -auto
  • Specifies whether to use the automatic packing/unpacking algo-
  • Tcl_GetBoolean, such as true, false, 0, 1, yes, or no.
  • For example, if a series of pages in a notebook simply change
  • Description
  • The iwidgets::notebook command creates a new window (given by the
  • A notebook is a widget that contains a set of pages. It displays
  • When first created a notebook has no pages. Pages may be added or
  • Notebook Pages
  • A notebook's pages area contains a single child site frame. When
  • However, sometimes it is desirable to handle page changes in a
  • In both cases the command option for a page specifies a Tcl Com-
  • Widget-specific Methods
  • The iwidgets::notebookfR command creates a new Tcl command whose
  • Many of the widget commands for a notebook take as one argument
  • Specifies the index of the the component. For menus, 0 corre-
  • Specifies the currently selected page's index. If no page is cur-
  • Specifes the last page in the notebooks's index. If the notebook
  • If the index doesn't satisfy the form of a number, then this form
  • The following commands are possible for notebook widgets:
  • Add a new page at the end of the notebook. A new child site frame
  • Specifies a background color to use for displaying the child site
  • Specifies a Tcl command to be executed when this page is
  • If the notebook has the auto option set to true, when a page is
  • If the auto option is set to false, when a page is selected the
  • Specifies a foreground color to use for displaying tab labels
  • Specifies a string to associate with this page. This label serves
  • If passed no arguments, returns a list of pathNames for all the
  • If index is passed, it returns the pathName for the page's child
  • If index is not a valid index, an empty string is returned.
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Delete all of the pages between index1 and index2 inclusive. If
  • Returns the numerical index corresponding to index.
  • Insert a new page in the notebook before the page specified by
  • Advances the selected page to the next page (order is determined
  • For notebooks with auto set to true the current page's child site
  • The Tcl command given with the command option will be invoked
  • For notebooks with auto set to false the Tcl command given with
  • Returns the current value of the configuration option given by
  • This command is similar to the configure command, except that it
  • Tk_ConfigureInfo for information on the format of this list).
  • Moves the selected page to the previous page (order is determined
  • For notebooks with auto set to true the current page's child site
  • For notebooks with auto set to false the Tcl command given with
  • Selects the page specified by index as the currently selected
  • For notebooks with auto set to true the current page's child site
  • The Tcl command given with the command option will be invoked
  • For notebooks with auto set to false the Tcl command given with
  • Returns the currently selected page. This command is for compati-
  • Selects the page specified by index as the currently selected
  • Uses the fraction value to determine the corresponding page to
  • Uses the num value to determine how many pages to move forward or
  • Example
  • Following is an example that creates a notebook with two pages.
  • In this example, we use a scrollbar widget to control the note-
  • Author
  • Bill W. Scott
  • Keywords


IWidgets optionmenu

 Table of Contents

iwidgets::optionmenu - Create and manipulate a option menu widget

Synopsis

iwidgets::optionmenu pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Optionmenu

Standard Options

activeBackground activeBorderWidth activeForeground background borderWidth cursor disabledForeground font

foreground
highlightColor highlightThickness relief

See the «options» manual entry for details on the standard

options.

Inherited Options

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable
state
sticky

See the «LabeledWidget» manual entry for details on the inherited

options.

Widget-specific Options

Name: clickTime

Class: ClickTime

Command-Line Switch: -clicktime

Interval time, in msec, used to determine that a single mouse

click has occurred. Used to post menu on a «quick» mouse click.

Note: changing this value may cause the sigle-click functionality

to not work properly. The default is 150 msec.

Name: command

Class: Command

Command-Line Switch: -command

Specifies a Tcl command procedure to be evaluated following a

change in the current option menu selection.

Name: cyclicOn

Class: CyclicOn

Command-Line Switch: -cyclicon

Turns on/off the 3rd mouse button capability. The value may be

specified in any of the forms acceptable to Tcl_GetBoolean. This feature allows the right mouse button to cycle through the popup menu list without poping it up. The right mouse button cycles through the menu in reverse order. The default is true.

Name: popupCursor

Class: Cursor

Command-Line Switch: -popupcursor

Specifies the mouse cursor to be used for the popup menu. The

value may have any of the forms acceptable to Tk_GetCursor.

Name: state

Class: State

Command-Line Switch: -state

Specified one of two states for the optionmenu: normal, or dis-

abled. If the optionmenu is disabled, then option menu selection is ignored.

Name: width

Class: Width

Command-Line Switch: -width

Specifies a fixed size for the menu button label in any of the

forms acceptable to Tk_GetPixels. If the text is too small to fit in the label, the text is clipped. Note: Normally, when a new list is created, or new items are added to an existing list, the menu button label is resized automatically. Setting this option overrides that functionality.
_________________________________________________________________

Description

The iwidgets::optionmenu command creates an option menu widget

with options to manage it. An option menu displays a frame con- taining a label and a button. A pop-up menu will allow for the value of the button to change.

Methods

The iwidgets::optionmenu command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

Many of the widget commands for an optionmenu take as one argu-

ment an indicator of which entry of the option menu to operate on. These indicators are called indexes and may be specified in any of the following forms:

number
Specifies the entry numerically, where 0 corresponds to the top-most entry of the option menu, 1 to the entry below it, and so on.
end
Indicates the bottommost entry in the menu. If there are no entries in the menu then zero is returned.
select
Returns the numerical index of the currently selected option menu entry. If no entries exist in the menu, then -1 is returned.
pattern
If the index doesn't satisfy one of the above forms then this form is used. Pattern is pattern-matched against the label of each entry in the option menu, in order from the top down, until a matching entry is found. The rules of Tcl_StringMatch are used.

The following widget commands are possible for optionmenu wid-

gets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::optionmenu command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::optionmenu command. pathName delete first ?last?

Delete all of the option menu entries between first and last

inclusive. If last is omitted then it defaults to first. pathName disable index

Disable the option menu entry specified by index. Disabling a

menu item will prevent the user from being able to select this item from the menu. This only effects the state of the item in the menu, in other words, should the item be the currently selected item, the programmer is responsible for determining this condition and taking appropriate action.
pathName enable index

Enable the option menu entry specified by index. Enabling a menu

item allows the user to select this item from the menu. pathName get ?first? ?last?

If no arguments are specified, this operation returns the cur-

rently selected option menu item. Otherwise, it returns the name of the option at index first, or a range of options between first and last.

pathName index index

Returns the numerical index corresponding to index.

pathName insert index string ?string?

Insert an item, or list of items, into the menu at location

index.
pathName select index

Select an item from the option menu to be displayed as the cur-

rently selected item.
pathName sort mode

Sort the current menu in either ascending, or descending order.

The values increasing, or decreasing are also accepted.

Components

Name: menuBtn

Class: Menubutton

The menuBtn component is the option menu button which displays

the current choice from the popup menu. See the «menubutton" widget manual entry for details on the menuBtn component item.

Name: popupMenu

Class: Menu

The popupMenu component is menu displayed upon selection of the

menu button. The menu contains the choices for the option menu.

See the «menu» widget manual entry for details on the popupMenu

component item.

Example

package require Iwidgets 4.0
iwidgets::optionmenu .om -labelmargin 5 \
-labelon true -labelpos w -labeltext «Operating System :"

.om insert end Unix VMS Linux OS/2 {Windows NT} DOS .om sort ascending
.om select Linux

pack .om -padx 10 -pady 10

Acknowledgements:

Michael J. McLennan

Borrowed some ideas (next & previous) from OptionButton class.

Steven B. Jaggers

Provided an initial prototype in [incr Tcl].

Bret Schuhmacher

Helped with popup menu functionality.

Author

Alfredo Jahn

Keywords

optionmenu, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "LabeledWidget" manual entry for details on the inherited
  • Widget-specific Options
  • Name: clickTime
  • Class: ClickTime
  • Command-Line Switch: -clicktime
  • Interval time, in msec, used to determine that a single mouse
  • Note: changing this value may cause the sigle-click functionality
  • Name: command
  • Class: Command
  • Command-Line Switch: -command
  • Specifies a Tcl command procedure to be evaluated following a
  • Name: cyclicOn
  • Class: CyclicOn
  • Command-Line Switch: -cyclicon
  • Turns on/off the 3rd mouse button capability. The value may be
  • Name: popupCursor
  • Class: Cursor
  • Command-Line Switch: -popupcursor
  • Specifies the mouse cursor to be used for the popup menu. The
  • Name: state
  • Class: State
  • Command-Line Switch: -state
  • Specified one of two states for the optionmenu: normal, or dis-
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies a fixed size for the menu button label in any of the
  • Description
  • The iwidgets::optionmenu command creates an option menu widget
  • Methods
  • The iwidgets::optionmenu command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • Many of the widget commands for an optionmenu take as one argu-
  • The following widget commands are possible for optionmenu wid-
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Delete all of the option menu entries between first and last
  • Disable the option menu entry specified by index. Disabling a
  • Enable the option menu entry specified by index. Enabling a menu
  • If no arguments are specified, this operation returns the cur-
  • Returns the numerical index corresponding to index.
  • Insert an item, or list of items, into the menu at location
  • Select an item from the option menu to be displayed as the cur-
  • Sort the current menu in either ascending, or descending order.
  • The values increasing, or decreasing are also accepted.
  • Components
  • Name: menuBtn
  • Class: Menubutton
  • The menuBtn component is the option menu button which displays
  • Name: popupMenu
  • Class: Menu
  • The popupMenu component is menu displayed upon selection of the
  • See the "menu" widget manual entry for details on the popupMenu
  • Example
  • Acknowledgements:
  • Michael J. McLennan
  • Borrowed some ideas (next & previous) from OptionButton class.
  • Steven B. Jaggers
  • Provided an initial prototype in [incr Tcl].
  • Bret Schuhmacher
  • Helped with popup menu functionality.
  • Author
  • Alfredo Jahn
  • Keywords


IWidgets panedwindow

 Table of Contents

iwidgets::panedwindow - Create and manipulate a paned window wid- get

Synopsis

iwidgets::panedwindow pathName ?options?

Inheritance

itk::Widget <- iwidgets::Panedwindow

Standard Options

background
cursor

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: height

Class: Height

Command-Line Switch: -height

Specifies the overall height of the paned window in any of the

forms acceptable to Tk_GetPixels. The default is 10 pixels.

Name: orient

Class: Orient

Command-Line Switch: -orient

Specifies the orientation of the separators: vertical or horizon-

tal. The default is horizontal.

Name: sashBorderWidth

Class: BorderWidth

Command-Line Switch: -sashborderwidth

Specifies a value indicating the width of the 3-D border to draw

around the outside of the sash in any of the forms acceptable to

Tk_GetPixels. The default is 2 pixels.

Name: sashCursor

Class: Cursor

Command-Line Switch: -sashcursor

Specifies the type of cursor to be displayed in the sash. The

default is crosshair.

Name: sashHeight

Class: Height

Command-Line Switch: -sashheight

Specifies the height of the sash in any of the forms acceptable

to Tk_GetPixels. The default is 10 pixels.

Name: sashIndent

Class: SashIndent

Command-Line Switch sashindent

Specifies the placement of the sash along the panes in any of the

forms acceptable to Tk_GetPixels. A positive value causes the sash to be offset from the near (left/top) side of the pane, and a negative value causes the sash to be offset from the far (right/bottom) side. If the offset is greater than the width, then the sash is placed flush against the side. The default is -10 pixels.

Name: sashWidth

Class: Width

Command-Line Switch: -sashwidth

Specifies the width of the sash in any of the forms acceptable to

Tk_GetPixels. The default is 10 pixels.

Name: showHandle

Class: ShowHandle

Command-Line Switch: -showhandle

Specifies whether or not to display the sashes on the window

panes. The default is 1, and valid options are 0 and 1.

Name: thickness

Class: Thickness

Command-Line Switch: -thickness

Specifies the thickness of the separators in any of the forms

acceptable to Tk_GetPixels. The default is 3 pixels.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the overall width of the paned window in any of the

forms acceptable to Tk_GetPixels. The default is 10 pixels. _________________________________________________________________

Description

The iwidgets::panedwindow command creates a multiple paned window

widget capable of orienting the panes either vertically or hori- zontally. Each pane is itself a frame acting as a child site for other widgets. The border separating each pane contains a sash which allows user positioning of the panes relative to one another.

Methods

The iwidgets::panedwindow command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

Many of the widget commands for the panedwindow take as one argu-

ment an indicator of which pane of the paned window to operate on. These indicators are called indexes and allow reference and manipulation of panes regardless of their current map state.

Paned window indexes may be specified in any of the following

forms:

number
Specifies the pane numerically, where 0 corresponds to the nearest (top/left-most) pane of the paned window.
end
Indicates the farthest (bottom/right-most) pane of the paned window.
pattern
If the index doesn't satisfy one of the above forms then this form is used. Pattern is pattern-matched against the tag of each pane in the panedwindow, in order from left/top to right/left, until a matching entry is found. The rules of Tcl_StringMatch are used.

Widget-specific Methods

pathName add tag ?option value option value?

Adds a new pane to the paned window on the far side (right/bot-

tom). The following options may be specified: -margin value

Specifies the border distance between the pane and pane contents

is any of the forms acceptable to Tk_GetPixels. The default is 8 pixels.
-minimum value

Specifies the minimum size that a pane's contents may reach not

inclusive of twice the margin in any of the forms acceptable to

Tk_GetPixels. The default is 10 pixels.

The add method returns the path name of the pane.

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::panedwindow command.
pathName childsite ?index?

Returns a list of the child site path names or a specific child

site given an index. The list is constructed from the near side (left/top) to the far side (right/bottom).
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::panedwindow command. pathName delete index

Deletes a specified pane given an index.

pathName fraction percentage percentage ?percentage percentage ...?

Sets the visible percentage of the panes. Specifies a set of

percentages which are applied to the visible panes from the near side (left/top). The number of percentages must be equal to the current number of visible (mapped) panes and add up to 100. pathName hide index

Changes the visiblity of the specified pane, allowing a previ-

ously displayed pane to be visually removed rather than deleted. pathName index index

Returns the numerical index corresponding to index.

pathName insert index tag ?option value option value ...?

Same as the add command except that it inserts the new pane just

before the one given by index, instead of appending to the end of the panedwindow. The option, and value arguments have the same interpretation as for the add widget command. pathName paneconfigure index ?options?

This command is similar to the configure command, except that it

applies to the options for an individual pane, whereas configure applies to the options for the paned window as a whole. Options may have any of the values accepted by the add widget command.

If options are specified, options are modified as indicated in

the command and the command returns an empty string. If no options are specified, returns a list describing the current options for entry index (see Tk_ConfigureInfo for information on the format of this list).
pathName reset

Redisplays the pane window using default percentages.

pathName show index

Changes the visiblity of the specified pane, allowing a previ-

ously hidden pane to be displayed.

Notes

Dynamic changing of the margin and or minimum options to values

which make the current configuration invalid will block subse- quent sash movement until the fractions are modified via the fraction method. For example a panedwindow is created with three panes and the minimum and margin options are at their default settings. Next the user moves the sashes to compact the panes to one side. Now, if the minimum is increased on the most com- pressed pane via the paneconfigure method to a large enough value, then sash movement is blocked until the fractions are adjusted. This situation is unusual and under normal operation of the panedwindow, this problem will never occur.

Example

package require Iwidgets 4.0
iwidgets::panedwindow .pw -width 300 -height 300 .pw add top
.pw add middle -margin 10
.pw add bottom -margin 10 -minimum 10

pack .pw -fill both -expand yes

foreach pane [.pw childSite] {
button $pane.b -text $pane -relief raised -borderwidth 2 pack $pane.b -fill both -expand yes
}

.pw fraction 50 30 20
.pw paneconfigure 0 -minimum 20
.pw paneconfigure bottom -margin 15

Acknowledgements:

Jay Schmidgall

1994 - Base logic posted to comp.lang.tcl

Joe Hidebrand <hildjj@fuentez.com>

07/25/94 - Posted first multipane version to comp.lang.tcl 07/28/94 - Added support for vertical panes

Ken Copeland <ken@hilco.com>

09/28/95 - Smoothed out the sash movement and added squeezable panes.

Author

Mark L. Ulferts

Keywords

panedwindow, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the overall height of the paned window in any of the
  • Name: orient
  • Class: Orient
  • Command-Line Switch: -orient
  • Specifies the orientation of the separators: vertical or horizon-
  • Name: sashBorderWidth
  • Class: BorderWidth
  • Command-Line Switch: -sashborderwidth
  • Specifies a value indicating the width of the 3-D border to draw
  • Tk_GetPixels. The default is 2 pixels.
  • Name: sashCursor
  • Class: Cursor
  • Command-Line Switch: -sashcursor
  • Specifies the type of cursor to be displayed in the sash. The
  • Name: sashHeight
  • Class: Height
  • Command-Line Switch: -sashheight
  • Specifies the height of the sash in any of the forms acceptable
  • Name: sashIndent
  • Class: SashIndent
  • Command-Line Switch sashindent
  • Specifies the placement of the sash along the panes in any of the
  • Name: sashWidth
  • Class: Width
  • Command-Line Switch: -sashwidth
  • Specifies the width of the sash in any of the forms acceptable to
  • Tk_GetPixels. The default is 10 pixels.
  • Name: showHandle
  • Class: ShowHandle
  • Command-Line Switch: -showhandle
  • Specifies whether or not to display the sashes on the window
  • Name: thickness
  • Class: Thickness
  • Command-Line Switch: -thickness
  • Specifies the thickness of the separators in any of the forms
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the overall width of the paned window in any of the
  • Description
  • The iwidgets::panedwindow command creates a multiple paned window
  • Methods
  • The iwidgets::panedwindow command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • Many of the widget commands for the panedwindow take as one argu-
  • Paned window indexes may be specified in any of the following
  • Widget-specific Methods
  • Adds a new pane to the paned window on the far side (right/bot-
  • Specifies the border distance between the pane and pane contents
  • Specifies the minimum size that a pane's contents may reach not
  • Tk_GetPixels. The default is 10 pixels.
  • The add method returns the path name of the pane.
  • Returns the current value of the configuration option given by
  • Returns a list of the child site path names or a specific child
  • Query or modify the configuration options of the widget. If no
  • Deletes a specified pane given an index.
  • Sets the visible percentage of the panes. Specifies a set of
  • Changes the visiblity of the specified pane, allowing a previ-
  • Returns the numerical index corresponding to index.
  • Same as the add command except that it inserts the new pane just
  • This command is similar to the configure command, except that it
  • If options are specified, options are modified as indicated in
  • Redisplays the pane window using default percentages.
  • Changes the visiblity of the specified pane, allowing a previ-
  • Notes
  • Dynamic changing of the margin and or minimum options to values
  • Example
  • Acknowledgements:
  • Jay Schmidgall
  • Joe Hidebrand
  • Ken Copeland
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets promptdialog

 Table of Contents

iwidgets::promptdialog - Create and manipulate a prompt dialog widget

Synopsis

iwidgets::promptdialog pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Dialogshell <- iwidgets::Dialog <- iwidgets::Promptdialog

Standard Options

background borderWidth cursor exportSelection

foreground
highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth
relief
selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

show

See the «entry» widget manual entry for details on the above

associated options.

invalid
textBackground textFont validate

See the «entryfield» widget manual entry for details on the above

associated options.
labelFont labelPos labelText

See the «labeledwidget» widget manual entry for details on the

above associated options.

Inherited Options

buttonBoxPadX buttonBoxPadY buttonBoxPos padX

padY
separator thickness

See the «dialogshell» widget manual entry for details on the

above inherited options.
height master modality width

See the «shell» widget manual entry for details on the above

inherited options.
title

See the «Toplevel» widget manual entry for details on the above

inherited options.
_________________________________________________________________

Description

The iwidgets::promptdialog command creates a prompt dialog simi-

lar to the OSF/Motif standard prompt dialog composite widget.

The promptdialog is derived from the dialog class and is composed

of a EntryField with commands to manipulate the dialog buttons.

Methods

The iwidgets::promptdialog command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for promptdialog widgets:

Associated Methods

delete get icursor index insert scan selection xview

See the «entry» widget manual entry for details on the above

associated methods.
clear

See the «entryfield» widget manual entry for details on the above

associated methods.

Inherited Methods

add buttonconfigure defaulthide

invoke
show

See the «buttonbox» widget manual entry for details on the above

inherited methods.
childsite

See the «dialogshell» widget manual entry for details on the

above inherited methods.
activate center deactivate

See the «shell» widget manual entry for details on the above

inherited methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::promptdialog command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::promptdialog command.

Components

Name: prompt

Class: Entryfield

The prompt component is the entry field for user input in the

prompt dialog. See the «entryfield» widget manual entry for details on the prompt component item.

Example

package require Iwidgets 4.0
option add *textBackground white

iwidgets::promptdialog .pd -modality global -title Password -labeltext Password: -show * .pd hide Apply

if {[.pd activate]} {
puts «Password entered: [.pd get]"
} else {
puts «Password prompt cancelled"
}

Author

Mark L. Ulferts

Keywords

promptdialog, dialog, dialogshell, shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "entry" widget manual entry for details on the above
  • See the "entryfield" widget manual entry for details on the above
  • See the "labeledwidget" widget manual entry for details on the
  • Inherited Options
  • See the "dialogshell" widget manual entry for details on the
  • See the "shell" widget manual entry for details on the above
  • See the "Toplevel" widget manual entry for details on the above
  • Description
  • The iwidgets::promptdialog command creates a prompt dialog simi-
  • The promptdialog is derived from the dialog class and is composed
  • Methods
  • The iwidgets::promptdialog command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for promptdialog widgets:
  • Associated Methods
  • See the "entry" widget manual entry for details on the above
  • See the "entryfield" widget manual entry for details on the above
  • Inherited Methods
  • See the "buttonbox" widget manual entry for details on the above
  • See the "dialogshell" widget manual entry for details on the
  • See the "shell" widget manual entry for details on the above
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: prompt
  • Class: Entryfield
  • The prompt component is the entry field for user input in the
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets pushbutton

 Table of Contents

iwidgets::pushbutton - Create and manipulate a push button widget

Synopsis

iwidgets::pushbutton pathName ?options?

Inheritance

itk::Widget <- iwidgets::Pushbutton

Standard Options

activeBackground activeForeground background

bitmap
borderWidth command
cursor
disabledForeground font
foreground
highlightBackground highlightColor highlightThickness image padX padY state text
underline
wrapLength

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: defaultRing

Class: DefaultRing

Command-Line Switch: -defaultring

Boolean describing whether the button displays its default ring

given in any of the forms acceptable to Tcl_GetBoolean. The default is false.

Name: defaultRingPad

Class: Pad

Command-Line Switch: -defaultringpad

Specifies the amount of space to be allocated to the indentation

of the default ring ring given in any of the forms acceptable to

Tcl_GetPixels. The option has no effect if the defaultring

option is set to false. The default is 2 pixels.

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the button inclusive of any default ring

given in any of the forms acceptable to Tk_GetPixels. A value of zero lets the push button determine the height based on the requested height plus highlightring and defaultringpad.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the button inclusive of any default ring

given in any of the forms acceptable to Tk_GetPixels. A value of zero lets the push button determine the width based on the requested width plus highlightring and defaultringpad. _________________________________________________________________

Description

The iwidgets::pushbutton command creates a push button with an

optional default ring used for default designation and traversal.

Methods

The iwidgets::pushbutton command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for pushbutton widgets:

Associated Methods

flash
invoke

See the «button» manual entry for details on the associated meth-

ods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::pushbutton command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::pushbutton command.

Components

Name: pushbutton

Class: Button

The pushbutton component is the button surrounded by the optional

default ring. See the «button» widget manual entry for details on the pushbutton component item.

Example

package require Iwidgets 4.0
iwidgets::pushbutton .pb -text «Hello» -command {puts «Hello World"} -defaultring 1 pack .pb -padx 10 -pady 10

Author

Bret A. Schuhmacher

Mark L. Ulferts

Keywords

pushbutton, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: defaultRing
  • Class: DefaultRing
  • Command-Line Switch: -defaultring
  • Boolean describing whether the button displays its default ring
  • Name: defaultRingPad
  • Class: Pad
  • Command-Line Switch: -defaultringpad
  • Specifies the amount of space to be allocated to the indentation
  • Tcl_GetPixels. The option has no effect if the defaultring
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the button inclusive of any default ring
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the button inclusive of any default ring
  • Description
  • The iwidgets::pushbutton command creates a push button with an
  • Methods
  • The iwidgets::pushbutton command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for pushbutton widgets:
  • Associated Methods
  • See the "button" manual entry for details on the associated meth-
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: pushbutton
  • Class: Button
  • The pushbutton component is the button surrounded by the optional
  • Example
  • Author
  • Bret A. Schuhmacher
  • Mark L. Ulferts
  • Keywords


IWidgets radiobox

 Table of Contents

iwidgets::radiobox - Create and manipulate a radiobox widget

Synopsis

iwidgets::radiobox pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledframe <- iwidgets::Radiobox

Standard Options

background borderWidth cursor disabledForeground foreground relief selectColor

See the «options» manual entry for details on the standard

options.

Inherited Options

labelBitmap labelFont labelImage labelMargin

labelPos
labelText labelVariable

See the «labeledframe» class manual entry for details on the

inherited options.

Widget-specific Options

Name: command

Class: Command

Command-Line Switch: -command

Specifies a Tcl command procedure to be evaluated following a

change in the current radio box selection.

Name: orient

Class: Orient

Command-Line Switch: -orient

Default Value: vertical

Specifies the orientation of the radiobuttons within the

radiobox. Valid values are either «horizontal» or «vertical". _________________________________________________________________

Description

The iwidgets::radiobox command creates a radio button box widget

capable of adding, inserting, deleting, selecting, and configur- ing radiobuttons as well as obtaining the currently selected but- ton.

Methods

The iwidgets::radiobox command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

Many of the widget commands for the radiobox take as one argument

an indicator of which radiobutton of the radiobox to operate on.

These indicators are called indexes and allow reference and

manipulation of radiobuttons. Radiobox indexes may be specified in any of the following forms:

number
Specifies the radiobutton numerically, where 0 corresponds to the top radiobutton of the radiobox.
end
Indicates the last radiobutton of the radiobox.
pattern
If the index doesn't satisfy one of the above forms then this form is used. Pattern is pattern-matched against the tag of each radiobutton in the radiobox, in order from top to bottom, until a matching entry is found. The rules of Tcl_StringMatch are used.

Widget-specific Methods

pathName add tag ?option value option value?

Adds a new radiobutton to the radiobuttond window on the bottom.

The command takes additional options which are passed on to the

radiobutton as construction arguments. These include the stan- dard Tk radiobutton options. The tag is returned.

pathName buttonconfigure index ?options?

This command is similar to the configure command, except that it

applies to the options for an individual radiobutton, whereas configureapplies to the options for the radiobox as a whole.

Options may have any of the values accepted by the add widget

command. If options are specified, options are modified as indi- cated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for entry index (see Tk_ConfigureInfo for information on the format of this list).
pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::radiobox command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::radiobox command. pathName delete index

Deletes a specified radiobutton given an index.

pathName deselect index

Deselects a specified radiobutton given an index.

pathName flash index

Flashes a specified radiobutton given an index.

pathName get

Returns the tag of the currently selected radiobutton.

pathName index index

Returns the numerical index corresponding to index.

pathName insert index tag ?option value option value ...?

Same as the add command except that it inserts the new radiobut-

ton just before the one given by index, instead of appending to the end of the radiobox. The option, and value arguments have the same interpretation as for the add widget command. pathName select index

Selects a specified radiobutton given an index.

Example

package require Iwidgets 4.0
iwidgets::radiobox .rb -labeltext Fonts
.rb add times -text Times
.rb add helvetica -text Helvetica
.rb add courier -text Courier
.rb add symbol -text Symbol
.rb select courier

pack .rb -padx 10 -pady 10 -fill both -expand yes

Author

Michael J. McLennan

Mark L. Ulferts

Keywords

radiobox, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "labeledframe" class manual entry for details on the
  • Widget-specific Options
  • Name: command
  • Class: Command
  • Command-Line Switch: -command
  • Specifies a Tcl command procedure to be evaluated following a
  • Name: orient
  • Class: Orient
  • Command-Line Switch: -orient
  • Default Value: vertical
  • Specifies the orientation of the radiobuttons within the
  • Description
  • The iwidgets::radiobox command creates a radio button box widget
  • Methods
  • The iwidgets::radiobox command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • Many of the widget commands for the radiobox take as one argument
  • These indicators are called indexes and allow reference and
  • Widget-specific Methods
  • Adds a new radiobutton to the radiobuttond window on the bottom.
  • The command takes additional options which are passed on to the
  • This command is similar to the configure command, except that it
  • Options may have any of the values accepted by the add widget
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Deletes a specified radiobutton given an index.
  • Deselects a specified radiobutton given an index.
  • Flashes a specified radiobutton given an index.
  • Returns the tag of the currently selected radiobutton.
  • Returns the numerical index corresponding to index.
  • Same as the add command except that it inserts the new radiobut-
  • Selects a specified radiobutton given an index.
  • Example
  • Author
  • Michael J. McLennan
  • Mark L. Ulferts
  • Keywords


IWidgets scopedobject

 Table of Contents

scopedobject - Create and manipulate a scoped Tcl] class object.

Synopsis

scopedobject objName ?options?

Inheritance

None

Standard Options

Name: enterscopecommand:

Command-Line Switch: -enterscopecommand

Specifies a Tcl command to invoke when an object enters scope

(i.e. when it is created..). The default is {}.

Name: enterscopecommand:

Command-Line Switch: -enterscopecommand

Specifies a Tcl command to invoke when an object exits scope

(i.e. when it is deleted..). The default is {}. _________________________________________________________________

Description

The scopedobject command creates a base class for defining Itcl

classes which posses scoped behavior like Tcl variables. The objects are only accessible within the procedure in which they are instantiated and are deleted when the procedure returns.

This class was designed to be a general purpose base class for

supporting scoped incr Tcl classes. The options include the exe- cute a Tcl script command when an object enters and exits its scope.

Methods

The scopedobject command creates a new Tcl command whose name is

pathName. This command may be used to invoke various operations on the object. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for scopedobject objects:

Object-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the scope- dobject command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the object. If no

option is specified, returns a list describing all of the avail- able options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given objects option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the scopedobject command.

Example

The scopedobject was primarily meant to be a base class. The

following is an example of usage without inheritance:

proc scopedobject_demo {} {

iwidgets::scopedobject #auto
-exitscopecommand {puts «enter scopedobject_demo"} -exitscopecommand {puts «exit scopedobject_demo"} }

scopedobject_demo

Author

John A. Tucker

Keywords

scopedobject, object

Table of Contents

  • Synopsis
  • Inheritance
  • None
  • Standard Options
  • Name: enterscopecommand:
  • Command-Line Switch: -enterscopecommand
  • Specifies a Tcl command to invoke when an object enters scope
  • Name: enterscopecommand:
  • Command-Line Switch: -enterscopecommand
  • Specifies a Tcl command to invoke when an object exits scope
  • Description
  • The scopedobject command creates a base class for defining Itcl
  • This class was designed to be a general purpose base class for
  • Methods
  • The scopedobject command creates a new Tcl command whose name is
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for scopedobject objects:
  • Object-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the object. If no
  • Example
  • The scopedobject was primarily meant to be a base class. The
  • Author
  • John A. Tucker
  • Keywords


IWidgets scrolledcanvas

 Table of Contents

iwidgets::scrolledcanvas - Create and manipulate scrolled canvas widgets

Synopsis

iwidgets::scrolledcanvas pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Scrolledwid- get <- iwidgets::Scrolledcanvas

Standard Options

activeBackground background borderWidth cursor exportSelection font foreground highlightColor highlightThickness insertBorderWidth insertOffTime insertOnTime insertWidth relief selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

closeEnough confine scrollRegion xScrollIncrement yScrollIncrement

See the «canvas» widget manual entry for details on the above

associated options.
activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget manual entry for details on the above

associated options.

Inherited Options

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable
state
sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: autoMargin

Class: AutoMargin

Command-Line Switch: -automargin

Specifies the autoresize extra margin to reserve. This option is

only effective with autoresize turned on. The default is 10.

Name: autoResize

Class: AutoResize

Command-Line Switch: -autoresize

Automatically adjusts the scrolled region to be the bounding box

covering all the items in the canvas following the execution of any method which creates or destroys items. Thus, as new items are added, the scrollbars adjust accordingly.

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the scrolled canvas widget in any of the

forms acceptable to Tk_GetPixels. The default height is 30 pix- els.

Name: hscrollMode

Class: ScrollMode

Command-Line Switch: -hscrollmode

Specifies the the display mode to be used for the horizontal

scrollbar: static, dynamic, or none. In static mode, the scroll bar is displayed at all times. Dynamic mode displays the scroll bar as required, and none disables the scroll bar display. The default is static.

Name: sbWidth

Class: Width

Command-Line Switch: -sbwidth

Specifies the width of the scrollbar in any of the forms accept-

able to Tk_GetPixels. The default width is 15 pixels..

Name: scrollMargin

Class: ScrollMargin

Command-Line Switch: -scrollmargin

Specifies the distance between the canvas and scrollbar in any of

the forms acceptable to Tk_GetPixels. The default is 3 pixels.

Name: textBackground

Class: Background

Command-Line Switch -textbackground

Specifies the background color for the canvas. This allows the

background within the canvas to be different from the normal background color.

Name: vscrollMode

Class: ScrollMode

Command-Line Switch: -vscrollmode

Specifies the the display mode to be used for the vertical

scrollbar: static, dynamic, or none. In static mode, the scroll bar is displayed at all times. Dynamic mode displays the scroll bar as required, and none disables the scroll bar display. The default is static.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the scrolled canvas widget in any of the

forms acceptable to Tk_GetPixels. The default height is 30 pix- els.
_________________________________________________________________

Description

The iwidgets::scrolledcanvas command creates a scrolled canvas

with additional options to manage horizontal and vertical scroll- bars. This includes options to control which scrollbars are dis- played and the method, i.e. statically or dynamically.

Methods

The iwidgets::scrolledcanvas command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for scrolledcanvas widgets:

Associated Methods

addtag bbox bind canvasx canvasy coords create dchars delete dtag find focus gettags icursor index insert itemconfigure lower move postscript raise scale scan select

type
xview yview

See the «canvas» manual entry for details on the associated meth-

ods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::scrolledcanvas command.
pathName childsite

Returns the child site widget path name.

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::scrolledcanvas command. pathName justify direction

Justifies the canvas contents via the scroll bars in one of four

directions: left, right, top, or bottom.

Components

Name: canvas

Class: Canvas

The canvas component is the canvas widget. See the «canvas» wid-

get manual entry for details on the canvas component item.

Name: horizsb

Class: Scrollbar

The horizsb component is the horizontal scroll bar. See the

«ScrollBar» widget manual entry for details on the horizsb compo- nent item.

Name: vertsb

Class: Scrollbar

The vertsb component is the vertical scroll bar. See the

«ScrollBar» widget manual entry for details on the vertsb compo- nent item.

Example

package require Iwidgets 4.0
iwidgets::scrolledcanvas .sc

.sc create rectangle 100 100 400 400 -fill red .sc create rectangle 300 300 600 600 -fill green .sc create rectangle 200 200 500 500 -fill blue

pack .sc -padx 10 -pady 10 -fill both -expand yes

Author

Mark L. Ulferts

Keywords

scrolledcanvas, canvas, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "canvas" widget manual entry for details on the above
  • See the "scrollbar" widget manual entry for details on the above
  • Inherited Options
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: autoMargin
  • Class: AutoMargin
  • Command-Line Switch: -automargin
  • Specifies the autoresize extra margin to reserve. This option is
  • Name: autoResize
  • Class: AutoResize
  • Command-Line Switch: -autoresize
  • Automatically adjusts the scrolled region to be the bounding box
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the scrolled canvas widget in any of the
  • Name: hscrollMode
  • Class: ScrollMode
  • Command-Line Switch: -hscrollmode
  • Specifies the the display mode to be used for the horizontal
  • Name: sbWidth
  • Class: Width
  • Command-Line Switch: -sbwidth
  • Specifies the width of the scrollbar in any of the forms accept-
  • Name: scrollMargin
  • Class: ScrollMargin
  • Command-Line Switch: -scrollmargin
  • Specifies the distance between the canvas and scrollbar in any of
  • Name: textBackground
  • Class: Background
  • Command-Line Switch -textbackground
  • Specifies the background color for the canvas. This allows the
  • Name: vscrollMode
  • Class: ScrollMode
  • Command-Line Switch: -vscrollmode
  • Specifies the the display mode to be used for the vertical
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the scrolled canvas widget in any of the
  • Description
  • The iwidgets::scrolledcanvas command creates a scrolled canvas
  • Methods
  • The iwidgets::scrolledcanvas command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for scrolledcanvas widgets:
  • Associated Methods
  • See the "canvas" manual entry for details on the associated meth-
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Returns the child site widget path name.
  • Query or modify the configuration options of the widget. If no
  • Justifies the canvas contents via the scroll bars in one of four
  • Components
  • Name: canvas
  • Class: Canvas
  • The canvas component is the canvas widget. See the "canvas" wid-
  • Name: horizsb
  • Class: Scrollbar
  • The horizsb component is the horizontal scroll bar. See the
  • Name: vertsb
  • Class: Scrollbar
  • The vertsb component is the vertical scroll bar. See the
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets scrolledframe

 Table of Contents

iwidgets::scrolledframe - Create and manipulate scrolled frame widgets

Synopsis

iwidgets::scrolledframe pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Scrolledwid- get <- iwidgets::Scrolledframe

Standard Options

activeBackground background borderWidth cursor

font
foreground highlightColor highlightThickness
relief
selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» manual entry for details on the associated

options.

Inherited Options

LabelBitmap labelFont labelImage labelMargin

labelPos
labelText labelVariable sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the scrolled frame widget in any of the

forms acceptable to Tk_GetPixels. The default height is 100 pix- els.

Name: hscrollMode

Class: ScrollMode

Command-Line Switch: -hscrollmode

Specifies the the display mode to be used for the horizontal

scrollbar: static, dynamic, or none. In static mode, the scroll bar is displayed at all times. Dynamic mode displays the scroll bar as required, and none disables the scroll bar display. The default is static.

Name: sbWidth

Class: Width

Command-Line Switch: -sbwidth

Specifies the width of the scrollbar in any of the forms accept-

able to Tk_GetPixels. The default width is 15 pixels.

Name: scrollMargin

Class: Margin

Command-Line Switch: -scrollmargin

Specifies the distance between the frame and scrollbar in any of

the forms acceptable to Tk_GetPixels. The default is 3 pixels.

Name: vscrollMode

Class: ScrollMode

Command-Line Switch: -vscrollmode

Specifies the the display mode to be used for the vertical

scrollbar: static, dynamic, or none. In static mode, the scroll bar is displayed at all times. Dynamic mode displays the scroll bar as required, and none disables the scroll bar display. The default is static.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the scrolled frame widget in any of the

forms acceptable to Tk_GetPixels. The default height is 100 pix- els.
_________________________________________________________________

Description

The scrolledframe combines the functionallity of scrolling with

that of a typical frame widget to implement a clipable viewing area whose visible region may be modified with the scroll bars.

This enables the contruction of visually larger areas than which

could normally be displayed, containing a heterogenous mix of other widgets. Options exist which allow full control over which scrollbars are displayed and the method, i.e. statically or dynamically. The frame itself may be accessed by the childsite method and then filled with other widget combinations.

Methods

The iwidgets::scrolledframe command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for scrolledframe widgets:

Associated Methods

xview
yview

See the «canvas» manual entry for details on the associated meth-

ods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::scrolledframe command.
pathName childsite

Return the path name of the child site.

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::scrolledframe command. pathName justify direction

Justifies the frame contents via the scroll bars in one of four

directions: left, right, top, or bottom.

Components

Name: horizsb

Class: Scrollbar

The horizsb component is the horizontal scroll bar. See the

«ScrollBar» widget manual entry for details on the horizsb compo- nent item.

Name: vertsb

Class: Scrollbar

The vertsb component is the vertical scroll bar. See the

«ScrollBar» widget manual entry for details on the vertsb compo- nent item.

Example

package require Iwidgets 4.0
iwidgets::scrolledframe .sf -width 150 -height 180 \ -labelon yes -labeltext scrolledframe

set cs [.sf childsite]
pack [button $cs.b1 -text Hello] -pady 10
pack [button $cs.b2 -text World] -pady 10
pack [button $cs.b3 -text «This is a test"] -pady 10 pack [button $cs.b4 -text «This is a really big button"] -pady 10 pack [button $cs.b5 -text «This is another really big button"] -pady 10 pack [button $cs.b6 -text «This is the last really big button"] -pady 10

pack .sf -expand yes -fill both -padx 10 -pady 10

Author

Mark L. Ulferts

Sue Yockey

Keywords

scrolledframe, frame, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "scrollbar" manual entry for details on the associated
  • Inherited Options
  • LabelBitmap labelFont labelImage labelMargin
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the scrolled frame widget in any of the
  • Name: hscrollMode
  • Class: ScrollMode
  • Command-Line Switch: -hscrollmode
  • Specifies the the display mode to be used for the horizontal
  • Name: sbWidth
  • Class: Width
  • Command-Line Switch: -sbwidth
  • Specifies the width of the scrollbar in any of the forms accept-
  • Name: scrollMargin
  • Class: Margin
  • Command-Line Switch: -scrollmargin
  • Specifies the distance between the frame and scrollbar in any of
  • Name: vscrollMode
  • Class: ScrollMode
  • Command-Line Switch: -vscrollmode
  • Specifies the the display mode to be used for the vertical
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the scrolled frame widget in any of the
  • Description
  • The scrolledframe combines the functionallity of scrolling with
  • This enables the contruction of visually larger areas than which
  • Methods
  • The iwidgets::scrolledframe command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for scrolledframe widgets:
  • Associated Methods
  • See the "canvas" manual entry for details on the associated meth-
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Return the path name of the child site.
  • Query or modify the configuration options of the widget. If no
  • Justifies the frame contents via the scroll bars in one of four
  • Components
  • Name: horizsb
  • Class: Scrollbar
  • The horizsb component is the horizontal scroll bar. See the
  • Name: vertsb
  • Class: Scrollbar
  • The vertsb component is the vertical scroll bar. See the
  • Example
  • Author
  • Mark L. Ulferts
  • Sue Yockey
  • Keywords


IWidgets scrolledhtml

 Table of Contents

iwidgets::scrolledhtml - Create and manipulate a scrolled text widget with the capability of displaying HTML formatted docu- ments.

Synopsis

iwidgets::scrolledhtml pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Scrolledtext <- iwidgets::Scrolledhtml

Standard Options

activeBackground background borderWidth cursor exportSelection foreground highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth padX padY relief

repeatDelay
repeatInterval selectBackground selectBorderWidth selectForeground setGrid

See the «options» manual entry for details on the standard

options.

Associated Options

activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget manual entry for details on the above

associated options.
spacing1 spacing2 spacing3 state wrap

See the «text» widget manual entry for details on the above asso-

ciated options.

Inherited Options

labelBitmap labelFont labelImage labelMargin

labelPos
labelText labelVariable height hscrollMode sbWidth scrollMargin visibleitems
vscrollMode
width

See the «scrolledtext» class manual entry for details on the

inherited options.
sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: feedback

Class: FeedBack

Command-Line Switch: -feedback

Specifies the callback command to use to give feedback on current

status. The command is executed in the form command <number of characters remaining>

Name: fixedfont

Class: FixedFont

Command-Line Switch: -fixedfont

Specifies the name of the font to be used for fixed-width charac-

ter text (such as <pre>...</pre> or <tt>...</tt>.) The size, style, and other font attributes are determined by the format tags in the document. The default is courier.

Name: fontname

Class: FontName

Command-Line Switch: -fontname

Specifies the name of the font to be used for normal-width char-

acter spaced text. The size, style, and other font attributes are determined by the format tags in the document. The default is times.

Name: fontsize

Class: FontSize

Command-Line Switch: -fontsize

Specifies the general size of the fonts used. One of small,

medium, large, or huge. The default is medium.

Name: foreground

Class: Foreground

Command-Line Switch: -foreground

Specifies the color of text other than hypertext links, in any of

the forms acceptable to Tk_GetColor. This value may be overridden in a particular document by the text attribute of the Body HTML tag.

Name: link

Class: Link

Command-Line Switch: -link

Specifies the default color of hypertext links in any of the

forms acceptable to Tk_GetColor. This value may be overridden in a particular document by the link attribute of the Body HTML tag.

The default is blue.

Name: linkcommand

Class: LinkCommand

Command-Line Switch: -linkcommand

Specifies the command to execute when the user clicks on a hyper-

text link. Execution is of the form linkcommand href, where href is the value given in the href attribute of the A HTML tag.

Name: alink

Class: alink

Command-Line Switch: -alink

Specifies the color of hypertext links when the cursor is over

the link in any of the forms acceptable to Tk_GetColor. The default is red.

Name: textBackground

Class: Background

Command-Line Switch: -textbackground

Specifies the background color for the text area in any of the

forms acceptable to Tk_GetColor. This value may be overridden in a particular document by the bgcolor attribute of the Body HTML tag.

Name: unknownimage

Class: UnknownImage

Command-Line Switch: -unknownimage

Specifies the name of the image file to display when an img spec-

ified in the html document cannot be loaded.

Name: update

Class: Update

Command-Line Switch: -alink

A boolean value indicating whether to call update during html

rendering.
_________________________________________________________________

Description

The iwidgets::scrolledhtml command creates a scrolled text widget

with the additional capability to display html formatted docu- ments. An import method is provided to read an html document file, and a render method is provided to display a html formatted text string.

Methods

The iwidgets::scrolledhtml command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for scrolledhtml widgets:

Associated Methods

bbox
compare debug delete dlineinfo get index insert mark scan search see
tag
window xview yview

See the «text» manual entry for details on the standard methods.

Inherited Methods

export
clear

See the «scrolledhtml» manual entry for details on the inherited

methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::scrolledhtml command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::scrolledhtml command. pathName import ?option? href

Load html formatted text from a file. Href must exist. If

option is -link, href is assumed to be relative to the applica- tion's current working directory. Otherwise, href is assumed to be relative to the path of the last page loaded. Href is either a filename, or a reference of the form filename#anchorname. In the latter form, fIFilename and/or anchorname may be empty. If file- name is empty, the current document is assumed. If anchorname is empty, the top of the document is assumed.
pathName pwd

Print the current working directory of the widget, i.e. the

directory of the last page loaded.
pathName render htmltext ?wd?

Display HTML formatted text htmltext. Wd gives the base path to

use for all links and images in the document. Wd defaults to the application's current working directory.
pathName title

Return the title of the current page, as given in the

<title>...</title> field in the document.

HTML Compliance

This widget is compliant with HTML 3.2 with the following excep-

tions:

No features requiring a connection to an http server are sup-

ported.

Some image alignments aren't supported, because they are not sup-

ported by the text widget.

The <br> attributes dealing with image alignments aren't sup-

ported.

Automatic table sizing is not supported very well, due to limita-

tions of the text widget

Example

package require Iwidgets 4.0
option add *textBackground white

iwidgets::scrolledhtml .sh -fontname helvetica -linkcommand «this import -link"

pack .sh -padx 10 -pady 10 -fill both -expand yes

.sh import ~/public_html/index.html

Bugs

Cells in a table can be caused to overlap. ex:

<table border width="100%">
<tr><td>cell1</td><td align=right rowspan=2>cell2</td></tr> <tr><td colspan=2>cell3 w/ overlap</td>
</table> It hasn't been fixed because 1) it's a pain to fix, 2) it will slow tables down by a significant amount, and 3) netscape has the same bug, as of V3.01.

Acknowledgements

Sam Shen

This code is based largely on his tkhtml.tcl code from tk

inspect. Tkhtml is copyright 1995 Lawrence Berkeley Laboratory.

Author

Kris Raney

Keywords

scrolledhtml, html, text, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "scrollbar" widget manual entry for details on the above
  • See the "text" widget manual entry for details on the above asso-
  • Inherited Options
  • See the "scrolledtext" class manual entry for details on the
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: feedback
  • Class: FeedBack
  • Command-Line Switch: -feedback
  • Specifies the callback command to use to give feedback on current
  • Name: fixedfont
  • Class: FixedFont
  • Command-Line Switch: -fixedfont
  • Specifies the name of the font to be used for fixed-width charac-
  • Name: fontname
  • Class: FontName
  • Command-Line Switch: -fontname
  • Specifies the name of the font to be used for normal-width char-
  • Name: fontsize
  • Class: FontSize
  • Command-Line Switch: -fontsize
  • Specifies the general size of the fonts used. One of small,
  • Name: foreground
  • Class: Foreground
  • Command-Line Switch: -foreground
  • Specifies the color of text other than hypertext links, in any of
  • Name: link
  • Class: Link
  • Command-Line Switch: -link
  • Specifies the default color of hypertext links in any of the
  • The default is blue.
  • Name: linkcommand
  • Class: LinkCommand
  • Command-Line Switch: -linkcommand
  • Specifies the command to execute when the user clicks on a hyper-
  • Name: alink
  • Class: alink
  • Command-Line Switch: -alink
  • Specifies the color of hypertext links when the cursor is over
  • Name: textBackground
  • Class: Background
  • Command-Line Switch: -textbackground
  • Specifies the background color for the text area in any of the
  • Name: unknownimage
  • Class: UnknownImage
  • Command-Line Switch: -unknownimage
  • Specifies the name of the image file to display when an img spec-
  • Name: update
  • Class: Update
  • Command-Line Switch: -alink
  • A boolean value indicating whether to call update during html
  • Description
  • The iwidgets::scrolledhtml command creates a scrolled text widget
  • Methods
  • The iwidgets::scrolledhtml command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for scrolledhtml widgets:
  • Associated Methods
  • See the "text" manual entry for details on the standard methods.
  • Inherited Methods
  • See the "scrolledhtml" manual entry for details on the inherited
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Load html formatted text from a file. Href must exist. If
  • Print the current working directory of the widget, i.e. the
  • Display HTML formatted text htmltext. Wd gives the base path to
  • Return the title of the current page, as given in the
  • HTML Compliance
  • This widget is compliant with HTML 3.2 with the following excep-
  • No features requiring a connection to an http server are sup-
  • Some image alignments aren't supported, because they are not sup-
  • The
    attributes dealing with image alignments aren't sup-
  • Automatic table sizing is not supported very well, due to limita-
  • Example
  • Bugs
  • Cells in a table can be caused to overlap. ex:
  • Acknowledgements
  • Sam Shen
  • This code is based largely on his tkhtml.tcl code from tk
  • Author
  • Kris Raney
  • Keywords


IWidgets scrolledlistbox

 Table of Contents

iwidgets::scrolledlistbox - Create and manipulate scrolled list- box widgets

Synopsis

iwidgets::scrolledlistbox pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Scrolledwid- get <- iwidgets::Scrolledlistbox

Standard Options

activeBackground background borderWidth cursor exportSelection foreground highlightColor highlightThickness

relief
selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

selectMode
listvariable

See the «listbox» widget manual entry for details on the above

associated options.
activeRelief elementBorderwidth jumptroughColor

See the «scrollbar» widget manual entry for details on the above

associated options.

Inherited Options

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable
state
sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: dblClickCommand

Class: Command

Command-Line Switch: -dblclickcommand

Specifies a Tcl command procedure which is called when an item is

double clicked. Typically this occurs when mouse button 1 is double clicked over an item. Selection policy does not matter.

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the scrolled list box as an entire unit.

The value may be specified in any of the forms acceptable to

Tk_GetPixels. Any additional space needed to display the other

components such as labels, margins, and scrollbars force the listbox to be compressed. A value of zero along with the same value for the width causes the value given for the visibleitems option to be applied which administers geometry constraints in a different manner. The default height is zero.

Name: hscrollMode

Class: ScrollMode

Command-Line Switch: -hscrollmode

Specifies the the display mode to be used for the horizontal

scrollbar: static, dynamic, or none. In static mode, the scroll bar is displayed at all times. Dynamic mode displays the scroll bar as required, and none disables the scroll bar display. The default is static.

Name: sbWidth

Class: Width

Command-Line Switch: -sbwidth

Specifies the width of the scrollbar in any of the forms accept-

able to Tk_GetPixels. The default width is 15 pixels..

Name: scrollMargin

Class: Margin

Command-Line Switch: -scrollmargin

Specifies the distance between the listbox and scrollbar in any

of the forms acceptable to Tk_GetPixels. The default is 3 pix- els.

Name: selectionCommand

Class: Command

Command-Line Switch: -selectioncommand

Specifies a Tcl command procedure which is called when an item is

selected. Selection policy does not matter.

Name: state

Class: State

Command-Line Switch: -state

Specifies one of two states for the listbox: normal or disabled.

If the listbox is disabled then selection is ignored. The

default is normal.

Name: textBackground

Class: Background

Command-Line Switch -textbackground

Specifies the background color for the listbox. This allows the

background within the listbox to be different from the normal background color.

Name: textFont

Class: Font

Command-Line Switch: -textfont

Specifies the font to be used for text in the listbox. This

allows for the font associated with text internal to the scrolled listbox to be different than the font for labels.

Name: visibleitems

Class: VisibleItems

Command-Line Switch: -visibleitems

Specifies the widthxheight in characters and lines for the list-

box. This option is only administered if the width and height options are both set to zero, otherwise they take precedence.

The default value is 20x10. With the visibleitems option

engaged, geometry constraints are maintained only on the listbox.

The size of the other components such as labels, margins, and

scroll bars, are additive and independent, effecting the overall size of the scrolled list box. In contrast, should the width and height options have non zero values, they are applied to the scrolled list box as a whole. The listbox is compressed or expanded to maintain the geometry constraints.

Name: vscrollMode

Class: ScrollMode

Command-Line Switch: -vscrollmode

Specifies the the display mode to be used for the vertical

scrollbar: static, dynamic, or none. In static mode, the scroll bar is displayed at all times. Dynamic mode displays the scroll bar as required, and none disables the scroll bar display. The default is static.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the scrolled list box as an entire unit.

The value may be specified in any of the forms acceptable to

Tk_GetPixels. Any additional space needed to display the other

components such as labels, margins, and scrollbars force the listbox to be compressed. A value of zero along with the same value for the height causes the value given for the visibleitems option to be applied which administers geometry constraints in a different manner. The default width is zero. _________________________________________________________________

Description

The iwidgets::scrolledlistbox command creates a scrolled listbox

with additional options to manage horizontal and vertical scroll- bars. This includes options to control which scrollbars are dis- played and the method, i.e. statically or dynamically.

Methods

The iwidgets::scrolledlistbox command creates a new Tcl command

whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

Many of the widget commands for a scrolledlistbox take as one

argument an indicator of which entry of the list box to operate on. These indicators are called indexes and may be specified in any of the following forms:

number
Specifies the element as a numerical index, where 0 corresponds to the first element in the listbox.
active
Indicates the element that has the location cursor. This element will be displayed with an underline when the listbox has the keyboard focus, and it is specified with the activate widget command.
anchor
Indicates the anchor point for the selection, which is set with the selection anchor widget command.
end
Indicates the end of the listbox. For some commands this means just after the last element; for other commands it means the last element.
@x,y
Indicates the element that covers the point in the listbox window specified by x and y (in pixel coordinates). If no element covers that point, then the closest element to that point is used.
pattern
If the index doesn't satisfy one of the above forms then this form is used. Pattern is pattern-matched against the items in the list box, in order from the top down, until a matching entry is found. The rules of Tcl_StringMatch are used.

The following widget commands are possible for scrolledlistbox

widgets:

Associated Methods

activate bbox curselection delete

get
index insert itemconfigure nearest scan see selection
size
xview yview

See the «listbox» manual entry for details on the associated

methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::scrolledlistbox command.
pathName clear

Clears the listbox of all items.

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::scrolledlistbox command. pathName getcurselection

Returns the contents of the listbox element indicated by the cur-

rent selection indexes. Short cut version of get and curselec- tion command combination.
pathName justify direction

Justifies the list contents via teh scroll bars in one of four

directions: left, right, top, or bottom.
pathName selecteditemcount

Returns the number of items currently selected in the list.

pathName sort order

Sort the current list in either ascending or descending order.

The values increasing and decreasing are also accepted.

Components

Name: listbox

Class: listbox

The listbox component is the listbox widget. See the «listbox"

widget manual entry for details on the listbox component item.

Name: horizsb

Class: Scrollbar

The horizsb component is the horizontal scroll bar. See the

«scrollbar» widget manual entry for details on the horizsb compo- nent item.

Name: vertsb

Class: Scrollbar

The vertsb component is the vertical scroll bar. See the

«scrollbar» widget manual entry for details on the vertsb compo- nent item.

Example

package require Iwidgets 4.0
option add *textBackground white
proc selCmd {} {
puts stdout «[.slb getcurselection]"
}
proc defCmd {} {
puts stdout «Double Click"
return [selCmd]
}
iwidgets::scrolledlistbox .slb -selection single \ -vscrollmode static -hscrollmode dynamic -labeltext «List» \ -selectioncommand selCmd -dblclickcommand defCmd pack .slb -padx 10 -pady 10 -fill both -expand yes .slb insert end {Hello {Out There} World}

Author

Mark L. Ulferts

Keywords

scrolledlistbox, listbox, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "listbox" widget manual entry for details on the above
  • See the "scrollbar" widget manual entry for details on the above
  • Inherited Options
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: dblClickCommand
  • Class: Command
  • Command-Line Switch: -dblclickcommand
  • Specifies a Tcl command procedure which is called when an item is
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the scrolled list box as an entire unit.
  • The value may be specified in any of the forms acceptable to
  • Tk_GetPixels. Any additional space needed to display the other
  • Name: hscrollMode
  • Class: ScrollMode
  • Command-Line Switch: -hscrollmode
  • Specifies the the display mode to be used for the horizontal
  • Name: sbWidth
  • Class: Width
  • Command-Line Switch: -sbwidth
  • Specifies the width of the scrollbar in any of the forms accept-
  • Name: scrollMargin
  • Class: Margin
  • Command-Line Switch: -scrollmargin
  • Specifies the distance between the listbox and scrollbar in any
  • Name: selectionCommand
  • Class: Command
  • Command-Line Switch: -selectioncommand
  • Specifies a Tcl command procedure which is called when an item is
  • Name: state
  • Class: State
  • Command-Line Switch: -state
  • Specifies one of two states for the listbox: normal or disabled.
  • If the listbox is disabled then selection is ignored. The
  • Name: textBackground
  • Class: Background
  • Command-Line Switch -textbackground
  • Specifies the background color for the listbox. This allows the
  • Name: textFont
  • Class: Font
  • Command-Line Switch: -textfont
  • Specifies the font to be used for text in the listbox. This
  • Name: visibleitems
  • Class: VisibleItems
  • Command-Line Switch: -visibleitems
  • Specifies the widthxheight in characters and lines for the list-
  • The default value is 20x10. With the visibleitems option
  • The size of the other components such as labels, margins, and
  • Name: vscrollMode
  • Class: ScrollMode
  • Command-Line Switch: -vscrollmode
  • Specifies the the display mode to be used for the vertical
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the scrolled list box as an entire unit.
  • The value may be specified in any of the forms acceptable to
  • Tk_GetPixels. Any additional space needed to display the other
  • Description
  • The iwidgets::scrolledlistbox command creates a scrolled listbox
  • Methods
  • The iwidgets::scrolledlistbox command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • Many of the widget commands for a scrolledlistbox take as one
  • The following widget commands are possible for scrolledlistbox
  • Associated Methods
  • See the "listbox" manual entry for details on the associated
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Clears the listbox of all items.
  • Query or modify the configuration options of the widget. If no
  • Returns the contents of the listbox element indicated by the cur-
  • Justifies the list contents via teh scroll bars in one of four
  • Returns the number of items currently selected in the list.
  • Sort the current list in either ascending or descending order.
  • The values increasing and decreasing are also accepted.
  • Components
  • Name: listbox
  • Class: listbox
  • The listbox component is the listbox widget. See the "listbox"
  • Name: horizsb
  • Class: Scrollbar
  • The horizsb component is the horizontal scroll bar. See the
  • Name: vertsb
  • Class: Scrollbar
  • The vertsb component is the vertical scroll bar. See the
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets scrolledtext

 Table of Contents

iwidgets::scrolledtext - Create and manipulate a scrolled text widget

Synopsis

iwidgets::scrolledtext pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Scrolledwid- get <- iwidgets::Scrolledtext

Standard Options

activeBackground
background borderWidthcursor
exportSelection
foreground highlightColor
highlightThickness
insertBackground
insertBorderWidth
insertOffTime insertOnTime
insertWidth
padX padY
relief
selectBackground
selectBorderWidth
selectForeground setGrid

See the «options» manual entry for details on the standard

options.

Associated Options

activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget manual entry for details on the above

associated options.
spacing1 spacing2 spacing3 state wrap

See the «text» widget manual entry for details on the above asso-

ciated options.

Inherited Options

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable
state
sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the scrolled text as an entire unit. The

value may be specified in any of the forms acceptable to Tk_Get-

Pixels. Any additional space needed to display the other compo-

nents such as labels, margins, and scrollbars force the text to be compressed. A value of zero along with the same value for the width causes the value given for the visibleitems option to be applied which administers geometry constraints in a different manner. The default height is zero.

Name: hscrollMode

Class: ScrollMode

Command-Line Switch: -hscrollmode

Specifies the the display mode to be used for the horizontal

scrollbar: static, dynamic, or none. In static mode, the scroll bar is displayed at all times. Dynamic mode displays the scroll bar as required, and none disables the scroll bar display. The default is static.

Name: sbWidth

Class: Width

Command-Line Switch: -sbwidth

Specifies the width of the scrollbar in any of the forms accept-

able to Tk_GetPixels.

Name: scrollMargin

Class: Margin

Command-Line Switch: -scrollmargin

Specifies the distance between the text area and scrollbar in any

of the forms acceptable to Tk_GetPixels. The default is 3 pix- els.

Name: textBackground

Class: Background

Command-Line Switch: -textbackground

Specifies the background color for the text area in any of the

forms acceptable to Tk_GetColor.

Name: textFont

Class: Font

Command-Line Switch: -textfont

Specifies the font to be used in the scrolled text area.

Name: visibleitems

Class: VisibleItems

Command-Line Switch: -visibleitems

Specifies the widthxheight in characters and lines for the text.

This option is only administered if the width and height options

are both set to zero, otherwise they take precedence. The default value is 80x24. With the visibleitems option engaged, geometry constraints are maintained only on the text. The size of the other components such as labels, margins, and scroll bars, are additive and independent, effecting the overall size of the scrolled text. In contrast, should the width and height options have non zero values, they are applied to the scrolled text as a whole. The text is compressed or expanded to maintain the geome- try constraints.

Name: vscrollMode

Class: ScrollMode

Command-Line Switch: -vscrollmode

Specifies the the display mode to be used for the vertical

scrollbar: static, dynamic, or none. In static mode, the scroll bar is displayed at all times. Dynamic mode displays the scroll bar as required, and none disables the scroll bar display. The default is static.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the scrolled text as an entire unit. The

value may be specified in any of the forms acceptable to Tk_Get-

Pixels. Any additional space needed to display the other compo-

nents such as labels, margins, and scrollbars force the text to be compressed. A value of zero along with the same value for the height causes the value given for the visibleitems option to be applied which administers geometry constraints in a different manner. The default width is zero.
_________________________________________________________________

Description

The iwidgets::scrolledtext command creates a scrolled text widget

with additional options to manage the scrollbars. This includes options to control the method in which the scrollbars are dis- played, i.e. statically or dynamically. Options also exist for adding a label to the scrolled text area and controlling its position. Import/export of methods are provided for file I/O.

Methods

The iwidgets::scrolledtext command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for scrolledtext widgets:

Associated Methods

bbox
compare debug delete dlineinfo get image index insert mark scan search
see
tag window xview yview

See the «text» manual entry for details on the standard methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::scrolledtext command.
pathName childsite

Returns the child site widget path name.

pathName clear

Clear the text area of all characters.

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::scrolledtext command. pathName import filename ?index?

Load the text from a file into the text area at the index. The

filename must exist.
pathName export filename

Write text to a file. If filename exists then contents are

replaced with text widget contents.

Components

Name: text

Class: Text

The text component is the text widget. See the «text» widget

manual entry for details on the text component item.

Name: horizsb

Class: Scrollbar

The horizsb component is the horizontal scroll bar. See the

«scrollbar» widget manual entry for details on the horizsb compo- nent item.

Name: vertsb

Class: Scrollbar

The vertsb component is the vertical scroll bar. See the

«scrollbar» widget manual entry for details on the vertsb compo- nent item.

Example

package require Iwidgets 4.0
option add *textBackground white

iwidgets::scrolledtext .st -hscrollmode dynamic -labeltext «Password File"

pack .st -padx 10 -pady 10 -fill both -expand yes

.st import /etc/passwd

Author

Mark L. Ulferts

Keywords

scrolledtext, text, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "scrollbar" widget manual entry for details on the above
  • See the "text" widget manual entry for details on the above asso-
  • Inherited Options
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the scrolled text as an entire unit. The
  • Pixels. Any additional space needed to display the other compo-
  • Name: hscrollMode
  • Class: ScrollMode
  • Command-Line Switch: -hscrollmode
  • Specifies the the display mode to be used for the horizontal
  • Name: sbWidth
  • Class: Width
  • Command-Line Switch: -sbwidth
  • Specifies the width of the scrollbar in any of the forms accept-
  • Name: scrollMargin
  • Class: Margin
  • Command-Line Switch: -scrollmargin
  • Specifies the distance between the text area and scrollbar in any
  • Name: textBackground
  • Class: Background
  • Command-Line Switch: -textbackground
  • Specifies the background color for the text area in any of the
  • Name: textFont
  • Class: Font
  • Command-Line Switch: -textfont
  • Specifies the font to be used in the scrolled text area.
  • Name: visibleitems
  • Class: VisibleItems
  • Command-Line Switch: -visibleitems
  • Specifies the widthxheight in characters and lines for the text.
  • This option is only administered if the width and height options
  • Name: vscrollMode
  • Class: ScrollMode
  • Command-Line Switch: -vscrollmode
  • Specifies the the display mode to be used for the vertical
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the scrolled text as an entire unit. The
  • Pixels. Any additional space needed to display the other compo-
  • Description
  • The iwidgets::scrolledtext command creates a scrolled text widget
  • Methods
  • The iwidgets::scrolledtext command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for scrolledtext widgets:
  • Associated Methods
  • See the "text" manual entry for details on the standard methods.
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Returns the child site widget path name.
  • Clear the text area of all characters.
  • Query or modify the configuration options of the widget. If no
  • Load the text from a file into the text area at the index. The
  • Write text to a file. If filename exists then contents are
  • Components
  • Name: text
  • Class: Text
  • The text component is the text widget. See the "text" widget
  • Name: horizsb
  • Class: Scrollbar
  • The horizsb component is the horizontal scroll bar. See the
  • Name: vertsb
  • Class: Scrollbar
  • The vertsb component is the vertical scroll bar. See the
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets selectionbox

 Table of Contents

iwidgets::selectionbox - Create and manipulate a selection box widget

Synopsis

iwidgets::selectionbox pathName ?options?

Inheritance

itk::Widget <- iwidgets::Selectionbox

Standard Options

activeBackground background borderWidth cursor exportSelection foreground highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth relief repeatDelay repeatInterval selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

textBackground textFont

See the «entryfield» widget class manual entry for details on the

above associated options.

labelFont
labelMargin

See the «labeledwidget» class manual entry for details on the

above associated options.
activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget class manual entry for details on the

above associated options.
dblClickCommand hscrollMode sbWidth scrollMargin textBackground textFont vscrollMode

See the «scrolledlistbox» widget class manual entry for details

on the above associated options.

Widget-specific Options

Name: childSitePos

Class: Position

Command-Line Switch: -childsitepos

Specifies the position of the child site in the selection box: n,

s, e, w, or . The default is center

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the selection box. The value may be

specified in any of the forms acceptable to Tk_GetPixels. The default is 320 pixels.

Name: itemsCommand

Class: Command

Command-Line Switch: -itemscommand

Specifies a command to be evaluated following selection of an

item.

Name: itemsLabel

Class: Text

Command-Line Switch: -itemslabel

Specifies the text of the label for the items list. The default

is «List".

Name: itemsLabelPos

Class: Position

Command-Line Switch: -itemslabelpos

Specifies the position of the label along the side of the items

list: n, ne, e, se, s, sw, w, or nw. The default is nw.

Name: itemsOn

Class: ItemsOn

Command-Line Switch: -itemson

Specifies whether or not to display the items list in any of the

forms acceptable to Tcl_GetBoolean. The default is true.

Name: margin

Class: Margin

Command-Line Switch: -margin

Specifies distance between the items list and selection entry in

any of the forms acceptable to Tk_GetPixels. The default is 7 pixels.

Name: selectionCommand

Class: Command

Command-Line Switch: -selectioncommand

Specifies a Tcl procedure to be associated with a return key

press event in the selection entry field.

Name: selectionLabel

Class: Text

Command-Line Switch: -selectionlabel

Specifies the text of the label for the selection entry field.

The default is «Selection".

Name: selectionLabelPos

Class: Position

Command-Line Switch: -selectionlabelpos

Specifies the position of the label along the side of the selec-

tion: n, ne, e, se, s, sw, w, or nw. The default is nw.

Name: selectionOn

Class: SelectionOn

Command-Line Switch: -selectionon

Specifies whether or not to display the selection entry in any of

the forms acceptable to Tcl_GetBoolean. The default is true.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the selection box. The value may be spec-

ified in any of the forms acceptable to Tk_GetPixels. The default is 260 pixels.
_________________________________________________________________

Description

The iwidgets::selectionbox command creates a scrolled list of

items and a selection entry field. The user may choose any of the items displayed in the scrolled list of alternatives and the selection field will be filled with the choice. The user is also free to enter a new value in the selection entry field. Both the list and entry areas have labels. A child site is also provided in which the user may create other widgets to be used in conjunc- tion with the selection box.

Methods

The iwidgets::selectionbox command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

Associated Methods

curselection delete index nearest

scan
selection size

See the «listbox» widget class manual entry for details on the

associated methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::selectionbox command.
pathName childsite

Returns the child site widget path name.

pathName clear component

Delete the contents of either the selection entry widget or items

list. The component argument may be either items or selection. pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::selectionbox command. pathName get

Returns the current value of the selection entry widget.

pathName insert component args

Insert element(s) into either the selection entry widget or items

list. The component argument may be either items or selection.

The args follow the rules of either an entry or list widget

depending on the component value.
pathName selectitem

Replace the selection entry field contents with the currently

selected items value.

Components

Name: childsite

Class: Frame

The childsite component is the user child site for the selection

box. See the «frame» widget manual entry for details on the childsite component item.

Name: items

Class: Scrolledlistbox

The items component provides the scrolled list box of items for

the selection box. See the «scrolledlistbox» widget manual entry for details on the items component item.

Name: selection

Class: Entryfield

The selection component provides the entry field in the selection

box for display of the selected item in the items component. See the «entryfield» widget manual entry for details on the selection component item.

Example

package require Iwidgets 4.0
option add *textBackground white

iwidgets::selectionbox .sb -items {Hello {Out There} World} pack .sb -padx 10 -pady 10 -fill both -expand yes

set cs [label [.sb childsite].label -text «Child Site"] pack $cs -fill x -padx 10 -pady 10

.sb insert items 2 {Cruel Cruel}

.sb selection set 1

Author

Mark L. Ulferts

Keywords

selectionbox, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "entryfield" widget class manual entry for details on the
  • See the "labeledwidget" class manual entry for details on the
  • See the "scrollbar" widget class manual entry for details on the
  • See the "scrolledlistbox" widget class manual entry for details
  • Widget-specific Options
  • Name: childSitePos
  • Class: Position
  • Command-Line Switch: -childsitepos
  • Specifies the position of the child site in the selection box: n,
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the selection box. The value may be
  • Name: itemsCommand
  • Class: Command
  • Command-Line Switch: -itemscommand
  • Specifies a command to be evaluated following selection of an
  • Name: itemsLabel
  • Class: Text
  • Command-Line Switch: -itemslabel
  • Specifies the text of the label for the items list. The default
  • Name: itemsLabelPos
  • Class: Position
  • Command-Line Switch: -itemslabelpos
  • Specifies the position of the label along the side of the items
  • Name: itemsOn
  • Class: ItemsOn
  • Command-Line Switch: -itemson
  • Specifies whether or not to display the items list in any of the
  • Name: margin
  • Class: Margin
  • Command-Line Switch: -margin
  • Specifies distance between the items list and selection entry in
  • Name: selectionCommand
  • Class: Command
  • Command-Line Switch: -selectioncommand
  • Specifies a Tcl procedure to be associated with a return key
  • Name: selectionLabel
  • Class: Text
  • Command-Line Switch: -selectionlabel
  • Specifies the text of the label for the selection entry field.
  • The default is "Selection".
  • Name: selectionLabelPos
  • Class: Position
  • Command-Line Switch: -selectionlabelpos
  • Specifies the position of the label along the side of the selec-
  • Name: selectionOn
  • Class: SelectionOn
  • Command-Line Switch: -selectionon
  • Specifies whether or not to display the selection entry in any of
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the selection box. The value may be spec-
  • Description
  • The iwidgets::selectionbox command creates a scrolled list of
  • Methods
  • The iwidgets::selectionbox command creates a new Tcl command
  • Option and the args determine the exact behavior of the command.
  • Associated Methods
  • See the "listbox" widget class manual entry for details on the
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Returns the child site widget path name.
  • Delete the contents of either the selection entry widget or items
  • Query or modify the configuration options of the widget. If no
  • Returns the current value of the selection entry widget.
  • Insert element(s) into either the selection entry widget or items
  • The args follow the rules of either an entry or list widget
  • Replace the selection entry field contents with the currently
  • Components
  • Name: childsite
  • Class: Frame
  • The childsite component is the user child site for the selection
  • Name: items
  • Class: Scrolledlistbox
  • The items component provides the scrolled list box of items for
  • Name: selection
  • Class: Entryfield
  • The selection component provides the entry field in the selection
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets selectiondialog

 Table of Contents

iwidgets::selectiondialog - Create and manipulate a selection dialog widget

Synopsis

iwidgets::selectiondialog pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Shell <- iwidgets::Dialogshell <- iwidgets::Dialog <- iwidgets::Selectiondialog

Standard Options

activeBackground background borderWidth cursor exportSelection foreground highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime

insertWidth
selectBackground selectBorderWidth selectForeground

See the «options» manual entry for details on the standard

options.

Associated Options

textBackground textFont

See the «entryfield» widget manual entry for details on the above

associated options.
labelFont

See the «labeledwidget» widget manual entry for details on the

above associated options.
activeRelief elementBorderWidth jumptroughColor

See the «scrollbar» widget class manual entry for details on the

above associated options.
textBackground textFont

See the «scrolledlistbox» widget class manual entry for details

on the above associated options. childsitepos itemsCommand itemsLabel itemsOn

selectionCommand
selectionLabel selectionOn

See the «selectionbox» widget manual entry for details on the

above associated options.

Inherited Options

buttonBoxPadX buttonBoxPadY buttonBoxPos padX

padY
separator thickness

See the «dialogshell» widget manual entry for details on the

above inherited options.
height master modality width

See the «shell» widget manual entry for details on the above

inherited options.
title

See the «Toplevel» widget manual entry for details on the above

inherited options.
_________________________________________________________________

Description

The iwidgets::selectiondialog command creates a selection box

similar to the OSF/Motif standard selection dialog composite wid- get. The selectiondialog is derived from the Dialog class and is composed of a selectionbox with commands to manipulate the dialog buttons.

Methods

The iwidgets::selectiondialog command creates a new Tcl command

whose name is pathName. This command may be used to invoke vari- ous operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Associated Methods

childsite clear get insert selectitem

See the «selectionbox» widget manual entry for details on the

above associated methods.
curselection delete index nearest

scan
selection size

See the «listbox» widget manual entry for details on the above

associated methods.

Inherited Methods

add buttonconfigure defaulthide

invoke
show

See the «buttonbox» widget manual entry for details on the above

inherited methods.
activate center deactivate

See the «shell» widget manual entry for details on the above

inherited methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::selectiondialog command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::selectiondialog command.

Components

Name: selectionbox

Class: Selectionbox

The selectionbox component is the selection box for the selection

dialog. See the «selectionbox» widget manual entry for details on the selectionbox component item.

Example

package require Iwidgets 4.0
iwidgets::selectiondialog .sd
.sd activate

Author

Mark L. Ulferts

Keywords

selectiondialog, selectionbox, dialog, dialogshell, shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "entryfield" widget manual entry for details on the above
  • See the "labeledwidget" widget manual entry for details on the
  • See the "scrollbar" widget class manual entry for details on the
  • See the "scrolledlistbox" widget class manual entry for details
  • See the "selectionbox" widget manual entry for details on the
  • Inherited Options
  • See the "dialogshell" widget manual entry for details on the
  • See the "shell" widget manual entry for details on the above
  • See the "Toplevel" widget manual entry for details on the above
  • Description
  • The iwidgets::selectiondialog command creates a selection box
  • Methods
  • The iwidgets::selectiondialog command creates a new Tcl command
  • Associated Methods
  • See the "selectionbox" widget manual entry for details on the
  • See the "listbox" widget manual entry for details on the above
  • Inherited Methods
  • See the "buttonbox" widget manual entry for details on the above
  • See the "shell" widget manual entry for details on the above
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: selectionbox
  • Class: Selectionbox
  • The selectionbox component is the selection box for the selection
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets shell

 Table of Contents

iwidgets::shell - Create and manipulate a shell widget

Synopsis

iwidgets::shell pathName ?options?

Inheritance

itk::Toplevel <- iwidgets::Shell

Standard Options

background cursor foreground

See the «options» manual entry for details on the standard

options.

Inherited Options

title

See the «Toplevel» manual entry for details on the above inher-

ited options.

Widget-specific Options

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the shell. The value may be specified in

any of the forms acceptable to Tk_GetPixels. A value of zero causes the height to be adjusted to the required value based on the size requests of the components placed in the childsite.

Otherwise, the height is fixed. The default is zero. NOTE: This

may cause some amount of flickering on slower machines. To pre- vent it simply set the width and height to a appropriate value.

Name: master

Class: Window

Command-Line Switch: -master

Defines the shell as being a transient window with the master

window given by the master option. The master window should be either another existing toplevel window or {} for no master. The default is {} for shells and «.» for dialogs.

Name: modality

Class: Modality

Command-Line Switch: -modality

Allows the shell to grab control of the screen in one of three

different ways: application, system, or none. Application modal prevents any other toplevel windows within the application which are direct children of `.' from gaining focus. System modal locks the screen and prevents all windows from gaining focus regardless of application. A modality of none performs no grabs at all. The default is none.

Name: padX

Class: Pad

Command-Line Switch: -padx

Specifies a padding distance for the childsite in the X-direction

in any of the forms acceptable to Tk_GetPixels. The default is 10.

Name: padY

Class: Pad

Command-Line Switch: -pady

Specifies a padding distance for the childsite in the Y-direction

in any of the forms acceptable to Tk_GetPixels. The default is 10.

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the shell. The value may be specified in

any of the forms acceptable to Tk_GetPixels. A value of zero causes the width to be adjusted to the required value based on the size requests of the components placed in the childsite.

Otherwise, the width is fixed. The default is zero. NOTE: This

may cause some amount of flickering on slower machines. To pre- vent it simply set the width and height to a appropriate value. _________________________________________________________________

Description

The iwidgets::shell command creates a shell which is a top level

widget which supports modal operation.

Methods

The iwidgets::shell command create a new Tcl command whose name

is pathName. This command may be used to invoke various opera- tions on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for shell widgets:

Widget-specific Methods

pathName activate

Display the shell and wait based on the modality. For applica-

tion and system modal activations, perform a grab operation, and wait for the result. The result may be returned via an argument to the deactivate method.
pathName center ?widget?

Centers the shell with respect to another widget. The widget

argument is optional. If provided, it should be the path of another widget with to center upon. If absent, then the shell will be centered on the screen as a whole. pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::shell command.
pathName childsite

Returns the pathname of the child site widget.

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::shell command. pathName deactivate ?arg?

Deactivate the display of the shell. The method takes an

optional argument to be passed to the activate method which returns the value. The optional argument is only effective for application and system modal dialogs.

Components

Name: shellchildsite

Class: frame

The shellchildsite component is the user child site for the

shell. See the «frame» widget manual entry for details on the shellchildsite component item.

Example

package require Iwidgets 4.0
iwidgets::shell .sh -modality application -padx 20 -pady 20 -title Shell

pack [label [.sh childsite].l -text SHELL]

.sh center
.sh activate

Author

Mark L. Ulferts

Kris Raney

Keywords

shell, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "Toplevel" manual entry for details on the above inher-
  • Widget-specific Options
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the shell. The value may be specified in
  • Otherwise, the height is fixed. The default is zero. NOTE: This
  • Name: master
  • Class: Window
  • Command-Line Switch: -master
  • Defines the shell as being a transient window with the master
  • Name: modality
  • Class: Modality
  • Command-Line Switch: -modality
  • Allows the shell to grab control of the screen in one of three
  • Name: padX
  • Class: Pad
  • Command-Line Switch: -padx
  • Specifies a padding distance for the childsite in the X-direction
  • Name: padY
  • Class: Pad
  • Command-Line Switch: -pady
  • Specifies a padding distance for the childsite in the Y-direction
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the shell. The value may be specified in
  • Otherwise, the width is fixed. The default is zero. NOTE: This
  • Description
  • The iwidgets::shell command creates a shell which is a top level
  • Methods
  • The iwidgets::shell command create a new Tcl command whose name
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for shell widgets:
  • Widget-specific Methods
  • Display the shell and wait based on the modality. For applica-
  • Centers the shell with respect to another widget. The widget
  • Returns the current value of the configuration option given by
  • Returns the pathname of the child site widget.
  • Query or modify the configuration options of the widget. If no
  • Deactivate the display of the shell. The method takes an
  • Components
  • Name: shellchildsite
  • Class: frame
  • The shellchildsite component is the user child site for the
  • Example
  • Author
  • Mark L. Ulferts
  • Kris Raney
  • Keywords


IWidgets spindate

 Table of Contents

iwidgets::spindate - Create and manipulate time spinner widgets

Synopsis

iwidgets::spindate pathName ?options?

Inheritance

itk::Widget <- iwidgets::Spindate

Standard Options

background cursor foreground relief

See the «options» manual entry for details on the standard

options.

Associated Options

textBackground textFont

See the «entryfield» manual entry for details on the above asso-

ciated options.

labelFont
labelMargin

See the «labeledwidget» manual entry for details on the above

associated options.
arrowOrient repeatDelay repeatInterval

See the «spinner» manual entry for details on the above associ-

ated options.

Widget-specific Options

Name: dateMargin

Class: Margin

Command-Line Switch: -datemargin

Specifies the margin space between the month, day, and year spin-

ners is any of the forms accpetable to Tcl_GetPixels. The default is 1 pixel.

Name: dayLabel

Class: Text

Command-Line Switch: -daylabel

Specifies the text of the label for the day spinner. The default

is «Day".

Name: dayOn

Class: dayOn

Command-Line Switch: -dayon

Specifies whether or not to display the day spinner in any of the

forms acceptable to Tcl_GetBoolean. The default is true.

Name: dayWidth

Class: Width

Command-Line Switch: -daywidth

Specifies the width of the day spinner in any of the forms

acceptable to Tcl_GetPixels. The default is 3 pixels.

Name: labelPos

Class: Position

Command-Line Switch: -labelpos

Specifies the position of the label along the sides of the vari-

ous spinners: n, e, s, or w. The default is w.

Name: monthFormat

Class: MonthFormat

Command-Line Switch: -monthformat

Specifies the format of month display, integer (1-12) or brief

strings (Jan - Dec), or full strings (January - December).

Name: monthLabel

Class: Text

Command-Line Switch: -monthlabel

Specifies the text of the label for the month spinner. The

default is «Month".

Name: monthOn

Class: monthOn

Command-Line Switch: -monthon

Specifies whether or not to display the month spinner in any of

the forms acceptable to Tcl_GetBoolean. The default is true.

Name: monthWidth

Class: Width

Command-Line Switch: -monthwidth

Specifies the width of the month spinner in any of the forms

acceptable to Tcl_GetPixels. The default is 3 pixels.

Name: orient

Class: Orient

Command-Line Switch: -orient

Specifies the orientation of the month, day, and year spinners:

vertical or horizontal. The default is horizontal.

Name: yearDigits

Class: YearDigits

Command-Line Switch: -yeardigits

Specifies the number of digits to be displayed as the value for

the year spinner. The valid values are 2 and 4. The default is 2.

Name: yearLabel

Class: Text

Command-Line Switch: -yearlabel

Specifies the text of the label for the year spinner. The

default is «Year"

Name: yearOn

Class: yearOn

Command-Line Switch: -yearon

Specifies whether or not to display the year spinner in any of

the forms acceptable to Tcl_GetBoolean. The default is true.

Name: yearWidth

Class: Width

Command-Line Switch: -yearwidth

Specifies the width of the year spinner in any of the forms

acceptable to Tcl_GetPixels. The default is 3 pixels. _________________________________________________________________

Description

The iwidgets::spindate command creates a set of spinners for use

in date value entry. The set includes an month, day, and year spinner widget.

Methods

The iwidgets::spindate command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for spindate widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::spindate command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::spindate command. pathName get ?format?

Returns the current contents of the spindate widget in a format

of string or as an integer clock value using the -string and -clicks format options respectively. The default is by string.

Reference the clock command for more information on obtaining

dates and their formats.
pathName show date

Changes the currently displayed date to be that of the date argu-

ment. The date may be specified either as a string, an integer clock value or the keyword «now". Reference the clock command for more information on obtaining dates and their formats.

Components

Name: month

Class: Spinner

The month spinner component is the month spinner of the date

spinner. See the Spinner widget manual entry for details on the month component item.

Name: day

Class: Spinint

The day spinner component is the day spinner of the date spinner.

See the SpinInt widget manual entry for details on the day compo-

nent item.

Name: year

Class: Spinint

The year spinner component is the year spinner of the date spin-

ner. See the SpinInt widget manual entry fordetails on the year component item.

Example

package require Iwidgets 4.0
iwidgets::spindate .sd
pack .sd -padx 10 -pady 10

Author

Sue Yockey

Mark L. Ulferts

Keywords

spindate, spinint, spinner, entryfield, entry, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "entryfield" manual entry for details on the above asso-
  • See the "labeledwidget" manual entry for details on the above
  • See the "spinner" manual entry for details on the above associ-
  • Widget-specific Options
  • Name: dateMargin
  • Class: Margin
  • Command-Line Switch: -datemargin
  • Specifies the margin space between the month, day, and year spin-
  • Name: dayLabel
  • Class: Text
  • Command-Line Switch: -daylabel
  • Specifies the text of the label for the day spinner. The default
  • Name: dayOn
  • Class: dayOn
  • Command-Line Switch: -dayon
  • Specifies whether or not to display the day spinner in any of the
  • Name: dayWidth
  • Class: Width
  • Command-Line Switch: -daywidth
  • Specifies the width of the day spinner in any of the forms
  • Name: labelPos
  • Class: Position
  • Command-Line Switch: -labelpos
  • Specifies the position of the label along the sides of the vari-
  • Name: monthFormat
  • Class: MonthFormat
  • Command-Line Switch: -monthformat
  • Specifies the format of month display, integer (1-12) or brief
  • Name: monthLabel
  • Class: Text
  • Command-Line Switch: -monthlabel
  • Specifies the text of the label for the month spinner. The
  • Name: monthOn
  • Class: monthOn
  • Command-Line Switch: -monthon
  • Specifies whether or not to display the month spinner in any of
  • Name: monthWidth
  • Class: Width
  • Command-Line Switch: -monthwidth
  • Specifies the width of the month spinner in any of the forms
  • Name: orient
  • Class: Orient
  • Command-Line Switch: -orient
  • Specifies the orientation of the month, day, and year spinners:
  • Name: yearDigits
  • Class: YearDigits
  • Command-Line Switch: -yeardigits
  • Specifies the number of digits to be displayed as the value for
  • Name: yearLabel
  • Class: Text
  • Command-Line Switch: -yearlabel
  • Specifies the text of the label for the year spinner. The
  • Name: yearOn
  • Class: yearOn
  • Command-Line Switch: -yearon
  • Specifies whether or not to display the year spinner in any of
  • Name: yearWidth
  • Class: Width
  • Command-Line Switch: -yearwidth
  • Specifies the width of the year spinner in any of the forms
  • Description
  • The iwidgets::spindate command creates a set of spinners for use
  • Methods
  • The iwidgets::spindate command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for spindate widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Returns the current contents of the spindate widget in a format
  • Reference the clock command for more information on obtaining
  • Changes the currently displayed date to be that of the date argu-
  • Components
  • Name: month
  • Class: Spinner
  • The month spinner component is the month spinner of the date
  • Name: day
  • Class: Spinint
  • The day spinner component is the day spinner of the date spinner.
  • See the SpinInt widget manual entry for details on the day compo-
  • Name: year
  • Class: Spinint
  • The year spinner component is the year spinner of the date spin-
  • Example
  • Author
  • Sue Yockey
  • Mark L. Ulferts
  • Keywords


IWidgets spinint

 Table of Contents

iwidgets::spinint - Create and manipulate a integer spinner wid- get

Synopsis

iwidgets::spinint pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Spinner <- iwidgets::Spinint

Standard Options

background borderWidth cursor exportSelection

foreground
highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth
justify
relief selectBackground selectBorderWidth selectForeground textVariable

See the «options» manual entry for details on the standard

options.

Associated Options

show
state

See the «entry» manual entry for details on the associated

options.

Inherited Options

command
childSitePos fixed focusCommand
invalid
textBackground textFont validate width

See the «entryfield» widget manual entry for details on the above

inherited options.

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable
state
sticky

See the «labeledwidget» widget manual entry for details on the

above inherited options.
arroworient decrement increment repeatDelay repeatInterval

See the «spinner» widget manual entry for details on the above

inherited options.

Widget-specific Options

Name: range

Class: Range

Command-Line Switch: -range

Specifies a two element list of minimum and maximum integer val-

ues. The default is no range, {{} {}}.

Name: step

Class: Step

Command-Line Switch: -step

Specifies the increment/decrement value. The default is 1.

Name: wrap

Class: Wrap

Command-Line Switch: -wrap

Specifies whether to wrap the spinner value upon reaching the

minimum or maximum value in any of the forms acceptable to

Tcl_GetBoolean. The default is true.

_________________________________________________________________

Description

The iwidgets::spinint command creates a spinint widget. The

spinint allows «spinning» of integer values within a specified range with wrap support. The spinner arrows may be drawn hori- zontally or vertically.

Methods

The iwidgets::spinint command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for spinint widgets:

Associated Methods

delete get icursor index insert peek scan selection xview

See the «entry» manual entry for details on the associated meth-

ods.

Inherited Methods

childsite
clear

See the «entryfield» manual entry for details on the associated

methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::spinint command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::spinint command. pathName down

Decrement the spinner value by the value given in the step

option.
pathName up

Increment the spinner value by the value given in the step

option.

Components

See the «Spinner» widget manual entry for details on the integer

spinner component items.

Example

package require Iwidgets 4.0
option add *textBackground white

iwidgets::spinint .si -labeltext «Temperature» -labelpos w \ -fixed yes -width 5 -range {32 212}

pack .si -pady 10

Author

Sue Yockey

Keywords

spinint, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "entry" manual entry for details on the associated
  • Inherited Options
  • See the "entryfield" widget manual entry for details on the above
  • See the "labeledwidget" widget manual entry for details on the
  • See the "spinner" widget manual entry for details on the above
  • Widget-specific Options
  • Name: range
  • Class: Range
  • Command-Line Switch: -range
  • Specifies a two element list of minimum and maximum integer val-
  • Name: step
  • Class: Step
  • Command-Line Switch: -step
  • Specifies the increment/decrement value. The default is 1.
  • Name: wrap
  • Class: Wrap
  • Command-Line Switch: -wrap
  • Specifies whether to wrap the spinner value upon reaching the
  • Tcl_GetBoolean. The default is true.
  • Description
  • The iwidgets::spinint command creates a spinint widget. The
  • Methods
  • The iwidgets::spinint command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for spinint widgets:
  • Associated Methods
  • See the "entry" manual entry for details on the associated meth-
  • Inherited Methods
  • See the "entryfield" manual entry for details on the associated
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Decrement the spinner value by the value given in the step
  • Increment the spinner value by the value given in the step
  • Components
  • See the "Spinner" widget manual entry for details on the integer
  • Example
  • Author
  • Sue Yockey
  • Keywords


IWidgets spinner

 Table of Contents

iwidgets::spinner - Create and manipulate a spinner widget

Synopsis

iwidgets::spinner pathName ?options?

Inheritance

itk::Widget <- iwidgets::Labeledwidget <- iwidgets::Spinner

Standard Options

background borderWidth cursor exportSelection

foreground
highlightColor highlightThickness insertBackground insertBorderWidth insertOffTime insertOnTime insertWidth
justify
relief selectBackground selectBorderWidth selectForeground textVariable

See the «options» manual entry for details on the standard

options.

Associated Options

show
state

See the «entry» manual entry for details on the associated

options.

Inherited Options

childSitePos command fixed focusCommand

invalid
textBackground textFont validate width

See the «entryfield» widget manual entry for details on the above

inherited options.

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable state sticky

See the «labeledwidget» widget manual entry for details on the

above inherited options.

Widget-specific Options

Name: arrowOrient

Class: Orient

Command-Line Switch: -arroworient

Specifies placement of arrow buttons: horizontal or vertical.

The default is vertical.

Name: decrement

Class: Command

Command-Line Switch: -decrement

Tcl command to be executed when down arrow is pressed.

Name: increment

Class: Command

Command-Line Switch: -increment

Tcl command to be executed when up arrow is pressed.

Name: repeatDelay

Class: RepeatDelay

Command-Line Switch: -repeatdelay

Specifies the initial delay in milliseconds before the spinner

repeat action on the arrow buttons engages. The default is 300 milliseconds.

Name: repeatInterval

Class: RepeatInterval

Command-Line Switch: -repeatinterval

Specifies the repeat delay in milliseconds between selections of

the arrow buttons. A repeatinterval of 0 disables button repeat.

The default is 100 milliseconds.

_________________________________________________________________

Description

The iwidgets::spinner command creates a spinner widget. The

spinner is comprised of an entryfield plus up and down arrow but- tons. Arrows may be drawn horizontally or vertically.

Methods

The iwidgets::spinner command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for spinner widgets:

Associated Methods

delete get icursor index insert scan selection xview

See the «entry» manual entry for details on the associated meth-

ods.

Inherited Methods

childsite clear peek

See the «entryfield» manual entry for details on the associated

methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::spinner command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::spinner command. pathName down

Derived classes may overload this method to specialize function-

ality.
pathName up

Derived classes may overload this method to specialize function-

ality.

Components

Name: downarrow

Class: Canvas

The downarrow component is the downward pointing button of the

spinner. See the «canvas» widget manual entry for details on the downarrow component item.

Name: uparrow

Class: Canvas

The uparrow component is the upward pointing button of the spin-

ner. See the «canvas» widget manual entry for details on the uparrow component item.

Example

package require Iwidgets 4.0
set months {January February March April May June July \ August September October November December}

proc blockInput {char} {
return 0
}

proc spinMonth {step} {
global months

set index [expr [lsearch $months [.sm get]] + $step]

if {$index < 0} {set index 11}
if {$index > 11} {set index 0}

.sm delete 0 end
.sm insert 0 [lindex $months $index] }

iwidgets::spinner .sm -labeltext «Month : « -width 10 -fixed 10 \ -validate blockInput -decrement {spinMonth -1} -increment {spinMonth 1} .sm insert 0 January

pack .sm -padx 10 -pady 10

Acknowledgements:

Ken Copeland <ken@hilco.com>

10/18/95 - Added auto-repeat action to spinner arrow buttons.

Author

Sue Yockey

Keywords

spinner, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "entry" manual entry for details on the associated
  • Inherited Options
  • See the "entryfield" widget manual entry for details on the above
  • See the "labeledwidget" widget manual entry for details on the
  • Widget-specific Options
  • Name: arrowOrient
  • Class: Orient
  • Command-Line Switch: -arroworient
  • Specifies placement of arrow buttons: horizontal or vertical.
  • The default is vertical.
  • Name: decrement
  • Class: Command
  • Command-Line Switch: -decrement
  • Tcl command to be executed when down arrow is pressed.
  • Name: increment
  • Class: Command
  • Command-Line Switch: -increment
  • Tcl command to be executed when up arrow is pressed.
  • Name: repeatDelay
  • Class: RepeatDelay
  • Command-Line Switch: -repeatdelay
  • Specifies the initial delay in milliseconds before the spinner
  • Name: repeatInterval
  • Class: RepeatInterval
  • Command-Line Switch: -repeatinterval
  • Specifies the repeat delay in milliseconds between selections of
  • The default is 100 milliseconds.
  • Description
  • The iwidgets::spinner command creates a spinner widget. The
  • Methods
  • The iwidgets::spinner command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for spinner widgets:
  • Associated Methods
  • See the "entry" manual entry for details on the associated meth-
  • Inherited Methods
  • See the "entryfield" manual entry for details on the associated
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Derived classes may overload this method to specialize function-
  • Derived classes may overload this method to specialize function-
  • Components
  • Name: downarrow
  • Class: Canvas
  • The downarrow component is the downward pointing button of the
  • Name: uparrow
  • Class: Canvas
  • The uparrow component is the upward pointing button of the spin-
  • Example
  • Acknowledgements:
  • Ken Copeland
  • Author
  • Sue Yockey
  • Keywords


IWidgets spintime

 Table of Contents

iwidgets::spintime - Create and manipulate time spinner widgets

Synopsis

iwidgets::spintime pathName ?options?

Inheritance

itk::Widget <- iwidgets::Spintime

Standard Options

background cursor foreground relief

See the «options» manual entry for details on the standard

options.

Associated Options

textBackground textFont

See the «entryfield» manual entry for details on the above asso-

ciated options.

labelFont
labelMargin

See the «labeledwidget» manual entry for details on the above

associated options.
arrowOrient repeatDelay repeatInterval

See the «spinner» manual entry for details on the above associ-

ated options.

Widget-specific Options

Name: labelPos

Class: Position

Command-Line Switch: -labelpos

Specifies the position of the label along the sides of the vari-

ous spinners: n, e, s, or w. The default is w.

Name: hourLabel

Class: Text

Command-Line Switch: -hourlabel

Specifies the text of the label for the hour spinner. The

default is «Hour".

Name: hourOn

Class: hourOn

Command-Line Switch: -houron

Specifies whether or not to display the hour spinner in any of

the forms acceptable to Tcl_GetBoolean. The default is true.

Name: hourWidth

Class: Width

Command-Line Switch: -hourwidth

Specifies the width of the hour spinner in any of the forms

acceptable to Tcl_GetPixels. The default is 3 pixels.

Name: militaryOn

Class: militaryOn

Command-Line Switch: -militaryon

Specifies use of a 24 hour clock for hour display in any of the

forms acceptable to Tcl_GetBoolean. The default is true.

Name: minuteLabel

Class: Text

Command-Line Switch: -minutelabel

Specifies the text of the label for the minute spinner. The

default is «Minute".

Name: minuteOn

Class: minuteOn

Command-Line Switch: -minuteon

Specifies whether or not to display the minute spinner in any of

the forms acceptable to Tcl_GetBoolean. The default is true.

Name: minuteWidth

Class: Width

Command-Line Switch: -minutewidth

Specifies the width of the minute spinner in any of the forms

acceptable to Tcl_GetPixels. The default is 3 pixels.

Name: orient

Class: Orient

Command-Line Switch: -orient

Specifies the orientation of the hour, minute, and second spin-

ners: vertical or horizontal. The default is horizontal.

Name: secondLabel

Class: Text

Command-Line Switch: -secondlabel

Specifies the text of the label for the second spinner. The

default is «Second"

Name: secondOn

Class: secondOn

Command-Line Switch: -secondon

Specifies whether or not to display the second spinner in any of

the forms acceptable to Tcl_GetBoolean. The default is true.

Name: secondWidth

Class: Width

Command-Line Switch: -secondwidth

Specifies the width of the second spinner in any of the forms

acceptable to Tcl_GetPixels. The default is 3 pixels.

Name: timeMargin

Class: Margin

Command-Line Switch: -timemargin

Specifies the margin space between the hour, minute, and second

spinners is any of the forms accpetable to Tcl_GetPixels. The default is 1 pixel.
_________________________________________________________________

Description

The iwidgets::spintime command creates a set of spinners for use

in time value entry. The set includes an hour, minute, and sec- ond spinner widget.

Methods

The iwidgets::spintime command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for spintime widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::spintime command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::spintime command. pathName get ?format?

Returns the current contents of the spintime widget in a format

of string or as an integer clock value using the -string and -clicks format options respectively. The default is by string.

Reference the clock command for more information on obtaining

time and its formats.
pathName show time

Changes the currently displayed time to be that of the time

argument. The time may be specified either as a string, an inte- ger clock value or the keyword «now". Reference the clock com- mand for more information on obtaining times and its format.

Components

Name: hour

Class: Spinint

The hour component is the hour spinner of the time spinner. See

the SpinInt widget manual entry for details on the hour component item.

Name: minute

Class: Spinint

The minute component is the minute spinner of the time spinner.

See the SpinInt widget manual entry for details on the minute

component item.

Name: second

Class: Spinint

The second component is the second spinner of the time spinner.

See the SpinInt widget manual entry for details on the second

component item.

Example

package require Iwidgets 4.0
iwidgets::spintime .st
pack .st -padx 10 -pady 10

Author

Sue Yockey

Mark L. Ulferts

Keywords

spintime, spinint, spinner, entryfield, entry, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "entryfield" manual entry for details on the above asso-
  • See the "labeledwidget" manual entry for details on the above
  • See the "spinner" manual entry for details on the above associ-
  • Widget-specific Options
  • Name: labelPos
  • Class: Position
  • Command-Line Switch: -labelpos
  • Specifies the position of the label along the sides of the vari-
  • Name: hourLabel
  • Class: Text
  • Command-Line Switch: -hourlabel
  • Specifies the text of the label for the hour spinner. The
  • Name: hourOn
  • Class: hourOn
  • Command-Line Switch: -houron
  • Specifies whether or not to display the hour spinner in any of
  • Name: hourWidth
  • Class: Width
  • Command-Line Switch: -hourwidth
  • Specifies the width of the hour spinner in any of the forms
  • Name: militaryOn
  • Class: militaryOn
  • Command-Line Switch: -militaryon
  • Specifies use of a 24 hour clock for hour display in any of the
  • Name: minuteLabel
  • Class: Text
  • Command-Line Switch: -minutelabel
  • Specifies the text of the label for the minute spinner. The
  • Name: minuteOn
  • Class: minuteOn
  • Command-Line Switch: -minuteon
  • Specifies whether or not to display the minute spinner in any of
  • Name: minuteWidth
  • Class: Width
  • Command-Line Switch: -minutewidth
  • Specifies the width of the minute spinner in any of the forms
  • Name: orient
  • Class: Orient
  • Command-Line Switch: -orient
  • Specifies the orientation of the hour, minute, and second spin-
  • Name: secondLabel
  • Class: Text
  • Command-Line Switch: -secondlabel
  • Specifies the text of the label for the second spinner. The
  • Name: secondOn
  • Class: secondOn
  • Command-Line Switch: -secondon
  • Specifies whether or not to display the second spinner in any of
  • Name: secondWidth
  • Class: Width
  • Command-Line Switch: -secondwidth
  • Specifies the width of the second spinner in any of the forms
  • Name: timeMargin
  • Class: Margin
  • Command-Line Switch: -timemargin
  • Specifies the margin space between the hour, minute, and second
  • Description
  • The iwidgets::spintime command creates a set of spinners for use
  • Methods
  • The iwidgets::spintime command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for spintime widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Returns the current contents of the spintime widget in a format
  • Reference the clock command for more information on obtaining
  • Changes the currently displayed time to be that of the time
  • Components
  • Name: hour
  • Class: Spinint
  • The hour component is the hour spinner of the time spinner. See
  • Name: minute
  • Class: Spinint
  • The minute component is the minute spinner of the time spinner.
  • See the SpinInt widget manual entry for details on the minute
  • Name: second
  • Class: Spinint
  • The second component is the second spinner of the time spinner.
  • See the SpinInt widget manual entry for details on the second
  • Example
  • Author
  • Sue Yockey
  • Mark L. Ulferts
  • Keywords


IWidgets tabnotebook

 Table of Contents

iwidgets::tabnotebook - create and manipulate tabnotebook widgets

Synopsis

iwidgets::tabnotebook pathName? options?

Inheritance

itk::Widget <- iwidgets::Tabnotebook

Standard Options

background disabledForeground foreground scrollCommand cursor font height width

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: angle

Class: Angle

Command-Line Switch: -angle

Specifes the angle of slope from the inner edge to the outer edge

of the tab. An angle of 0 specifies square tabs. Valid ranges are 0 to 45 degrees inclusive. Default is 15 degrees. If tabPos is e or w, this option is ignored.

Name: auto

Class: Auto

Command-Line Switch: -auto

Specifies whether to use the automatic packing/unpacking algo-

rithm of the notebook. A value of true indicates that page frames will be unpacked and packed acoording to the algorithm described in the select command. A value of false leaves the current page packed and subsequent selects, next, or previous commands do not switch pages automatically. In either case the page's associated command (see the add command's description of the command option) is invoked. The value may have any of the forms accepted by the

Tcl_GetBoolean, such as true, false, 0, 1, yes, or no.

Name: backdrop

Class: Backdrop

Command-Line Switch: -backdrop

Specifies a background color to use when filling in the backdrop

area behind the tabs.

Name: background

Class: Background

Command-Line Switch: -background

Specifies a background color to use for displaying a page and its

associated tab. This can be thought of as the selected tab back- ground color, since the tab associated with the selected page is the selected tab.

Name: bevelAmount

Class: BevelAmount

Command-Line Switch: -bevelamount

Specifes the size of tab corners. A value of 0 with angle set to

0 results in square tabs. A bevelAmount of 4, means that the tab will be drawn with angled corners that cut in 4 pixels from the edge of the tab. The default is 0.

Name: borderWidth

Class: BorderWidth

Command-Line Switch: -borderwidth

Specifies the width of shadowed border to place around the note-

book area of the tabnotebook. The default value is 2.

Name: disabledForeground

Class: DisabledForeground

Command-Line Switch: -disabledforeground

Specifies a foreground color to use for displaying a tab's label

when its state is disabled.

Name: equalTabs

Class: EqualTabs

Command-Line Switch: -equaltabs

Specifies whether to force tabs to be equal sized or not. A value

of true means constrain tabs to be equal sized. A value of false allows each tab to size based on the text label size. The value may have any of the forms accepted by the Tcl_GetBoolean, such as true, false, 0, 1, yes, or no.

For horizontally positioned tabs (tabpos is either s or n), true

forces all tabs to be equal width (the width being equal to the longest label plus any padX specified). Horizontal tabs are always equal in height.

For vertically positioned tabs (tabpos is either w or e), true

forces all tabs to be equal height (the height being equal to the height of the label with the largest font). Vertically oriented tabs are always equal in width.

Name: foreground

Class: Foreground

Command-Line Switch: -foreground

Specifies a foreground color to use for displaying a page and its

associated tab label. This can be thought of as the selected tab background color, since the tab associated with the selected page is the selected tab.

Name: gap

Class: Gap

Command-Line Switch: -gap

Specifies the amount of pixel space to place between each tab.

Value may be any pixel offset value. In addition, a special key-

word overlap can be used as the value to achieve a standard over- lap of tabs. This value may have any of the forms acceptable to

Tk_GetPixels.

Name: margin

Class: Margin

Command-Line Switch: -Bmargin

Specifies the amount of space to place between the outside edge

of the tabnotebook and the outside edge of its tabs. If tabPos is s, this is the amount of space between the bottom edge of the tabnotebook and the bottom edge of the set of tabs. If tabPos is n, this is the amount of space between the top edge of the tab- notebook and the top edge of the set of tabs. If tabPos is e, this is the amount of space between the right edge of the tab- notebook and the right edge of the set of tabs. If tabPos is w, this is the amount of space between the left edge of the tabnote- book and the left edge of the set of tabs. This value may have any of the forms acceptable to Tk_GetPixels.

Name: padX

Class: PadX

Command-Line Switch: -padx

Specifies a non-negative value indicating how much extra space to

request for a tab around its label in the X-direction. When com- puting how large a window it needs, the tab will add this amount to the width it would normally need The tab will end up with extra internal space to the left and right of its text label.

This value may have any of the forms acceptable to Tk_GetPixels.

Name: padY

Class: PadY

Command-Line Switch: -pady

Specifies a non-negative value indicating how much extra space to

request for a tab around its label in the Y-direction. When com- puting how large a window it needs, the tab will add this amount to the height it would normally need The tab will end up with extra internal space to the top and bottom of its text label.

This value may have any of the forms acceptable to Tk_GetPixels.

Name: raiseSelect

Class: RaiseSelect

Command-Line Switch: -raiseselect

Specifes whether to slightly raise the selected tab from the rest

of the tabs. The selected tab is drawn 2 pixels closer to the outside of the tabnotebook than the unselected tabs. A value of true says to raise selected tabs, a value of false turns this feature off. The default is false. The value may have any of the forms accepted by the Tcl_GetBoolean, such as true, false, 0, 1, yes, or no.

Name: start

Class: Start

Command-Line Switch: -start

Specifies the amount of space to place between the left or top

edge of the tabnotebook and the starting edge of its tabs. For horizontally positioned tabs, this is the amount of space between the left edge of the notebook and the left edge of the first tab.

For vertically positioned tabs, this is the amount of space

between the top of the notebook and the top of the first tab.

This value may change if the user performs a MButton-2 scroll on

the tabs. This value may have any of the forms acceptable to

Tk_GetPixels.

Name: state

Class: State

Command-Line Switch: -state

Sets the active state of the tabnotebook. Specifying normal

allows all pages to be selectable. Specifying disabled disables the notebook causing all page tabs to be drawn in the disabled-

Foreground color.

Name: tabBackground

Class: TabBackground

Command-Line Switch: -tabbackground

Specifies a background color to use for displaying tab back-

grounds when they are in their unselected state. This is the background associated with tabs on all pages other than the selected page.

Name: tabBorders

Class: TabBorders

Command-Line Switch: -tabborders

Specifies whether to draw the borders of tabs that are not

selected. Specifying true (the default) draws these borders, specifying false draws only the border around the selected tab.

The value may have any of the forms accepted by the Tcl_Get-

Boolean, such as true, false, 0, 1, yes, or no.

Name: tabForeground

Class: TabForeground

Command-Line Switch: -tabforeground

Specifies a foreground color to use for displaying tab labels

when they are in their unselected state. This is the foreground associated with tabs on all pages other than the selected page.

Name: tabPos

Class: TabPos

Command-Line Switch: -tabpos

Specifies the location of the set of tabs in relation to the

notebook area. Must be n, s, e, or w. Defaults to s. _________________________________________________________________

Description

The iwidgets::tabnotebook command creates a new window (given by

the pathName argument) and makes it into a tabnotebook widget.

Additional options, described above may be specified on the com-

mand line or in the option database to configure aspects of the tabnotebook such as its colors, font, and text. The iwid- gets::tabnotebook command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A tabnotebook is a widget that contains a set of tabbed pages. It

displays one page from the set as the selected page. A Tab dis- plays the label for the page to which it is attached and serves as a page selector. When a page's tab is selected, the page's contents are displayed in the page area. The selected tab has a three-dimensional effect to make it appear to float above the other tabs. The tabs are displayed as a group along either the left, top, right, or bottom edge. When first created a tabnote- book has no pages. Pages may be added or deleted using widget commands described below.

A special option may be provided to the tabnotebook. The -auto

option specifies whether the tabnotebook will automatically han- dle the unpacking and packing of pages when pages are selected. A value of true signifies that the notebook will automatically man- age it. This is the default value. A value of false signifies the notebook will not perform automatic switching of pages.

Notebook Pages

A tabnotebook's pages area contains a single child site frame.

When a new page is created it is a child of this frame. The

page's child site frame serves as a geometry container for appli- cations to pack widgets into. It is this frame that is automati- cally unpacked or packed when the auto option is true. This cre- ates the effect of one page being visible at a time. When a new page is selected, the previously selected page's child site frame is automatically unpacked from the tabnotebook's child site frame and the newly selected page's child site is packed into the tab- notebook's child site frame.

However, sometimes it is desirable to handle page changes in a

different manner. By specifying the auto option as false, child site packing can be disabled and done differently. For example, all widgets might be packed into the first page's child site frame. Then when a new page is selected, the application can reconfigure the widgets and give the appearance that the page was flipped.

In both cases the command option for a page specifies a Tcl Com-

mand to execute when the page is selected. In the case of auto being true, it is between the unpacking of the previously selected page and the packing of the newly selected page.

Notebook pages can also be controlled with scroll bars or other

widgets that obey the scrollcommand protocol. By giving a scroll- bar a -command to call the tabnotebook's select method, the tab- notebook can be controlled with a scrollbar.

The notebook area is implemented with the notebook mega widget.

Tabs

Tabs appear along the edge of the notebook area. Tabs are drawn

to appear attached to their associated page. When a tab is clicked on, the associated page is selected and the tab is drawn as raised above all other tabs and as a seamless part of its notebook page. Tabs can be controlled in their location along the edges, the angle tab sides are drawn with, gap between tabs, starting margin of tabs, internal padding around text labels in a tab, the font, and its label.

The Tab area is implemented with the tabset mega widget. See

tabset(1) . Tabs may be oriented along either the north, south, east, or west sides with the tabPos option. North and south tabs may appear as angled, square, or bevelled. West and east tabs may appear as square or bevelled. By changing tab gaps, tab angles, bevelling, orientations, colors, fonts, start locations, and mar- gins; tabs may appear in a wide variety of styles. For example, it is possible to implement Microsoft-style tabs, Borland prop- erty tab styles, or Borland Delphi style tabs all with the same tabnotebook.

Widget-specific Methods

The iwidgets::tabnotebook command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

option and the args determine the exact behavior of the command.

Many of the widget commands for a notebook take as one argument

an indicator of which page of the notebook to operate on. These indicators are called indexes and may be specified in any of the following forms:

number

Specifies the page numerically, where 0 corresponds to the first

page in the notebook, 1 to the second, and so on. select

Specifies the currently selected page's index. If no page is cur-

rently selected, the value -1 is returned.
end

Specifes the last page in the tabnotebook's index. If the note-

book is empty this will return -1.
pattern

If the index doesn't satisfy any of the above forms, then this

form is used. Pattern is pattern-matched against the label of each page in the notebook, in order from the first to the last page, until a matching entry is found. The rules of Tcl_String-

Match are used. The following commands are possible for tabnote-

book widgets:
pathName add ?option value option value ...?

Add a new page at the end of the tabnotebook. A new child site

frame is created. Returns the child site pathName. If additional arguments are present, they specify any of the following options: -angle value

Specifes the angle of slope from the inner edge to the outer edge

of the tab. An angle of 0 specifies square tabs. Valid ranges are 0 to 45 degrees inclusive. Default is 15 degrees. If this option is specified as an empty string (the default), then the angle option for the overall tabnotebook is used. This is generally only set at the tabnotebook level. Tabs normally will want to share the same angle value.
-background value

Specifies a background color to use for displaying tabs when they

are selected and for displaying the current page. If this option is specified as an empty string (the default), then the back- ground option for the overall tabnotebook is used. -bevelamount value

Specifes the size of tab corners. A value of 0 with angle set to

0 results in square tabs. A bevelAmount of 4, means that the tab will be drawn with angled corners that cut in 4 pixels from the edge of the tab. The default is 0. This is generally only set at the tabnotebook level. Tabs normally will want to share the same bevelAmount.
-bitmap value

If label is a non-empty string, specifies a bitmap to display in

this page's tab. Bitmap may be of any of the forms accepted by

Tk_GetPixmap.

-command value

Specifies a Tcl command to be executed when this page is

selected. This allows the programmer a hook to reconfigure this page's widgets or any other page's widgets.

If the tabnotebook has the auto option set to true, when a page

is selected this command will be called immediately after the previously selected page is unpacked and immediately before this page is selected. The index value select is valid during this Tcl command. `index select' will return this page's page number.

If the auto option is set to false, when a page is selected the

unpack and pack calls are bypassed. This Tcl command is still called.
-disabledforeground value

Specifies a foreground color to use for displaying tab labels

when tabs are in their disable state. If this option is specified as an empty string (the default), then the disabledforeground option for the overall tabnotebook is used.
-font value

Specifies the font to use when drawing a text label on a page

tab. If this option is specified as an empty string then the font option for the overall tabnotebook is used..

-foreground value

Specifies a foreground color to use for displaying tab labels

when they are selected. If this option is specified as an empty string (the default), then the foreground option for the overall tabnotebook is used.
-label value

Specifies a string to display as an identifying label for a note-

book page. This label serves as an additional identifier used to reference the page. This label may be used for the index value in widget commands.
-tabbackground value

Specifies a background color to use for displaying a tab when it

is not elected. If this option is specified as an empty string (the default), then the tabBackground option for the overall tab- notebook is used.
-tabforeground value

Specifies a foreground color to use for displaying the tab's text

label when it is not selected. If this option is specified as an empty string (the default), then the tabForeground option for the overall tabnotebook is used.
-padx value

Specifies a non-negative value indicating how much extra space to

request for a tab around its label in the X-direction. When com- puting how large a window it needs, the tab will add this amount to the width it would normally need The tab will end up with extra internal space to the left and right of its text label.

This value may have any of the forms acceptable to Tk_GetPixels.

If this option is specified as an empty string (the default),

then the padX option for the overall tabnotebook is used -pady value

Specifies a non-negative value indicating how much extra space to

request for a tab around its label in the Y-direction. When com- puting how large a window it needs, the tab will add this amount to the height it would normally need The tab will end up with extra internal space to the top and bottom of its text label.

This value may have any of the forms acceptable to Tk_GetPixels.

If this option is specified as an empty string (the default),

then the padY option for the overall tabnotebook is used -state value

Specifies one of two states for the page: normal or disabled. In

normal state unselected tabs are displayed using the tabfore- ground and tabbackground option from the tabnotebook or the page.

Selected tabs and pages are displayed using the foreground and

background option from the tabnotebook or the page. The disabled state means that the page and its tab is insensitive: it doesn't respond to mouse button presses or releases. In this state the entry is displayed according to its disabledForeground option for the tabnotebook and the background/tabbackground option from the page or the tabnotebook.
pathName childSite ?index?

If passed no arguments, returns a list of pathNames for all the

pages in the tabnotebook. If the tab notebook is empty, an empty list is returned

If index is passed, it returns the pathName for the page's child

site frame specified by index. Widgets that are created with this pathName will be displayed when the associated page is selected.

If index is not a valid index, an empty string is returned.

pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::tabnotebook command. pathName delete index1 ?index2?

Delete all of the pages between index1 and index2 inclusive. If

index2 is omitted then it defaults to index1. Returns an empty string.
pathName index index

Returns the numerical index corresponding to index.

pathName insert index ?option value option value ...?

Insert a new page in the tabnotebook before the page specified by

index. A new child site frame is created. The additional argu- ments are the same as for the add command. Returns the child site pathName.
pathName next

Advances the selected page to the next page (order is determined

by insertion order). If the currently selected page is the last page in the notebook, the selection wraps around to the first page in the notebook. It behaves as if the user selected the new page.

For notebooks with auto set to true the current page's child site

is unpacked from the notebook's child site frame. Then the next page's child site is packed into the notebook's child site frame.

The Tcl command given with the command option will be invoked

between these two operations.

For notebooks with auto set to false the Tcl command given with

the command option will be invoked.
pathName pageconfigure index ?option? ?value option value ...?

This command is similar to the configure command, except that it

applies to the options for an individual page, whereas configure applies to the options for the tabnotebook as a whole. Options may have any of the values accepted by the add widget command. If options are specified, options are modified as indicated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for page index (see Tk_ConfigureInfo for information on the format of this list).
pathName prev

Moves the selected page to the previous page (order is determined

by insertion order). If the currently selected page is the first page in the notebook, the selection wraps around to the last page in the notebook. It behaves as if the user selected the new page.

For notebooks with auto set to true the current page's child site

is unpacked from the notebook's child site frame. Then the previ- ous page's child site is packed into the notebook's child site frame. The Tcl command given with the command option will be invoked between these two operations.

For notebooks with auto set to false the Tcl command given with

the command option will be invoked.
pathName select index

Selects the page specified by index as the currently selected

page. It behaves as if the user selected the new page.

For notebooks with auto set to true the current page's child site

is unpacked from the notebook's child site frame. Then the index page's child site is packed into the notebook's child site frame.

The Tcl command given with the command option will be invoked

between these two operations.

For notebooks with auto set to false the Tcl command given with

the command option will be invoked.
pathName view

Returns the currently selected page. This command is for compati-

bility with the scrollbar widget.
pathName view index

Selects the page specified by index as the currently selected

page. This command is for compatibility with the scrollbar wid- get.
pathName view moveto fraction

Uses the fraction value to determine the corresponding page to

move to. This command is for compatibility with the scrollbar widget.
pathName view scroll num what

Uses the num value to determine how many pages to move forward or

backward (num can be negative or positive). The what argument is ignored. This command is for compatibility with the scrollbar widget.

Components

Generally all behavior of the internal components, tabset and

notebook are controlled via the pageconfigure method. The fol- lowing section documents these two components.

Name: tabset

Class: Tabset

This is the tabset component. It implements the tabs that are

associated with the notebook component.

See the «Tabset» widget manual entry for details on the tabset

component item.

Name: notebook

Class: Notebook

This is the notebook component. It implements the notebook that

contains the pages of the tabnotebook.

See the «Notebook» widget manual entry for details on the note-

book component item.

Example

Following is an example that creates a tabnotebook with two

pages.
package require Iwidgets 4.0
# Create the tabnotebook widget and pack it. iwidgets::tabnotebook .tn -width 100 -height 100 pack .tn \
-anchor nw \
-fill both \
-expand yes \
-side left \
-padx 10 \
-pady 10
# Add two pages to the tabnotebook,
# labelled «Page One» and «Page Two"
.tn add -label «Page One"
.tn add -label «Page Two"
# Get the child site frames of these two pages. set page1CS [.tn childsite 0]
set page2CS [.tn childsite «Page Two"]
# Create buttons on each page of the tabnotebook. button $page1CS.b -text «Button One"
pack $page1CS.b
button $page2CS.b -text «Button Two"
pack $page2CS.b
# Select the first page of the tabnotebook. .tn select 0

Author

Bill W. Scott

Keywords

tab tabset notebook tabnotebook page

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: angle
  • Class: Angle
  • Command-Line Switch: -angle
  • Specifes the angle of slope from the inner edge to the outer edge
  • Name: auto
  • Class: Auto
  • Command-Line Switch: -auto
  • Specifies whether to use the automatic packing/unpacking algo-
  • Tcl_GetBoolean, such as true, false, 0, 1, yes, or no.
  • Name: backdrop
  • Class: Backdrop
  • Command-Line Switch: -backdrop
  • Specifies a background color to use when filling in the backdrop
  • Name: background
  • Class: Background
  • Command-Line Switch: -background
  • Specifies a background color to use for displaying a page and its
  • Name: bevelAmount
  • Class: BevelAmount
  • Command-Line Switch: -bevelamount
  • Specifes the size of tab corners. A value of 0 with angle set to
  • Name: borderWidth
  • Class: BorderWidth
  • Command-Line Switch: -borderwidth
  • Specifies the width of shadowed border to place around the note-
  • Name: disabledForeground
  • Class: DisabledForeground
  • Command-Line Switch: -disabledforeground
  • Specifies a foreground color to use for displaying a tab's label
  • Name: equalTabs
  • Class: EqualTabs
  • Command-Line Switch: -equaltabs
  • Specifies whether to force tabs to be equal sized or not. A value
  • For horizontally positioned tabs (tabpos is either s or n), true
  • For vertically positioned tabs (tabpos is either w or e), true
  • Name: foreground
  • Class: Foreground
  • Command-Line Switch: -foreground
  • Specifies a foreground color to use for displaying a page and its
  • Name: gap
  • Class: Gap
  • Command-Line Switch: -gap
  • Specifies the amount of pixel space to place between each tab.
  • Value may be any pixel offset value. In addition, a special key-
  • Tk_GetPixels.
  • Name: margin
  • Class: Margin
  • Command-Line Switch: -Bmargin
  • Specifies the amount of space to place between the outside edge
  • Name: padX
  • Class: PadX
  • Command-Line Switch: -padx
  • Specifies a non-negative value indicating how much extra space to
  • This value may have any of the forms acceptable to Tk_GetPixels.
  • Name: padY
  • Class: PadY
  • Command-Line Switch: -pady
  • Specifies a non-negative value indicating how much extra space to
  • This value may have any of the forms acceptable to Tk_GetPixels.
  • Name: raiseSelect
  • Class: RaiseSelect
  • Command-Line Switch: -raiseselect
  • Specifes whether to slightly raise the selected tab from the rest
  • Name: start
  • Class: Start
  • Command-Line Switch: -start
  • Specifies the amount of space to place between the left or top
  • For vertically positioned tabs, this is the amount of space
  • This value may change if the user performs a MButton-2 scroll on
  • Tk_GetPixels.
  • Name: state
  • Class: State
  • Command-Line Switch: -state
  • Sets the active state of the tabnotebook. Specifying normal
  • Foreground color.
  • Name: tabBackground
  • Class: TabBackground
  • Command-Line Switch: -tabbackground
  • Specifies a background color to use for displaying tab back-
  • Name: tabBorders
  • Class: TabBorders
  • Command-Line Switch: -tabborders
  • Specifies whether to draw the borders of tabs that are not
  • The value may have any of the forms accepted by the Tcl_Get-
  • Boolean, such as true, false, 0, 1, yes, or no.
  • Name: tabForeground
  • Class: TabForeground
  • Command-Line Switch: -tabforeground
  • Specifies a foreground color to use for displaying tab labels
  • Name: tabPos
  • Class: TabPos
  • Command-Line Switch: -tabpos
  • Specifies the location of the set of tabs in relation to the
  • Description
  • The iwidgets::tabnotebook command creates a new window (given by
  • Additional options, described above may be specified on the com-
  • A tabnotebook is a widget that contains a set of tabbed pages. It
  • A special option may be provided to the tabnotebook. The -auto
  • Notebook Pages
  • A tabnotebook's pages area contains a single child site frame.
  • When a new page is created it is a child of this frame. The
  • However, sometimes it is desirable to handle page changes in a
  • In both cases the command option for a page specifies a Tcl Com-
  • Notebook pages can also be controlled with scroll bars or other
  • The notebook area is implemented with the notebook mega widget.
  • Tabs
  • Tabs appear along the edge of the notebook area. Tabs are drawn
  • The Tab area is implemented with the tabset mega widget. See
  • Widget-specific Methods
  • The iwidgets::tabnotebook command creates a new Tcl command whose
  • Many of the widget commands for a notebook take as one argument
  • Specifies the page numerically, where 0 corresponds to the first
  • Specifies the currently selected page's index. If no page is cur-
  • Specifes the last page in the tabnotebook's index. If the note-
  • If the index doesn't satisfy any of the above forms, then this
  • Match are used. The following commands are possible for tabnote-
  • Add a new page at the end of the tabnotebook. A new child site
  • Specifes the angle of slope from the inner edge to the outer edge
  • Specifies a background color to use for displaying tabs when they
  • Specifes the size of tab corners. A value of 0 with angle set to
  • If label is a non-empty string, specifies a bitmap to display in
  • Tk_GetPixmap.
  • Specifies a Tcl command to be executed when this page is
  • If the tabnotebook has the auto option set to true, when a page
  • If the auto option is set to false, when a page is selected the
  • Specifies a foreground color to use for displaying tab labels
  • Specifies the font to use when drawing a text label on a page
  • Specifies a foreground color to use for displaying tab labels
  • Specifies a string to display as an identifying label for a note-
  • Specifies a background color to use for displaying a tab when it
  • Specifies a foreground color to use for displaying the tab's text
  • Specifies a non-negative value indicating how much extra space to
  • This value may have any of the forms acceptable to Tk_GetPixels.
  • If this option is specified as an empty string (the default),
  • Specifies a non-negative value indicating how much extra space to
  • This value may have any of the forms acceptable to Tk_GetPixels.
  • If this option is specified as an empty string (the default),
  • Specifies one of two states for the page: normal or disabled. In
  • Selected tabs and pages are displayed using the foreground and
  • If passed no arguments, returns a list of pathNames for all the
  • If index is passed, it returns the pathName for the page's child
  • If index is not a valid index, an empty string is returned.
  • Query or modify the configuration options of the widget. If no
  • Delete all of the pages between index1 and index2 inclusive. If
  • Returns the numerical index corresponding to index.
  • Insert a new page in the tabnotebook before the page specified by
  • Advances the selected page to the next page (order is determined
  • For notebooks with auto set to true the current page's child site
  • The Tcl command given with the command option will be invoked
  • For notebooks with auto set to false the Tcl command given with
  • This command is similar to the configure command, except that it
  • Moves the selected page to the previous page (order is determined
  • For notebooks with auto set to true the current page's child site
  • For notebooks with auto set to false the Tcl command given with
  • Selects the page specified by index as the currently selected
  • For notebooks with auto set to true the current page's child site
  • The Tcl command given with the command option will be invoked
  • For notebooks with auto set to false the Tcl command given with
  • Returns the currently selected page. This command is for compati-
  • Selects the page specified by index as the currently selected
  • Uses the fraction value to determine the corresponding page to
  • Uses the num value to determine how many pages to move forward or
  • Components
  • Generally all behavior of the internal components, tabset and
  • Name: tabset
  • Class: Tabset
  • This is the tabset component. It implements the tabs that are
  • See the "Tabset" widget manual entry for details on the tabset
  • Name: notebook
  • Class: Notebook
  • This is the notebook component. It implements the notebook that
  • See the "Notebook" widget manual entry for details on the note-
  • Example
  • Following is an example that creates a tabnotebook with two
  • Author
  • Bill W. Scott
  • Keywords


IWidgets tabset

 Table of Contents

iwidgets::tabset - create and manipulate tabs as as set

Synopsis

iwidgets::tabset pathName ?options?

Inheritance

itk::Widget <- iwidgets::Tabset

Standard Options

background font selectBackground cursor foreground selectForeground disabledForeground height width

See the «options» manual entry for details on the standard

options.

Widget-specific Options

Name: angle

Class: Angle

Command-Line Switch: -angle

Specifes the angle of slope from the inner edge to the outer edge

of the tab. An angle of 0 specifies square tabs. Valid ranges are 0 to 45 degrees inclusive. Default is 15 degrees. If tabPos is e or w, this option is ignored.

Name: backdrop

Class: Backdrop

Command-Line Switch: -backdrop

Specifies a background color to use when filling in the area

behind the tabs.

Name: bevelAmount

Class: BevelAmount

Command-Line Switch: -bevelamount

Specifes the size of tab corners. A value of 0 with angle set to

0 results in square tabs. A bevelAmount of 4, means that the tab will be drawn with angled corners that cut in 4 pixels from the edge of the tab. The default is 0.

Name: command

Class: Command

Command-Line Switch: -command

Specifes the prefix of a Tcl command to invoke to change the view in the

widget associated with the tabset. When a user selects a tab, a Tcl command is invoked. The actual command consists of this option followed by a space and a number. The number is the numerical index of the tab that has been selected.

Name: equalTabs

Class: EqualTabs

Command-Line Switch: -equaltabs

Specifies whether to force tabs to be equal sized or not. A value

of true means constrain tabs to be equal sized. A value of false allows each tab to size based on the text label size. The value may have any of the forms accepted by the Tcl_GetBoolean, such as true, false, 0, 1, yes, or no.

For horizontally positioned tabs (tabPos is either s or n), true

forces all tabs to be equal width (the width being equal to the longest label plus any padX specified). Horizontal tabs are always equal in height.

For vertically positioned tabs (tabPos is either w or e), true

forces all tabs to be equal height (the height being equal to the height of the label with the largest font). Vertically oriented tabs are always equal in width.

Name: gap

Class: Gap

Command-Line Switch: -gap

Specifies the amount of pixel space to place between each tab.

Value may be any pixel offset value. In addition, a special key-

word overlap can be used as the value to achieve a standard over- lap of tabs. This value may have any of the forms acceptable to

Tk_GetPixels.

Name: margin

Class: Margin

Command-Line Switch: -margin

Specifies the amount of space to place between the outside edge

of the tabset and the outside edge of its tabs. If tabPos is s, this is the amount of space between the bottom edge of the tabset and the bottom edge of the set of tabs. If tabPos is n, this is the amount of space between the top edge of the tabset and the top edge of the set of tabs. If tabPos is e, this is the amount of space between the right edge of the tabset and the right edge of the set of tabs. If tabPos is w, this is the amount of space between the left edge of the tabset and the left edge of the set of tabs. This value may have any of the forms acceptable to

Tk_GetPixels.

Name: padX

Class: PadX

Command-Line Switch: -padx

Specifies a non-negative value indicating how much extra space to

request for a tab around its label in the X-direction. When com- puting how large a window it needs, the tab will add this amount to the width it would normally need The tab will end up with extra internal space to the left and right of its text label.

This value may have any of the forms acceptable to Tk_GetPixels.

Name: padY

Class: PadY

Command-Line Switch: -pady

Specifies a non-negative value indicating how much extra space to

request for a tab around its label in the Y-direction. When com- puting how large a window it needs, the tab will add this amount to the height it would normally need The tab will end up with extra internal space to the top and bottom of its text label.

This value may have any of the forms acceptable to Tk_GetPixels.

Name: raiseSelect

Class: RaiseSelect

Command-Line Switch: -raiseselect

Specifes whether to slightly raise the selected tab from the rest

of the tabs. The selected tab is drawn 2 pixels closer to the outside edge of the tabset than the unselected tabs. A value of true says to raise selected tabs, a value of false turns this off. The default is false. The value may have any of the forms accepted by the Tcl_GetBoolean, such as true, false, 0, 1, yes, or no.

Name: start

Class: Start

Command-Line Switch: -start

Specifies the amount of space to place between the left or top

edge of the tabset and the starting edge of its tabs. For hori- zontally positioned tabs, this is the amount of space between the left edge of the tabset and the left edge of the first tab. For vertically positioned tabs, this is the amount of space between the top of the tabset and the top of the first tab. This value may change if the user performs a MButton-2 scroll on the tabs.

This value may have any of the forms acceptable to Tk_GetPixels.

Name: state

Class: State

Command-Line Switch: -state

Sets the active state of the tabset. Specifying normal allows all

tabs to be selectable. Specifying disabled disables the tabset causing all tabs to be drawn in the disabledForeground color.

Name: tabBorders

Class: TabBorders

Command-Line Switch: -tabborders

Specifies whether to draw the borders of tabs that are not

selected. Specifying true (the default) draws these borders, specifying false draws only the border around the selected tab.

The value may have any of the forms accepted by the Tcl_Get-

Boolean, such as true, false, 0, 1, yes, or no.

Name: tabPos

Class: TabPos

Command-Line Switch: -tabpos

Specifies the location of the set of tabs in relation to another

widget. Must be n, s, e, or w. Defaults to s. North tabs open downward, South tabs open upward. West tabs open to the right, east tabs open to the left.
_________________________________________________________________

Description

The iwidgets::tabset command creates a new window (given by the

pathName argument) and makes it into a tabset widget. Additional options, described above may be specified on the command line or in the option database to configure aspects of the tabset such as its colors, font, and text. The iwidgets::tabset command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A tabset is a widget that contains a set of Tab buttons. It dis-

plays these tabs in a row or column depending on it tabpos. When a tab is clicked on, it becomes the only tab in the tab set that is selected. All other tabs are deselected. The Tcl command pre- fix associated with this tab (through the command tab configure option) is invoked with the tab index number appended to its argument list. This allows the tabset to control another widget such as a Notebook.

Tabs

Tabs are drawn to appear attached to another widget. The tabset

draws an edge boundary along one of its edges. This edge is known as the attachment edge. This edge location is dependent on the value of tabPos. For example, if tabPos is s, the attachment edge wil be on the top side of the tabset (in order to attach to the bottom or south side of its attached widget). The selected tab is draw with a 3d relief to appear above the other tabs. This selected tab «opens» toward attachment edge.

Tabs can be controlled in their location along the edges, the

angle that tab sides are drawn with, gap between tabs, starting margin of tabs, internal padding around labels in a tab, the font, and its text or bitmap.

Widget-specific Methods

The iwidgets::tabset command creates a new Tcl command whose name

is pathName. This command may be used to invoke various opera- tions on the widget. It has the following general form:

pathName option ?arg arg ...?

option and the args determine the exact behavior of the command.

Many of the widget commands for a tabset take as one argument an

indicator of which tab of the tabset to operate on. These indica- tors are called indexes and may be specified in any of the fol- lowing forms:
number

Specifies the tab numerically, where 0 corresponds to the first

tab in the tab set, 1 to the second, and so on. select

Specifies the currently selected tab's index. If no tab is cur-

rently selected, the value -1 is returned.
end

Specifes the last tab in the tabset's index. If the tabset is

empty this will return -1.
pattern

If the index doesn't satisfy any of the above forms, then this

form is used. Pattern is pattern-matched against the label of each tab in the tabset, in order from the first to the last tab, until a matching entry is found. The rules of Tcl_StringMatch are used.

The following commands are possible for tabset widgets:

pathName add ?option value option value ...?

Add a new tab at the end of the tabset. Returns the child site

pathName. If additional arguments are present, they specify any of the following options:
-angle value

Specifes the angle of slope from the inner edge to the outer edge

of the tab. An angle of 0 specifies square tabs. Valid ranges are 0 to 45 degrees inclusive. Default is 15 degrees. If this option is specified as an empty string (the default), then the angle option for the overall tabset is used.
-background value

Specifies a background color to use for displaying tabs when they

are in their normal state (unselected). If this option is speci- fied as an empty string (the default), then the background option for the overall tabset is used.
-bevelamount value

Specifes the size of tab corners. A value of 0 with angle set to

0 results in square tabs. A bevelAmount of 4, means that the tab will be drawn with angled corners that cut in 4 pixels from the edge of the tab. The default is 0. This is generally only set at the tabset configuration level. Tabs normally will want to share the same bevelAmount.
-bitmap value

If label is a non-empty string, specifies a bitmap to display in

the tab. Bitmap may be of any of the forms accepted by Tk_Get-

Bitmap.

-disabledforeground value

Specifies a foreground color to use for displaying tab labels

when tabs are in their disable state. If this option is specified as an empty string (the default), then the disabledforeground option for the overall tabset is used.
-font value

Specifies the font to use when drawing the label on a tab. If

this option is specified as an empty string then the font option for the overall tabset is used.
-foreground value

Specifies a foreground color to use for displaying tab labels

when tabs are in their normal unselected state. If this option is specified as an empty string (the default), then the foreground option for the overall tabset is used.
-image value

If label is a non-empty string, specifies an image to display in

the tab. Image must have been created with the image create com- mand. Typically, if the image option is specified then it over- rides other options that specify a bitmap or textual value to display in the widget; the image option may be reset to an empty string to re-enable a bitmap or text display. -label value

Specifies a text string to be placed in the tabs label. If this

value is set, the bitmap option is overridden and this option is used instead. This label serves as an additional identifier used to reference the tab. This label may be used for the index value in widget commands.
-selectbackground value

Specifies a background color to use for displaying the selected

tab. If this option is specified as an empty string (the default), then the selectBackground option for the overall tabset is used.
-selectforeground value

Specifies a foreground color to use for displaying the selected

tab. If this option is specified as an empty string (the default), then the selectForeground option for the overall tabset is used.
-padx value

Specifies a non-negative value indicating how much extra space to

request for a tab around its label in the X-direction. When computing how large a window it needs, the tab will add this amount to the width it would normally need The tab will end up with extra internal space to the left and right of its text label. This value may have any of the forms acceptable to Tk_Get-

Pixels. If this option is specified as an empty string (the

default), then the padX option for the overall tabset is used -pady value

Specifies a non-negative value indicating how much extra space to

request for a tab around its label in the Y-direction. When com- puting how large a window it needs, the tab will add this amount to the height it would normally need The tab will end up with extra internal space to the top and bottom of its text label.

This value may have any of the forms acceptable to Tk_GetPixels.

If this option is specified as an empty string (the default),

then the padY option for the overall tabset is used -state value

Sets the state of the tab. Specifying normal allows this tab to

be selectable. Specifying disabled disables the this tab causing its tab label to be drawn in the disabledForeground color. The tab will not respond to events until the state is set back to normal.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::tabset command. pathName delete index1 ?index2?

Delete all of the tabs between index1 and index2 inclusive. If

index2 is omitted then it defaults to index1. Returns an empty string.
pathName index index

Returns the numerical index corresponding to index.

pathName insert index ?option value option value ...?

Insert a new tab in the tabset before the tab specified by index.

The additional arguments are the same as for the add command.

Returns the tab's pathName.

pathName next

Advances the selected tab to the next tab (order is determined by

insertion order). If the currently selected tab is the last tab in the tabset, the selection wraps around to the first tab. It behaves as if the user selected the next tab. pathName tabconfigure index ?option? ?value?

This command is similar to the configure command, except that it

applies to the options for an individual tab, whereas configure applies to the options for the tabset as a whole. Options may have any of the values accepted by the add widget command. If options are specified, options are modified as indicated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for tab index (see Tk_ConfigureInfo for information on the format of this list).
pathName prev

Moves the selected tab to the previous tab (order is determined

by insertion order). If the currently selected tab is the first tab in the tabset, the selection wraps around to the last tab in the tabset. It behaves as if the user selected the previous tab. pathName select index

Selects the tab specified by index as the currently selected tab.

It behaves as if the user selected the new tab.

Example

Following is an example that creates a tabset with two tabs and a

list box that the tabset controls. In addition selecting an item from the list also selects the corresponding tab. package require Iwidgets 4.0
# Define a proc that knows how to select an item # from a list given an index from the tabset -command callback. proc selectItem { item } {
.l selection clear [.l curselection]
.l selection set $item
.l see $item
}
# Define a proc that knows how to select a tab # given a y pixel coordinate from the list.. proc selectTab { y } {
set whichItem [.l nearest $y]
.ts select $whichItem
}
# Create a listbox with two items (one and two) # and bind button 1 press to the selectTab procedure. listbox .l -selectmode single -exportselection false .l insert end one
.l insert end two
.l selection set 0
pack .l
bind .l <ButtonPress-1> { selectTab %y }
# Create a tabset, set its -command to call selectItem # Add two labels to the tabset (one and two). iwidgets::tabset .ts -command selectItem
.ts add -label 1
.ts add -label 2
.ts select 0
pack .ts -fill x -expand no

Author

Bill W. Scott

Keywords

tab tabset notebook tabnotebook

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: angle
  • Class: Angle
  • Command-Line Switch: -angle
  • Specifes the angle of slope from the inner edge to the outer edge
  • Name: backdrop
  • Class: Backdrop
  • Command-Line Switch: -backdrop
  • Specifies a background color to use when filling in the area
  • Name: bevelAmount
  • Class: BevelAmount
  • Command-Line Switch: -bevelamount
  • Specifes the size of tab corners. A value of 0 with angle set to
  • Name: command
  • Class: Command
  • Command-Line Switch: -command
  • Specifes the prefix of a Tcl command to invoke to change the view in the
  • Name: equalTabs
  • Class: EqualTabs
  • Command-Line Switch: -equaltabs
  • Specifies whether to force tabs to be equal sized or not. A value
  • For horizontally positioned tabs (tabPos is either s or n), true
  • For vertically positioned tabs (tabPos is either w or e), true
  • Name: gap
  • Class: Gap
  • Command-Line Switch: -gap
  • Specifies the amount of pixel space to place between each tab.
  • Value may be any pixel offset value. In addition, a special key-
  • Tk_GetPixels.
  • Name: margin
  • Class: Margin
  • Command-Line Switch: -margin
  • Specifies the amount of space to place between the outside edge
  • Tk_GetPixels.
  • Name: padX
  • Class: PadX
  • Command-Line Switch: -padx
  • Specifies a non-negative value indicating how much extra space to
  • This value may have any of the forms acceptable to Tk_GetPixels.
  • Name: padY
  • Class: PadY
  • Command-Line Switch: -pady
  • Specifies a non-negative value indicating how much extra space to
  • This value may have any of the forms acceptable to Tk_GetPixels.
  • Name: raiseSelect
  • Class: RaiseSelect
  • Command-Line Switch: -raiseselect
  • Specifes whether to slightly raise the selected tab from the rest
  • Name: start
  • Class: Start
  • Command-Line Switch: -start
  • Specifies the amount of space to place between the left or top
  • This value may have any of the forms acceptable to Tk_GetPixels.
  • Name: state
  • Class: State
  • Command-Line Switch: -state
  • Sets the active state of the tabset. Specifying normal allows all
  • Name: tabBorders
  • Class: TabBorders
  • Command-Line Switch: -tabborders
  • Specifies whether to draw the borders of tabs that are not
  • The value may have any of the forms accepted by the Tcl_Get-
  • Boolean, such as true, false, 0, 1, yes, or no.
  • Name: tabPos
  • Class: TabPos
  • Command-Line Switch: -tabpos
  • Specifies the location of the set of tabs in relation to another
  • Description
  • The iwidgets::tabset command creates a new window (given by the
  • A tabset is a widget that contains a set of Tab buttons. It dis-
  • Tabs
  • Tabs are drawn to appear attached to another widget. The tabset
  • Tabs can be controlled in their location along the edges, the
  • Widget-specific Methods
  • The iwidgets::tabset command creates a new Tcl command whose name
  • Many of the widget commands for a tabset take as one argument an
  • Specifies the tab numerically, where 0 corresponds to the first
  • Specifies the currently selected tab's index. If no tab is cur-
  • Specifes the last tab in the tabset's index. If the tabset is
  • If the index doesn't satisfy any of the above forms, then this
  • The following commands are possible for tabset widgets:
  • Add a new tab at the end of the tabset. Returns the child site
  • Specifes the angle of slope from the inner edge to the outer edge
  • Specifies a background color to use for displaying tabs when they
  • Specifes the size of tab corners. A value of 0 with angle set to
  • If label is a non-empty string, specifies a bitmap to display in
  • Bitmap.
  • Specifies a foreground color to use for displaying tab labels
  • Specifies the font to use when drawing the label on a tab. If
  • Specifies a foreground color to use for displaying tab labels
  • If label is a non-empty string, specifies an image to display in
  • Specifies a text string to be placed in the tabs label. If this
  • Specifies a background color to use for displaying the selected
  • Specifies a foreground color to use for displaying the selected
  • Specifies a non-negative value indicating how much extra space to
  • Pixels. If this option is specified as an empty string (the
  • Specifies a non-negative value indicating how much extra space to
  • This value may have any of the forms acceptable to Tk_GetPixels.
  • If this option is specified as an empty string (the default),
  • Sets the state of the tab. Specifying normal allows this tab to
  • Query or modify the configuration options of the widget. If no
  • Delete all of the tabs between index1 and index2 inclusive. If
  • Returns the numerical index corresponding to index.
  • Insert a new tab in the tabset before the tab specified by index.
  • The additional arguments are the same as for the add command.
  • Returns the tab's pathName.
  • Advances the selected tab to the next tab (order is determined by
  • This command is similar to the configure command, except that it
  • Moves the selected tab to the previous tab (order is determined
  • Selects the tab specified by index as the currently selected tab.
  • It behaves as if the user selected the new tab.
  • Example
  • Following is an example that creates a tabset with two tabs and a
  • Author
  • Bill W. Scott
  • Keywords


IWidgets timeentry

 Table of Contents

iwidgets::timeentry - Create and manipulate a timeentry widget

Synopsis

iwidgets::timeentry pathName ?options?

Inheritance

itk::Widget <- iwidgets::LabeledWidget <- iwidgets::Timefield <- iwidgets::Timeentry

Standard Options

background borderWidth cursor exportSelection foreground highlightColor highlightThickness insertBackground

justify
relief

See the «options» manual entry for details on the standard

options.

Inherited Options

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable state sticky

See the «labeledwidget» class manual entry for details on these

inherited options.
command format seconds textBackground textFont

See the «timefield» class manual entry for details on these

inherited options.

Associated Options

hourRadius hourColor minuteRadius minuteColor pivotRadius pivotColor secondRadius secondColor clockColor clockStipple tickColor watchHeight watchWidth

See the «watch» manual entry for details on the associated

options.

Widget-specific Options

Name: closeText

Class: Text

Command-Line Switch: -closetext

Specifies the text to be displayed on the close button of the

watch popup. The default is Close.

Name: grab

Class: Grab

Command-Line Switch: -grab

Specifies the grab level, local or global, to be obtained before

bringing up the popup watch. The default is global. For more information concerning grab levels, consult the documentation for

Tk's grab command.

Name: icon

Class: Icon

Command-Line Switch: -icon

Specifies the watch icon image to be used in the timeentry. This

image must have been created previously with the image create command. Should one not be provided, then one will be generated, pixmap if possible, bitmap otherwise.

Name: state

Class: State

Command-Line Switch: -state

Specifies the state of the widget which may be disabled or nor-

mal. A disabled state prevents selection of the timefield or time icon button.
_________________________________________________________________

Description

The iwidgets::timeentry command creates a time entry field with a

popup watch by combining the timefield and watch widgets together. This allows a user to enter the time via the keyboard or by using the mouse and selecting the watch icon which brings up a popup watch.

Methods

The iwidgets::timeentry command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for timeentry widgets:

Inherited Methods

get
isvalid show

See the «timefield» manual entry for details on the associated

methods.

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::timeentry command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::timeentry command.

Components

Name: label

Class: Label

The label component provides a label component to used to iden-

tify the time. See the «label» widget manual entry for details on the label component item.

Name: iconbutton

Class: Label

The iconbutton component provides a labelbutton component to act

as a lightweight button displaying the watch icon. Upon pressing the labelbutton, the watch appears. See the «label» widget man- ual entry for details on the labelbutton component item.

Name: time

Class: Entry

The time component provides the entry field for time input and

display. See the «entry» widget manual entry for details on the time component item.

Example

package require Iwidgets 4.0
iwidgets::timeentry .te
pack .te

Author

Mark L. Ulferts

Keywords

timeentry, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "labeledwidget" class manual entry for details on these
  • See the "timefield" class manual entry for details on these
  • Associated Options
  • See the "watch" manual entry for details on the associated
  • Widget-specific Options
  • Name: closeText
  • Class: Text
  • Command-Line Switch: -closetext
  • Specifies the text to be displayed on the close button of the
  • Name: grab
  • Class: Grab
  • Command-Line Switch: -grab
  • Specifies the grab level, local or global, to be obtained before
  • Tk's grab command.
  • Name: icon
  • Class: Icon
  • Command-Line Switch: -icon
  • Specifies the watch icon image to be used in the timeentry. This
  • Name: state
  • Class: State
  • Command-Line Switch: -state
  • Specifies the state of the widget which may be disabled or nor-
  • Description
  • The iwidgets::timeentry command creates a time entry field with a
  • Methods
  • The iwidgets::timeentry command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for timeentry widgets:
  • Inherited Methods
  • See the "timefield" manual entry for details on the associated
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Components
  • Name: label
  • Class: Label
  • The label component provides a label component to used to iden-
  • Name: iconbutton
  • Class: Label
  • The iconbutton component provides a labelbutton component to act
  • Name: time
  • Class: Entry
  • The time component provides the entry field for time input and
  • Example
  • Author
  • Mark L. Ulferts
  • Keywords


IWidgets timefield

 Table of Contents

iwidgets::timefield - Create and manipulate a time field widget

Synopsis

iwidgets::timefield pathName ?options?

Inheritance

itk::Widget <- iwidgets::LabeledWidget <- iwidgets::Timefield

Standard Options

background borderWidth cursor exportSelection foreground highlightColor highlightThickness insertBackground

justify
relief

See the «options» manual entry for details on the standard

options.

Inherited Options

disabledForeground
labelBitmap labelFontlabelImage labelMargin labelPos labelText labelVariable
state
sticky

See the «labeledwidget» class manual entry for details on the

inherited options.

Widget-specific Options

Name: childSitePos

Class: Position

Command-Line Switch: -childsitepos

Specifies the position of the child site in the time field: n, s,

e, or w. The default is e.

Name: command

Class: Command

Command-Line Switch: -command

Specifies a Tcl command to be executed upon detection of a Return

key press event.

Name: gmt

Class: Gmt

Command-Line Switch: -gmt

Determines whether the time is calculated relative to Greenwich

Mean Time. Accepts a boolean value. The default is no.

Name: state Class: State Command-Line

Switch: -state

Specifies one of two states for the timefield: normal or dis-

abled. If the timefield is disabled then input is not accepted.

The default is normal.

Name: textBackground

Class: Background

Command-Line Switch: -textbackground

Background color for inside textual portion of the entry field.

The value may be given in any of the forms acceptable to Tk_Get-

Color.

Name: textFont

Class: Font

Command-Line Switch: -textfont

Name of font to use for display of text in timefield. The value

may be given in any of the forms acceptable to Tk_GetFont. _________________________________________________________________

Description

The iwidgets::timefield command creates an enhanced text entry

widget for the purpose of time entry with various degrees of built-in intelligence.

Methods

The iwidgets::timefield command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

Option and the args determine the exact behavior of the command.

The following commands are possible for timefield widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::timefield command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::timefield command. pathName get ?format?

Returns the current contents of the timefield in a format of

string or as an integer clock value using the -string and -clicks format options respectively. The default is by string. Refer- ence the clock command for more information on obtaining times and their formats.
pathName isvalid

Returns a boolean indication of the validity of the currently

displayed time value. For example, 12:59:59 is valid whereas 25:59:59 is invalid.
pathName show time

Changes the currently displayed time to be that of the time argu-

ment. The time may be specified either as a string, an integer clock value or the keyword «now» (the default). Reference the clock command for more information on obtaining times and their formats.

Components

Name: time

Class: Entry

The time component provides the entry field for time input and

display. See the «entry» widget manual entry for details on the time component item.

Example

package require Iwidgets 4.0
proc returnCmd {} {
puts [.tf get]
}

iwidgets::timefield .tf -command returnCmd
pack .tf -fill x -expand yes -padx 10 -pady 10

Author

John A. Tucker

Mark L. Ulferts

Keywords

timefield, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Inherited Options
  • See the "labeledwidget" class manual entry for details on the
  • Widget-specific Options
  • Name: childSitePos
  • Class: Position
  • Command-Line Switch: -childsitepos
  • Specifies the position of the child site in the time field: n, s,
  • Name: command
  • Class: Command
  • Command-Line Switch: -command
  • Specifies a Tcl command to be executed upon detection of a Return
  • Name: gmt
  • Class: Gmt
  • Command-Line Switch: -gmt
  • Determines whether the time is calculated relative to Greenwich
  • Mean Time. Accepts a boolean value. The default is no.
  • Name: state Class: State Command-Line
  • Switch: -state
  • Specifies one of two states for the timefield: normal or dis-
  • The default is normal.
  • Name: textBackground
  • Class: Background
  • Command-Line Switch: -textbackground
  • Background color for inside textual portion of the entry field.
  • The value may be given in any of the forms acceptable to Tk_Get-
  • Color.
  • Name: textFont
  • Class: Font
  • Command-Line Switch: -textfont
  • Name of font to use for display of text in timefield. The value
  • Description
  • The iwidgets::timefield command creates an enhanced text entry
  • Methods
  • The iwidgets::timefield command creates a new Tcl command whose
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for timefield widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Returns the current contents of the timefield in a format of
  • Returns a boolean indication of the validity of the currently
  • Changes the currently displayed time to be that of the time argu-
  • Components
  • Name: time
  • Class: Entry
  • The time component provides the entry field for time input and
  • Example
  • Author
  • John A. Tucker
  • Mark L. Ulferts
  • Keywords


IWidgets toolbar

 Table of Contents

iwidgets::toolbar - Create and manipulate a tool bar

Synopsis

iwidgets::toolbar pathName ?options?

Inheritance

itk::Widget <- iwidgets::Toolbar

Standard Options

activeBackground
activeForeground background borderWidth
cursor
disabledForeground font foreground highlightBackground highlightColor highlightThickness insertBackground insertForeground orient selectBackground selectBorderWidth selectForeground state troughColor

See the «options» manual entry for details on the standard

options. For widgets added to the toolbar, these options will be propogated if the widget supports the option. For example, all widgets that support a font option will be changed if the the toolbar's font option is configured.

Widget-specific Options

Name: balloonBackground

Class: BalloonBackground

Command-Line Switch: -ballooonbackground

Specifies the background color of the balloon help displayed at

the bottom center of a widget on the toolbar that has a non empty string for its balloonStr option. The default color is yellow.

Name: balloonDelay1

Class: BalloonDelay1

Command-Line Switch: -balloondelay1

Specifies the length of time (in milliseconds) to wait before

initially posting a balloon help hint window. This delay is in effect whenever 1) the mouse leaves the toolbar, or 2) a toolbar item is selected with the mouse button.

Name: balloonDelay2

Class: BalloonDelay2

Command-Line Switch: -balloondelay2

Specifies the length of time (in milliseconds) to wait before

continuing to post balloon help hint windows. This delay is in effect after the first time a balloon hint window is activated.

It remains in effect until 1) the mouse leaves the toolbar, or 2)

a toolbar item is selected with the mouse button.

Name: balloonFont

Class: BalloonFont

Command-Line Switch: -balloonfont

Specifies the font of the balloon help text displayed at the bot-

tom center of a widget on the toolbar that has a non empty string for its balloonStr option. The default font is 6x10.

Name: balloonForeground

Class: BalloonForeground

Command-Line Switch: -ballooonforeground

Specifies the foreground color of the balloon help displayed at

the bottom center of a widget on the toolbar that has a non empty string for its balloonStr option. The default color is black.

Name: helpVariable

Class: HelpVariable

Command-Line Switch: -helpvariable

Specifies the global variable to update whenever the mouse is in

motion over a toolbar widget. This global variable is updated with the current value of the active widget's helpStr. Other wid- gets can «watch» this variable with the trace command, or as is the case with entry or label widgets, they can set their textVariable to the same global variable. This allows for a sim- ple implementation of a help status bar. Whenever the mouse leaves a menu entry, the helpVariable is set to the empty string {}.

Name: orient

Class: Orient

Command-Line Switch: -orient

Specifies the orientation of the toolbar. Must be either horizon-

tal or vertical.
_________________________________________________________________

Description

The iwidgets::toolbar command creates a new window (given by the

pathName argument) and makes it into a toolbar widget. Additional options, described above may be specified on the command line or in the option database to configure aspects of the toolbar such as its colors, font, and orientation. The iwidgets::toolbar com- mand returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but path-

Name's parent must exist.

A toolbar is a widget that displays a collection of widgets

arranged either in a row or a column (depending on the value of the -orient option). This collection of widgets is usually for user convenience to give access to a set of commands or settings.

Any widget may be placed on a toolbar. However, command or

value-oriented widgets (such as button, radiobutton, etc.) are usually the most useful kind of widgets to appear on a toolbar.

In addition, the toolbar adds two new options to all widgets that

are added to it. These are the helpStr and balloonStr options.

See the discussion for the widget command add below.

Widget-specific Methods

The iwidgets::toolbar command creates a new Tcl command whose

name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and args determine the exact behavior of the command.

Many of the widget commands for a toolbar take as one argument an

indicator of which widget item of the toolbar to operate on. The indicator is called an index and may be specified in any of the following forms:
number

Specifies the widget numerically, where 0 corresponds to the

first widget in the notebook, 1 to the second, and so on. (For horizontal, 0 is the leftmost; for vertical, 0 is the topmost). end

Specifes the last widget in the toolbar's index. If the toolbar

is empty this will return -1.
last

Same as end.

pattern

If the index doesn't satisfy any of the above forms, then this

form is used. Pattern is pattern-matched against the widgetName of each widget in the toolbar, in order from the first to the last widget, until a matching entry is found. An exact match must occur.

The following commands are possible for toolbar widgets:

pathName add widgetCommand widgetName ?option value?

Adds a widget with the command widgetCommand whose name is wid-

getName to the toolbar. If widgetCommand is radiobutton or check- button, its packing is slightly padded to match the geometry of button widgets. In addition, the indicatorOn option is false by default and the selectColor is that of the toolbar background by default. This allows Radiobutton and Checkbutton widgets to be added as icons by simply setting their bitmap or image options.

If additional arguments are present, they are the set of avail-

able options that the widget type of widgetCommand supports. In addition they may also be one of the following options: -helpstr value

Specifes the help string to associate with the widget. When the

mouse moves over the widget, the variable denoted by helpVariable is set to helpStr. Another widget can bind to the helpVariable and thus track status help.
-balloonstr value

Specifes the string to display in a balloon window for this wid-

get. A balloon window is a small popup window centered at the bottom of the widget. Usually the balloonStr value is the name of the item on the toolbar. It is sometimes known as a hint window.

When the mouse moves into an item on the toolbar, a timer is set

based on the value of balloonDelay1. If the mouse stays inside the item for balloonDelay1, the balloon window will pop up dis- playing the balloonStr value. Once the balloon window is posted, a new timer based on balloonDelay2 is set. This is typically a shorter timer. If the mouse is moved to another item, the window is unposted and a new window will be posted over the item if the shorter delay time is satisfied.

While the balloon window is posted, it can also be unposted if

the item is selected. In this case the timer is reset to balloon-

Delay1. Whenever the mouse leaves the toolbar, the timer is also

reset to balloonDelay1.

This window posting/unposting model is the same model used in the

Windows95 environment.

pathName cget option

Returns the current value of the configuration option given by

option.
pathName configure ?option value?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string.
pathName delete index ?index2?

This command deletes all items between index and index2 inclu-

sive. If index2 is omitted then it defaults to index. Returns an empty string.
pathName index index

Returns the widget's numerical index for the entry corresponding

to index. If index is not found, -1 is returned. pathName insert beforeIndex widgetCommand widgetName ?option value?

Insert a new item named widgetName with the

command widgetCommand before the item specified by beforeIndex.

If widgetCommand is radiobutton or checkbutton, its packing is

slightly padded to match the geometry of button widgets. In addi- tion, the indicatorOn option is false by default and the select-

Color is that of the toolbar background by default. This allows

Radiobutton and Checkbutton widgets to be added as icons by sim-

ply setting their bitmap or image options. The set of available options is the same as specified in the ad command. pathName itemcget index option

Returns the current value of the configuration option given by

option for index. The item type of index determines the valid available options.
pathName itemconfigure index ?option value?

Query or modify the configuration options of the widget of the

toolbar specified by index. If no option is specified, returns a list describing all of the available options for index (see

Tk_ConfigureInfo for information on the format of this list). If

option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string.

The item type of index determines the valid available options.

The set of available options is the same as specified in the ad

command.

Example

package require Iwidgets 4.0
iwidgets::toolbar .tb -helpvariable statusVar

.tb add button item1 \
-helpstr «Save It» -bitmap @./icons/Tool_32_box.xbm \ -balloonstr «Save» -command {puts 1}
.tb add button item2 \
-helpstr «Save It» -bitmap @./icons/Tool_32_brush.xbm \ -balloonstr «Save» -command {puts 1}
.tb add button item3 \
-helpstr «Save It» -bitmap @./icons/Tool_32_cut.xbm \ -balloonstr «Save» -command {puts 1}
.tb add button item4 \
-helpstr «Save It» -bitmap @./icons/Tool_32_draw.xbm \ -balloonstr «Save» -command {puts 1}
.tb add button item5 \
-bitmap @./icons/Tool_32_erase.xbm -helpstr «Play It» \ -command {puts 2}
.tb add frame filler \
-borderwidth 1 -width 10 -height 10
.tb add radiobutton item6 \
-bitmap @./icons/Tool_32_oval.xbm -command {puts 4} \ -variable result -value OPEN -helpstr «Radio Button # 1» \ -balloonstr «Radio"
.tb add radiobutton item7 \
-bitmap @./icons/Tool_32_line.xbm -command {puts 5} \ -variable result -value CLOSED
.tb add checkbutton item8 \
-bitmap @./icons/Tool_32_text.xbm -command {puts 6} \ -variable checkit -onvalue yes -offvalue no .tb add checkbutton check2 \
-bitmap @./icons/Tool_32_points.xbm -command {puts 7} \ -variable checkit2 -onvalue yes -offvalue no

pack .tb -side top -anchor nw

Author

Bill Scott

Keywords

toolbar, button, radiobutton, checkbutton, iwidgets, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Widget-specific Options
  • Name: balloonBackground
  • Class: BalloonBackground
  • Command-Line Switch: -ballooonbackground
  • Specifies the background color of the balloon help displayed at
  • Name: balloonDelay1
  • Class: BalloonDelay1
  • Command-Line Switch: -balloondelay1
  • Specifies the length of time (in milliseconds) to wait before
  • Name: balloonDelay2
  • Class: BalloonDelay2
  • Command-Line Switch: -balloondelay2
  • Specifies the length of time (in milliseconds) to wait before
  • It remains in effect until 1) the mouse leaves the toolbar, or 2)
  • Name: balloonFont
  • Class: BalloonFont
  • Command-Line Switch: -balloonfont
  • Specifies the font of the balloon help text displayed at the bot-
  • Name: balloonForeground
  • Class: BalloonForeground
  • Command-Line Switch: -ballooonforeground
  • Specifies the foreground color of the balloon help displayed at
  • Name: helpVariable
  • Class: HelpVariable
  • Command-Line Switch: -helpvariable
  • Specifies the global variable to update whenever the mouse is in
  • Name: orient
  • Class: Orient
  • Command-Line Switch: -orient
  • Specifies the orientation of the toolbar. Must be either horizon-
  • Description
  • The iwidgets::toolbar command creates a new window (given by the
  • Name's parent must exist.
  • A toolbar is a widget that displays a collection of widgets
  • Any widget may be placed on a toolbar. However, command or
  • In addition, the toolbar adds two new options to all widgets that
  • See the discussion for the widget command add below.
  • Widget-specific Methods
  • The iwidgets::toolbar command creates a new Tcl command whose
  • Option and args determine the exact behavior of the command.
  • Many of the widget commands for a toolbar take as one argument an
  • Specifies the widget numerically, where 0 corresponds to the
  • Specifes the last widget in the toolbar's index. If the toolbar
  • Same as end.
  • If the index doesn't satisfy any of the above forms, then this
  • The following commands are possible for toolbar widgets:
  • Adds a widget with the command widgetCommand whose name is wid-
  • If additional arguments are present, they are the set of avail-
  • Specifes the help string to associate with the widget. When the
  • Specifes the string to display in a balloon window for this wid-
  • When the mouse moves into an item on the toolbar, a timer is set
  • While the balloon window is posted, it can also be unposted if
  • Delay1. Whenever the mouse leaves the toolbar, the timer is also
  • This window posting/unposting model is the same model used in the
  • Windows95 environment.
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • This command deletes all items between index and index2 inclu-
  • Returns the widget's numerical index for the entry corresponding
  • Insert a new item named widgetName with the
  • If widgetCommand is radiobutton or checkbutton, its packing is
  • Color is that of the toolbar background by default. This allows
  • Radiobutton and Checkbutton widgets to be added as icons by sim-
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget of the
  • Tk_ConfigureInfo for information on the format of this list). If
  • The item type of index determines the valid available options.
  • The set of available options is the same as specified in the ad
  • Example
  • Author
  • Bill Scott
  • Keywords


IWidgets watch

 Table of Contents

iwidgets::watch - Create and manipulate time with a watch widgets

Synopsis

iwidgets::watch pathName ?options?

Inheritance

itk::Widget <- iwidgets::Watch

Standard Options

background cursor foreground relief

See the «options» manual entry for details on the standard

options.

Associated Options

See the «Canvas» manual entry for details on the above associated

options.

Widget-specific Options

Name: clockColor

Class: ColorfR

Command-Line Switch: -clockcolor

Fill color for the main oval encapsulating the watch, in any of

the forms acceptable to Tk_GetColor. The default is «White".

Name: clockStipple

Class: BitmapfR

Command-Line Switch: -clockstipple

Bitmap for the main oval encapsulating the watch, in any of the

forms acceptable to Tk_GetBitmap. The default is «".

Name: height

Class: Height

Command-Line Switch: -height

Specifies the height of the watch widget in any of the forms

acceptable to Tk_GetPixels. The default height is 175 pixels.

Name: hourColor

Class: ColorfR

Command-Line Switch: -hourcolor

Fill color for the hour hand, in any of the forms acceptable to

Tk_GetColor. The default is «Red".

Name: hourRadius

Class: Radius

Command-Line Switch: -hourradius

Specifies the radius of the hour hand as a percentage of the

radius from the center to the out perimeter of the clock. The value must be a fraction <= 1. The default is «.5".

Name: minuteColor

Class: ColorfR

Command-Line Switch: -minutecolor

Fill color for the minute hand, in any of the forms acceptable to

Tk_GetColor. The default is «Yellow".

Name: minuteRadius

Class: Radius

Command-Line Switch: -minuteradius

Specifies the radius of the minute hand as a percentage of the

radius from the center to the out perimeter of the clock. The value must be a fraction <= 1. The default is «.8".

Name: pivotColor

Class: ColorfR

Command-Line Switch: -pivotcolor

Fill color for the circle in which the watch hands rotate in any

of the forms acceptable to Tk_GetColor. The default is «White".

Name: pivotRadius

Class: Radius

Command-Line Switch: -pivotradius

Specifies the radius of the circle in which the watch hands

rotate as a percentage of the radius. The value must be a frac- tion <= 1. The default is «.1".

Name: secondColor

Class: ColorfR

Command-Line Switch: -secondcolor

Fill color for the second hand, in any of the forms acceptable to

Tk_GetColor. The default is «Black".

Name: secondRadius

Class: Radius

Command-Line Switch: -secondradius

Specifies the radius of the second hand as a percentage of the

radius from the center to the out perimeter of the clock. The value must be a fraction <= 1. The default is «.9".

Name: showAmPm

Class: ShosAmPm

Command-Line Switch: -showampm

Specifies whether the AM/PM radiobuttons should be displayed, in

any of the forms acceptable to Tcl_GetBoolean. The default is yes.

Name: state

Class: State

Command-Line Switch: -state

Specifies the editable state for the hands on the watch. In a

normal state, the user can select and move the hands via mouse button 1. The valid values are normal, and disabled. The defult is normal.

Name: tickColor

Class: ColorfR

Command-Line Switch: -tickcolor

Fill color for the 60 ticks around the perimeter of the watch, in

any of the forms acceptable to Tk_GetColor. The default is «Black".

Name: width

Class: Width

Command-Line Switch: -width

Specifies the width of the watch widget in any of the forms

acceptable to Tk_GetPixels. The default height is 155 pixels. _________________________________________________________________

Description

The iwidgets::watch command creates a watch with hour, minute,

and second hands modifying the time value.

Methods

The iwidgets::watch command creates a new Tcl command whose name

is pathName. This command may be used to invoke various opera- tions on the widget. It has the following general form:

pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for watch widgets:

Widget-specific Methods

pathName cget option

Returns the current value of the configuration option given by

option. Option may have any of the values accepted by the iwid- gets::watch command.
pathName configure ?option? ?value option value ...?

Query or modify the configuration options of the widget. If no

option is specified, returns a list describing all of the avail- able options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the iwidgets::watch command. pathName get ?format?

Returns the current time of the watch in a format of string or as

an integer clock value using the -string and -clicks format options respectively. The default is by string. Reference the clock command for more information on obtaining time and its for- mats.
pathName show time

Changes the currently displayed time to be that of the time argu-

ment. The time may be specified either as a string, an integer clock value or the keyword «now". Reference the clock command for more information on obtaining time and its format. pathName watch ?args?

Evaluates the specifieds args against the canvas component.

Components

Name: canvas

Class: Canvas

The canvas component is the where the clock is drawn. See the

Canvas widget manual entry for details.

Name: frame

Class: Frame

The frame component is the where the «AM» and «PM» radiobuttons

are displayed. See the Frame widget manual entry for details.

Name: am

Class: Radiobutton

The am component indicates whether on not the time is relative to

«AM". See the Radiobutton widget manual entry for details.

Name: pm

Class: Radiobutton

The pm component indicates whether on not the time is relative to

«PM". See the Radiobutton widget manual entry for details.

Example

package require Iwidgets 4.0
iwidgets::watch .w -state disabled -showampm no -width 155 -height 155 pack .w -padx 10 -pady 10 -fill both -expand yes

while {1} {
after 1000
.w show
update
}

Author

John Tucker

Mark L. Ulferts

Keywords

watch, hand, ticks, pivot, widget

Table of Contents

  • Synopsis
  • Inheritance
  • Standard Options
  • See the "options" manual entry for details on the standard
  • Associated Options
  • See the "Canvas" manual entry for details on the above associated
  • Widget-specific Options
  • Name: clockColor
  • Class: ColorfR
  • Command-Line Switch: -clockcolor
  • Fill color for the main oval encapsulating the watch, in any of
  • Name: clockStipple
  • Class: BitmapfR
  • Command-Line Switch: -clockstipple
  • Bitmap for the main oval encapsulating the watch, in any of the
  • Name: height
  • Class: Height
  • Command-Line Switch: -height
  • Specifies the height of the watch widget in any of the forms
  • Name: hourColor
  • Class: ColorfR
  • Command-Line Switch: -hourcolor
  • Fill color for the hour hand, in any of the forms acceptable to
  • Tk_GetColor. The default is "Red".
  • Name: hourRadius
  • Class: Radius
  • Command-Line Switch: -hourradius
  • Specifies the radius of the hour hand as a percentage of the
  • Name: minuteColor
  • Class: ColorfR
  • Command-Line Switch: -minutecolor
  • Fill color for the minute hand, in any of the forms acceptable to
  • Tk_GetColor. The default is "Yellow".
  • Name: minuteRadius
  • Class: Radius
  • Command-Line Switch: -minuteradius
  • Specifies the radius of the minute hand as a percentage of the
  • Name: pivotColor
  • Class: ColorfR
  • Command-Line Switch: -pivotcolor
  • Fill color for the circle in which the watch hands rotate in any
  • Name: pivotRadius
  • Class: Radius
  • Command-Line Switch: -pivotradius
  • Specifies the radius of the circle in which the watch hands
  • Name: secondColor
  • Class: ColorfR
  • Command-Line Switch: -secondcolor
  • Fill color for the second hand, in any of the forms acceptable to
  • Tk_GetColor. The default is "Black".
  • Name: secondRadius
  • Class: Radius
  • Command-Line Switch: -secondradius
  • Specifies the radius of the second hand as a percentage of the
  • Name: showAmPm
  • Class: ShosAmPm
  • Command-Line Switch: -showampm
  • Specifies whether the AM/PM radiobuttons should be displayed, in
  • Name: state
  • Class: State
  • Command-Line Switch: -state
  • Specifies the editable state for the hands on the watch. In a
  • Name: tickColor
  • Class: ColorfR
  • Command-Line Switch: -tickcolor
  • Fill color for the 60 ticks around the perimeter of the watch, in
  • Name: width
  • Class: Width
  • Command-Line Switch: -width
  • Specifies the width of the watch widget in any of the forms
  • Description
  • The iwidgets::watch command creates a watch with hour, minute,
  • Methods
  • The iwidgets::watch command creates a new Tcl command whose name
  • Option and the args determine the exact behavior of the command.
  • The following commands are possible for watch widgets:
  • Widget-specific Methods
  • Returns the current value of the configuration option given by
  • Query or modify the configuration options of the widget. If no
  • Returns the current time of the watch in a format of string or as
  • Changes the currently displayed time to be that of the time argu-
  • Evaluates the specifieds args against the canvas component.
  • Components
  • Name: canvas
  • Class: Canvas
  • The canvas component is the where the clock is drawn. See the
  • Canvas widget manual entry for details.
  • Name: frame
  • Class: Frame
  • The frame component is the where the "AM" and "PM" radiobuttons
  • Name: am
  • Class: Radiobutton
  • The am component indicates whether on not the time is relative to
  • Name: pm
  • Class: Radiobutton
  • The pm component indicates whether on not the time is relative to
  • Example
  • Author
  • John Tucker
  • Mark L. Ulferts
  • Keywords


Simple Widgets
Label | Label widget with state option, dynamic help and drag and drop facilities
Entry | Entry widget with state option, dynamic help and drag and drop facilities
Button | Button widget with enhanced options
ArrowButton | Button widget with an arrow shape.
ProgressBar | Progress indicator widget
ScrollView | Display the visible area of a scrolled window
Separator | 3D separator widget

Manager Widgets
MainFrame | Manage toplevel with menu, toolbar and statusbar
LabelFrame | Frame with a Label
TitleFrame | Frame with a title
ScrolledWindow | Generic scrolled widget
ScrollableFrame | Scrollable frame containing widget
PanedWindow | Tiled layout manager widget
ButtonBox | Set of buttons with horizontal or vertical layout
PagesManager | Pages manager widget
NoteBook | Notebook manager widget
Dialog | Dialog abstraction with custom buttons

Composite Widgets
LabelEntry | LabelFrame containing an Entry widget.
ComboBox | ComboBox widget
SpinBox | SpinBox widget
Tree | Tree widget
ListBox | ListBox widget
MessageDlg | Message dialog box
ProgressDlg | Progress indicator dialog box
PasswdDlg | Login/Password dialog box
SelectFont | Font selection widget
SelectColor | Color selection widget

Commands Classes
Widget | The Widget base class
DynamicHelp | Provide help to Tk widget or BWidget
DragSite | Commands set for Drag facilities
DropSite | Commands set for Drop facilities
BWidget | Description text


Label

NAME
Label - Label widget with state option, dynamic help and drag and drop facilities
CREATION
Label pathName ?option value...?
STANDARD OPTIONS
-anchor
-background or -bg
-bitmap
-borderwidth or -bd
-cursor
-disabledforeground
-font
-foreground or -fg
-highlightbackground
-highlightcolor
-highlightthickness
-image
-justify
-padx
-pady
-relief
-takefocus
-text
-textvariable
-wraplength
WIDGET-SPECIFIC OPTIONS
-dragenabled
-dragendcmd
-dragevent
-draginitcmd
-dragtype
-dropcmd
-dropenabled
-dropovercmd
-droptypes
-focus
-height
-helptext
-helptype
-helpvar
-name
-state
-underline
-width
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName setfocus

DESCRIPTION

The Label widget extends the default Tk label. Options have been added to provide visual effect depending on the state of the Label, DynamicHelp options, and Drag and Drop.

WIDGET-SPECIFIC OPTIONS
-dragenabled
A boolean specifying if drag is enabled.
-dragendcmd
Specifies a command to be called when drag ended. dragendcmd must be a command conforming to the description of the option dragendcmd of DragSite::register.
-dragevent
Specifies the number of the mouse button associated to the drag. Must be 1, 2 or 3.
-draginitcmd
Specifies a command to be called when dragevent occurs on widget. draginitcmd must be a command conforming to the description of the option draginitcmd of DragSite::register.
If draginitcmd is empty, the internal draginitcmd command is used instead and returns:
IMAGE {copy} <image name> | if an image is displayed.
BITMAP {copy} <bitmap name> | if a bitmap is displayed.
TEXT {copy} <text> | if a text is displayed.
Note that if dragtype option is not empty, its value is used instead of those above.
-dragtype
Specifies an alternate type of dragged object.
-dropcmd
Specifies a command to be called when drop occurs on the widget. dropcmd must be a command conforming to the description of the option dropcmd of DropSite::register.
If dropcmd is empty, the command updates the label following the type of the data:
COLOR or FGCOLOR | reconfigure the foreground of the Label.
BGCOLOR | reconfigure the background of the Label.
IMAGE | reconfigure the Label to display the associated image.
BITMAP | reconfigure the Label to display the associated bitmap. image option is set to empty.
TEXT,
or any other tag 		reconfigure the Label to display the associated string. image and bitmap options are set to empty.
and returns 1.
-dropenabled
A boolean specifying if drop is enabled.
-dropovercmd
Specifies a command to be called when drag icon is over the widget. dropovercmd must be a command conforming to the description of the option dropovercmd of DropSite::register.
If dropovercmd is empty, Label always accepts the drop if data type is FGCOLOR, COLOR, BGCOLOR, and accepts all other data type only if state is normal.
-droptypes
Specifies a list of accepted dropped object/operation. See option droptypes of DropSite::register. for more infromation. Default accepts FGCOLOR, COLOR, BGCOLOR, TEXT, BITMAP and IMAGE, all with copy and move operations.
-focus
Specifies a pathname to set the focus on for Label::setfocus command.
-height
Specifies a desired height for the label. If an image or bitmap is being displayed in the label then the value is in screen units, for text it is in lines of text. If this option isn't specified, the label's desired height is computed from the size of the image or bitmap or text being displayed in it.
-helptext
Text for dynamic help. If empty, no help is available for this widget. See also DynamicHelp.
-helptype
Type of dynamic help. Use balloon or variable. See also DynamicHelp.
-helpvar
Variable to use when helptype option is variable. See also DynamicHelp.
-name
Specifies a standard name for the label. If the option *nameName is found in the resource database, then text and underline options are extracted from its value.
-state
Specifies one of two states for the Label: normal or disabled. In normal state the text of the Label is displayed using the foreground option. In disabled state the text of the Label is displayed using the disabledforeground option.
-underline
Specifies the integer index of a character to underline in the label. 0 corresponds to the first character of the text displayed, 1 to the next character, and so on.
The binding <Alt-char> is automatically set on the toplevel of the Label to call Label::setfocus.
-width
Specifies a desired width for the label. If an image or bitmap is being displayed in the label then the value is in screen units, for text it is in characters. If this option isn't specified, the label's desired width is computed from the size of the image or bitmap or text being displayed in it.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName setfocus
Set the focus on the pathname given by -focus option if -state is normal.


Entry

NAME
Entry - Entry widget with state option, dynamic help and drag and drop facilities
CREATION
Entry pathName ?option value...?
STANDARD OPTIONS
-background or -bg -borderwidth or -bd
-disabledforeground
-exportselection
-font
-foreground or -fg
-highlightbackground
-highlightcolor
-highlightthickness
-insertbackground
-insertborderwidth
-insertofftime
-insertontime
-insertwidth
-justify
-relief
-selectbackground
-selectborderwidth
-selectforeground
-takefocus
-text
-textvariable
-xscrollcommand
WIDGET-SPECIFIC OPTIONS
-command
-dragenabled
-dragendcmd
-dragevent
-draginitcmd
-dragtype
-dropcmd
-dropenabled
-dropovercmd
-droptypes
-editable
-helptext
-helptype
-helpvar
-show
-state
-width
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName invoke

DESCRIPTION

The Entry widget extends the default Tk entry. Options have been added to provide visual effect depending on the state of the Entry, DynamicHelp options, and Drag and Drop. Entry behaves much like a Label, with text option to set its contents.
Tk entry command can also be used on Entry widget.

WIDGET-SPECIFIC OPTIONS
-command
Specifies a command when user press <Return> in the Entry.
-dragenabled
A boolean specifying if drag is enabled.
-dragendcmd
Specifies a command to be called when drag ended. dragendcmd must be a command conforming to the description of the option dragendcmd of DragSite::register.
If dragendcmd is empty, the internal dragend command updates the entry following the operation (move or copy) and the dragged data (whole or selected part of the entry).
-dragevent
Specifies the number of the mouse button associated to the drag. Must be 1, 2 or 3.
-draginitcmd
Specifies a command to be called when dragevent occurs on widget. draginitcmd must be a command conforming to the description of the option draginitcmd of DragSite::register.
if draginitcmd is empty, the command refuse the drag if entry is empty or if portion of text is selected and event doesn't occur above the selection. In all other cases, the command returns:
  • as the data type, the value of option dragtype or TEXT if empty,
  • as the operations, {copy move} if state is normal and editable is true, or {copy} only in other cases,
  • as the data, the whole content or the selected portion of the entry.
-dragtype
Specifies an alternate type of dragged object.
-dropcmd
Entry has a command wrapper for drop events. This command stops auto scrolling and extract current position.
If dropcmd is not empty, it is called with the following arguments:
  • the pathname of the Entry,
  • the pathname of the drag source,
  • the numeric index in the entry designated by the cursor,
  • the current operation,
  • the data type,
  • the data.
and must return a value conforming to dropcmd option described in DropSite::register. If dropcmd is empty, the wrapper updates the entry following the type of data:
COLOR or FGCOLOR | reconfigure the foreground of the Entry
BGCOLOR | reconfigure the background of the Entry
TEXT,
or any other tag 		reconfigure the Entry to display the associated string.
and returns 1.
-dropenabled
A boolean specifying if drop is enabled.
-dropovercmd
Entry has a command wrapper for drag-over events. This command enables auto scrolling and position extraction during the drag-over.
If dropovercmd is empty, the wrapper accepts the drop if editable option is true and state option is normal.
If dropovercmd is not empty, it is called with the following arguments:
  • the pathname of the Entry,
  • the pathname of the drag source,
  • the event,
  • the numeric index in the entry designated by the cursor,
  • the current operation,
  • the data type,
  • the data.
and must return a value conforming to dropovercmd option described in DropSite::register.
-droptypes
Specifies a list of accepted dropped object/operation. See option droptypes of DropSite::register. for more infromation. Default accepts FGCOLOR, COLOR, BGCOLOR and TEXT, all with copy and move operations.
-editable
Specifies whether the Entry is editable by the user. Equivalent to the state option of the Tk entry widget.
-helptext
Text for dynamic help. If empty, no help is available for this widget. See also DynamicHelp.
-helptype
Type of dynamic help. Use balloon or variable. See also DynamicHelp.
-helpvar
Variable to use when helptype option is variable. See also DynamicHelp.
-show
If this option is specified, then the true contents of the entry are not displayed in the window. Instead, each character in the entry's value will be displayed as the first character in the value of this option, such as ``*''. This is useful, for example, if the entry is to be used to enter a password. If characters in the entry are selected and copied elsewhere, the information copied will be what is displayed, not the true contents of the entry.
-state
Specifies one of two states for the Entry: normal or disabled. In normal state the text of the Entry is displayed using the foreground option. In disabled state the text of the Entry is displayed using the disabledforeground option. If the entry is disabled then the value may not be changed by user input and no insertion cursor will be displayed, even if the input focus is in the widget. Disabled state is the same as not editable with visual effect.
-width
Specifies an integer value indicating the desired width of the entry window, in average-size characters of the widget's font. If the value is less than or equal to zero, the widget picks a size just large enough to hold its current text.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName invoke
Calls the command specified by the option -command.


Button

NAME
Button - Button widget with enhanced options
CREATION
Button pathName ?option value...?
STANDARD OPTIONS
-activebackground
-activeforeground
-anchor
-background or -bg
-bitmap
-borderwidth or -bd
-cursor
-disabledforeground
-font
-foreground or -fg
-highlightbackground
-highlightcolor
-highlightthickness
-image
-justify
-padx
-pady
-repeatdelay
-repeatinterval
-takefocus
-text
-textvariable
-wraplength
WIDGET-SPECIFIC OPTIONS
-armcommand
-command
-default
-disarmcommand
-height
-helptext
-helptype
-helpvar
-name
-relief
-state
-underline
-width
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName invoke

DESCRIPTION

Button widget extends the Tk button with new options. DynamicHelp options, a new relief style, callback for arm/disarm, and repeatdelay/repeatinterval options has been added.

WIDGET-SPECIFIC OPTIONS
-armcommand
Specifies a Tcl command to associate with the Button when mouse button 1 is pressed over the Button. When repeatdelay or repeatinterval option is positive integer, this command is repeatedly called if mouse pointer is over the Button and until mouse button 1 is released.
-command
Specifies a Tcl command to associate with the Button. This command is typically invoked when mouse button 1 is released over the Button window.
-default
Specifies one of three states for the default ring: normal, active, or disabled. In active state, the button is drawn with the platform specific appearance for a default button. In normal state, the button is drawn with the platform specific appearance for a non-default button, leaving enough space to draw the default button appearance. The normal and active states will result in buttons of the same size. In disabled state, the button is drawn with the non-default button appearance without leaving space for the default appearance. The disabled state may result in a smaller button than the active state.
-disarmcommand
Specifies a Tcl command to associate with the Button when mouse button 1 is released. This command is called even if pointer is not over the Button, and always before the command specified by command option. It is typically used in conjuntion with armcommand, repeatdelay and repeatinterval.
-height
Specifies a desired height for the Button. If an image or bitmap is being displayed in the Button then the value is in screen units; for text it is in lines of text. If this option isn't specified, the Button's desired height is computed from the size of the image or bitmap or text being displayed in it.
-helptext
Text for dynamic help. If empty, no help is available for this widget. See also DynamicHelp.
-helptype
Type of dynamic help. Use balloon or variable. See also DynamicHelp.
-helpvar
Variable to use when helptype option is variable. See also DynamicHelp.
-name
Specifies a standard name for the button. If the option *nameName is found in the resources database, then text and underline options are extracted from its value.
-relief
Specifies the 3-D effect desired for the widget. Acceptable values are standard values for button relief (raised, sunken, flat, ridge, solid, and groove) and link, which specifies that button relief is flat when pointer is outside the button and raised when pointer is inside.
-state
Specifies one of three states for the Button: normal, active, or disabled. In normal state the Button is displayed using the foreground and background options. The active state is typically used when the pointer is over the Button. In active state the Button is displayed using the activeforeground and activebackground options. Disabled state means that the Button should be insensitive: the default bindings will refuse to activate the widget and will ignore mouse button presses. In this state the disabledforeground and background options determine how the Button is displayed.
-underline
Specifies the integer index of a character to underline in the label of the button. 0 corresponds to the first character of the text displayed, 1 to the next character, and so on.
The binding <Alt-char> is automatically set on the toplevel of the Button to call Button::setfocus.
-width
If an image or bitmap is being displayed in the Button then the value is in screen units; for text it is in characters. If this option isn't specified, the Button's desired width is computed from the size of the image or bitmap or text being displayed in it.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName invoke
If Button state is not disabled, this invoke the commands of the Button. Button is redisplayed with active color and sunken relief, and armcommand is called. Then Button is redisplayed with normal color and its defined relief, and disarmcommand then command are called.

invoke is called when Button has input focus and user press the space bar.


ArrowButton

NAME
ArrowButton - Button widget with an arrow shape.
CREATION
ArrowButton pathName ?option value...?
STANDARD OPTIONS
-activebackground
-activeforeground
-background or -bg -borderwidth or -bd
-disabledforeground
-foreground or -fg
-highlightbackground
-highlightcolor
-highlightthickness
-relief
-repeatdelay
-repeatinterval
-takefocus
-troughcolor
WIDGET-SPECIFIC OPTIONS
-armcommand
-arrowbd
-arrowrelief
-clean
-command
-dir
-disarmcommand
-height
-helptext
-helptype
-helpvar
-ipadx
-ipady
-state
-type
-width
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName invoke

DESCRIPTION

ArrowButton can be of two types following type option: for button type, it is standard button with an arrow drawn on it; for arrow type, it is an arrow like scrollbar's arrow.

WIDGET-SPECIFIC OPTIONS
-armcommand
Specifies a Tcl command to associate with the ArrowButton when mouse button 1 is pressed over the ArrowButton. When repeatdelay or repeatinterval option is positive integer, this command is repeatedly called if mouse pointer is over the button and until mouse button 1 is released.
-arrowbd
When ArrowButton type is arrow, specifies the border width of the arrow. Must be 1 or 2.
-arrowrelief
When ArrowButton type is arrow, specifies the relief of the arrow. Must be raised or sunken.
-clean
Specifies a level of quality, between 0 and 2, for the arrow. If 0, the arrow is drawn with its maximum width and height. If 1, the base of arrow is arranged to be odd to have same edges. If 2, the base of arrow is arranged to be odd and the orthogonal to be (base+1)/2 to have 'straight' diagonal for edges.
-command
Specifies a Tcl command to associate with the ArrowButton. This command is typically invoked when mouse button 1 is released over the ArrowButton window.
-dir
Specifies the direction of the arrow: top, bottom, left or right.
-disarmcommand
Specifies a Tcl command to associate with the ArrowButton when mouse button 1 is released. This command is called even if pointer is not over the ArrowButton, and always before the command specified by command option. It is typically used in conjuntion with armcommand, repeatdelay and repeatinterval.
-height
Specifies a desired height for the ArrowButton. The value is in screen units.
-helptext
Text for dynamic help. If empty, no help is available for this widget. See also DynamicHelp.
-helptype
Type of dynamic help. Use balloon or variable. See also DynamicHelp.
-helpvar
Variable to use when helptype option is variable. See also DynamicHelp.
-ipadx
Specifies a minimun pad between the ArrowButton border and the right and left side of the arrow. The value is in screen units.
-ipady
Specifies a minimun pad between the ArrowButton border and the top and bottom side of the arrow. The value is in screen units.
-state
Specifies one of three states for the ArrowButton: normal, active, or disabled.
If ArrowButton type is button:
In normal state the ArrowButton is displayed using the foreground and background options. The active state is typically used when the pointer is over the ArrowButton. In active state the ArrowButton is displayed using the activeforeground and activebackground options. In disabled state the disabledforeground and background options determine how the ArrowButton is displayed.
If ArrowButton type is arrow:
Only colors of arrow change. The background of ArrowButton is always displayed using troughcolor option. In normal state the ArrowButton is displayed using the background option. The active state is typically used when the pointer is over the ArrowButton. In active state the ArrowButton is displayed using the activebackground option. In disabled state the ArrowButton is displayed with a dark stipple.
Disabled state means that the ArrowButton should be insensitive: the default bindings will refuse to activate the widget and will ignore mouse button presses.
-type
Determines the type of the ArrowButton: button for standard button look, or arrow scrollbar's arrow look.
-width
Specifies a desired width for the ArrowButton. The value is in screen units.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName invoke
If ArrowButton state is not disabled, this invoke the commands of the button. ArrowButton is redisplayed with active color and sunken relief, and armcommand is called. Then ArrowButton is redisplayed with normal color and its defined relief, and disarmcommand then command are called.

invoke is called when ArrowButton has input focus and user press the space bar.


ProgressBar

NAME
ProgressBar - Progress indicator widget
CREATION
ProgressBar pathName ?option value...?
STANDARD OPTIONS
-background or -bg -borderwidth or -bd
-foreground or -fg -orient
-relief
-troughcolor
WIDGET-SPECIFIC OPTIONS
-height
-maximum
-type
-variable
-width
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?

DESCRIPTION

ProgressBar widget indicates the user the progress of a lengthly operation. It is used by MainFrame and ProgressDlg.

WIDGET-SPECIFIC OPTIONS
-height
Specifies the desired height for the progress indicator.
-maximum
Specifies the maximum value of the variable.
-type
Specifies the type of the ProgressBar. Must be one of normal, incremental or infinite.
If type is normal, the progress indicator is drawn proportional to the variable value and maximum option each time the variable is set.
If type is incremental, the value of the progress indicator is maintained internally, and incremented each time the variable is set by its value. The progress indicator is drawn proportional to the internal value and maximum option.
If type is infinite, the value of the progress indicator is maintained internally, and incremented each time the variable is set by its value. The progress indicator grow from left to right if internal value (modulo maximum) is less than maximum/2, and from right to left if internal value is greater than maximum/2.
See -variable option for special case of its value,
-variable
Specifies the variable attached to the progress indicator. Progress indicator is updated when the value of the variable changes. If the value of the variable is negative, the progress indicator is not displayed (it is drawn flat with background color - usefull for ProgressDlg to make it invisible). If its value 0, progress indicator is reinitialized.
-width
Specifies the desired width for the progress indicator.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.


ScrollView

NAME
ScrollView - Display the visible area of a scrolled window
CREATION
ScrollView pathName ?option value...?
STANDARD OPTIONS
-background or -bg -borderwidth or -bd
-cursor
-relief
WIDGET-SPECIFIC OPTIONS
-fill
-foreground or -fg
-height
-width
-window
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?

DESCRIPTION

ScrollView displays the visible area of a scrolled window within its scroll region.

WIDGET-SPECIFIC OPTIONS
-fill
Specifies the fill color of the rectangle.
-foreground
Specifies the color of the border of the rectangle.
-height
Specifies the desired height for the ScrollView.
-width
Specifies the desired width for the ScrollView.
-window
Specifies the window to view. This widget must have -xscrollcommand and -yscrollcommand options, and respond to xview and yview command. In order to make ScrollView working with other scrollbar, -xscrollcommand and -yscrollcommand options of the widget must be set before the widget is passed to the -window option of the ScrollView (for example, if the widget is handled by a ScrolledWindow, call setwidget before setting -window option).

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.

BINDINGS

If mouse button 1 is pressed and dragged over the ScrollView, the top left corner of the visible area of the scrolled window is moved proportionally to the mouse displacement.
If mouse button 3 is pressed over the ScrollView, the top left corner of the visible area is proportionally set to this point.


Separator

NAME
Separator - 3D separator widget
CREATION
Separator pathName ?option value...?
STANDARD OPTIONS
-background or -bg -orient
WIDGET-SPECIFIC OPTIONS
-relief
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?

DESCRIPTION

Separator is a widget that display an horizontal or vertical 3-D line.

WIDGET-SPECIFIC OPTIONS
-relief
Specifies the relief of the Separator. Must be groove (the default) or ridge.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.


MainFrame

NAME
MainFrame - Manage toplevel with menu, toolbar and statusbar
CREATION
MainFrame pathName ?option value...?
OPTIONS from ProgressBar
-background or -bg | -progressfg (see -foreground)
-progressmax (see -maximum) | -progresstype (see -type)
-progressvar (see -variable)
WIDGET-SPECIFIC OPTIONS
-height
-menu
-separator
-textvariable
-width
WIDGET COMMAND
pathName addindicator ?arg...?
pathName addtoolbar
pathName cget option
pathName configure ?option? ?value option value ...?
pathName getframe
pathName getindicator index
pathName getmenu menuid
pathName gettoolbar index
pathName setmenustate tag state
pathName showstatusbar name
pathName showtoolbar index bool

DESCRIPTION

MainFrame manage toplevel to have:

  • simple menu creation, with automatic accelerator bindings and DynamicHelp association,
  • one or more toolbar that user can hide,
  • a status bar, displaying a user message or a menu description, and optionnaly a ProgressBar.

WIDGET-SPECIFIC OPTIONS
-height
Specifies the desired height for the user frame in any of the forms acceptable to Tk_GetPixels. If this option is less than or equal to zero (the default) then the window will not request any size at all.
-menu (read-only)
This option describes the menu. This is a list whose each five elements describe one cascad menu. It has the following form: {menuname tags menuId tearoff menuentries...} where menuentries is a list where each element describe one menu entry, which can be:
  • for a separator:
    {separator}
  • for a command:
    {command menuname ?tags? ?description? ?accelerator? ?option value? ...}
  • for a check button:
    {checkbutton menuname ?tags? ?description? ?accelerator? ?option value? ...}
  • for a radio button:
    {radiobutton menuname ?tags? ?description? ?accelerator ?option value? ...}
  • for a cascad menu:
    {cascad menuname tags menuId tearoff menuentries}
where:
  • menuname is the name of the menu. If it contains a &, the following character is automatically converted to the corresponding -underline option of menu add command.
  • tags is the tags list for the entry, used for enabling or disabling menu entries with MainFrame::setmenustate.
  • menuId is an id for the menu, from which you can get menu pathname with MainFrame::getmenu.
  • tearoff specifies if menu has tearoff entry.
  • description specifies a string for DynamicHelp.
  • accelerator specifies a key sequence. It is a list of two elements, where the first is one of Ctrl, Alt or CtrlAlt, and the second as letter or a digit. An accelerator string is build and corresponding binding set on the toplevel to invoke the menu entry.
  • option value specifies additionnal options for the entry (see menu add command).
Each value enclosed by ? are optional and defaulted to empty string, but must be provided if one or more following options is not empty.
Example:
set descmenu {
    "&File" {} {} 0 {
        {command "&New"     {} "Create a new document"     {Ctrl n} -command Menu::new}
        {command "&Open..." {} "Open an existing document" {Ctrl o} -command Menu::open}
        {command "&Save"    open "Save the document" {Ctrl s} -command Menu::save}
        {cascad  "&Export"  {} export 0 {
            {command "Format &1" open "Export document to format 1" {} -command {Menu::export 1}}
            {command "Format &2" open "Export document to format 2" {} -command {Menu::export 2}}
        }}
        {separator}
        {cascad "&Recent files" {} recent 0 {}}
        {separator}
        {command "E&xit" {} "Exit the application" {} -command Menu::exit}
    }
    "&Options" {} {} 0 {
        {checkbutton "Toolbar" {} "Show/hide toolbar" {}
            -variable Menu::_drawtoolbar
            -command  {$Menu::_mainframe showtoolbar toolbar $Menu::_drawtoolbar}
        }
    }
}
-separator (read-only)
Specifies if separator should be drawn at the top and/or at the bottom of the user window. Must be one of the values none, top, bottom or both. It depends on the relief of subwidgets of user window.
-textvariable
Specifies the textvariable option for the label of the status bar. DynamicHelp description of menu entries are mapped to this variable at the creation of the MainFrame. If this variable is changed by MainFrame::configure, menu description will not be available.
You change the text of the label by modifying the value of the variable.
-width
Specifies the desired width for the user frame in any of the forms acceptable to Tk_GetPixels. If this option is less than or equal to zero (the default) then the window will not request any size at all.

WIDGET COMMAND
pathName addindicator ?arg...?
Add an indicator box at the right of the status bar. Each indicator are added from left to right. An indicator is a Tk label widget configured with option-value pair given by ?arg...?. -relief and -borderwidth options are respetively defaulted to sunken and 1. Returns the pathname of the created label.
pathName addtoolbar
Add a toolbar to the MainFrame. Returns the pathname of the new window where to place toolbar items.
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName getframe
Returns the pathname of the user window.
pathName getindicator index
Returns the pathname of the indexth added indicator.
pathName getmenu menuid
Returns the pathname of the menu whose id is menuid.
pathName gettoolbar index
Returns the pathname of the indexth added toolbar.
pathName setmenustate tag state
Set the -state option value of all the menu entries that have the tag tag to state.
pathName showstatusbar name
name is one of none, status or progression. Use none to hide the status bar, status to display the label only, or progression to display the label and the ProgressBar.
pathName showtoolbar index bool
Hide if bool is 0, or show if bool is 1 the indexth added toolbar. To prevent your toplevel from resizing while hiding/showing toolbar, do [wm geometry $top [wm geometry $top]] when it is managed.


LabelFrame

NAME
LabelFrame - Frame with a Label
CREATION
LabelFrame pathName ?option value...?
STANDARD OPTIONS
-borderwidth or -bd -relief
OPTIONS from Label
-anchor | -background or -bg
-disabledforeground | -focus
-font | -foreground or -fg
-height | -helptext
-helptype | -helpvar
-justify | -name
-padx | -pady
-state | -text
-underline | -width
-wraplength
WIDGET-SPECIFIC OPTIONS
-side
WIDGET COMMAND
LabelFrame::align ?arg...?
pathName cget option
pathName configure ?option? ?value option value ...?
pathName getframe

DESCRIPTION

LabelFrame enables user to create a frame with a Label positionned at any side. LabelFrame is used by ComboBox and SpinBox.

WIDGET-SPECIFIC OPTIONS
-side (read-only)
Specifies where to position the Label relative to the user frame: top, bottom, left or right.

WIDGET COMMAND
LabelFrame::align ?arg...?
This command align label of all widget given by args of class LabelFrame (or "derived") by setting their width to the max one +1
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName getframe
Return the frame where the user can create any other widget.


TitleFrame

NAME
TitleFrame - Frame with a title
CREATION
TitleFrame pathName ?option value...?
STANDARD OPTIONS
-background or -bg -borderwidth or -bd
-font
-foreground or -fg
-relief
-text
WIDGET-SPECIFIC OPTIONS
-baseline
-ipad
-side
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName getframe

DESCRIPTION

TitleFrame enables user to create a frame with a title like XmFrame Motif widget.

WIDGET-SPECIFIC OPTIONS
-baseline
Specifies the vertical alignment of the title: top, center or bottom.
-ipad
Specifies a pad between the border of the frame and the user frame. The value is in screen units.
-side
Specifies the horizontal alignment of the title: left, center or right.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName getframe
Return the frame where the user can create any other widget.


ScrolledWindow

NAME
ScrolledWindow - Generic scrolled widget
CREATION
ScrolledWindow pathName ?option value...?
STANDARD OPTIONS
-background or -bg -borderwidth or -bd
-relief
WIDGET-SPECIFIC OPTIONS
-auto
-scrollbar
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName getframe
pathName setwidget widget

DESCRIPTION

ScrolledWindow enables user to create easily a widget with its scrollbar. Scrollbars are created by ScrolledWindow and scroll commands are automatically associated to a scrollable widget with ScrolledWindow::setwidget.

WIDGET-SPECIFIC OPTIONS
-auto
Specifies the desired auto managed scrollbar:
  • none means scrollbar are always drawn
  • horizontal means horizontal scrollbar is drawn as needed
  • vertical means vertical scrollbar is drawn as needed
  • both means horizontal and vertical scrollbars are drawn as needed
  • horizontal means horizontal scrollbar is drawn as needed
    • -scrollbar (read-only)
    Specifies the desired scrollbar: none, horizontal, vertical or both. This option is not modifiable with ScrolledWindow::configure.

    WIDGET COMMAND
    pathName cget option
    Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
    pathName configure ?option? ?value option value ...?
    Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
    pathName getframe
    Return the pathname of the frame where the scrolled widget should be created. This command is no longer needed. You can directly create the scrolled widget as the child of pathName.
    pathName setwidget widget
    Associate widget to the the scrollbars. widget is packed in with option expand to yes and fill to both. widget must be a scrollable widget, i.e. have the options xscrollcommand/yscrollcommand and the command xview/yview, such as canvas or text.


ScrollableFrame

NAME
ScrollableFrame - Scrollable frame containing widget
CREATION
ScrollableFrame pathName ?option value...?
STANDARD OPTIONS
-background or -bg -xscrollcommand
-yscrollcommand
WIDGET-SPECIFIC OPTIONS
-areaheight
-areawidth
-constrainedheight
-constrainedwidth
-height
-width
-xscrollincrement
-yscrollincrement
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName getframe
pathName see widget ?vert? ?horz?
pathName xview ?arg...?
pathName yview ?arg...?

DESCRIPTION

ScrollableFrame widget containing widget.

WIDGET-SPECIFIC OPTIONS
-areaheight
Specifies the height for the scrollable area. If zero, then the height of the scrollable area is made just large enough to hold all its children.
-areawidth
Specifies the width for the scrollable area. If zero, then the width of the scrollable area window is made just large enough to hold all its children.
-constrainedheight
Specifies whether or not the scrollable area should have the same height of the scrolled window. If true, vertical scrollbar is not needed.
-constrainedwidth
Specifies whether or not the scrollable area should have the same width of the scrolled window. If true, horizontal scrollbar is not needed.
-height
Specifies the desired height for the window in pixels.
-width
Specifies the desired width for the window in pixels.
-xscrollincrement
See xscrollincrement option of canvas widget.
-yscrollincrement
See yscrollincrement option of canvas widget.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName getframe
Return the pathname of the scrolled frame where widget should be created.
pathName see widget ?vert? ?horz?
Arrange scrollable area to make widget visible in the window. vert and horz specify which part of widget must be preferably visible, in case where widget is too tall or too large to be entirely visible. vert must be top (the default) or bottom, and horz must be left (the default) or right. If vert or horz is not a valid value, area is not scrolled in this direction.
pathName xview ?arg...?
Standard command to enable horizontal scrolling of pathName.
pathName yview ?arg...?
Standard command to enable vertical scrolling of pathName.


PanedWindow

NAME
PanedWindow - Tiled layout manager widget
CREATION
PanedWindow pathName ?option value...?
STANDARD OPTIONS
-background or -bg
WIDGET-SPECIFIC OPTIONS
-pad
-side
-width
WIDGET COMMAND
pathName add ?option value...?
pathName cget option
pathName configure ?option? ?value option value ...?
pathName getframe index

DESCRIPTION

PanedWindow is a widget that lays out children in a vertically or horizontally tiled format. The user can adjust the size of the panes, with a pane control sash created between children.

WIDGET-SPECIFIC OPTIONS
-pad (read-only)
Specifies additional space between the button of the sash and children.
-side (read-only)
Specifies the side of the sash, which implies the layout: top or bottom (horizontal layout), left or right (vertical layout).
-width (read-only)
Specifies the width of the button of the sash.

WIDGET COMMAND
pathName add ?option value...?
This command add a new pane. The new pane is placed below the previous pane for vertical layout or at right for horizontal layout. This command returns a frame where user can place its widget. Valid options are:

-minsize
Specifies the minimum size requested for the pane. See the grid command for more information.
-weight
Specifies the relative weight for apportioning any extra spaces among panes. See the grid command for more information.
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName getframe index
Returns the pathname of the indexth added pane.


ButtonBox

NAME
ButtonBox - Set of buttons with horizontal or vertical layout
CREATION
ButtonBox pathName ?option value...?
WIDGET-SPECIFIC OPTIONS
-background or -bg -default
-homogeneous
-orient
-padx
-pady
-spacing
WIDGET COMMAND
pathName add ?option value...?
pathName cget option
pathName configure ?option? ?value option value ...?
pathName index index
pathName invoke index
pathName itemcget index option
pathName itemconfigure index ?option? ?value option value ...?
pathName setfocus index

DESCRIPTION

ButtonBox layouts Button horizontally or vertically. Some commands take an index as argument indicating on which Button it work. This index may be specified in any of the following forms:

number
Specifies the Button numerically, where 0 corresponds to the first added Button, 1 to the next, and so on.
end or last
Indicates the last item added.
default
Indicates the default Button.

WIDGET-SPECIFIC OPTIONS
-background
Specifies a default background color for all added buttons and for the frame.
-default
Specifies the default button of the button box. The value is an integer referencing the n-th added button, starting from 0. If this value is -1 (the default), all button wil be drawn with their -default option set to disabled, and this value can not be changed.
If this value is not -1, the associated button is drawn with -default option set to active and the others are drawn with -default option set to normal. The value can be changed by configure.
-homogeneous (read-only)
Specifies wether or not buttons must have the same width for horizontal layout.
-orient (read-only)
Specifies the orientation of the button box. If this option is horizontal (the default), buttons are added from top to bottom. If this option is vertical, buttons are added from left to right.
-padx
Specifies a default value for the -padx option of all added buttons.
-pady
Specifies a default value for the -pady option of all added buttons.
-spacing
Specifies the default spacing between buttons. This value can be changed before each call to add.

WIDGET COMMAND
pathName add ?option value...?
Add a button to the button box.

See Button for description of options.

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName index index
Return the numerical index corresponding to the item.
pathName invoke index
Invoke the Button given by index.
pathName itemcget index option
Returns the current value of a configuration option for the item. Option may have any of the values accepted by the item creation command.
pathName itemconfigure index ?option? ?value option value ...?
This command is similar to the configure command, except that it applies to the options for an individual item, whereas configure applies to the options for the widget as a whole. Options may have any of the values accepted by the item creation widget command. If options are specified, options are modified as indicated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for the item. Read-only options are not be modified.
pathName setfocus index
Set the focus to the Button given by index.


PagesManager

NAME
PagesManager - Pages manager widget
CREATION
PagesManager pathName ?option value...?
STANDARD OPTIONS
-background
WIDGET-SPECIFIC OPTIONS
-height
-width
WIDGET COMMAND
pathName add page
pathName cget option
pathName compute_size
pathName configure ?option? ?value option value ...?
pathName delete page
pathName getframe page
pathName page first ?last?
pathName pages ?first? ?last?
pathName raise ?page?

DESCRIPTION

PagesManager widget manage a set of pages and displays one of them. PagesManager does not provide any user access method, as NoteBook does, so it can be done through a listbox, a menu, radiobutton, or whatever.

WIDGET-SPECIFIC OPTIONS
-height
Specifies the desired height for the pages. If this option is equal to zero (the default) then the window will not request any size at all. In this case, user may want to call PagesManager::compute_size to make PagesManager larger enough to contains the largest page.
-width
Specifies the desired width for the pages. If this option is equal to zero (the default) then the window will not request any size at all. In this case, user may want to call PagesManager::compute_size to make PagesManager larger enough to contains the largest page.

WIDGET COMMAND
pathName add page
Add a new page idendified by page. The pathname of the new page is returned.
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName compute_size
This command can be called to make the PagesManager large enough to contain the largest page.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName delete page
Deletes the page page.
pathName getframe page
Returns the pathname of the page page.
pathName page first ?last?
Its use is deprecated. Use pages instead.
If last is omitted, returns the page at index first, or an empty string if first refers to a non-existent element. If last is specified, the command returns a list whose elements are all of the pages between first and last, inclusive. Both first and last may have any of the standard forms for indices.
pathName pages ?first? ?last?
If first and last are omitted, returns the list of all pages. If first is specified and last omitted, returns the page at index first, or an empty string if first refers to a non-existent element. If first and last are specified, the command returns a list whose elements are all of the pages between first and last, inclusive. Both first and last may have any of the standard forms for indices.
pathName raise ?page?
Raise the page page, or return the raised page if page is omitted.


NoteBook

NAME
NoteBook - Notebook manager widget
CREATION
NoteBook pathName ?option value...?
STANDARD OPTIONS
-font
OPTIONS from ArrowButton
-activebackground | -activeforeground
-background or -bg | -borderwidth or -bd
-disabledforeground | -foreground or -fg
-repeatdelay | -repeatinterval
WIDGET-SPECIFIC OPTIONS
-height
-homogeneous
-side
-width
WIDGET COMMAND
pathName bindtabs event script
pathName cget option
pathName compute_size
pathName configure ?option? ?value option value ...?
pathName delete page ?destroyframe?
pathName getframe page
pathName index page
pathName insert index page ?option value...?
pathName itemcget page option
pathName itemconfigure page ?option? ?value option value ...?
pathName move page index
pathName page first ?last?
pathName pages ?first? ?last?
pathName raise ?page?
pathName see page

DESCRIPTION

NoteBook widget manage a set of pages and displays one of them.

WIDGET-SPECIFIC OPTIONS
-height
Specifies the desired height for the pages. If this option is equal to zero (the default) then the window will not request any size at all. In this case, user may want to call NoteBook::compute_size to make NoteBook larger enough to contains the largest page.
-homogeneous
Specifies wether or not the label of the pages must have the same width.
-side (read-only)
Specifies the side where to place the label of the pages. Must be one of top or bottom. Only top is implemented for the moment.
-width
Specifies the desired width for the pages. If this option is equal to zero (the default) then the window will not request any size at all. In this case, user may want to call NoteBook::compute_size to make NoteBook larger enough to contains the largest page.

WIDGET COMMAND
pathName bindtabs event script
This command associates a command to execute whenever the event sequence given by event occurs on a tabs. The page idenfier on which the event occurs is appended to the command.
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName compute_size
This command can be called to make the NoteBook large enough to contain the largest page. Note that if all pages use -createcmd, they will have no requested size.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName delete page ?destroyframe?
Deletes the page page. If destroyframe is 1 (the default), the frame associated to page is destroyed. If destroyframe is 0, the frame is not destroyed and is reused by further call to insert with the same page.
pathName getframe page
Returns the pathname of the page page.
pathName index page
Return the numerical index corresponding to the item.
pathName insert index page ?option value...?
Insert a new page idendified by page at position index in the pages list. index must be numeric or end. The pathname of the new page is returned.

-createcmd
Specifies a command to be called the first time the page is raised.
-image
Specifies an image to display for the page at the left of the label
-leavecmd
Specifies a command to be called when a page is about to be leaved. The command must return 0 if the page can not be leaved, or 1 if it can.
-raisecmd
Specifies a command to be called each time the page is raised.
-state
Specifies the state of the page. Must be normal or disabled.
-text
Specifies a label to display for the page.
pathName itemcget page option
Returns the current value of a configuration option for the item. Option may have any of the values accepted by the item creation command.
pathName itemconfigure page ?option? ?value option value ...?
This command is similar to the configure command, except that it applies to the options for an individual item, whereas configure applies to the options for the widget as a whole. Options may have any of the values accepted by the item creation widget command. If options are specified, options are modified as indicated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for the item. Read-only options are not be modified.
pathName move page index
Moves page tab to index index.
pathName page first ?last?
Its use is deprecated. Use pages instead.
If last is omitted, returns the page at index first, or an empty string if first refers to a non-existent element. If last is specified, the command returns a list whose elements are all of the pages between first and last, inclusive. Both first and last may have any of the standard forms for indices.
pathName pages ?first? ?last?
If first and last are omitted, returns the list of all pages. If first is specified and last omitted, returns the page at index first, or an empty string if first refers to a non-existent element. If first and last are specified, the command returns a list whose elements are all of the pages between first and last, inclusive. Both first and last may have any of the standard forms for indices.
pathName raise ?page?
Raise the page page, or return the raised page if page is omitted.
pathName see page
Scrolls labels to make the label of the page page visible.


Dialog

NAME
Dialog - Dialog abstraction with custom buttons
CREATION
Dialog pathName ?option value...?
OPTIONS from ButtonBox
-background or -bg | -homogeneous
-padx | -pady
-spacing
WIDGET-SPECIFIC OPTIONS
-anchor
-bitmap
-cancel
-default
-image
-modal
-parent
-separator
-side
-title
WIDGET COMMAND
pathName add ?arg...?
pathName cget option
pathName configure ?option? ?value option value ...?
pathName draw ?focus?
pathName enddialog result
pathName getframe
pathName invoke index
pathName itemcget index option
pathName itemconfigure index ?option? ?value option value ...?
pathName setfocus index
pathName withdraw

DESCRIPTION

Dialog widget enables the user to create a dialog box. Some commands take an index as argument indicating on which Button it work. This index is the same specified for equivalent ButtonBox command:

number
Specifies the Button numerically, where 0 corresponds to the first added Button, 1 to the next, and so on.
end or last
Indicates the last item added.
default
Indicates the default Button.

WIDGET-SPECIFIC OPTIONS
-anchor (read-only)
Specifies the anchor point of the ButtonBox. Must be one of w, e, n, s or c. If side option is set to top or bottom, anchor values n, s and c have the same effect. If side option is set to left or right, anchor values w, e and c have the same effect.
-bitmap (read-only)
Specifies a bitmap to display at the left of the user frame. image option override bitmap.
-cancel
Specifies the number of the cancel button of the Dialog. When user press Esc in the Dialog, this button is invoked.
-default
Specifies the number of the default button of the Dialog. When user press Return in the Dialog, this button is invoked.
-image (read-only)
Specifies an image to display at the left of the user frame. image option override bitmap.
-modal
This option must be none, local or global. The value of this option specifies the grab mode of the dialog and how works Dialog::draw.
-parent
Parent of the Dialog. Dialog is centered in its parent. If empty, it is centered in root window.
-separator (read-only)
Specifies wether or not to draw a separator between the user frame and the ButtonBox.
-side (read-only)
Specifies where to draw the ButtonBox relative to the user frame. Must be one of top, left, bottom or right.
-title
Title of the Dialog toplevel.

WIDGET COMMAND
pathName add ?arg...?
Add a button to the button box of the dialog box. Default -command option is Dialog::enddialog $path index where index is number of button added.
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName draw ?focus?
This command draw the Dialog, and set grab to it following modal option. If modal option is set to none, the command returns immediatly an empty string. In all other case, the command returns when Dialog::enddialog is called or when Dialog is destroyed. The return value is the result argument of Dialog::enddialog or -1 if it is destroyed.

By default, the focus is set to the default button referenced by default option, or to the toplevel of Dialog if no default button has been set. If focus is present, it must be a pathname, or an index to a button. Initial focus is set on this pathname or corresponding button.

pathName enddialog result
This command is typically called within a command of a button to make Dialog::draw return.
pathName getframe
Returns the pathname of the user window.
pathName invoke index
Invoke the Button given by index.
pathName itemcget index option
Returns the current value of a configuration option for the item. Option may have any of the values accepted by the item creation command.
pathName itemconfigure index ?option? ?value option value ...?
This command is similar to the configure command, except that it applies to the options for an individual item, whereas configure applies to the options for the widget as a whole. Options may have any of the values accepted by the item creation widget command. If options are specified, options are modified as indicated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for the item. Read-only options are not be modified.
pathName setfocus index
Set the focus to the Button given by index.
pathName withdraw
Call this command to hide the dialog box.


LabelEntry

NAME
LabelEntry - LabelFrame containing an Entry widget.
CREATION
LabelEntry pathName ?option value...?
OPTIONS from Entry
-borderwidth or -bd | -command
-disabledforeground | -dragenabled
-dragendcmd | -dragevent
-draginitcmd | -dragtype
-dropcmd | -dropenabled
-dropovercmd | -droptypes
-editable | -entrybg (see -background)
-entryfg (see -foreground) | -exportselection
-font | -helptext
-helptype | -helpvar
-highlightbackground | -highlightcolor
-highlightthickness | -insertbackground
-insertborderwidth | -insertofftime
-insertontime | -insertwidth
-justify | -relief
-selectbackground | -selectborderwidth
-selectforeground | -show
-state | -takefocus
-text | -textvariable
-width | -xscrollcommand
OPTIONS from LabelFrame
-background or -bg | -disabledforeground
-foreground or -fg | -helptext
-helptype | -helpvar
-label (see -text) | -labelanchor (see -anchor)
-labelfont (see -font) | -labelheight (see -height)
-labeljustify (see -justify) | -labelwidth (see -width)
-name | -padx
-pady | -side
-state | -underline
-wraplength
WIDGET COMMAND
pathName bind ?arg...?
pathName cget option
pathName configure ?option? ?value option value ...?

DESCRIPTION

LabelEntry is a widget composed of LabelFrame widget containing an Entry widget. Tk entry command can also be used on LabelEntry widget.

WIDGET COMMAND
pathName bind ?arg...?
Set bindings on the entry widget.
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.


ComboBox

NAME
ComboBox - ComboBox widget
CREATION
ComboBox pathName ?option value...?
OPTIONS from ArrowButton
-background or -bg | -disabledforeground
-foreground or -fg | -state
OPTIONS from Entry
-command | -disabledforeground
-dragenabled | -dragendcmd
-dragevent | -draginitcmd
-dragtype | -dropcmd
-dropenabled | -dropovercmd
-droptypes | -editable
-entrybg (see -background) | -entryfg (see -foreground)
-exportselection | -font
-helptext | -helptype
-helpvar | -highlightbackground
-highlightcolor | -highlightthickness
-insertbackground | -insertborderwidth
-insertofftime | -insertontime
-insertwidth | -justify
-selectbackground | -selectborderwidth
-selectforeground | -show
-state | -takefocus
-text | -textvariable
-width | -xscrollcommand
OPTIONS from LabelFrame
-background or -bg | -borderwidth or -bd
-disabledforeground | -foreground or -fg
-helptext | -helptype
-helpvar | -label (see -text)
-labelanchor (see -anchor) | -labelfont (see -font)
-labelheight (see -height) | -labeljustify (see -justify)
-labelwidth (see -width) | -name
-padx | -pady
-relief | -side
-state | -underline
-wraplength
WIDGET-SPECIFIC OPTIONS
-height
-modifycmd
-postcommand
-values
WIDGET COMMAND
pathName bind ?arg...?
pathName cget option
pathName configure ?option? ?value option value ...?
pathName getvalue
pathName setvalue index

DESCRIPTION

ComboBox widget enables the user to select a value among a list given by the values option. The list of possible values can be popped by pressing the ArrowButton or by clicking in the entry when editable value of the ComboBox is false.
If editable value of the ComboBox is true and the entry has the focus, the user can press the top and bottom arrow keys to modify its value. If the current value exactly match a value in the list, then the previous (for top arrow key) or then next (for bottom arrow key) value in the list is displayed. If the current value match the beginning of a value in the list, then this value is displayed. If the current value doesnt match anything, then the first value is displayed.

WIDGET-SPECIFIC OPTIONS
-height
Specifies the desired height for the window, in lines. If zero or less, then the desired height for the window is made just large enough to hold all the elements in the listbox.
-modifycmd
Specifies a Tcl command called when the user modify the value of the ComboBox by selecting it in the listbox or pressing arrow key.
-postcommand
Specifies a Tcl command called before the listbox of the ComboBox is mapped.
-values
Specifies the values to display in the listbox of the ComboBox.

WIDGET COMMAND
pathName bind ?arg...?
Set bindings on the entry widget.
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName getvalue
Returns the index of the current text of the ComboBox in the list of values, or -1 if it doesn't match any value.
pathName setvalue index
Set the text of the ComboBox to the value indicated by index in the list of values. index may be specified in any of the following forms:

last
Specifies the last element of the list of values.
first
Specifies the first element of the list of values.
next
Specifies the element following the current (ie returned by getvalue) in the list of values.
previous
Specifies the element preceding the current (ie returned by getvalue) in the list of values.
@number
Specifies the integer index in the list of values.

BINDINGS

When Entry of the ComboBox has the input focus, it has the following bindings, in addition to the default Entry bindings:
  • Page up set the value of the ComboBox to the first value.
  • Page down set the value of the ComboBox to the last value.
  • Arrow up set the value of the ComboBox to the previous value.
  • Arrow down set the value of the ComboBox to the next value.
If the listbox is not mapped and ComboBox is not editable or disabled, mouse button 1 on the Entry cause the listbox to popup, as if the user press the ArrowButton.


SpinBox

NAME
SpinBox - SpinBox widget
CREATION
SpinBox pathName ?option value...?
OPTIONS from ArrowButton
-background or -bg | -disabledforeground
-foreground or -fg | -repeatdelay
-repeatinterval | -state
OPTIONS from Entry
-command | -disabledforeground
-dragenabled | -dragendcmd
-dragevent | -draginitcmd
-dragtype | -dropcmd
-dropenabled | -dropovercmd
-droptypes | -editable
-entrybg (see -background) | -entryfg (see -foreground)
-exportselection | -font
-helptext | -helptype
-helpvar | -highlightbackground
-highlightcolor | -highlightthickness
-insertbackground | -insertborderwidth
-insertofftime | -insertontime
-insertwidth | -justify
-selectbackground | -selectborderwidth
-selectforeground | -show
-state | -takefocus
-text | -textvariable
-width | -xscrollcommand
WIDGET-SPECIFIC OPTIONS
-modifycmd
-range
-values
WIDGET COMMAND
pathName bind ?arg...?
pathName cget option
pathName configure ?option? ?value option value ...?
pathName getvalue
pathName setvalue index

DESCRIPTION

SpinBox widget enables the user to select a value among a list given by the values option or a set of values defined by a mininum, a maximum and an increment. Notice that range option defines a list of values, so getvalue and setvalue work with both values and range.

WIDGET-SPECIFIC OPTIONS
-modifycmd
Specifies a Tcl command called when the user modify the value of the SpinBox.
-range
Specifies a list of three intergers (or real) describing the minimum, maximum and increment of the SpinBox.
-values
Specifies the values accepted by the SpinBox. This option takes precedence over range option.

WIDGET COMMAND
pathName bind ?arg...?
Set bindings on the entry widget.
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName getvalue
Returns the index of the current text of the SpinBox in the list of values, or -1 if it doesn't match any value.
pathName setvalue index
Set the text of the SpinBox to the value indicated by index in the list of values. index may be specified in any of the following forms:

last
Specifies the last element of the list of values.
first
Specifies the first element of the list of values.
next
Specifies the element following the current (ie returned by getvalue) in the list of values.
previous
Specifies the element preceding the current (ie returned by getvalue) in the list of values.
@number
Specifies the integer index in the list of values.

BINDINGS

When Entry of the SpinBox has the input focus, it has the following bindings, in addition to the default Entry bindings:
  • Page up set the value of the SpinBox to the last value.
  • Page down set the value of the SpinBox to the first value.
  • Arrow up set the value of the SpinBox to the next value.
  • Arrow down set the value of the SpinBox to the previous value.


Tree

NAME
Tree - Tree widget
CREATION
Tree pathName ?option value...?
STANDARD OPTIONS
-background or -bg -borderwidth or -bd
-cursor
-highlightbackground
-highlightcolor
-highlightthickness
-relief
-selectbackground
-selectforeground
-takefocus
-xscrollcommand
-yscrollcommand
WIDGET-SPECIFIC OPTIONS
-closecmd
-deltax
-deltay
-dragenabled
-dragendcmd
-dragevent
-draginitcmd
-dragtype
-dropcmd
-dropenabled
-dropovercmd
-dropovermode
-droptypes
-height
-linesfill
-linestipple
-opencmd
-padx
-redraw
-showlines
-width
WIDGET COMMAND
pathName bindImage event script
pathName bindText event script
pathName cget option
pathName closetree node
pathName configure ?option? ?value option value ...?
pathName delete ?arg...?
pathName edit node text ?verifycmd? ?clickres? ?select?
pathName exists node
pathName index node
pathName insert index parent node ?option value...?
pathName itemcget node option
pathName itemconfigure node ?option? ?value option value ...?
pathName move parent node index
pathName nodes node ?first? ?last?
pathName opentree node
pathName parent node
pathName reorder node neworder
pathName see node
pathName selection cmd ?arg...?
pathName visible node
pathName xview ?arg...?
pathName yview ?arg...?

DESCRIPTION

Tree widget uses canvas to display a hierarchical list of items (called nodes). Each node is composed of a label with its own font and foreground attributes, and an optional image or window. Each node can have a list of subnodes, which can be collapsed or expanded. Each node is drawn in a single line, whose height is defined by the deltay option, so they must have at most this height. A node is uniquely identified by a string given at creation (by the insert command). The node named root is the root of the tree and is not drawn. The tree structure is directly maintained by the widget.

WIDGET-SPECIFIC OPTIONS
-closecmd
Specifies a command to be called when user close a node. The closed node is appended to the command.
-deltax
Specifies horizontal indentation between a node and its children.
-deltay
Specifies vertical size of the nodes.
-dragenabled
A boolean specifying if drag is enabled.
-dragendcmd
Specifies a command to be called when drag ended. dragendcmd must be a command conforming to the description of the option dragendcmd of DragSite::register.
-dragevent
Specifies the number of the mouse button associated to the drag. Must be 1, 2 or 3.
-draginitcmd
Tree has a command wrapper for drag-init events. This command refused the drag if no node is designated. In other cases:
If draginitcmd is empty, it returns:
  • the value of option dragtype or TREE_NODE if empty as the data type,
  • {copy move link} as the operations,
  • the node identifier as the data.
If draginitcmd is not empty, it is called with the following arguments:
  • the pathname of the tree,
  • the identifier of the dragged node,
  • the toplevel created to represent dragged data.
and must return a value conforming to draginitcmd option described in DragSite::register.
-dragtype
Specifies an alternate type of dragged object.
-dropcmd
Tree has a command wrapper for drop events. This command stops auto scrolling and extract node and position.
If dropcmd is not empty, it is called with the following arguments:
  • the pathname of the tree,
  • the pathname of the drag source,
  • a list describing where the drop occurs. It can be:
    • {widget},
    • {node node} or
    • {position node index}.
  • the current operation,
  • the data type,
  • the data.
-dropenabled
A boolean specifying if drop is enabled.
-dropovercmd
Tree has a command wrapper for drag-over events. This command enables auto scrolling and position extraction during the drag-over. If dropovercmd is not empty, the command is called with the following aguments:
  • the pathname of the tree,
  • the pathname of the drag source,
  • a list describing where the drop can occur, whose elements are:
    • the string widget if dropovertype option contains w, else empty string.
    • the targeted node if drag icon points a node and dropovertype option contains n, else empty string.
    • a list containing a node and the position within the children of the node where drag icon points to if dropovertype option contains p, else empty string.
    • optionally, the preferred method if drop can occur both inside a node and between two nodes. The value is position or node.
  • the current operation,
  • the data type,
  • the data.
The command must return a list with two elements:
  • the drop status, conforming to those described in dropovercmd option of DropSite::register,
  • the choosen method: widget, node or position.
-dropovermode
Specifies the type of drop-over interaction. Must be a combination of w, which specifies that drop can occurs everywhere on widget, p, which specifies that drop can occurs between two nodes, and n, which specifies that drop occurs inside nodes.
-droptypes
Specifies a list of accepted dropped object/operation. See option droptypes of DropSite::register. for more infromation.
Default is TREE_NODE with operations copy and move.
-height
Specifies the desired height for the tree in units of deltay pixels.
-linesfill
Specifies a foreground color for the lines between nodes.
-linestipple
Specifies a stipple bitmap for the lines between nodes.
-opencmd
Specifies a command to be called when user open a node. The opened node is appended to the command.
-padx
Specifies distance between image or window and text of the nodes.
-redraw
Specifies wether or not the tree should be redrawn when entering idle. Set it to false if you call update while modifying the tree.
-showlines
Specifies whether or not lines should be drawn between nodes.
-width
Specifies the desired width for the tree in units of 8 pixels.

WIDGET COMMAND
pathName bindImage event script
This command associates a command to execute whenever the event sequence given by event occurs on the image of a node. The node idenfier on which the event occurs is appended to the command.
pathName bindText event script
This command associates a command to execute whenever the event sequence given by event occurs on the label of a node. The node idenfier on which the event occurs is appended to the command.
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName closetree node
This command close all the subtree given by node (recurse through the tree starting at node and set open option to 0)
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName delete ?arg...?
Deletes all nodes (and children of them) in arg. arg can be a list of nodes or a list of list of nodes. To delete all the tree, do $pathName delete [$pathName nodes root].
pathName edit node text ?verifycmd? ?clickres? ?select?
Provides a way for the user to edit in place the label of a node. This is possible only if node is visible (all its parents are open).
The command takes the initial text as argument and does not modify the label of the edited node, but returns an empty string if edition is canceled, or the typed text if edition is accepted.
When editing, the user can cancel by pressing Escape, or accept by pressing Return.
clickres specifies what to do if the user click outside the editable area. If clickres is 0 (the default), the edition is canceled. If clickres is 1, the edition is accepted. In all other case, the edition continues.
If edition is accepted and modifycmd is not empty, then it is called with the new text as argument and must return 1 to accept the new text, 0 to refuse it and continue edition.
select specifies wether or not the initial text should be selected. Default is 1.
pathName exists node
Returns whether or not node exists in the tree.
pathName index node
Returns the position of node in its parent.
pathName insert index parent node ?option value...?
Inserts a new node identified by node in the children list of parent at position index.

-data
User data associated to the node.
-drawcross
Specifies how the cross used to expand or collapse the children of a node should be drawn. Must be one of auto, allways or never.
If auto, the cross is drawn only if the node has children. If allways, the cross is always drawn. If never, the cross is never drawn.
-fill
Specifies the foreground color of the label of the node.
-font
Specifies a font for the label of the node.
-image
Specifies an image to display at the left of the label of the node. window option override image.
-open
Specifies wether or not the children of the node should be drawn.
-text
Specifies the label of the node.
-window
Specifies a pathname to display at the left of the label of the node. window option override image.
pathName itemcget node option
Returns the current value of a configuration option for the item. Option may have any of the values accepted by the item creation command.
pathName itemconfigure node ?option? ?value option value ...?
This command is similar to the configure command, except that it applies to the options for an individual item, whereas configure applies to the options for the widget as a whole. Options may have any of the values accepted by the item creation widget command. If options are specified, options are modified as indicated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for the item. Read-only options are not be modified.
pathName move parent node index
Moves node to the children list of parent at position index. parent can not be a descendant of node.
pathName nodes node ?first? ?last?
Returns parts of the children of node, following first and last.
If first and last are omitted, returns the list of all children. If first is specified and last omitted, returns the child at index first, or an empty string if first refers to a non-existent element. If first and last are specified, the command returns a list whose elements are all of the children between first and last, inclusive. Both first and last may have any of the standard forms for indices.
pathName opentree node
This command open all the subtree given by node (recurse through the tree starting at node and set open option to 1)
pathName parent node
Returns the parent of node.
pathName reorder node neworder
Modifies the order of children of node given by neworder. Children of node that do not appear in neworder are no moved.
pathName see node
Arrange the scrolling area to make node visible.
pathName selection cmd ?arg...?
Modifies the list of selected nodes following cmd:
clear
remove all nodes of the selection.
set
set the selection to all nodes in arg
add
add all nodes of arg in the selection
remove
remove all nodes of arg of the selection
get
return the current selected nodes
pathName visible node
Returns whether or not node is visible (all its parents are open).
pathName xview ?arg...?
Standard command to enable horizontal scrolling of pathName.
pathName yview ?arg...?
Standard command to enable vertical scrolling of pathName.


ListBox

NAME
ListBox - ListBox widget
CREATION
ListBox pathName ?option value...?
STANDARD OPTIONS
-background or -bg -borderwidth or -bd
-cursor
-highlightbackground
-highlightcolor
-highlightthickness
-relief
-selectbackground
-selectforeground
-takefocus
-xscrollcommand
-yscrollcommand
WIDGET-SPECIFIC OPTIONS
-deltax
-deltay
-dragenabled
-dragendcmd
-dragevent
-draginitcmd
-dragtype
-dropcmd
-dropenabled
-dropovercmd
-dropovermode
-droptypes
-height
-multicolumn
-padx
-redraw
-width
WIDGET COMMAND
pathName bindImage event script
pathName bindText event script
pathName cget option
pathName configure ?option? ?value option value ...?
pathName delete ?arg...?
pathName edit item text ?verifycmd? ?clickres? ?select?
pathName exists item
pathName index item
pathName insert index item ?option value...?
pathName item first ?last?
pathName itemcget item option
pathName itemconfigure item ?option? ?value option value ...?
pathName items ?first? ?last?
pathName move item index
pathName reorder neworder
pathName see item
pathName selection cmd ?arg...?
pathName xview ?arg...?
pathName yview ?arg...?

DESCRIPTION

ListBox widget uses canvas to display a list of items. Each item is composed of a label with its own font and foreground attributes, and an optional image or window. Each item is drawn in a single line, whose height is defined by the deltay option, so they must have at most this height. A item is uniquely identified by a string given at creation (by the insert command). The ListBox can have one or more columns, depending on multicolumn option. The user do not handle columns; the number of columns is determined following the height of the ListBox in order to see each item vertically.

WIDGET-SPECIFIC OPTIONS
-deltax
Specifies horizontal pad between each columns.
-deltay
Specifies vertical size of the items.
-dragenabled
A boolean specifying if drag is enabled.
-dragendcmd
Specifies a command to be called when drag ended. dragendcmd must be a command conforming to the description of the option dragendcmd of DragSite::register.
-dragevent
Specifies the number of the mouse button associated to the drag. Must be 1, 2 or 3.
-draginitcmd
ListBox has a command wrapper for drag-init events. This command refused the drag if no item is designated. In other cases:
If draginitcmd is empty, it returns:
  • the value of option dragtype or LISTBOX_ITEM if empty as the data type,
  • {move copy link} as the operations,
  • the item identifier as the data.
If draginitcmd is not empty, it is called with the following arguments:
  • the pathname of the listbox,
  • the identifier of the dragged item,
  • the toplevel created to represent dragged data.
and must return a value conforming to draginitcmd option described in DragSite::register.
-dragtype
Specifies an alternate type of dragged object.
-dropcmd
ListBox has a command wrapper for drop events. This command stops auto scrolling and extract item and position.
If dropcmd is not empty, it is called with the following arguments:
  • the pathname of the listbox,
  • the pathname of the drag source,
  • a list describing where the drop occurs. It can be:
    • {widget},
    • {item item} or
    • {position index}.
  • the current operation,
  • the data type,
  • the data.
-dropenabled
A boolean specifying if drop is enabled.
-dropovercmd
LsitBox has a command wrapper for drag-over events. This command enables auto scrolling and position extraction during the drag-over. If dropovercmd is not empty, the command is called with the following aguments:
  • the pathname of the listbox,
  • the pathname of the drag source,
  • a list describing where the drop can occur, whose elements are:
    • the string widget if dropovertype option contains w, else empty string.
    • the targeted item if drag icon points an item and dropovertype option contains i, else empty string.
    • an index within two items where drag icon points to if dropovertype option contains p, else empty string.
    • optionally, the preferred method if drop can occur both inside an item and between two items. The value is position or item.
  • the current operation,
  • the data type,
  • the data.
The command must return a list with two elements:
  • the drop status, conforming to those described in dropovercmd option of DropSite::register,
  • the choosen method: widget, item or position.
-dropovermode
Specifies the type of drop-over interaction. Must be a combination of w, which specifies that drop can occurs everywhere on widget, p, which specifies that drop can occurs between two items, and i, which specifies that drop occurs inside items.
-droptypes
Specifies a list of accepted dropped object/operation. See option droptypes of DropSite::register. for more infromation.
Default is LISTBOX_ITEM with operations copy and move.
-height
Specifies the desired height for the listbox in units of deltay pixels.
-multicolumn
Specifies wether or not ListBox layouts items in order to see each one vertically.
-padx
Specifies distance between image or window and text of the items.
-redraw
Specifies wether or not the listbox should be redrawn when entering idle. Set it to false if you call update while modifying the listbox.
-width
Specifies the desired width for the listbox in units of 8 pixels.

WIDGET COMMAND
pathName bindImage event script
This command associates a command to execute whenever the event sequence given by event occurs on the image of a item. The item idenfier on which the event occurs is appended to the command.
pathName bindText event script
This command associates a command to execute whenever the event sequence given by event occurs on the label of a item. The item idenfier on which the event occurs is appended to the command.
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
pathName delete ?arg...?
Deletes all items in arg. arg can be a list of items or a list of list of items. To delete all items, do $pathName delete [$pathName items].
pathName edit item text ?verifycmd? ?clickres? ?select?
Provides a way for the user to edit in place the label of an item.
The command takes the initial text as argument and does not modify the label of the edited node, but returns an empty string if edition is canceled, or the typed text if edition is accepted.
When editing, the user can cancel by pressing Escape, or accept by pressing Return.
clickres specifies what to do if the user click outside the editable area. If clickres is 0 (the default), the edition is canceled. If clickres is 1, the edition is accepted. In all other case, the edition continues.
If edition is accepted and modifycmd is not empty, then it is called with the new text as argument and must return 1 to accept the new text, 0 to refuse it and continue edition.
select specifies wether or not the initial text should be selected. Default is 1.
pathName exists item
Returns 1 if item exists in the listbox, else 0.
pathName index item
Returns the position of item in the list.
pathName insert index item ?option value...?
Inserts a new item identified by item in the list at position index.

-data
User data associated to the item.
-fill
Specifies the foreground color of the label of the item.
-font
Specifies a font for the label of the item.
-image
Specifies an image to display at the left of the label of the item. window option override image.
-indent
Specifies the amount of extra space in pixels at the left of the item.
-text
Specifies the label of the item.
-window
Specifies a pathname to display at the left of the label of the item. window option override image.
pathName item first ?last?
Its use is deprecated. Use items instead.
If last is omitted, returns the item at index first in the list, or an empty string if first refers to a non-existent element. If last is specified, the command returns a list whose elements are all of the items between first and last, inclusive. Both first and last may have any of the standard forms for indices.
pathName itemcget item option
Returns the current value of a configuration option for the item. Option may have any of the values accepted by the item creation command.
pathName itemconfigure item ?option? ?value option value ...?
This command is similar to the configure command, except that it applies to the options for an individual item, whereas configure applies to the options for the widget as a whole. Options may have any of the values accepted by the item creation widget command. If options are specified, options are modified as indicated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for the item. Read-only options are not be modified.
pathName items ?first? ?last?
If first and last are omitted, returns the list of all items. If first is specified and last omitted, returns the item at index first, or an empty string if first refers to a non-existent element. If first and last are specified, the command returns a list whose elements are all of the items between first and last, inclusive. Both first and last may have any of the standard forms for indices.
pathName move item index
Moves item at position index in the list.
pathName reorder neworder
Modifies the order of items in the listbox given by neworder. Items that do not appear in neworder are no moved.
pathName see item
Arrange the scrolling area to make item visible.
pathName selection cmd ?arg...?
Modifies the list of selected items following cmd:
clear
remove all items of the selection.
set
set the selection to all items in arg
add
add all items of arg in the selection
remove
remove all items of arg of the selection
get
return the current selected items
pathName xview ?arg...?
Standard command to enable horizontal scrolling of pathName.
pathName yview ?arg...?
Standard command to enable vertical scrolling of pathName.


MessageDlg

NAME
MessageDlg - Message dialog box
CREATION
MessageDlg pathName ?option value...?
STANDARD OPTIONS
-anchor
-font
-foreground or -fg -padx
-pady
OPTIONS from Dialog
-background or -bg | -cancel
-default | -parent
WIDGET-SPECIFIC OPTIONS
-aspect
-buttons
-icon
-justify
-message
-title
-type
-width

DESCRIPTION

MessageDlg provides a simple way to display a message dialog. MessageDlg::create creates the message dialog, displays it and return the index of the pressed button, or -1 if it is destroyed. When returning, the dialog no longer exists.

WIDGET-SPECIFIC OPTIONS
-aspect
Specifies a non-negative integer value indicating desired aspect ratio for the text. The aspect ratio is specified as 100*width/height. 100 means the text should be as wide as it is tall, 200 means the text should be twice as wide as it is tall, 50 means the text should be twice as tall as it is wide, and so on. Used to choose line length for text if width option isn't specified. Defaults to 150.
-buttons
Specifies a list of buttons to display when type option is user. If a button has a symbolic name, its associated text will be displayed.
-icon
Specifies an icon to display. Must be one of the following: error, info, question or warning.
-justify
Specifies how to justify lines of text. Must be one of left, center, or right. Defaults to left. This option works together with the anchor, aspect, padx, pady, and width options to provide a variety of arrangements of the text within the window. The aspect and width options determine the amount of screen space needed to display the text. The anchor, padx, and pady options determine where this rectangular area is displayed within the widget's window, and the justify option determines how each line is displayed within that rectangular region. For example, suppose anchor is e and justify is left, and that the message window is much larger than needed for the text. The the text will displayed so that the left edges of all the lines line up and the right edge of the longest line is padx from the right side of the window; the entire text block will be centered in the vertical span of the window.
-message
Specifies the message to display in this message box.
-title
Specifies a string to display as the title of the message box. If the value is empty (the default), a default title will be set corresponding to the icon option. The default associated title is in english, and can be modified to set it in another language by specifying the resource:
    *MessageDlg.nameTitle:   value
or the equivalent tcl command:
    option add *MessageDlg.nameTitle value
where name is the name of an icon as defined in the icon option.
For example, for french language, you can specify for a warning dialog:
    option add *MessageDlg.warningTitle  "Attention"
-type
Specifies a set of buttons to be displayed. The following values are possible:

abortretryignore
Displays three buttons whose symbolic names are abort, retry and ignore.

ok
Displays one button whose symbolic name is ok.

okcancel
Displays two buttons whose symbolic names are ok and cancel.

retrycancel
Displays two buttons whose symbolic names are retry and cancel.

yesno
Displays two buttons whose symbolic names are yes and no.

yesnocancel
Displays three buttons whose symbolic names are yes, no and cancel.

user
Displays buttons of -buttons option.

-width
Specifies the length of lines in the window. If this option has a value greater than zero then the aspect option is ignored and the width option determines the line length. If this option has a value less than or equal to zero, then the aspect option determines the line length.


ProgressDlg

NAME
ProgressDlg - Progress indicator dialog box
CREATION
ProgressDlg pathName ?option value...?
STANDARD OPTIONS
-font
-textvariable
OPTIONS from Dialog
-background or -bg | -parent
-separator | -title
OPTIONS from ProgressBar
-background or -bg | -borderwidth or -bd
-foreground or -fg | -maximum
-relief | -troughcolor
-type | -variable
WIDGET-SPECIFIC OPTIONS
-command
-height
-stop
-width
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?

DESCRIPTION

ProgressDlg provides a simple way to display a progress indicator dialog. ProgressDlg::create creates the dialog, displays it, set a local grab to it and immediatly return. The dialog is updated by modifying the value of the variable of options -textvariable and -variable. You have to destroy the dialog after use.

WIDGET-SPECIFIC OPTIONS
-command
Specifies a command to call when user press stop button.
-height
Specifies a desired height for the label in lines of text.
-stop
Specifies the text of the button typically used to stop process. If empty, no button will be drawn. This can be a symbolic name.
-width
Specifies a desired width for the label in characters.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.


PasswdDlg

NAME
PasswdDlg - Login/Password dialog box
CREATION
PasswdDlg pathName ?option value...?
OPTIONS from Dialog
-anchor | -background or -bg
-homogeneous | -modal
-padx | -pady
-parent | -spacing
-title
OPTIONS from LabelEntry
-background or -bg | -borderwidth or -bd
-disabledforeground | -entrybg
-entryfg | -exportselection
-font | -foreground or -fg
-helptype | -highlightbackground
-highlightcolor | -highlightthickness
-insertbackground | -insertborderwidth
-insertofftime | -insertontime
-insertwidth | -labelanchor
-labelfont | -labelheight
-labeljustify | -labelwidth
-loginhelptext (see -helptext) | -loginhelpvar (see -helpvar)
-loginlabel (see -label) | -logintext (see -text)
-logintextvariable (see -textvariable) | -loginunderline (see -underline)
-passwdeditable (see -editable) | -passwdhelptext (see -helptext)
-passwdhelpvar (see -helpvar) | -passwdlabel (see -label)
-passwdstate (see -state) | -passwdtext (see -text)
-passwdtextvariable (see -textvariable) | -passwdunderline (see -underline)
-relief | -selectbackground
-selectborderwidth | -selectforeground
-wraplength
WIDGET-SPECIFIC OPTIONS
-command
-type
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?

DESCRIPTION

PasswdDlg provides a simple way to display a login/password dialog. PasswdDlg::create creates the dialog, displays it, and return the value of login and password in a list, or an empty list if it is destroyed or user press cancel. When returning, the dialog no longer exists.
Additionnal resources can be set to modify other text:

    *loginName     Label for login LabelEntry
    *passwordName  Label for password LabelEntry

WIDGET-SPECIFIC OPTIONS
-command
Specifies a command to call when user press ok button.
-type
Specifies a set of buttons to be displayed. The following values are possible:

ok
Displays one button whose symbolic name is ok.

okcancel
Displays two buttons whose symbolic names are ok and cancel.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
Stephane Lavirotte (Stephane.Lavirotte@sophia.inria.fr)


SelectFont

NAME
SelectFont - Font selection widget
CREATION
SelectFont pathName ?option value...?
STANDARD OPTIONS
-background or -bg -font
WIDGET-SPECIFIC OPTIONS
-command
-parent
-sampletext
-title
-type
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
SelectFont::loadfont

DESCRIPTION

SelectFont provides a simple way to choose font. It can be displayed as a dialog box or as a toolbar.
Textual items in Dialog box uses -name options so they can be translated to any language. Symbolic name used are ok, cancel, font, size, style, bold, italic, underline and overstrike.

WIDGET-SPECIFIC OPTIONS
-command
Specifies a command to call when user select a new font when SelectFont type option is toolbar.
-parent
Parent of the Dialog. Dialog is centered in its parent. If empty, it is centered in root window.
-sampletext
Specifies the text displayed in the preview area.
-title
Title of the Dialog toplevel.
-type
Specifies the type of the SelectFont widget. Must be dialog or toolbar.
If type option is dialog, SelectFont::create directly creates the dialog, displays it and return an empty string if cancel button is pressed or if dialog is destroyed, and the selected font if ok button is pressed. In all cases, dialog is destroyed.
If type option is toolbar, SelectFont::create returns the pathname of the widget created.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
SelectFont::loadfont
Load the font available in the system.


SelectColor

NAME
SelectColor - Color selection widget
CREATION
SelectColor pathName ?option value...?
WIDGET-SPECIFIC OPTIONS
-color
-command
-height
-parent
-title
-type
-variable
-width
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
SelectColor::setcolor index color

DESCRIPTION

SelectColor provides a simple way to select color. It can be displayed as a dialog box or as a menubutton.

WIDGET-SPECIFIC OPTIONS
-color
Specifies the color value of the widget.
-command
When type is menubutton, specifies a command to call when user select a color.
-height
When type is menubutton, specifies the desired height for the button.
-parent
Parent of the Dialog. Dialog is centered in its parent. If empty, it is centered in root window.
-title
Title of the Dialog toplevel.
-type (read-only)
Specifies the type of the SelectColor widget. Must be dialog or menubutton.
If type option is dialog, SelectColor::create directly creates the dialog, displays it and return an empty string if cancel button is pressed or if dialog is destroyed, and the selected color if ok button is pressed. In all cases, dialog is destroyed.
If type option is menubutton, SelectColor::create returns the pathname of the widget created. It is composed of a button from which user can access a menu displaying predefined colors.
-variable
Specifies a variable to link to the color value of the widget.
-width
When type is menubutton, specifies the desired width for the button.

WIDGET COMMAND
pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the creation command.
pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the creation command. Read-only options are not be modified.
SelectColor::setcolor index color
Set the value of user predefined color at index index to color. index must be between 1 and 5.


Widget

 Under construction ...
NAME
Widget - The Widget base class
COMMAND
Widget::addmap class subclass subpath options
Widget::bwinclude class subclass subpath ?arg...?
Widget::cget path option
Widget::configure path options
Widget::declare class optlist
Widget::destroy path
Widget::focusNext w
Widget::focusOK w
Widget::focusPrev w
Widget::generate-doc dir widgetlist
Widget::generate-widget-doc class iscmd file
Widget::getoption path option
Widget::hasChanged path option pvalue
Widget::init class path options
Widget::setoption path option value
Widget::subcget path subwidget
Widget::syncoptions class subclass subpath options
Widget::tkinclude class tkwidget subpath ?arg...?

DESCRIPTION

The Widget namespace handle data associated to all BWidget and provide commands to easily define BWidget.
For commands can be used to define a BWidget: tkinclude, bwinclude, declare, addmap and syncoptions. Here is the definition of ComboBox widget:

namespace eval ComboBox {
    # We're using ArrowButton, Entry and LabelFrame
    ArrowButton::use
    Entry::use
    LabelFrame::use

    # Include resources of LabelFrame
    Widget::bwinclude ComboBox LabelFrame .labf \
        rename     {-text -label} \
        remove     {-focus} \
        prefix     {label -justify -width -anchor -height -font} \
        initialize {-relief sunken -borderwidth 2}

    # Include resources of Entry
    Widget::bwinclude ComboBox Entry .e \
        remove {-relief -bd -borderwidth -bg -fg} \
        rename {-foreground -entryfg -background -entrybg}

    # Declare new resources
    Widget::declare ComboBox {
        {-height      TkResource 0  0 listbox}
        {-values      String     "" 0}
        {-modifycmd   String     "" 0}
        {-postcommand String     "" 0}
    }

    # Map resources to subwidget
    Widget::addmap ComboBox "" :cmd {-background {}}
    Widget::addmap ComboBox ArrowButton .a \
        {-foreground {} -background {} -disabledforeground {} -state {}}

    # Synchronize subwidget options
    Widget::syncoptions ComboBox Entry .e {-text {}}
    Widget::syncoptions ComboBox LabelFrame .labf {-label -text -underline {}}

    proc use {} {}
}

COMMAND
Widget::addmap class subclass subpath options
This command map some resources to subwidget. Mapped resources automatically configure subwidget when widget is configured.
  • class is the class of the new BWidget
  • subclass is the class the subwidget (BWidget class, e.g Entry, or empty for Tk widget)
  • subpath is the path of the subwidget
  • options is the list {option realres ...} of options to map to subwidget
Widget::bwinclude class subclass subpath ?arg...?
This command includes into a new BWidget the resources of another BWidget. Arguments are:
  • class class of the new widget
  • subclass class name of the BWidget to be included
  • subpath path of the widget to configure when BWidget is configured
  • options is:
    • include {option option ...}
      list of options to include (all if not defined)
    • remove {option option ...}
      list of options to remove
    • rename {option name option name ...}
      list of options to rename
    • prefix {prefix option option ...}
      pefix all option by prefix
    • initialize {option value option value ...}
      default value of options
    • readonly {option value option value ...}
      new readonly flag
Widget::cget path option
Returns the value of option of BWidget path. cget tests the option existence and takes care of synchronization with subwidget. Typically called by the BWidget cget command.
Widget::configure path options
Description text
Widget::declare class optlist
This command declare new resources for a BWidget.
  • class is class of the new widget
  • options is the list describing new options. Each new option is a list {option type value ro ?args?} where:
    • option is the name of the option
    • type is the type of the option
    • value is the default value of the option
    • ro is the readonly flag of the option
    • args depends on type

type can be:
TkResource
value of option denotes a resource of a Tk widget. args must be class or {class realoption}. class is the creation command of the Tk widget, e.g. entry. The second form must be used if option has not the same name in Tk widget, but realoption.
If value is empty, it is initialized to the default value of the Tk widget.
BwResource
value of option denotes a resource of a BWidget. args must be class or {class realoption}. class is the name of the namespace of the BWidget, e.g. LabelFrame. The second form must be used if option has not the same name in BWidget, but realoption.
If value is empty, it is initialized to the default value of the BWidget.
Int
value of option is an integer. args can be {?min? ?max?} to force it to be in a range. The test is [expr $option > $min] && [expr $option < $max] so if args is {0 10}, value must be beetween 0 and 10 exclude, if args is {=0 =10} , value must be beetween 0 and 10 include.
Boolean
value of option is a boolean. True values can be 1, true or yes. False values can be 0, false or no. Widget::cget always return 0 or 1.
Enum
value of option is a element of a enumeration. args must be the list of enumeration, e.g. {top left bottom right}.
Flag
value of option is a combination of a set of chars. args must be a string defining the set.
String
value of option is any uncontrolled string.
Synonym
option is a synonym of option args. value has no effect here.
Widget::destroy path
Description text
Widget::focusNext w
Description text
Widget::focusOK w
Description text
Widget::focusPrev w
Description text
Widget::generate-doc dir widgetlist
Description text
Widget::generate-widget-doc class iscmd file
Description text
Widget::getoption path option
Returns the value of option of BWidget path. This command does not test option existence, does not handle synonym and does not take care of synchronization with subwidget.
Widget::hasChanged path option pvalue
Description text
Widget::init class path options
Description text
Widget::setoption path option value
Set the value of option of BWidget path without option test, subwidget mapping, synonym handling and does not set the modification flag.
Widget::subcget path subwidget
Returns the list of all option/value of BWidget path that are mapped to subwidget.
Widget::syncoptions class subclass subpath options
This command synchronize options value of a subwidget. Used when an option of a subwidget is modified out of the BWidget configure command.
  • class is the class of the new BWidget
  • subclass is the class the subwidget (BWidget class, e.g Entry, or empty for Tk widget)
  • subpath is the path of the subwidget
  • options is the list {option realres ...} of options to synchronize with subwidget
Widget::tkinclude class tkwidget subpath ?arg...?
This command includes into a new BWidget the resources of a Tk widget. Arguments are:
  • class class of the new widget
  • tkwidger command name of the Tk widget to be included
  • subpath path of the widget to configure when BWidget is configured
  • options is:
    • include {option option ...}
      list of options to include (all if not defined)
    • remove {option option ...}
      list of options to remove
    • rename {option name option name ...}
      list of options to rename
    • prefix {prefix option option ...}
      pefix all option by prefix
    • initialize {option value option value ...}
      default value of options
    • readonly {option value option value ...}
      new readonly flag


DynamicHelp

NAME
DynamicHelp - Provide help to Tk widget or BWidget
COMMAND
DynamicHelp::configure ?option? ?value option value ...?
DynamicHelp::include class type
DynamicHelp::register path type ?arg...?
DynamicHelp::sethelp path subpath ?force?

DESCRIPTION

Description text

COMMAND
DynamicHelp::configure ?option? ?value option value ...?
This command configure the ballon help.

-borderwidth
Width of the black border around the balloon.
-delay
Define the delay in millisecond of mouse inactivity before displaying the balloon.

Other standard options are:
-background or -bg -font
-foreground or -fg -justify
DynamicHelp::include class type
Description text
DynamicHelp::register path type ?arg...?
Register a help text to the widget path. type determines the type of the help or the type of the widget. Depending on type, other options must be provided.
type | options
balloon | text
variable | varName text
menu | varName
menuentry | index text

If one of the option is missing or is empty, help is removed for this widget.
For type other than balloon, varName is typically a variable linked to a label.
For menu, balloon type help is not available. To declare a help for menu, you first declare the menu, and then entries of this menu.
For example:

     # create menu
menu .m -type menubar
# associate menubar to toplevel BEFORE DynamicHelp::register
# to make it works with menu clone name
. configure -menu .m
.m add cascade -label "File" -menu .m.file
menu .m.file
.m.file add command -label "Open..."
.m.file add command -label "Quit"
# create label for help, using variable varinfo
label .l -textvariable varinfo
# associate all entries of menu .m.file to variable varinfo
DynamicHelp::register .m.file menu varinfo
# then declare entries of .m.file
DynamicHelp::register .m.file menuentry 0 "Detach menu"
DynamicHelp::register .m.file menuentry 1 "Open a file"
DynamicHelp::register .m.file menuentry 2 "Exit demo"

Notice that if popup menu is owned by a menubar, you must associate first the menubar to its toplevel. In this case, when you create a menu popup, its clone window is also created, and DynamicHelp::register detects the exitence of the clone window and maps events to it.
DynamicHelp::sethelp path subpath ?force?
Description text


DragSite

NAME
DragSite - Commands set for Drag facilities
COMMAND
DragSite::include class type event
DragSite::register path ?option value...?
DragSite::setdrag path subpath initcmd endcmd ?force?

DESCRIPTION

Commands of this namespace enable user to define a BWidget or a Tk widget as a drag site.

COMMAND
DragSite::include class type event
This command provides a simple way to include options relatives to a drag site into BWidget resources definition. It includes the options needed for register: -dragevent, initialized to event, -draginitcmd and -dragendcmd, initialized to empty string, and two new options:
-dragenabled | Specifies wether or not drag is active (initialized to 0)
-dragtype | Default or alternate dragged data type (initialized to type)
DragSite::register path ?option value...?
This command is used to declare path as a drag site. Options are:

-dragendcmd
Command called when drag terminates (ie when user release drag icon). This command is called with the following arguments:
  • the pathname of the drag source (the widget itself),
  • the pathname of the drop target,
  • the operation,
  • the type of the dragged data,
  • the dragged data,
  • result of the drop (result of the call to -dropcmd of the target),
If the drop does not occurs, the target and the operation are empty string and the result is 0.
-dragevent
Specifies the number of the mouse button associated to the drag. Must be 1, 2 or 3.
-draginitcmd
Command called when drag initiates. When the event of option dragevent occurs on path, this command is called with the following arguments:
  • pathname of the drag source (path),
  • root x-coordinate of pointer,
  • root y-coordinate of pointer,
  • a toplevel created to represent dragged data. When returning, if it has no children, a bitmap is automatically displayed.
The command must return a list containing three elements:
  • the type of the data,
  • the list of acceptable basic operations (copy, move and link)
  • and the data.
Note that even if copy does not appear in the list of basic operation, it is considered as an acceptable operation, since copy semantic does not modify the drag source.
DragSite::setdrag path subpath initcmd endcmd ?force?
This command provides a simple way to call register during a BWidget creation or configuration.
  • path is the pathname of the BWidget,
  • subpath is the pathname of the tk widget where drag event occurs,
  • initcmd BWidget command for drag-init event,
  • endcmd BWidget command for drag-end event,
  • force specifies wether or not to call register whenever no option value has changed (0 by default - for BWidget configuration, use 1 for BWidget creation).
setdrag verifies the modification flag of options dragenabled and dragevent and calls register if needed according to the options values and initcmd and endcmd arguments. draginitcmd and dragendcmd are not taken from options of widget because they are considered as user command, called by BWidget implementation of drag-init and drag-end events.


DropSite

NAME
DropSite - Commands set for Drop facilities
COMMAND
DropSite::include class types
DropSite::register path ?option value...?
DropSite::setcursor cursor
DropSite::setdrop path subpath dropover drop ?force?
DropSite::setoperation op

DESCRIPTION

Commands of this namespace enable user to define a BWidget or a Tk widget as a drop site. A drop site is composed of the type of object that can be dropped and associated operation, a command called when drop occurs, and a command when an object is dragged over the widget. A drop site must have at least one type of acceptable object and a drop command.

COMMAND
DropSite::include class types
This command provides a simple way to include options relatives to a drop site into BWidget resources definition. It includes the options needed for register, -dropovercmd and -dropcmd, initialized to empty string, and -droptypes, initialized to types, and one new option:
-dropenabled Specifies wether or not drop is active (initialized to 0)
DropSite::register path ?option value...?
This command is used to declare path as a drop site. Options are:

-dropcmd
This command is called when user release the drag icon over a valid drop target widget. It takes the same arguments as -dragovercmd command. Its return values is passed as a result to the -dragendcmd command of the drag source widget.
-dropovercmd
This command can be used to provide a dynamic drag while drag-over events. While a drag occurs, events <Enter>, <Motion> and <Leave> are catched. Arguments passed to the command are:
  • pathname of the drop target (the widget itself),
  • pathname of the drag source,
  • event over the drop target: enter, motion or leave,
  • root x-coordinate of the pointer,
  • root y-coordinate of the pointer,
  • operation,
  • type of the dragged data,
  • dragged data.
Command must the new status of the drag:
  • 0 if widget refuse this drag. Command will not be recalled on motion/leave event.
  • 1 if widget accept this drag. Command will not be recalled on motion/leave event.
  • 2 if widget refuse this drag. Command will be recalled on each motion event to reevaluate.
  • 3 if widget accept this drag. Command will be recalled on each motion event to reevaluate.
Here is a list of events and associated actions on a DropSite widget. This example assumes that dragged data type is valid for the drop target. status is the status of the drag on a DropSite. Its value is:

Event

Old status

Action

New status

<Enter>

-

if DropSite has dropovercmd, call it with enter

result of dropovercmd

else

1

<Motion>

0 or 1

unchanged

2 or 3

call dropovercmd with motion

result of dropovercmd

<Leave>

0 or 1

-

2 or 3

call dropovercmd with leave

-

<Drop>

0

call dragendcmd of drag source

-

1

call dropcmd and call dragendcmd of drag source

2

call dropovercmd with leave and call dragendcmd of drag source

3

call dropcmd and call dragendcmd of drag source

-droptypes
Specifies a list {type oplist ?type oplist? ...} of acceptable types and associated operations for the drop target. For each type, oplist is a list {descops mod ?descops mod? ...} describing operations and modifier keys for these operations. descops describe an operation. It can be a predefined operations (copy, move or link) or a new user defined operation, of the form {subop baseop ?bitmap?}. subop is the name given to the sub operation, baseop is the name of the base operation (copy, move or link) and bitmap is a bitmap to display for the operation.
If bitmap is empty, the default bitmap of the base operation is used for the sub operation.
subop can be a base operation, in order to change the bitmap of a base operation. In this case, baseop must be empty or equal to subop.
mod is the modifer key for the operation. It can be:
  • none to specify that no modifier key is pressed. This modifier can only be used with a sub operation named default (and vice versa), which has the behaviour of not display any bitmap operation. For all type, if the modifier none is not given, it is automatically associated to the default sub operation of a copy base operation.
  • program to specifies a sub operation accessible only by DropSite::setoperation.
  • A list combining shift, control and alt, which means their corresponding key.
DropSite::setcursor cursor
This command can be used within the script dragovercmd. It is usefull to provide visual effect about the state of the drag.
DropSite::setdrop path subpath dropover drop ?force?
This command provides a simple way to call register during a BWidget creation or configuration.
  • path is the pathname of the BWidget,
  • subpath is the pathname of the tk widget where drag event occurs,
  • dropover is a command for drag-over event,
  • drop is a command for drop event,
  • force specifies wether or not to call register whenever no option value has changed (0 by default - for BWidget configuration, use 1 for BWidget creation).
setdrop verifies the modification flag of options dropenabled and droptypes and calls register if needed according to the options values and dropover and drop arguments. dropovercmd and dropcmd are not taken from options of widget because they are considered as user command, called by BWidget implementation of drag-over and drop events.
DropSite::setoperation op
Description text


BWidget

 Under construction ...
NAME
BWidget - Description text
COMMAND
BWidget::XLFDfont cmd ?arg...?
BWidget::assert exp ?msg?
BWidget::clonename menu
BWidget::focus option path
BWidget::get3dcolor path bgcolor
BWidget::getname name
BWidget::grab option path
BWidget::lreorder list neworder
BWidget::parsetext text
BWidget::place path w h ?arg...?

DESCRIPTION

Description text

COMMAND
BWidget::XLFDfont cmd ?arg...?
Description text
BWidget::assert exp ?msg?
Description text
BWidget::clonename menu
Description text
BWidget::focus option path
Description text
BWidget::get3dcolor path bgcolor
Description text
BWidget::getname name
Description text
BWidget::grab option path
Description text
BWidget::lreorder list neworder
Description text
BWidget::parsetext text
Description text
BWidget::place path w h ?arg...?
Description text


Img Documentation

Img Manual

Introduction Installation Format handlers External libraries

Introduction

Img is a Tk extension, adding support for many other Image formats: BMP, XBM, XPM, GIF (with transparency, but without LZW), PNG, JPEG, TIFF and postscript. This version only works with Tcl/Tk 8.0 or higher (any patchlevel, tested up to 8.4a1). If you are using Tk4.2 or lower, please stick with Img1.1.4 (which is still available).

Currently there are two identical source distributions:

img124.zip | (for Windows) | (about 1.8 Mb)
img1.2.4.tar.gz | (for Unix) | (about 1.6 Mb)

And a binary distribution

img124.exe (for Windows) (about 800 kb)

If you want to write images to disk which contain transparency information (e.g. GIF89 or PNG with alpha channel), you need at least Tk8.3.

In stead of LZW the run-length encoding of Hutchison Avenue Software Corporation is used, also known as miGIF compression. The miGIF compression routines do not, strictly speaking, generate files conforming to the GIF spec, since the image data is not LZW-compressed (this is the point: in order to avoid transgression of the Unisys patent on the LZW algorithm.) However, miGIF generates data streams that any reasonably sane LZW decompresser will decompress to what we want.


TclDOM Reference

TclDOM is a Tcl language binding for the DOM - the Document Object Model. DOM provides a view of a XML (or HTML) document as a tree structure.

Currently, TclDOM only supports XML documents. It provides a convenience function to parse XML documents into a DOM structure, allows DOM structures to be built in-memory from scratch and finally provides a method to output XML formatted text from a DOM structure.

This version of TclDOM implements DOM Level 1.

The DOM Level 1 specification should be read in conjunction with this reference manual, as it explains the meaning and purpose of the various interfaces. This manual is not a tutorial on how to use the DOM.

Table Of Contents

  1. Packages and Namespaces
  2. Tokens
  3. DOM Commands
    • dom::DOMImplementation
      Methods:
      • dom::DOMImplementation hasFeature feature
      • dom::DOMImplementation create
      • dom::DOMImplementation destroy token
      • dom::DOMImplementation parse data ?options ...?
        Configuration options:
        • -parser
        • -progresscommand
        • -chunksize
      • dom::DOMImplementation serialize token ?options ...?
        Configuration options:
        • -newline
      • dom::DOMImplementation trim token
    • dom::document method token ?arguments...?
      Methods:
      • dom::document cget token option
      • dom::configure token option value
        Configuration options:
        • -doctype
        • -implementation
        • -documentElement
      • dom::document createElement token type
      • dom::document createDocumentFragment token
      • dom::document createTextNode token text
      • dom::document createComment token data
      • dom::document createCDATASection token text
      • dom::document createProcessingInstruction token target data
      • dom::document createAttribute token name
      • dom::document createEntity token
      • dom::document createEntityReference token
      • dom::document createDocTypeDecl token name extid dtd entities notations
      • dom::document getElementsByTagName token name
    • dom::node method token ?arguments...?
      Methods:
      • dom::node cget token option
      • dom::node token option value
        Configuration options:
        • -nodeName
        • -nodeType
        • -parentNode
        • -childNodes
        • -firstChild
        • -lastChild
        • -previousSibling
        • -nextSibling
        • -attributes
        • -nodeValue
      • dom::node insertBefore token newchild ?refchild?
      • dom::node replaceChild token newchild oldchild
      • dom::node removeChild token oldchild
      • dom::node appendChild token newchild
      • dom::node hasChildNodes token
      • dom::node cloneNode token ?deep?
      • dom::node children token
      • dom::node parent token
    • dom::element method token ?arguments...?
      Methods:
      • dom::element cget token option
      • dom::element token option value
        Configuration options:
        • -tagName
        • -empty
      • dom::element getAttribute token name
      • dom::element setAttribute token name value
      • dom::element removeAttribute token name
      • dom::element getAttributeNode token name
      • dom::element setAttributeNode token name
      • dom::element removeAttributeNode token name
      • dom::element getElementsByTagName token name
      • dom::element normalize token
    • dom::processinginstruction method token ?arguments...?
      Methods:
      • dom::processinginstruction cget token option
      • dom::processinginstruction token option value
        Configuration options:
        • -target
        • -data

Packages and Namespaces

 The TclDOM package defines the dom package and also a namespace using that name.

Tokens

 The TclDOM package uses "tokens" as identifiers for nodes within the document tree. This technique has been used to allow alternate implementations of TclDOM to be efficient, while retaining compatibility with the pure-Tcl implementation.

The format of the token itself as well as the data structure referred to by the token are not public and an application should not rely on these. Instead, an application should use the accessor methods provided by the package.

DOM Commands

Each Interface in the DOM specification is implemented with a Tcl command in the dom namespace. These commands are described below:
dom::DOMImplementation method ?args ...?
This command provides implementation-specific features not explicitly defined in the DOM specification. Methods include:
dom::DOMImplementation hasFeature feature
Provides a test for existence of a feature. Returns "1" if a feature is implemented, "0" otherwise.
dom::DOMImplementation create ?arrayName?
Creates the root node of a new DOM document. The return value is a token referring to the root node of the newly created document.

With no argument this command creates a data structure within the dom namespace. An arrayName argument may be supplied which the package will use to store its data structures in. Future implementations of TclDOM may choose to ignore this argument.

dom::DOMImplementation destroy token
This method frees all data structures associated with a DOM document. The token argument must refer to a valid token for any node in the document tree.
dom::DOMImplementation parse data ?options ...?
This method parses XML formatted text given by the data argument and constructs a DOM tree for the document. The return result is the token of the root node of the newly created document.

This method requires an event-based XML parser to be loaded to perform the parsing operation. The dom package itself does not include a XML parser. Support for the use of two Tcl event-based parsers is provided: TclXML and TclExpat. Any other Tcl event-based XML parser implementing the TclXML API may also be used.

By default the dom package will automatically attempt to load either of the supported parsers (using the package require Tcl command). It will first attempt to load TclExpat and if that fails it will then attempt to load TclXML. The command fails if neither parser can be loaded. This behaviour can be overridden by the -parser option.

Valid configuration options are:

-parser {}|expat|tcl
This option specifies which XML parser to use to parse the XML data. If an empty string is given then the default behaviour described above is used. The value "expat" specifies that the TclExpat package must be used. The value "tcl" specifies that the TclXML package must be used. If an explicit value is given and that parser cannot be loaded then the command will fail, despite the fact that the other parser may be available.
-progresscommand script
This option specifies a Tcl command to be invoked from time to time while the DOM tree is being constructed. The script will be invoked after a certain number of element start tags have been processed, given by the -chunksize option.
-chunksize integer
This option specifies how many element start tags to process before invoking the script given by the -progresscommand option.
dom::DOMImplementation serialize token ?options ...?
This method returns the XML formatted text corresponding to the node given by token. The text is guaranteed to be a well-formed XML document.

Valid configuration options are:

-newline elementlist
This option specifies a list of element types for which newline characters will be added before and after the start and end tags for those elements upon serialization.

White space is significant in XML, so the dom package never adds extra white space for purposes of "pretty-printing" the XML source document. On some platforms, such as VMS, this can actually cause serious problems due to line length limitations. This option provides the convenience of adding newlines to certain nominated element types for formatting the source into lines.

Examples:

Suppose the following DOM document is constructed:

set doc [::dom::DOMImplementation create]
set top [::dom::document createElement $doc Root]
set node [::dom::document createElement $top First]
::dom::document createElement $node Second
::dom::document createElement $top First
Without the -newline option the serialized document would be:
::dom::DOMImplementation serialize $doc
<?xml version="1.0"?>
<!DOCTYPE Root>
<Root><First><Second/></First><First/></Root>
With the -newline option the serialized document would be:
::dom::DOMImplementation serialize $doc -newline First
<?xml version="1.0"?>
<!DOCTYPE Root>
<Root>
<First>
<Second/>
</First>
<First/>
</Root>
dom::DOMImplementation trim token
This method removes any node containing only white space from the document tree of the node given by token.
dom::document method token ?arguments...?
This command implements the Document interface in the DOM specification. The most important aspect of this command are its factory methods for creating nodes.

The methods accepted by this command are as follows:

cget token option
This method returns the value of the given configuration option.
configure token option value
This method sets the value of the given configuration option.

Valid configuration options are:

-doctype token
Specifies the token of the Document Type Declaration node.

This is a read-only option. Use the factory method to create a Document Type Declaration node.

-implementation token
Specifies the token of the document's implementation.
-documentElement token
Specifies the token of the document's document element node. A document may only have one document element, but may have other types of children.

This is a read-only option. Use the factory method to create a document element node.

dom::document createElement token type
This method creates an element node as a child of the given node specified by token. token must be a node of type element, document or documentFragment. The new, child element is added as the last child of token's list of children. The new element's type is given by the type argument. The new element is created with an empty attribute list.
dom::document createDocumentFragment token
This method creates a documentFragment node as a child of the given node specified by token. token must be a node of type element, document or documentFragment. The new, child element is added as the last child of token's list of children.
dom::document createTextNode token text
This method creates a textNode node as a child of the given node specified by token. token must be a node of type element, document or documentFragment. The new, child element is added as the last child of token's list of children. The new element is created with its value set to text.
dom::document createComment token data
This method creates a comment node as a child of the given node specified by token. token must be a node of type element, document or documentFragment. The new, child element is added as the last child of token's list of children. The new element is created with its value set to data.
dom::document createCDATASection token text
This method creates a CDATASection node as a child of the given node specified by token. token must be a node of type element, document or documentFragment. The new, child element is added as the last child of token's list of children. The new element is created with its value set to text.
dom::document createProcessingInstruction token target data
This method creates a processingInstruction node as a child of the given node specified by token. token must be a node of type element, document or documentFragment. The new, child element is added as the last child of token's list of children. The new element is created with its name set to target and its value set to data.
dom::document createAttribute token name
This method creates an attribute node as a child of the given node specified by token. token must be a node of type element. The new attribute is created with its name set to name and an empty value.

NB. This method is included for completeness with respect to the DOM specification. The preferred method for setting element attributes is to use the element command.

dom::document createEntity token
Not currently implemented.
dom::document createEntityReference token
Not currently implemented.
dom::document createDocTypeDecl token name extid dtd entities notations
This method creates a Document Type Declaration node as a child of the given node specified by token. token must be a node of type document.

name is the element type of the document element. If the document already has a document element then this name must match with that element type.

extid is an external identifier to include in the document type declaration.

dtd is an internal DTD subset to incldue in the document type declaration. This is specified as XML text.

entities and notations are included for completeness with the DOM specification, but are not currently implemented.

Non-standard: This method is not a standard method as specified by the DOM Recommendation.

dom::document getElementsByTagName token name
This method searches the node given by the argument token for child elements with a type matching the argument name. The tokens for all those elements which match are returned as a Tcl list.

The search only occurs on the immediate children of token, not any descendants.

dom::node method token ?arguments...?
This command implements generic functions for DOM nodes.

The methods accepted by this command are as follows:

dom::node cget token option
This method returns the value of the given configuration option for the node given by token.
dom::node configure token option value
This method sets the value of the given configuration option for the node given by token.

Valid configuration options are as follows:

-nodeName
Returns the node name. This is a read-only option.

The DOM specification gives the meaning of names for different types of nodes. For example, the nodeName option of an element node is the element type.

-nodeType
Returns the type of the node given by token. This is a read-only option.
-parentNode
Returns the parent node of the node given by token. This is a read-only option.
-childNodes
Returns a Tcl variable which contains a list of the children of the node given by token. The variable contains the "live" list of children.

This is a read-only option.

-firstChild
Returns the first child node of the node given by token. This is a read-only option.
-lastChild
Returns the last child node of the node given by token. This is a read-only option.
-previousSibling
Returns the parent's child node which appears before this node. If this child is the first child of its parent then returns an empty string.

This is a read-only option.

-nextSibling
Returns the parent's child node which appears after this node. If this child is the last child of its parent then returns an empty string.

This is a read-only option.

-attributes
Returns a Tcl array variable which contains the attribute list for an element node. If the node is not an element type node then returns an empty string.

The indices of the array are attribute names, and the values of the array elements are their corresponding attribute values.

This is a read-only option.

-nodeValue data
Specifies the value of a node.

The DOM specification gives the meaning of values for different types of nodes. For example, the nodeValue option of a textNode node is the node's text.

dom::node insertBefore token newchild ?refchild?
This method removes the node given by newchild from its parent. If no refchild argument is given then newchild is appended to token's list of children.

If the refchild argument is given then this method adds newchild as a child of token. The new child node is positioned before the node refchild in token's list of children.

Returns an empty string.

dom::node replaceChild token newchild oldchild
This method removes the node given by newchild from its parent. It then also removes the node given by oldchild from token. newchild is then added as a child of token in oldchild's original position in the list of children.

The method returns the token oldchild, which will now have no parent.

dom::node removeChild token oldchild
This method removes the node given by oldchild from token.

The method returns the token oldchild, which will now have no parent.

dom::node appendChild token newchild
This method appends the node given by oldchild to the end of the list of children for node token.
dom::node hasChildNodes token
Returns "1" if the given node has any child nodes, "0" otherwise.
dom::node cloneNode token ?deep?
This method makes a copy the node given by token. If the argument deep is not specified or has the value "0" then only the node itself is copied, not its children. If the argument deep has the value "1" then token's children are also copied recursively.

This method returns the token of the newly created node. This new node will have no parent.

dom::node children token
This is a convenience method which returns the list of child nodes for the given node.

This is not a standard DOM method for this interface

dom::node parent token
This is a convenience method which returns the parent node for the given node.

This is not a standard DOM method for this interface

dom::element method token ?arguments...?
This command provides functions for element type nodes.

Valid methods for this command are as follows:

dom::element cget token option
This method returns the current setting of configuration options for an element. See the configure method for the list of valid configuration options.
dom::element configure token option value
This method sets configuration options for an element. Note that element type nodes only have read-only options.

Valid configuration options are as follows:

-tagName name
The tag name, or element type, of this element.
-empty boolean
Sets whether this element was specified as an empty element when the document was parsed. That is, XML empty element syntax such as <Empty/> was used.

This option has no effect upon output (serialization) of the XML document. Empty element syntax is automatically used where appropriate.

dom::element getAttribute token name
This method returns the attribute value of the attribute given by name. If the attribute does not exist, then an empty string is returned.
dom::element setAttribute token name value
This method sets the attribute value for the attribute given by name. If the attribute already exists then its value is replaced, otherwise the attribute is created.
dom::element removeAttribute token name
This method deletes the attribute given by name. If the attribute does not exist then the method has no effect.
dom::element getAttributeNode token name
dom::element setAttributeNode token name
dom::element removeAttributeNode token name
Interfaces to attributeNodes are not implemented.
dom::element getElementsByTagName token name
This method searches the node given by the argument token for child elements with a type matching the argument name. The tokens for all those elements which match are returned as a Tcl list.

The search only occurs on the immediate children of token, not any descendants.

dom::element normalize token
This method recursively coalesces textNodes within the children of the given node. textNodes which are adjacent in the DOM tree cannot be distinguished in the serialized XML document.
dom::processinginstruction method token ?arguments...?
This command provides functions for processingInstruction type nodes.

Valid methods for this command are as follows:

dom::processinginstruction cget token option
This method returns the current setting of configuration options for a processing instruction.
dom::processinginstruction configure token option value
This method sets the configuration options for a processing instruction.

Valid configuration options are as follows:

-target name
This option sets the target of the processing instruction.

This is a read-only configuration option.

-data string
This option sets the data of the processing instruction.

Copyright © 1998,1999 Zveno Pty Ltd. All Rights Reserved.
Comments on this site? Contact mailto:webmaster@zveno.com


SOAP 1.6 Package for Tcl 8.3

SourceForge Logo

Tcl SOAP Client Utility Packages

 TclSOAP Logo
Sections
Introduction
Commands
CGI Server
Implementation
Downloading
DOM packages
TclHTTPd SOAP
TclHTTPd XMLRPC
Project
Project Page
File Releases
WebPage
Documentation
Forums
Browse CVS
Interop
Round 1 Tests
Round 2 Base
Round 2B
Round 2C
Support
Bugs
Support Requests
Patches
Feature Requests

Contents

  1. Introduction to TclSOAP
  2. SOAP Package Commands
  3. CGI Server Package
  4. TclHTTPD SOAP Server Utilities
  5. TclHTTPD XML-RPC Server Utilities
  6. Download Information
  7. TclDOM Packages for TclSOAP

Introduction

I have been testing out using SOAP from Tcl and have come up with the following package to provide Tcl commands for SOAP remote procedure calls. The following code demonstrates the ease of use for simple RPC calls. This is a work in progress and some parts need more work. In particular the transport layer needs to be able to be configured to cope with proxy HTTP servers and authenticating proxys and the like. Still it may be usefull as-is.

This example connects the Tcl procedure getTemp to the remote method hosted by XMethods. In all these examples Tcl commands are prefixed with the % character that is my prompt under tclsh. Results are printed without the preceeding prompt character.

% package require SOAP
1.6
% SOAP::create getTemp \
    -uri "urn:xmethods-Temperature" \
    -proxy "http://services.xmethods.net/soap/servlet/rpcrouter" \
    -params { "zipcode" "string" }
::getTemp
% getTemp 90810
41.2
We bring in the package and then define the method. The configuration requires a URI for the XML namespace of the SOAP method and a URL for the service. The params configure option allows the Tcl procedure to do simple parameter checking without passing duff packets over the network.

Another example, this time using the extremely clever SOAP::Lite Perl package as a server, a Celcius to Fahrenheit convertor. We shall test it using that peculiar temperature -40. This time I want the Tcl procedure to be called C2F.

% package require SOAP
1.6
% SOAP::create C2F \
    -uri "http://www.soaplite.com/Temperatures" \
    -proxy "http://services.soaplite.com/temper.cgi" \
    -params { "temp" "float"}\
    -name c2f
::C2F
% C2F -40.0
-40
%

It will be possible to use different transport protocols to transfer the SOAP packets. At this time only HTTP is supported. You may need to configure the transport subsystem so the SOAP::configure command has a -transport option. For example, at work I live behind a Microsoft NT firewalling proxy web server. So I need to tell the SOAP transport about the proxy. This is an authenticating proxy, so I have to add a header to all HTTP requests using the Proxy-Authorization HTTP field. Here's how I set up my system and then create a command for the SOAP::Lite languages method.

% package require SOAP
1.6
% SOAP::configure -transport http -proxy proxyhost:8080 \
    -headers { "Proxy-Authorization" "Basic dXNlcm5hbWUgOiBwYXNzd29yZA==" }
% SOAP::create languages \
    -uri "http://www.soaplite.com/Demo" \
    -proxy "http://services.soaplite.com/hibye.cgi" \
    -params {}
::languages
% languages
Perl sh C
%

To setup a method to use a different transport there is a -transport option for the method configure command. This should be set to the name of a procedure that will be called with the URL of the SOAP service and the XML data of the SOAP request. It should return the reply packet or error. For example, I have a dummy transport procedure that prints the SOAP request and doesn't send it anywhere. To see what is being generated for a method:

# A dummy SOAP transport procedure to examine the SOAP requests generated.

proc SOAP::Transport::print::print {procVarName url soap} {
    puts "$soap"
}

% SOAP::configure languages -transport SOAP::Transport::print::print
::languages
% languages
<?xml version='1.0'?>
<SOAP-ENV:Envelope
    xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
   <ns:languages xmlns:ns="http://www.soaplite.com/Demo" />
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
%
For debugging purposes it can be useful to see the XML that was generated for the SOAP method request at each end. The SOAP::dump command will return the XML for the last transaction using HTTP for a named method.

Using Complex Variable Types

The SOAP protocol specifies a number of variable types in the default encoding style. Most of these are simply mapped into Tcl however the Array and Struct types create a special problem for Tcl users. Given a string such as "The cat sat on the mat" there is no way in Tcl to determine if this is a string of 6 words, a list with 6 elements or the list representation of a three element array. In SOAP terms, these would be a string, an array of strings, or a struct. To properly implement SOAP clients we must provide a method by which the SOAP framework can determine what the parameters should be mapped into. This is achieved by the -params configuration option and the rpcvar package.

The -params option is used the specify both the number of parameters, their names and their types. In SOAP, the names of the parameters is supposed to be more important than their positions. So:

SOAP::create a -params {num double} | Parameter num is a double
SOAP::create a -params {num dateTime} | Parameter num is a SOAP dateTime date.
SOAP::create a -params {nums int()} | nums is an array of integers
SOAP::create a -params {dates dateTime()} | dates is an array of SOAP dateTime values
SOAP::create a -params {anArray array} | anArray is an array of mixed types.
The final version in an untyped array. This can also be specified as ur-type() or any(). In the SOAP 1.1 specification these arrays are set to ur-type[n]

Structs can be handled in a similar fashion. The simplest case of a structure of simple guessable types can be handled by specifying a type of struct. In this case the parameter is expected to be a list of name-value pairs. For more complex types, particularly structs containing structs we need to define a new type. This is done using the typedef procedure from the rpcvar package.

package require rpcvar
namespace import -force rpcvar::typedef

typedef {
   intValue    int
   floatValue  float
   stringValue string
} simpleStruct

SOAP::create a -params {myStruct simpleStruct}

a {intValue 2 stringValue "Hello, World!" floatValue 2.5}

An example using a nested struct type can be found in the samples/soapinterop.tcl file shipped with TclSOAP.

Methods

SOAP::create methodName ?option value ...?

Create a Tcl binding for a remote procedure call using SOAP. See configure for the permitted options.

SOAP::configure -transport protocol ?option value ...?

Used for global configuration of the available transports. The options passed in to this command are dependent on the transport mchanism. The only transports currently available

The HTTP transport may require a proxy server and possible other headers to be included. This is where to add this information. For example, to pass an authenticating proxy server I need to provide the name of the server and a Proxy-Authorize HTTP header using the Trf package to provide the base64 encoding procedure.

SOAP::configure -transport http -proxy wwwproxy:8080 \
       -headers { "Proxy-Authorize" "Basic [base64 -enc user:pass]" }
SOAP::configure methodName ?option value ...?
-uri URI
The URI for the XML namespace in which this method has been defined.
-proxy URL
Specify the URL of the server providing the implementation of this method.
-params list
Configure the parameters required for this method. list should be a list of pairs consisting of the parameter name and the parameter type. The Tcl procedure will check the number of parameters when constructing the SOAP request. e.g.:
SOAP::configure getTemp -params { "zipcode" "string" }
SOAP::configure c2f -params { "temperature" "float" }
SOAP::configure hi -params {}
-transport protocolProc
Select the transport protocol used for this method. protocolProc should be a Tcl command procedure that takes the URL of the SOAP server and the SOAP XML data to be sent. This procedure will send the request and receive the answer.
-name methodName
By default a Tcl command is created in the current namespace with the same name as the SOAP method. If the Tcl procedure is created with a different name then the -name configuration option must be used to set the SOAP method name explicitly.
-action SOAPActionValue
The SOAP 1.1 specification requires SOAP POST requests to have an HTTP SOAPAction header. This may have an empty value if not required (which is the default) or it may be required to be set to a specific value to pass though firewalls.
-wrapProc procedureName
Set the procedure used to wrap up the method parameters for transport to the server. This procedure takes the SOAP methodName followed by all the parameters required for the method call and returns the generated XML data for the RPC call. By default for SOAP requests this is set to SOAP::soap_request and for XML-RPC methods to SOAP::xmlrpc_request. This option is only likely to be used if you are implementing a new RPC protocol.
-replyProc procedureName
A hook procedure can be defined to be called once the response packet has been received but before the XML is parsed. Provided the server returned an HTTP 200 response then this procedure is guarunteed to be called even if the reply contains an error response. The procedure is called with two parameters, the first being the SOAP method name and the second being the XML text of the reply. The hook procedure should return the new XML text suitable for processing by the -parseProc procedure. For example:
proc my_reply_hook { methodName xml } {
   puts "$xml"
   return $xml
}
-parseProc procedureName
Specify the procedure used to parse the XML of the reply and to extract the result value. The default depends upon the setting of the -xmlrpc configuration option and is either SOAP::parse_soap_response or SOAP::parse_xmlrpc_response. The procedure takes two parameters as for the -replyProc option but should return the result value from the XML packet.
-postProc procedureName
An optional hook procedure may be specified here that will be called once the result value has been obtained from the XML packet. This procedure will take two parameters, the first is the SOAP method name and the second the result value extracted from the XML. The procedure should return the new result value. By default no procedure is defined.
-command callback
Provide support for asynchronous methods. This option causes the SOAP method invocation to return immediately and the callback procedure is called once the round trip finally completes. The procedure will be called with an additional argument that is the data returned by the remote method. The callback procedure must exist before the SOAP method is configured as the procedure name is namespace qualified during configuration.
   proc gotInfo {window data} { ... }
   SOAP::configure getInfo -command {gotInfo .frame1.edit} ...

SOAP::cget methodName option

Retrieve a configuration value from the method. The optionName should be one of those listed for configure. There is one additional read-only value to be obtained:

http
retrieve the handle for the last HTTP request. This is only set if the transport in use is HTTP. You can examine the HTTP data using procedures from the http package. i.e.:
puts "[::http::data [SOAP::cget getTemp http]]"
or
set r [::http::code [SOAP::cget getTemp http]]

SOAP::dump option methodName

Returns information about the last HTTP transaction.

-reply
returns the XML text of the servers reply
-request
returns the XML text that was sent to the server
-meta
returns the HTTP protocol meta information

SOAP::invoke methodName methodParameters

Make a SOAP call to the configured server. This is not expected to be called by a user but is called by the Tcl command procedure for this SOAP method.

SOAP::proxyconfig

This command presents a dialog box used to configure the SOAP package to work with a proxy server. The fields are used to call SOAP::configure -transport http with the relevant options. The first entry field takes the name and port of the proxy server (eg: webproxy:8080) and the second two fields are used to configure a Basic Authentication HTTP header to allow operation with an authenticating proxy. (such as a Windows NT IIS server).

Download

The package can be downloaded from the SourceForge project site . This file should be unpacked somewhere handy and you should set your TCLLIBPATH environment variable to suit. For windows users, you may as well unpack it to X:\Program Files\Tcl\lib\

You can also obtain the source via anonymous CVS or browse the CVS repository. You might also find recent news and update information on the TclSOAP project page. This is also the place to report bugs, submit patches and discuss any issues.

$Id: TclSOAP.html,v 1.20 2001/10/11 22:40:37 patthoyts Exp $


Snack Manual

Snack v2.1.3 manual

Last updated
snack::audio
snack::debug
snack::filter
snack::mixer
snack::sound
spectrogram canvas item
spectrum section canvas item
waveform canvas item
Standard extension packages (sound, snackogg, snacksphere)
Snack library

NAME

snack::audio - Get/set properties of audio devices

SYNOPSIS

snack::audio property ?arg? ...

DESCRIPTION

The audio command is used to get properties of audio devices such as supported sample encoding formats and sample rates.

snack::audio encodings

    Returns a list of supported sample encoding formats for the current selected device.
snack::audio rates
    Returns a list of supported sample rates for the current selected device.
snack::audio inputDevices
Returns a list of available audio input devices.
snack::audio playLatency
Sets/queries (in ms) how much sound will be queued up at any time to the audio device for playback. A low value makes new sound samples reach the loudspeakers quickly at the risk of gaps in the output stream. An appropriate value should be chosen with regard to processor speed and load. The default value has been choosen to give adequate performance for a mix of tasks and might be to low for simple playback in some cases. If spurious gaps in the playback stream occur, try using a latency of a couple of thousand milliseconds. On UNIX systems, the environment variable PLAYLATENCY can also be used to control this property.
snack::audio pause
    Toggles between pause/play for all playback on the audio device.
snack::audio play
    Resumes paused playback on the audio device.
snack::audio play_gain ?value?
    Returns the current play gain value if invoked without a parameter. If a an integer value is given play gain is set to the given value. Valid values are in the range 0-100.
snack::audio outputDevices
Returns a list of available audio output devices.
snack::audio record_gain ?value?
    Returns the current record gain value if invoked without a parameter. If a an integer value is given record gain is set to the given value. Valid values are in the range 0-100.
snack::audio selectOutput ?device?
Selects an audio output device to be used as default.
snack::audio scaling ?factor?
Scale the global output stream by multiplying with factor. Useful to prevent clipping when playing many simultaneous sounds. If no value is specified the current factor is returned, default is 1.0.
snack::audio selectInput ?device?
Selects an audio input device to be used as default.
snack::audio stop
    Stops all playback on the audio device.

NAME

snack::debug - Control Snack debugging facilities

SYNOPSIS

snack::debug level ?logFile? ?audioDumpFile?

DESCRIPTION

The debug command is used to control the debugging facilities of Snack. The level flag is an integer (1-5) specifying the detail level of the generated debug log. Level 1 just prints entry/exit points of sound commands during execution. An optional second filename argument can be given to specify a file where the log will be written. An optional third filename can be given to specify a file where a raw dump of all audio being played through the audio device is to be generated. The sound file will be created in RAW (headerless) format. Note that debugging has to be turned on for each individual sound object of interest. Reports on bugs/problems with Snack should typically include a minimal script that shows the problem, any associated sound files, and a debug log in order to facilitate a quick solution.

NAME

snack::filter - Create and manipulate filters

SYNOPSIS

snack::filter type ?arg? ...

filterName option ?arg arg ...?

DESCRIPTION

The filter command is used to create filter objects. These can interact with sound objects either using the sound filter command or during playback. Note that since a filter object may contain state information about a sound stream it should only be used for one play operation at a time.

FILTER COMMAND

When a filter object is created, Snack returns the name of a newly created object command. This command may be used to invoke various operations on the filter.

filterCmd configure ?arg ...?

Configures the filter command, see the filter types for their respective options.
filterCmd destroy
Removes the filter command and frees the storage associated with it. If the filter is currently used for playback an unfiltered stream will be output as soon as the internal buffer has been played.

FILTERS TYPES

Current filter types.

compose filter filter ...

Creates a new filter which is a linear combination of two or more other filters. The output of the first is fed into the input of the next and so on.
echo inGain outGain delay decay ?delay decay ...?
Creates an echo effect. inGain is a multiplicative factor applied on the input stream. outGain is applied on the output. Both factors should be between 0.0 and 1.0. For each echo a delay/decay pair should be specified. The delay is specified in milliseconds and decay is a factor relative to inGain.
formant frequency bandwidth
A formant filter with given frequency and bandwidth.
generator frequency ?amplitude? ?shape? ?type? ?ntot?
A signal generator with given frequency and amplitude. shape is a value between 0.0 and 1.0 used to influence the shape of the signal. type can be any of rectangle, triangle, sine, noise, or sampled. In the case of sampled the generator will repeatedly get data from the sound it is applied on. ntot specifies how many samples to generate. The default, -1, will generate forever.
iir ?-denominator list? ?-dither value? ?-impulse list? ?-noise value? ?-numerator list?
Creates an IIR or FIR filter. For FIR filters the coefficients are given as a list using the -impulse option. For IIR filters the coefficients are given as lists using the options -numerator and -denominator. The option -dither specifies the amount of triangular dithering to add to the output. The option -noise specifies the amount of additive gaussian noise to add to the output.
map val ?val val val ...?
Applies a linear transformation on each sample frame. For one channel sounds this is simply a multiplication. For multi-channel sounds, a transformation matrix can be specified with values row by row. One column per channel is needed. If mono output is used, only one row needs to be specified. If stereo output is used, only two rows needs to be specified. If only one value is specified and the filter is used for multi-channel data, each channel is multiplied with the given value.
reverb outGain time delay ?delay ...?
A reverb effect. outGain is a value between 0.0 and 1.0. time and delay are given in milliseconds.

BUGS

This command is under development.

NAME

snack::mixer - Get/set properties of mixer devices

SYNOPSIS

snack::mixer property ?arg? ...

DESCRIPTION

The mixer command is used to get and set properties of mixer devices such as current input/output jack, supported ports, mixer lines, and gain.

snack::mixer channels line

    Returns a list with the names of the channels for the specified line.
snack::mixer devices
Returns a list of available mixer devices.
snack::mixer input ?jack? ?varName?
    Gets/sets the current input jack. Optionally link a boolean Tcl variable.
snack::mixer inputs
    Returns a list of available input ports.
snack::mixer lines
    Returns a list with the names of the lines of the mixer device.
snack::mixer output ?jack? ?varName?
    Gets/sets the current output jack. Optionally link a boolean Tcl variable.
snack::mixer outputs
    Returns a list of available output ports.
snack::mixer update
    Updates all linked variables to reflect the status of the mixer device.
snack::mixer volume line ?varName? ?varName?
    Return the current volume setting for mixer. Optionally link a Tcl variable to the value. If two variable names are specified they are used for the left and right channels respectively.
snack::mixer select ?device?
Selects a mixer device to be used as default.

NAME
snack::sound - Create and manipulate sounds
SYNOPSIS
snack::sound ?name? ?options?
DESCRIPTION
CREATING SOUNDS
snack::sound ?name? ?-load filename? ?-file filename? ?-channel channelname? ?-rate f? ?-channels n? ?-encoding fmt? ?-fileformat fmt? ?-skiphead n? ?-byteorder endianess? ?-guessproperties boolean? ?-buffersize n? ?-precision prec? -changecommand procedure? ?-debug level?
SOUND COMMAND
soundName append variable ?-rate f? ?-channels n? ?-encoding fmt? ?-skiphead n? ?-byteorder endianess? ?-start start? ?-end end? ?-guessproperties boolean?
soundName cget option
soundName changed flag
soundName concatenate sound
soundName configure option value ...
soundName convert option value
soundName copy sound ?-start start? ?-end end?
soundName cut sound start end
soundName crop start end
soundName data variable ?-rate f? ?-channels n? ?-encoding fmt? ?-skiphead n? ?-byteorder endianess? ?-start start? ?-end end? ?-guessproperties boolean?
soundName data ?-start start? ?-end end? ?-fileformat fileformat? ?-byteorder endianess?
soundName destroy
soundName dBPowerSpectrum ?-start sample? ?-end sample? ?-skip samples? ?-fftlength length? ?-windowlength length? ?-channel channel? ?-preemphasisfactor factor? ?-windowtype type? ?-analysistype type? ?-lpcorder n?
soundName filter filterName ?-start sample? ?-end sample? ?-continedrain boolean? ?-progress procedure?
soundName flush
soundName info
soundName insert sound position ?-start start? ?-end end?
soundName length ?n? ?-unit u?
soundName max ?-start start? ?-end end? ?-channel channel?
soundName min ?-start start? ?-end end? ?-channel channel?
soundName pause
soundName pitch ?-start start? ?-end end? ?-maxpitch val? ?-minpitch val? ?-progress callback?
soundName play ?-start start? ?-end end? ?-output jack? ?-blocking boolean? -command ?callback? ?-device outputDevice? ?-devicerate rate? ?-devicechannels channels?
soundName power ?-start sample? ?-end sample? ?-framelength length? ?-windowlength length? ?-windowtype type? ?-preemphasisfactor factor? ?-channel channel? ?-progress callback?
soundName read filename ?-rate f? ?-channels n? ?-encoding fmt? ?-skiphead n? ?-byteorder endianess??-start start? ?-end end? ?-guessproperties boolea n? ?-progress procedure?
soundName record ?-input jack? ?-append boolean? ?-device inputDevice?
soundName reverse ?-start start? ?-end end? ?-progress procedure?
soundName sample n ?value? ...
soundName stop
soundName write filename ?-start start? ?-end end? ?-fileformat fileformat? ?-progress procedure? -byteorder ?endianess?

NAME

snack::sound - Create and manipulate sounds

SYNOPSIS

snack::sound soundName

soundName option ?arg arg ...?

DESCRIPTION

The snack::sound command is used to create sound objects. Sound objects can interact with files, variables, canvas items and the audio hardware.

CREATING SOUNDS

The sound command is used to create sound objects. It can take several different forms, depending on the option argument. The legal forms are:

snack::sound ?soundName? ?-load filename? ?-file filename? ?-channel channelname? ?-rate f? ?-channels n? ?-encoding fmt? ?-fileformat fmt? ?-skiphead n? ?-byteorder endianess? ?-guessproperties boolean? ?-buffersize n? ?-precision prec? ?-changecommand procedure? ?-debug level?

soundName specifies the name of the sound. If it is omitted then Snack picks a name of the form soundn, where n is an integer. The -load option specifies that the file filename should be read into memory after creating the sound. The -file option specifies an on-disk file which should be linked to the sound. The -channel option specifies that audio data resides on a channel which should be linked to the sound. In these cases the audio data is not loaded into memory, which is useful when playing large files or when using streaming audio. A value of 1 or larger must be specified for the -channels option (Mono, or Stereo are also valid). If not specified a default value of 1 is assumed. Possible values for sample encoding format, given using the -encoding option, are Lin16, Lin8offset, Lin8, Lin24, Lin32, Float, Alaw, or Mulaw. Default encoding is Lin16. The option -rate can take any positive value but usually only sample rates supported by the audio hardware are useful. Note that the default value is 16000, a common value for speech related applications, but less frequent for other uses, such as music. -fileformat works as for the read command. -skiphead is used to skip an unknown file header of size n bytes. Byte order can be specified as littleEndian or bigEndian using the -byteorder option. The option -guessproperties is used to specify that Snack should try to infer properties, such as byte order, sample encoding format, and sample rate for a raw file by analyzing the contents of the file. Byte order is almost always detected correctly. For channel based sounds the -buffersize option can be used to specify the size of the internal buffer in samples. The option -precision is used to specify if sound data is to be handled using simple or double precision internally. -changecommand is used to specify a procedure which is to be called every time a property of the sound is changed. This is the Tcl level counterpart of Snack_AddCallback(). The procedure should expect one argument, one of the strings New, More, or Destroy. This feature is particularly useful when embedding sound objects in other higher level constructs. The flag -debug is used to control debug output for operations on the sound object. The option takes a level argument, an integer in the range 1-5, specifying the detail of the trace information.

SOUND COMMAND
When a sound object is created, Snack also creates a new object command whose name is the same as the sound. This command is used to invoke various operations (or sub-commands) on the sound. This is the current set:

soundName append variable ?-rate f? ?-channels n? ?-encoding fmt? ?-skiphead n? ?-byteorder endianess? ?-start start? ?-end end? ?-fileformat fmt? ?-guessproperties boolean?

    Appends binary string data to the end of soundName. The same options apply as for the read command. This command applies to in-memory sounds only.
soundName cget option
    The cget command retrieves the current value of an option for a sound. Option can be any of the following: -load, -file, -channel, -rate, -channels, -encoding, -skiphead, -byteorder, -guessproperties, -precision, and -buffersize. See the sound command for more information on these.
soundName changed flag
    This command is used to inform Snack that the sound object has been modified. Normally Snack tracks changes to sound objects automatically, but in a few cases this must be performed explicitly. For example, setting of samples using the sample command is not tracked for preformance reasons. Here a changed command might be necessary. flag can be either New or More. New is used for any type of change while More only applies to the case where more samples has been appended.
soundName concatenate sound
    Concatenates the sample data from sound to the end of soundName. The sound to be added must be of the same type as the base sound, i.e. have the same sample rate, sample encoding format, and number of channels). Note that even an initially empty sound has these properties defined. This command applies to in-memory sounds only.
soundName configure option value ...
    The configure command is used to set options for a sound. Options can be any of the following: -load, -file, -channel, -rate, -channels, -encoding, -skiphead, -byteorder, -guessproperties, -precision, -debug and -buffersize. See the sound command for more information on these.
soundName convert option value ...
    The convert command is used to convert a sound to a different sample encoding, sample rate, or number of channels. Options can be any of the following: -rate, -channels, -encoding, and -progress. A value of 1 or larger must be specified for the -channels option (Mono, or Stereo are also valid). Only conversions from many channels to one or the reverse are possible. Values for sample encoding format are Lin16, Lin8offset, Lin8, Lin24, Lin32, Float, Alaw, or Mulaw. The current sample rate conversion algorithm is simple and may not be suitable for all needs. See the read command for a description on how to use the -progress option. This command applies to in-memory sounds only.
soundName copy sound ?-start start? ?-end end?
    Copies sample data from sound. Optionally a range of samples to copy can be specified. Any active play operation is stopped before the command is executed if the format of the new sound differs from the current. This command applies to in-memory sounds only.
soundName crop start end
    Crops the sound to the given range [start end], i.e. all samples before and after these limits will be removed. This command applies to in-memory sounds only.
soundName cut start end
    Cuts the given range [start end] from the sound, i.e. all samples between and including these limits will be removed. This command applies to in-memory sounds only.
soundName data ?variable? ?option value? ...
    Loads sound data from, or writes to, a binary string.

    When loading data the same options apply as for the read command:

    soundName data variable ?-rate f? ?-channels n? ?-encoding fmt? ?-skiphead n? ?-byteorder endianess? ?-start start? ?-end end??-fileformat fmt? ?-guessproperties boolean?

    The command returns the file format detected. Any active play operation is stopped before data is loaded.

    When writing data to a binary string -start and -end options can be given (as for the write command). Also, a -fileformat option can be given if the file format should be different from the original. In the case of RAW file format the endianess can be specified as either bigEndian or littleEndian.

    soundName data ?-start start? ?-end end? ?-fileformat fileformat? -byteorder ?endianess?

    This command applies to in-memory sounds only.

soundName destroy
    Removes the sound command and frees the storage associated with it.
soundName dBPowerSpectrum ?-start sample? ?-end sample? ?-fftlength length? ?-windowlength length? ?-windowtype type? ?-skip samples? ?-channel channel? ?-preemphasisfactor factor? ?-analysistype type? ?-lpcorder n?
    Computes the log FFT power spectrum of the sound at -start and returns a list of dB values. See the section item for the rest of the options. Optionally an ending point can be given, using -end. In this case the result is the average of consecutive FFT's in the specified range. Their default spacing is taken from -fftlength but this can be changed using the -skip option which specifies how many points to move the FFT window forward at each step.
soundName filter filterName ?-start sample? ?-end sample? ?-continuedrain boolean? ?-progress procedure?
    Applies the filter filterName to the sound. Optionally, a range to apply the filter on can be specified. The -continuedrain option specifies whether the filter should be allowed to drain out past the end point. See the read command for a description on how to use the -progress option. This command applies to in-memory sounds only.
soundName flush
    Removes all audio data from the sound. This command applies to in-memory sounds only.
soundName info
    Returns a list with information about the sound. The entries are {length rate "maximum sample" "minimum sample" "sample encoding" "number of channels" "file format" "header size in bytes"}
soundName insert sound position ?-start start? ?-end end?
    Inserts sound at position. Optionally a range of samples to insert can be specified. This command applies to in-memory sounds only.
soundName length ?n? ?-unit u?
    Gets or sets the length of the sound in number of samples (default), or seconds, by setting u to either SAMPLES or SECONDS. If the new length is larger than the current the sound is padded with additional silence.
soundName max ?-start start? ?-end end? ?-channel channel?
    Returns the largest positive sample value of the sound. A range of samples and a channel to be examined can be specified. The default is to check all channels and return the maximum value.
soundName min ?-start start? ?-end end? ?-channel channel?
    Returns the largest negative sample value of the sound. A range of samples and a channel to be examined can be specified. The default is to check all channels and return the minimum value.
soundName pause
    Pause current play/record operation. Next pause invocation resumes play/record. If several play operations for one sound object are in progress all of them are paused using pause.
soundName pitch ?-start start? ?-endend? ?-maxpitch val? ?-minpitch val? ?-progress procedure?
    Returns a list of pitch values computed using the AMDF method. The values are spaced at 10ms intervals. A range of samples can be given using -start and -end. If a frequency range of valid pitch values is known this can be specified using the options -maxpitch and -minpitch. See the read command for a description on how to use the -progress option.
soundName play ?-start start? ?-end end? ?-output jack??-blocking boolean? ?-command callback? ?-device outputDevice? ?-filter filter? ?-devicerate f? ?-devicechannels n?
    Plays a sound. A range of samples to play can be specified using the -start and -end options. The -output option is used to specify any of the possible output ports returned by the audio outputs command. The -blocking option is used to specify whether playback should be asynchronous or not, i.e. if it is to be played in the background or if the play command should return only after the sound has been played. Asynchronous playback from tclsh is only possible if the event loop is running, using for example vwait. The -command option specifies a command to be executed when the end of the sound is reached. The -device option selects which audio output device to use. The -filter option is used to specify a filter which is to be applied during output. The audio device can be opened with different properties from those of the sound object using -devicerate and -devicechannels, which might be useful in some rare cases. The option -starttime is used to schedule the start of playback (in ms) relative to a previous play operation. All options are ignored if play is used to resume a paused play operation. If a play command is issued while another one is in progress, the latter one is queued up and starts to play as soon as possible. The lag before this new sound is audible can be controlled using the snack::audio latency command.
soundName power ?-start sample? ?-end sample? ?-framelength length? ?-windowlength length? ?-windowtype type? ?-preemphasisfactor factor? ?-channel channel? ?-progress callback?
    Returns a list of windowed log power values. The -framelength option specifies the intervals between the values. The option -windowtype is used to select windowing function, (valid values are Hamming, Hanning, Bartlett, Blackman, or Rectangle). -windowlength specifies the size of the window in points. -preemphasisfactor is used to specify the amount of preemphasis applied to the signal prior to windowing. A range of samples can be given using -start and -end. See the read command for a description on how to use the -progress option and the section item for the -channel option.
soundName read filename ?-fileformat fmt? ?-rate f? ?-channels n? ?-encoding fmt? ?-skiphead n? ?-byteorder endianess? ?-start start? ?-end end? ?-guessproperties boolean? ?-progress procedure?
    Reads new sound data from a file. Current supported file formats are WAV, MP3, AU, SND, AIFF, SD, SMP, CSL, and RAW binary. The command returns the file format detected. It is possible to force a file to be read as RAW using "-fileformat RAW". In this case the properties of the sound data should be specified by hand. -rate and -channels are used to set the sampling rate and the number of channels (Mono/Stereo). The -encoding option is used to specify sample encoding format. Currently, the formats Lin16, Lin8offset, Lin8, Lin24, Lin32, Float, Alaw, and Mulaw are supported. -skiphead is used to skip an unknown header of size n bytes, and -byteorder is used to specify endianess (bigEndian/littleEndian). The option -guessproperties is used to specify that Snack should try to infer properties, such as byte order, sample encoding format, and sample rate for raw files by analyzing the contents of the file. Byte order is almost always detected correctly. It is possible to add a progress callback procedure which is to be called at regular intervals using the -progress option. This procedure is called with two arguments, first the string "Read sound" and then a double value specifying the fraction of the command that currently has been completed. If the callback returns with an error code (return -code error) the read operation is cancelled. The convenience routine snack::progressCallback opens up a message box with an appropriate message if used as argument procedure to this option. Any active play operation is stopped before the command is executed, if the format of the new sound data differs from the current. This command applies to in-memory sounds only.
soundName record ?option value? ...
    Starts recording data from the audio device into the sound object. For in-memory sound objects the command has the following form:

    soundName record ?-input jack? ?-append boolean? ?-device inputDevice?

    The -input option specifies one of the available input ports returned by the audio inputs command. -append specifies that new audio data should be appended at the end of the existing sound instead of replacing it. The -device option selects which audio input device to use.

    File and channel based sounds have the options:

    soundName record ?-input jack? ?-fileformat fmt? ?-device inputDevice?

    The -fileformat option can be used to specify the file format to be used when writing data to a channel. In this case there is no file name to infer the format from.

soundName reverse ?-start start? ?-end end? ?-progress procedure?
    Reverses a sound. Optionally a range of samples to be reversed can be specified. See the read command for a description on how to use the -progress option. This command applies to in-memory sounds only.
soundName sample n ?value? ...
    Gets or sets sample number n. When setting samples one value should be specified for each channel. A ? character can be used to specify that a certain value should not be affected, i. e. "snd sample 10000 ? 999", would set the right channel of sample number 10000 of sound snd to the value of 999 without influencing the left channel. Samples can be read for all sound types but can only be set for in-memory sounds.
soundName stop
    Stops current play or record operation. If there is a queue of sounds to play, each of them can stop playback using stop. Any callbacks registered using the -command option of the play command will not be executed.
soundName write filename ?-start start? ?-end end? ?-fileformat fileformat? ?-byteorder endianess? ?-progress procedure?
    Writes sound data to a file. A range of samples to save can be specified using the -start and -end options. The file format is inferred from the filename extension. Currently, the supported formats are WAV, AU, SND, AIFF, SMP, CSL, and RAW. The -fileformat option overrides the guess from file name extension. If you specify RAW file format the sound will be saved to file without a header using the natural byte order of the machine. This can be overridden using the option -byteorder. See the read command for a description on how to use the -progress option.

NAME

spectrogram - Spectrogram canvas item

SYNOPSIS

pathName create spectrogram x y ?options value option value ...?

OPTIONS

-anchor anchorPos
-brightness value
-channel channel
-colormap colorlist
-contrast value
-debug level
-end sample
-fftlength length
-gridcolor color
-gridfspacing value
-gridtspacing value
-height size
-pixelspersecond value
-preemphasisfactor factor
-sound name
-start sample
-tags tagList
-topfrequency frequency
-width size
-windowtype type
-winlength length

DESCRIPTION

This command draws a spectrogram of a sound on a canvas. The options -anchor, and -tags work as for ordinary Tk canvas items. -sound specifies which sound object to link to and -height the height of the spectrogram. The option -fftlength specifies the number of FFT points (8, 16, 32, 64, 128, 256, 512, 1024, 2048, or 4096). The option -windowtype is used to select windowing function, (valid values are Hamming, Hanning, Bartlett, Blackman, or Rectangle). -winlength specifies the size of the hamming window, which should be equal to or less than the number of FFT points. -preemphasisfactor is used to specify the amount of preemphasis applied to the signal prior to the FFT calculation. -start and -end controls which part of the sound to display. -pixelspersecond determines the scaling factor in the x-direction. The -width option specifies the width of the spectrogram. If both -width and -pixelspersecond are specified the spectrogram will be cut at one end depending on if a -start or -end option was also given. Currently, spectrograms have a width limit of 32767 pixels. Use the -channel option to select which channel to show for multichannel sounds. Use left, right, both, all, -1 (all) or a channel number counting from 0 (left). The default is to show all, i.e. to add all channels. -brightness and -contrast takes values beteween -100.0 and 100.0 with the default being 0.0. -topfrequency is the frequency value at the top of the spectrogram, default is the Nyquist frequency. -gridtspacing is the spacing between markers in seconds (default 0 means no grid) and -gridfspacing is the frequency spacing in Hz (default 0 means no grid). -gridcolor specifies the color of the grid. A colormap for the spectrogram is given with the -colormap option. It takes a list of colors as parameter and at least two must be specified. The first color is used for the lowest intensity in the spectrogram. An empty list gives the default 32-level grey scale. The flag -debug is used to control debug output for the item. The option takes a level argument, an integer in the range 1-5, specifying the detail of the trace information.
See also the code examples in the widget demonstration.

NAME

section - Spectrum section canvas item

SYNOPSIS

pathName create section x y ?options value option value ...?

OPTIONS

-anchor anchorPos
-analysistype type
-channel channel
-debug level
-end sample
-fftlength length
-fill color
-frame boolean
-height size
-lpcorder n
-maxvalue value
-minvalue value
-preemphasisfactor factor
-skip points
-sound name
-start sample
-stipple value
-tags tagList
-topfrequency frequency
-width size
-windowtype type
-winlength length

DESCRIPTION

This command draws an FFT log power spectrum section of a sound on a canvas. The options -anchor, -fill, -stipple, and -tags work as for ordinary Tk canvas line items. -sound specifies which sound object to link to and -height and -width the height/width of the section. The option -fftlength specifies the number of FFT points (8, 16, 32, 64, 128, 256, 512, 1024, 2048, or 4096). The option -windowtype is used to select windowing function, (valid values are Hamming, Hanning, Bartlett, Blackman, or Rectangle). -analysistype is either FFT or LPC, for LPC analysis the order is specified using -lpcorder (default 20). -winlength specifies the size of the window, which should be equal to or less than the number of FFT points. -preemphasisfactor is used to specify the amount of preemphasis applied to the signal prior to the FFT calculation. -start and -end controls which part of the sound to display. -topfrequency is the frequency value at the right end of the section. -maxvalue and -minvalue specify the range (in dB) which will be shown (default 0.0 to -80.0). Use the -channel option to select which channel to show for multichannel sounds. Use left, right, both, all, -1 (all) or a channel number counting from 0 (left). The default is to show all, i.e. to add all channels. -frame specifies whether a frame will be drawn around the spectrum section. The flag -debug is used to control debug output for the item. The option takes a level argument, an integer in the range 1-5, specifying the detail of the trace information.
See also the code examples in the widget demonstration.

NAME

waveform - Waveform canvas item

SYNOPSIS

pathName create waveform x y ?option value option value ...?

OPTIONS

-anchor anchorPos
-channel channel
-debug level
-end sample
-fill color
-frame boolean
-height size
-limit value
-pixelspersecond value
-progress procedure
-shapefile filename
-sound name
-start sample
-stipple bitmap
-subsample value
-tags tagList
-width size
-zerolevel boolean

DESCRIPTION

This command draws the waveform of a sound on a canvas. The options -anchor, -fill, -stipple, and -tags work as for ordinary Tk canvas line items. -sound specifies which sound object to link to and -height the height of the waveform. The options -start and -end controls which part of the sound to display. -pixelspersecond determines the scaling factor in the x-direction. The -width option specifies the width of the waveform. If both -width and -pixelspersecond are specified the waveform will be cut at one end depending on if a -start or -end option was also given. Use the -channel option to select which channel to show for multichannel sounds. Use left, right, both, all, -1 (all) or a channel number counting from 0. The default is to show all, i.e. to add all channels. Use -limit to specify the maximum shown value for the sound amplitude. -zerolevel specifies whether the zero level will be displayed and -frame whether a frame will be drawn around the waveform. The -subsample option is useful for large sounds to specify how precisely they should be analyzed for shape calculation. The default value 1 uses every sample in the sound to draw the waveform envelope, which can be slow for large sounds. A value of 10 uses every 10th. Care should be used when specifying this because a large value could lead to an incorrect envelope shape. The option -shapefile is used to specify a file for storing/retrieving precomputed waveform shape information. If the file doesn't exist it is created. If it exists it is accessed instead of the sound data itself, thus speeding up on-screen display. There exists two convenience routines, snack::deleteInvalidShapeFile and snack::makeShapeFileDeleteable, which can be used to enclose a create waveform statement when using the shape file functionality. These will make sure that shape files are handled properly, see the demo cool.tcl, for an example of this. See the read command for a description on how to use the -progress option. The flag -debug is used to control debug output for the item. The option takes a level argument, an integer in the range 1-5, specifying the detail of the trace information.
See also code examples in the widget demonstration.

Standard extension packages

The following packages are included in the Snack distribution or can be downloaded separately.

sound

    The sound package gives you the snack::audio, snack::filter, snack::mixer, and snack::sound commands. Basicly the same functions as the snack package except for graphics. This is useful on some systems if you want to use the tclsh interpreter.

snackogg

    The snackogg package adds support for the Ogg/Vorbis compressed sound file format. Ogg format files and streams are detected automatically. Encoding is supported. Simply use the extension .ogg when writing files or use the option -fileformat ogg. When creating Ogg files the additional options -nominalbitrate, -maxbitrate, -minbitrate, and -comment apply.

snacksphere

    The snacksphere package adds support for reading the NIST/Sphere sound file formats. Sphere files are detected automatically.

Snack home


expect

 Table of Contents

Name

expect - programmed dialogue with interactive programs, Version 5

Synopsis

expect [ -dDinN ] [ -c cmds ] [ -[f|b] ] cmdfile ] [ args ]

Introduction

Expect is a program that «talks» to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be. An interpreted language provides branching and high-level control structures to direct the dialogue. In addition, the user can take control and interact directly when desired, afterward returning control to the script.

Expectk is a mixture of Expect and Tk. It behaves just like Expect and Tk's wish. Expect can also be used directly in C or C++ (that is, without Tcl). See libexpect(3) .

The name «Expect» comes from the idea of send/expect sequences popularized by uucp, kermit and other modem control programs. However unlike uucp, Expect is generalized so that it can be run as a user-level command with any program and task in mind. Expect can actually talk to several programs at the same time.

For example, here are some things Expect can do:

· Cause your computer to dial you back, so that
you can login without paying for the call.
· Start a game (e.g., rogue) and if the optimal
configuration doesn't appear, restart it (again and again) until it does, then hand over control to you.
· Run fsck, and in response to its questions,
answer «yes", «no» or give control back to you, based on predetermined criteria.
· Connect to another network or BBS (e.g., MCI
Mail, CompuServe) and automatically retrieve your mail so that it appears as if it was originally sent to your local system.
· Carry environment variables, current directory,
or any kind of information across rlogin, telnet, tip, su, chgrp, etc.

There are a variety of reasons why the shell cannot perform these tasks. (Try, you'll see.) All are possible with Expect.

In general, Expect is useful for running any program which requires interaction between the program and the user. All that is necessary is that the interaction can be characterized programmatically. Expect can also give the user back control (without halting the program being controlled) if desired. Similarly, the user can return control to the script at any time.

Usage

Expect reads cmdfile for a list of commands to execute. Expect may also be invoked implicitly on systems which support the #! notation by marking the script executable, and making the first line in your script:

#!/usr/local/bin/expect -f

Of course, the path must accurately describe where Expect lives. /usr/local/bin is just an example.

The -c flag prefaces a command to be executed before any in the script. The command should be quoted to prevent being broken up by the shell. This option may be used multiple times. Multiple commands may be executed with a single -c by separating them with semicolons. Commands are executed in the order they appear. (When using Expectk, this option is specified as -command.)

The -d flag enables some diagnostic output, which primarily reports internal activity of commands such as expect and interact. This flag has the same effect as «exp_internal 1» at the beginning of an Expect script, plus the version of Expect is printed. (The strace command is useful for tracing statements, and the trace command is useful for tracing variable assignments.) (When using Expectk, this option is specified as -diag.)

The -D flag enables an interactive debugger. An integer value should follow. The debugger will take control before the next Tcl procedure if the value is non-zero or if a ^C is pressed (or a breakpoint is hit, or other appropriate debugger command appears in the script). See the README file or SEE ALSO (below) for more information on the debugger. (When using Expectk, this option is specified as -Debug.)

The -f flag prefaces a file from which to read commands from. The flag itself is optional as it is only useful when using the #! notation (see above), so that other arguments may be supplied on the command line. (When using Expectk, this option is specified as -file.)

By default, the command file is read into memory and executed in its entirety. It is occasionally desirable to read files one line at a time. For example, stdin is read this way. In order to force arbitrary files to be handled this way, use the -b flag. (When using Expectk, this option is specified as -buffer.)

If the string «-» is supplied as a filename, standard input is read instead. (Use «./-» to read from a file actually named «-".)

The -i flag causes Expect to interactively prompt for commands instead of reading them from a file. Prompting is terminated via the exit command or upon EOF. See interpreter (below) for more information. -i is assumed if neither a command file nor -c is used. (When using Expectk, this option is specified as -interactive.)

-- may be used to delimit the end of the options.
This is useful if you want to pass an option-like argument to your script without it being interpreted by Expect. This can usefully be placed in the #! line to prevent any flag-like interpretation by Expect. For example, the following will leave the original arguments (including the script name) in the variable argv.

#!/usr/local/bin/expect -
Note that the usual getopt(3) and execve(2) conventions must be observed when adding arguments to the #! line.

The file $exp_library/expect.rc is sourced automatically if present, unless the -N flag is used. (When using

Expectk, this option is specified as -NORC.)
Immediately after this, the file ~/.expect.rc is sourced automatically, unless the -n flag is used. If the environment variable DOTDIR is defined, it is treated as a directory and .expect.rc is read from there. (When using Expectk, this option is specified as -norc.) This sourcing occurs only after executing any -c flags.
-v causes Expect to print its
version number and exit. (The corresponding flag in Expectk, which uses long flag names, is -version.)

Optional args are constructed into a list and stored in the variable named argv. argc is initialized to the length of argv.

argv0 is defined to be the name of the script (or binary if no script is used). For example, the following prints out the name of the script and the first three arguments:

send_user «$argv0 [lrange $argv 0 2]\n"

Commands

Expect uses Tcl (Tool Command Language). Tcl provides control flow (e.g., if, for, break), expression evaluation and several other features such as recursion, procedure definition, etc. Commands used here but not defined (e.g., set, if, exec) are Tcl commands (see tcl(3) ). Expect supports additional commands, described below. Unless otherwise specified, commands return the empty string.

Commands are listed alphabetically so that they can be quickly located. However, new users may find it easier to start by reading the descriptions of spawn, send, expect, and interact, in that order.

Note that the best introduction to the language (both Expect and Tcl) is provided in the book «Exploring Expect" (see SEE ALSO below). Examples are included in this man page but they are very limited since this man page is meant primarily as reference material.

Note that in the text of this man page, «Expect» with an uppercase «E» refers to the Expect program while «expect" with a lower-case «e» refers to the expect command within the Expect program.)

close [-slave] [-onexec 0|1] [-i spawn_id] closes the connection to the current process. Most interactive programs will detect EOF on their stdin and exit; thus close usually suffices to kill the process as well. The -i flag declares the process to close corresponding to the named spawn_id.

Both expect and interact will detect when the current process exits and implicitly do a close. But if you kill the process by, say, «exec kill $pid", you will need to explicitly call close.

The -onexec flag determines whether the spawn id will be closed in any new spawned processes or if the process is overlayed. To leave a spawn id open, use the value 0. A non-zero integer value will force the spawn closed (the default) in any new processes.

The -slave flag closes the slave associated with the spawn id. (See «spawn -pty".) When the connection is closed, the slave is automatically closed as well if still open.

No matter whether the connection is closed implicitly or explicitly, you should call wait to clear up the corresponding kernel process slot. close does not call wait since there is no guarantee that closing a process connection will cause it to exit. See wait below for more info.

debug [[-now] 0|1]
controls a Tcl debugger allowing you to step through statements, set breakpoints, etc.

With no arguments, a 1 is returned if the debugger is not running, otherwise a 0 is returned.

With a 1 argument, the debugger is started. With a 0 argument, the debugger is stopped. If a 1 argument is preceded by the -now flag, the debugger is started immediately (i.e., in the middle of the debug command itself). Otherwise, the debugger is started with the next Tcl statement.

The debug command does not change any traps. Compare this to starting Expect with the -D flag (see above).

See the README file or SEE ALSO (below) for more information on the debugger.

disconnect
disconnects a forked process from the terminal. It continues running in the background. The process is given its own process group (if possible). Standard I/O is redirected to /dev/null.

The following fragment uses disconnect to continue running the script in the background.

if {[fork]!=0} exit
disconnect
. . .

The following script reads a password, and then runs a program every hour that demands a password each time it is run. The script supplies the password so that you only have to type it once. (See the stty command which demonstrates how to turn off password echoing.)

send_user «password?\ «
expect_user -re «(.*)\n"
for {} 1 {} {
if {[fork]!=0} {sleep 3600;continue} disconnect
spawn priv_prog
expect Password:
send «$expect_out(1,string)\r" . . .
exit

}

An advantage to using disconnect over the shell asynchronous process feature (&) is that Expect can save the terminal parameters prior to disconnection, and then later apply them to new ptys. With &, Expect does not have a chance to read the terminal's parameters since the terminal is already disconnected by the time Expect receives control.

exit [-opts] [status]
causes Expect to exit or otherwise prepare to do so.

The -onexit flag causes the next argument to be used as an exit handler. Without an argument, the current exit handler is returned.

The -noexit flag causes Expect to prepare to exit but stop short of actually returning control to the operating system. The user-defined exit handler is run as well as Expect's own internal handlers. No further Expect commands should be executed. This is useful if you are running Expect with other Tcl extensions. The current interpreter (and main window if in the Tk environment) remain so that other Tcl extensions can clean up. If Expect's exit is called again (however this might occur), the handlers are not rerun.

Upon exiting, all connections to spawned processes are closed. Closure will be detected as an EOF by spawned processes. exit takes no other actions beyond what the normal _exit(2) procedure does. Thus, spawned processes that do not check for EOF may continue to run. (A variety of conditions are important to determining, for example, what signals a spawned process will be sent, but these are system-dependent, typically documented under exit(3) .) Spawned processes that continue to run will be inherited by init.

status (or 0 if not specified) is returned as the exit status of Expect. exit is implicitly executed if the end of the script is reached.

exp_continue
The command exp_continue allows expect itself to continue executing rather than returning as it normally would. (See expect for more information.)

exp_internal [-f file] value
causes further commands to send diagnostic information internal to Expect to stderr if value is nonzero. This output is disabled if value is 0. The diagnostic information includes every character received, and every attempt made to match the current output against the patterns.

If the optional file is supplied, all normal and debugging output is written to that file (regardless of the value of value). Any previous diagnostic output file is closed.

The -info flag causes exp_internal to return a description of the most recent non-info arguments given.

exp_open [args] [-i spawn_id]
returns a Tcl file identifier that corresponds to the original spawn id. The file identifier can then be used as if it were opened by Tcl's open command. (The spawn id should no longer be used. A wait should not be executed.

The -leaveopen flag leaves the spawn id open for access through Expect commands. A wait must be executed on the spawn id.

exp_pid [-i spawn_id]
returns the process id corresponding to the currently spawned process. If the -i flag is used, the pid returned corresponds to that of the given spawn id.

exp_send
is an alias for send.

exp_send_error
is an alias for send_error.

exp_send_log
is an alias for send_log.

exp_send_tty
is an alias for send_tty.

exp_send_user
is an alias for send_user.

exp_version [[-exit] version]
is useful for assuring that the script is compatible with the current version of Expect.

With no arguments, the current version of Expect is returned. This version may then be encoded in your script. If you actually know that you are not using features of recent versions, you can specify an earlier version.

Versions consist of three numbers separated by dots. First is the major number. Scripts written for versions of Expect with a different major number will almost certainly not work. exp_version returns an error if the major numbers do not match.

Second is the minor number. Scripts written for a version with a greater minor number than the current version may depend upon some new feature and might not run. exp_version returns an error if the major numbers match, but the script minor number is greater than that of the running Expect.

Third is a number that plays no part in the version comparison. However, it is incremented when the Expect software distribution is changed in any way, such as by additional documentation or optimization. It is reset to 0 upon each new minor version.

With the -exit flag, Expect prints an error and exits if the version is out of date.

expect [[-opts] pat1 body1] ... [-opts] patn [bodyn] waits until one of the patterns matches the output of a spawned process, a specified time period has passed, or an end-of-file is seen. If the final body is empty, it may be omitted.

Patterns from the most recent expect_before command are implicitly used before any other patterns. Patterns from the most recent expect_after command are implicitly used after any other patterns.

If the arguments to the entire expect statement require more than one line, all the arguments may be «braced» into one so as to avoid terminating each line with a backslash. In this one case, the usual Tcl substitutions will occur despite the braces.

If a pattern is the keyword eof, the corresponding body is executed upon end-of-file. If a pattern is the keyword timeout, the corresponding body is executed upon timeout. If no timeout keyword is used, an implicit null action is executed upon timeout. The default timeout period is 10 seconds but may be set, for example to 30, by the command «set timeout 30". An infinite timeout may be designated by the value -1. If a pattern is the keyword default, the corresponding body is executed upon either timeout or end-of-file.

If a pattern matches, then the corresponding body is executed. expect returns the result of the body (or the empty string if no pattern matched). In the event that multiple patterns match, the one appearing first is used to select a body.

Each time new output arrives, it is compared to each pattern in the order they are listed. Thus, you may test for absence of a match by making the last pattern something guaranteed to appear, such as a prompt. In situations where there is no prompt, you must use timeout (just like you would if you were interacting manually).

Patterns are specified in three ways. By default, patterns are specified as with Tcl's string match command. (Such patterns are also similar to C-shell regular expressions usually referred to as «glob" patterns). The -gl flag may may be used to protect patterns that might otherwise match expect flags from doing so. Any pattern beginning with a «-" should be protected this way. (All strings starting with «-» are reserved for future options.)

For example, the following fragment looks for a successful login. (Note that abort is presumed to be a procedure defined elsewhere in the script.)

expect {

busy
{puts busy\n ; exp_continue}
failed
abort «invalid password» abort
timeout
abort connected }

Quotes are necessary on the fourth pattern since it contains a space, which would otherwise separate the pattern from the action. Patterns with the same action (such as the 3rd and 4th) require listing the actions again. This can be avoid by using regexpstyle patterns (see below). More information on forming glob-style patterns can be found in the Tcl manual.

Regexp-style patterns follow the syntax defined by Tcl's regexp (short for «regular expression") command. regexp patterns are introduced with the flag -re. The previous example can be rewritten using a regexp as:

expect {

busy
{puts busy\n ; exp_continue} -re «failed|invalid password» abort
timeout
abort connected
}

Both types of patterns are «unanchored". This means that patterns do not have to match the entire string, but can begin and end the match anywhere in the string (as long as everything else matches). Use ^ to match the beginning of a string, and $ to match the end. Note that if you do not wait for the end of a string, your responses can easily end up in the middle of the string as they are echoed from the spawned process. While still producing correct results, the output can look unnatural. Thus, use of $ is encouraged if you can exactly describe the characters at the end of a string.

Note that in many editors, the ^ and $ match the beginning and end of lines respectively. However, because expect is not line oriented, these characters match the beginning and end of the data (as opposed to lines) currently in the expect matching buffer. (Also, see the note below on «system indigestion.")

The -ex flag causes the pattern to be matched as an «exact» string. No interpretation of *, ^, etc is made (although the usual Tcl conventions must still be observed). Exact patterns are always unanchored.

The -nocase flag causes uppercase characters of the output to compare as if they were lowercase characters. The pattern is not affected.

While reading output, more than 2000 bytes can force earlier bytes to be «forgotten". This may be changed with the function match_max. (Note that excessively large values can slow down the pattern matcher.) If patlist is full_buffer, the corresponding body is executed if match_max bytes have been received and no other patterns have matched. Whether or not the full_buffer keyword is used, the forgotten characters are written to expect_out(buffer).

If patlist is the keyword null, and nulls are allowed (via the remove_nulls command), the corresponding body is executed if a single ASCII 0 is matched. It is not possible to match 0 bytes via glob or regexp patterns.

Upon matching a pattern (or eof or full_buffer), any matching and previously unmatched output is saved in the variable expect_out(buffer). Up to 9 regexp substring matches are saved in the variables expect_out(1,string) through expect_out(9,string). If the -indices flag is used before a pattern, the starting and ending indices (in a form suitable for lrange) of the 10 strings are stored in the variables expect_out(X,start) and expect_out(X,end) where X is a digit, corresponds to the substring position in the buffer. 0 refers to strings which matched the entire pattern and is generated for glob patterns as well as regexp patterns. For example, if a process has produced output of «abcdefgh\n", the result of:

expect «cd"

is as if the following statements had executed:

set expect_out(0,string) cd
set expect_out(buffer) abcd

and «efgh\n» is left in the output buffer. If a process produced the output «abbbcabkkkka\n", the result of:

expect -indices -re «b(b*).*(k+)"

is as if the following statements had executed:

set expect_out(0,start) 1
set expect_out(0,end) 10
set expect_out(0,string) bbbcabkkkk
set expect_out(1,start) 2
set expect_out(1,end) 3
set expect_out(1,string) bb
set expect_out(2,start) 10
set expect_out(2,end) 10
set expect_out(2,string) k
set expect_out(buffer) abbbcabkkkk

and «a\n» is left in the output buffer. The pattern «*» (and -re «.*") will flush the output buffer without reading any more output from the process.

Normally, the matched output is discarded from Expect's internal buffers. This may be prevented by prefixing a pattern with the -notransfer flag. This flag is especially useful in experimenting (and can be abbreviated to «-n» for convenience while experimenting).

The spawn id associated with the matching output (or eof or full_buffer) is stored in expect_out(spawn_id).

The -timeout flag causes the current expect command to use the following value as a timeout instead of using the value of the timeout variable.

By default, patterns are matched against output from the current process, however the -i flag declares the output from the named spawn_id list be matched against any following patterns (up to the next -i). The spawn_id list should either be a whitespace separated list of spawn_ids or a variable referring to such a list of spawn_ids.

For example, the following example waits for «connected" from the current process, or «busy", «failed» or «invalid password» from the spawn_id named by $proc2.

expect {
-i $proc2 busy {puts busy\n ; exp_continue} -re «failed|invalid password» abort timeout abort
connected
}

The value of the global variable any_spawn_id may be used to match patterns to any spawn_ids that are named with all other -i flags in the current expect command. The spawn_id from a -i flag with no associated pattern (i.e., followed immediately by another -i) is made available to any other patterns in the same expect command associated with any_spawn_id.

The -i flag may also name a global variable in which case the variable is read for a list of spawn ids. The variable is reread whenever it changes. This provides a way of changing the I/O source while the command is in execution. Spawn ids provided this way are called «indirect» spawn ids.

Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way. The command exp_continue allows expect itself to continue executing rather than returning as it normally would.

This is useful for avoiding explicit loops or repeated expect statements. The following example is part of a fragment to automate rlogin. The exp_continue avoids having to write a second expect statement (to look for the prompt again) if the rlogin prompts for a password.

expect {
Password: {

stty -echo
send_user «password (for $user) on $host: « expect_user -re «(.*)\n" send_user «\n"
send «$expect_out(1,string)\r" stty echo
exp_continue
} incorrect {
send_user «invalid password or account\n" exit
} timeout {
send_user «connection to $host timed out\n" exit
} eof {
send_user \
«connection to host failed: $expect_out(buffer)" exit
} -re $prompt
}

For example, the following fragment might help a user guide an interaction that is already totally automated. In this case, the terminal is put into raw mode. If the user presses «+", a variable is incremented. If «p» is pressed, several returns are sent to the process, perhaps to poke it in some way, and «i» lets the user interact with the process, effectively stealing away control from the script. In each case, the exp_continue allows the current expect to continue pattern matching after executing the current action.

stty raw -echo
expect_after {
-i $user_spawn_id
«p» {send «\r\r\r"; exp_continue}
«+» {incr foo; exp_continue}
«i» {interact; exp_continue}
«quit» exit
}

By default, exp_continue resets the timeout timer. The timer is not restarted, if exp_continue is called with the -continue_timer flag.

expect_after [expect_args]
works identically to the expect_before except that if patterns from both expect and expect_after can match, the expect pattern is used. See the expect_before command for more information.

expect_background [expect_args]
takes the same arguments as expect, however it returns immediately. Patterns are tested whenever new input arrives. The pattern timeout and default are meaningless to expect_background and are silently discarded. Otherwise, the expect_background command uses expect_before and expect_after patterns just like expect does.

When expect_background actions are being evaluated, background processing for the same spawn id is blocked. Background processing is unblocked when the action completes. While background processing is blocked, it is possible to do a (foreground) expect on the same spawn id.

It is not possible to execute an expect while an expect_background is unblocked. expect_background for a particular spawn id is deleted by declaring a new expect_background with the same spawn id. Declaring expect_background with no pattern removes the given spawn id from the ability to match patterns in the background.

expect_before [expect_args]
takes the same arguments as expect, however it returns immediately. Pattern-action pairs from the most recent expect_before with the same spawn id are implicitly added to any following expect commands. If a pattern matches, it is treated as if it had been specified in the expect command itself, and the associated body is executed in the context of the expect command. If patterns from both expect_before and expect can match, the expect_before pattern is used.

If no pattern is specified, the spawn id is not checked for any patterns.

Unless overridden by a -i flag, expect_before patterns match against the spawn id defined at the time that the expect_before command was executed (not when its pattern is matched).

The -info flag causes expect_before to return the current specifications of what patterns it will match. By default, it reports on the current spawn id. An optional spawn id specification may be given for information on that spawn id. For example

expect_before -info -i $proc

At most one spawn id specification may be given. The flag -indirect suppresses direct spawn ids that come only from indirect specifications.

Instead of a spawn id specification, the flag «-all" will cause «-info» to report on all spawn ids.

The output of the -info flag can be reused as the argument to expect_before.

expect_tty [expect_args]
is like expect but it reads characters from /dev/tty (i.e. keystrokes from the user). By default, reading is performed in cooked mode. Thus, lines must end with a return in order for expect to see them. This may be changed via stty (see the stty command below).

expect_user [expect_args]
is like expect but it reads characters from stdin (i.e. keystrokes from the user). By default, reading is performed in cooked mode. Thus, lines must end with a return in order for expect to see them. This may be changed via stty (see the stty command below).

fork creates a new process. The new process is an exact copy of the current Expect process. On success, fork returns 0 to the new (child) process and returns the process ID of the child process to the parent process. On failure (invariably due to lack of resources, e.g., swap space, memory), fork returns -1 to the parent process, and no child process is created.

Forked processes exit via the exit command, just like the original process. Forked processes are allowed to write to the log files. If you do not disable debugging or logging in most of the processes, the result can be confusing.

Some pty implementations may be confused by multiple readers and writers, even momentarily. Thus, it is safest to fork before spawning processes.

interact [string1 body1] ... [stringn [bodyn]] gives control of the current process to the user, so that keystrokes are sent to the current process, and the stdout and stderr of the current process are returned.

String-body pairs may be specified as arguments, in which case the body is executed when the corresponding string is entered. (By default, the string is not sent to the current process.) The interpreter command is assumed, if the final body is missing.

If the arguments to the entire interact statement require more than one line, all the arguments may be «braced» into one so as to avoid terminating each line with a backslash. In this one case, the usual Tcl substitutions will occur despite the braces.

For example, the following command runs interact with the following string-body pairs defined: When ^Z is pressed, Expect is suspended. (The -reset flag restores the terminal modes.) When ^A is pressed, the user sees «you typed a control-A» and the process is sent a ^A. When $ is pressed, the user sees the date. When ^C is pressed, Expect exits. If «foo» is entered, the user sees «bar". When ~~ is pressed, the Expect interpreter runs interactively.

set CTRLZ \032
interact {
-reset $CTRLZ {exec kill -STOP [pid]}

\001
{send_user «you typed a control-A\n"; send «\001" }
$
{send_user «The date is [exec date]."} \003 exit
foo
{send_user «bar"} ~~ }

In string-body pairs, strings are matched in the order they are listed as arguments. Strings that partially match are not sent to the current process in anticipation of the remainder coming. If characters are then entered such that there can no longer possibly be a match, only the part of the string will be sent to the process that cannot possibly begin another match. Thus, strings that are substrings of partial matches can match later, if the original strings that was attempting to be match ultimately fails.

By default, string matching is exact with no wild cards. (In contrast, the expect command uses globstyle patterns by default.) The -ex flag may be used to protect patterns that might otherwise match interact flags from doing so. Any pattern beginning with a «-» should be protected this way. (All strings starting with «-» are reserved for future options.)

The -re flag forces the string to be interpreted as a regexp-style pattern. In this case, matching substrings are stored in the variable interact_out similarly to the way expect stores its output in the variable expect_out. The -indices flag is similarly supported.

The pattern eof introduces an action that is executed upon end-of-file. A separate eof pattern may also follow the -output flag in which case it is matched if an eof is detected while writing output. The default eof action is «return", so that interact simply returns upon any EOF.

The pattern timeout introduces a timeout (in seconds) and action that is executed after no characters have been read for a given time. The timeout pattern applies to the most recently specified process. There is no default timeout. The special variable «timeout» (used by the expect command) has no affect on this timeout.

For example, the following statement could be used to autologout users who have not typed anything for an hour but who still get frequent system messages:

interact -input $user_spawn_id timeout 3600 return -output \ $spawn_id

If the pattern is the keyword null, and nulls are allowed (via the remove_nulls command), the corresponding body is executed if a single ASCII 0 is matched. It is not possible to match 0 bytes via glob or regexp patterns.

Prefacing a pattern with the flag -iwrite causes the variable interact_out(spawn_id) to be set to the spawn_id which matched the pattern (or eof).

Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way. However return causes interact to return to its caller, while inter_return causes interact to cause a return in its caller. For example, if «proc foo» called interact which then executed the action inter_return, proc foo would return. (This means that if interact calls interpreter interactively typing return will cause the interact to continue, while inter_return will cause the interact to return to its caller.)

During interact, raw mode is used so that all characters may be passed to the current process. If the current process does not catch job control signals, it will stop if sent a stop signal (by default ^Z). To restart it, send a continue signal (such as by «kill -CONT <pid>"). If you really want to send a

SIGSTOP to such a process (by ^Z), consider spawning csh first and then running your program. On the other hand, if you want to send a SIGSTOP to Expect itself, first press the escape character, and then press ^Z.

String-body pairs can be used as a shorthand for avoiding having to enter the interpreter and execute commands interactively. The previous terminal mode is used while the body of a string-body pair is being executed.

For speed, actions execute in raw mode by default. The -reset flag resets the terminal to the mode it had before interact was executed (invariably, cooked mode). Note that characters entered when the mode is being switched may be lost (an unfortunate feature of the terminal driver on some systems). The only reason to use -reset is if your action depends on running in cooked mode.

The -echo flag sends characters that match the following pattern back to the process that generated them as each character is read. This may be useful when the user needs to see feedback from partially typed patterns.

If a pattern is being echoed but eventually fails to match, the characters are sent to the spawned process. If the spawned process then echoes them, the user will see the characters twice. -echo is probably only appropriate in situations where the user is unlikely to not complete the pattern. For example, the following excerpt is from rftp, the recursiveftp script, where the user is prompted to enter ~g, ~p, or ~l, to get, put, or list the current directory recursively. These are so far away from the normal ftp commands, that the user is unlikely to type ~ followed by anything else, except mistakenly, in which case, they'll probably just ignore the result anyway.

interact {
-echo ~g {getcurdirectory 1}
-echo ~l {getcurdirectory 0}
-echo ~p {putcurdirectory}
}

The -nobuffer flag sends characters that match the following pattern on to the output process as characters are read.

This is useful when you wish to let a program echo back the pattern. For example, the following might be used to monitor where a person is dialing (a Hayes-style modem). Each time «atd» is seen the script logs the rest of the line.

proc lognumber {} {
interact -nobuffer -re «(.*)\r» return puts $log «[exec date]: dialed $interact_out(1,string)" }

interact -nobuffer «atd» lognumber

During interact, previous use of log_user is ignored. In particular, interact will force its output to be logged (sent to the standard output) since it is presumed the user doesn't wish to interact blindly.

The -o flag causes any following key-body pairs to be applied to the output of the current process. This can be useful, for example, when dealing with hosts that send unwanted characters during a telnet session.

By default, interact expects the user to be writing stdin and reading stdout of the Expect process itself. The -u flag (for «user") makes interact look for the user as the process named by its argument (which must be a spawned id).

This allows two unrelated processes to be joined together without using an explicit loop. To aid in debugging, Expect diagnostics always go to stderr (or stdout for certain logging and debugging information). For the same reason, the interpreter command will read interactively from stdin.

For example, the following fragment creates a login process. Then it dials the user (not shown), and finally connects the two together. Of course, any process may be substituted for login. A shell, for example, would allow the user to work without supplying an account and password.

spawn login
set login $spawn_id
spawn tip modem
# dial back out to user
# connect user to login
interact -u $login

To send output to multiple processes, list each spawn id list prefaced by a -output flag. Input for a group of output spawn ids may be determined by a spawn id list prefaced by a -input flag. (Both -input and -output may take lists in the same form as the -i flag in the expect command, except that any_spawn_id is not meaningful in interact.) All following flags and strings (or patterns) apply to this input until another -input flag appears. If no

-input
appears, -output implies «-input $user_spawn_id -output". (Similarly, with patterns that do not have -input.) If one -input is specified, it overrides $user_spawn_id. If a second -input is specified, it overrides $spawn_id. Additional -input flags may be specified.

The two implied input processes default to having their outputs specified as $spawn_id and $user_spawn_id (in reverse). If a -input flag appears with no -output flag, characters from that process are discarded.

The -i flag introduces a replacement for the current spawn_id when no other -input or -output flags are used. A -i flag implies a -o flag.

It is possible to change the processes that are being interacted with by using indirect spawn ids. (Indirect spawn ids are described in the section on the expect command.) Indirect spawn ids may be specified with the -i, -u, -input, or -output flags.

interpreter
causes the user to be interactively prompted for Expect and Tcl commands. The result of each command is printed.

Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way. However return causes interpreter to return to its caller, while inter_return causes interpreter to cause a return in its caller. For example, if «proc foo» called interpreter which then executed the action inter_return, proc foo would return. Any other command causes interpreter to continue prompting for new commands.

By default, the prompt contains two integers. The first integer describes the depth of the evaluation stack (i.e., how many times Tcl_Eval has been called). The second integer is the Tcl history identifier. The prompt can be set by defining a procedure called «prompt1» whose return value becomes the next prompt. If a statement has open quotes, parens, braces, or brackets, a secondary prompt (by default «+> «) is issued upon newline. The secondary prompt may be set by defining a procedure called «prompt2".

During interpreter, cooked mode is used, even if the its caller was using raw mode.

log_file [args] [[-a] file]
If a filename is provided, log_file will record a transcript of the session (beginning at that point) in the file. log_file will stop recording if no argument is given. Any previous log file is closed.

Instead of a filename, a Tcl file identifier may be provided by using the -open or -leaveopen flags. This is similar to the spawn command. (See spawn for more info.)

The -a flag forces output to be logged that was suppressed by the log_user command.

By default, the log_file command appends to old files rather than truncating them, for the convenience of being able to turn logging off and on multiple times in one session. To truncate files, use the -noappend flag.

The -info flag causes log_file to return a description of the most recent non-info arguments given.

log_user -info|0|1
By default, the send/expect dialogue is logged to stdout (and a logfile if open). The logging to stdout is disabled by the command «log_user 0» and reenabled by «log_user 1". Logging to the logfile is unchanged.

The -info flag causes log_user to return a description of the most recent non-info arguments given.

match_max [-d] [-i spawn_id] [size]
defines the size of the buffer (in bytes) used internally by expect. With no size argument, the current size is returned.

With the -d flag, the default size is set. (The initial default is 2000.) With the -i flag, the size is set for the named spawn id, otherwise it is set for the current process.

overlay [-# spawn_id] [-# spawn_id] [...] program [args] executes program args in place of the current Expect program, which terminates. A bare hyphen argument forces a hyphen in front of the command name as if it was a login shell. All spawn_ids are closed except for those named as arguments. These are mapped onto the named file identifiers.

Spawn_ids are mapped to file identifiers for the new program to inherit. For example, the following line runs chess and allows it to be controlled by the current process - say, a chess master.

overlay -0 $spawn_id -1 $spawn_id -2 $spawn_id chess

This is more efficient than «interact -u", however, it sacrifices the ability to do programmed interaction since the Expect process is no longer in control.

Note that no controlling terminal is provided. Thus, if you disconnect or remap standard input, programs that do job control (shells, login, etc) will not function properly.

parity [-d] [-i spawn_id] [value]
defines whether parity should be retained or stripped from the output of spawned processes. If value is zero, parity is stripped, otherwise it is not stripped. With no value argument, the current value is returned.

With the -d flag, the default parity value is set. (The initial default is 1, i.e., parity is not stripped.) With the -i flag, the parity value is set for the named spawn id, otherwise it is set for the current process.

remove_nulls [-d] [-i spawn_id] [value] defines whether nulls are retained or removed from the output of spawned processes before pattern matching or storing in the variable expect_out or interact_out. If value is 1, nulls are removed. If value is 0, nulls are not removed. With no value argument, the current value is returned.

With the -d flag, the default value is set. (The initial default is 1, i.e., nulls are removed.) With the -i flag, the value is set for the named spawn id, otherwise it is set for the current process.

Whether or not nulls are removed, Expect will record null bytes to the log and stdout.

send [-flags] string
Sends string to the current process. For example, the command

send «hello world\r"

sends the characters, h e l l o <blank> w o r l d <return> to the current process. (Tcl includes a printf-like command (called format) which can build arbitrarily complex strings.)

Characters are sent immediately although programs with line-buffered input will not read the characters until a return character is sent. A return character is denoted «\r".

The -- flag forces the next argument to be interpreted as a string rather than a flag. Any string can be preceded by «--» whether or not it actually looks like a flag. This provides a reliable mechanism to specify variable strings without being tripped up by those that accidentally look like flags. (All strings starting with «-» are reserved for future options.)

The -i flag declares that the string be sent to the named spawn_id. If the spawn_id is user_spawn_id, and the terminal is in raw mode, newlines in the string are translated to return-newline sequences so that they appear as it the terminal was in cooked mode. The -raw flag disables this translation.

The -null flag sends null characters (0 bytes). By default, one null is sent. An integer may follow the -null to indicate how many nulls to send.

The -break flag generates a break condition. This only makes sense if the spawn id refers to a tty device opened via «spawn -open". If you have spawned a process such as tip, you should use tip's convention for generating a break.

The -s flag forces output to be sent «slowly", thus avoid the common situation where a computer outtypes an input buffer that was designed for a human who would never outtype the same buffer. This output is controlled by the value of the variable «send_slow" which takes a two element list. The first element is an integer that describes the number of bytes to send atomically. The second element is a real number that describes the number of seconds by which the atomic sends must be separated. For example, «set send_slow {10 .001}» would force «send -s» to send strings with 1 millisecond in between each 10 characters sent.

The -h flag forces output to be sent (somewhat) like a human actually typing. Human-like delays appear between the characters. (The algorithm is based upon a Weibull distribution, with modifications to suit this particular application.) This output is controlled by the value of the variable «send_human" which takes a five element list. The first two elements are average interarrival time of characters in seconds. The first is used by default. The second is used at word endings, to simulate the subtle pauses that occasionally occur at such transitions. The third parameter is a measure of variability where .1 is quite variable, 1 is reasonably variable, and 10 is quite invariable. The extremes are 0 to infinity. The last two parameters are, respectively, a minimum and maximum interarrival time. The minimum and maximum are used last and «clip» the final time. The ultimate average can be quite different from the given average if the minimum and maximum clip enough values.

As an example, the following command emulates a fast and consistent typist:

set send_human {.1 .3 1 .05 2} send -h «I'm hungry. Let's do lunch."

while the following might be more suitable after a hangover:

set send_human {.4 .4 .2 .5 100} send -h «Goodd party lash night!"

Note that errors are not simulated, although you can set up error correction situations yourself by embedding mistakes and corrections in a send argument.

The flags for sending null characters, for sending breaks, for forcing slow output and for human-style output are mutually exclusive. Only the one specified last will be used. Furthermore, no string argument can be specified with the flags for sending null characters or breaks.

It is a good idea to precede the first send to a process by an expect. expect will wait for the process to start, while send cannot. In particular, if the first send completes before the process starts running, you run the risk of having your data ignored. In situations where interactive programs offer no initial prompt, you can precede send by a delay as in:

# To avoid giving hackers hints on how to break in, # this system does not prompt for an external password. # Wait for 5 seconds for exec to complete spawn telnet very.secure.gov sleep 5
send password\r

exp_send is an alias for send. If you are using Expectk or some other variant of Expect in the Tk environment, send is defined by Tk for an entirely different purpose. exp_send is provided for compatibility between environments. Similar aliases are provided for other Expect's other send commands.

send_error [-flags] string
is like send, except that the output is sent to stderr rather than the current process.

send_log [--] string
is like send, except that the string is only sent to the log file (see log_file.) The arguments are ignored if no log file is open.

send_tty [-flags] string
is like send, except that the output is sent to /dev/tty rather than the current process.

send_user [-flags] string
is like send, except that the output is sent to stdout rather than the current process.

sleep seconds
causes the script to sleep for the given number of seconds. Seconds may be a decimal number. Interrupts (and Tk events if you are using Expectk) are processed while Expect sleeps.

spawn [args] program [args]
creates a new process running program args. Its stdin, stdout and stderr are connected to Expect, so that they may be read and written by other Expect commands. The connection is broken by close or if the process itself closes any of the file identifiers.

When a process is started by spawn, the variable spawn_id is set to a descriptor referring to that process. The process described by spawn_id is considered the current process. spawn_id may be read or written, in effect providing job control.

user_spawn_id is a global variable containing a descriptor which refers to the user. For example, when spawn_id is set to this value, expect behaves like expect_user.

error_spawn_id is a global variable containing a descriptor which refers to the standard error. For example, when spawn_id is set to this value, send behaves like send_error.

tty_spawn_id is a global variable containing a descriptor which refers to /dev/tty. If /dev/tty does not exist (such as in a cron, at, or batch script), then tty_spawn_id is not defined. This may be tested as:

if {[info vars tty_spawn_id]} { # /dev/tty exists
} else {
# /dev/tty doesn't exist
# probably in cron, batch, or at script }

spawn returns the UNIX process id. If no process is spawned, 0 is returned. The variable spawn_out(slave,name) is set to the name of the pty slave device.

By default, spawn echoes the command name and arguments. The -noecho flag stops spawn from doing this.

The -console flag causes console output to be redirected to the spawned process. This is not supported on all systems.

Internally, spawn uses a pty, initialized the same way as the user's tty. This is further initialized so that all settings are «sane» (according to stty(1) ). If the variable stty_init is defined, it is interpreted in the style of stty arguments as further configuration. For example, «set stty_init raw» will cause further spawned processes's terminals to start in raw mode. -nottycopy skips the initialization based on the user's tty. -nottyinit skips the «sane» initialization.

Normally, spawn takes little time to execute. If you notice spawn taking a significant amount of time, it is probably encountering ptys that are wedged. A number of tests are run on ptys to avoid entanglements with errant processes. (These take 10 seconds per wedged pty.) Running Expect with the -d option will show if Expect is encountering many ptys in odd states. If you cannot kill the processes to which these ptys are attached, your only recourse may be to reboot.

If program cannot be spawned successfully because exec(2) fails (e.g. when program doesn't exist), an error message will be returned by the next interact or expect command as if program had run and produced the error message as output. This behavior is a natural consequence of the implementation of spawn. Internally, spawn forks, after which the spawned process has no way to communicate with the original Expect process except by communication via the spawn_id.

The -open flag causes the next argument to be interpreted as a Tcl file identifier (i.e., returned by open.) The spawn id can then be used as if it were a spawned process. (The file identifier should no longer be used.) This lets you treat raw devices, files, and pipelines as spawned processes without using a pty. 0 is returned to indicate there is no associated process. When the connection to the spawned process is closed, so is the Tcl file identifier. The -leaveopen flag is similar to -open except that -leaveopen causes the file identifier to be left open even after the spawn id is closed.

The -pty flag causes a pty to be opened but no process spawned. 0 is returned to indicate there is no associated process. Spawn_id is set as usual.

The variable spawn_out(slave,fd) is set to a file identifier corresponding to the pty slave. It can be closed using «close -slave".

The -ignore flag names a signal to be ignored in the spawned process. Otherwise, signals get the default behavior. Signals are named as in the trap command, except that each signal requires a separate flag.

strace level
causes following statements to be printed before being executed. (Tcl's trace command traces variables.) level indicates how far down in the call stack to trace. For example, the following command runs Expect while tracing the first 4 levels of calls, but none below that.

expect -c «strace 4» script.exp

The -info flag causes strace to return a description of the most recent non-info arguments given.

stty args
changes terminal modes similarly to the external stty command.

By default, the controlling terminal is accessed.

Other terminals can be accessed by appending «< /dev/tty...» to the command. (Note that the arguments should not be grouped into a single argument.)

Requests for status return it as the result of the command. If no status is requested and the controlling terminal is accessed, the previous status of the raw and echo attributes are returned in a form which can later be used by the command.

For example, the arguments raw or -cooked put the terminal into raw mode. The arguments -raw or cooked put the terminal into cooked mode. The arguments echo and -echo put the terminal into echo and noecho mode respectively.

The following example illustrates how to temporarily disable echoing. This could be used in otherwiseautomatic scripts to avoid embedding passwords in them. (See more discussion on this under EXPECT HINTS below.)

stty -echo
send_user «Password: «
expect_user -re «(.*)\n"
set password $expect_out(1,string) stty echo

system args
gives args to sh(1) as input, just as if it had been typed as a command from a terminal. Expect waits until the shell terminates. The return status from sh is handled the same way that exec handles its return status.

In contrast to exec which redirects stdin and stdout to the script, system performs no redirection (other than that indicated by the string itself). Thus, it is possible to use programs which must talk directly to /dev/tty. For the same reason, the results of system are not recorded in the log.

timestamp [args]
returns a timestamp. With no arguments, the number of seconds since the epoch is returned.

The -format flag introduces a string which is returned but with substitutions made according to the POSIX rules for strftime. For example %a is replaced by an abbreviated weekday name (i.e., Sat). Others are:

%a
abbreviated weekday name
%A
full weekday name
%b
abbreviated month name
%B
full month name
%c
date-time as in: Wed Oct 6 11:45:56 1993
%d
day of the month (01-31)
%H
hour (00-23)
%I
hour (01-12)
%j
day (001-366)
%m
month (01-12)
%M
minute (00-59)
%p
am or pm
%S
second (00-61)
%u
day (1-7, Monday is first day of week)
%U
week (00-53, first Sunday is first day of week one)
%V
week (01-53, ISO 8601 style)
%w
day (0-6)
%W
week (00-53, first Monday is first day of week one)
%x
date-time as in: Wed Oct 6 1993
%X
time as in: 23:59:59
%y
year (00-99)
%Y
year as in: 1993
%Z
timezone (or nothing if not determinable)
%%
a bare percent sign

Other % specifications are undefined. Other characters will be passed through untouched. Only the C locale is supported.

The -seconds flag introduces a number of seconds since the epoch to be used as a source from which to format. Otherwise, the current time is used.

The -gmt flag forces timestamp output to use the GMT timezone. With no flag, the local timezone is used.

trap [[command] signals]
causes the given command to be executed upon future receipt of any of the given signals. The command is executed in the global scope. If command is absent, the signal action is returned. If command is the string SIG_IGN, the signals are ignored. If command is the string SIG_DFL, the signals are result to the system default. signals is either a single signal or a list of signals. Signals may be specified numerically or symbolically as per signal(3) . The «SIG» prefix may be omitted.

With no arguments (or the argument -number), trap returns the signal number of the trap command currently being executed.

The -code flag uses the return code of the command in place of whatever code Tcl was about to return when the command originally started running.

The -interp flag causes the command to be evaluated using the interpreter active at the time the command started running rather than when the trap was declared.

The -name flag causes the trap command to return the signal name of the trap command currently being executed.

The -max flag causes the trap command to return the largest signal number that can be set.

For example, the command «trap {send_user «Ouch!"} SIGINT» will print «Ouch!» each time the user presses ^C.

By default, SIGINT (which can usually be generated by pressing ^C) and SIGTERM cause Expect to exit. This is due to the following trap, created by default when Expect starts.

trap exit {SIGINT SIGTERM}

If you use the -D flag to start the debugger, SIGINT is redefined to start the interactive debugger. This is due to the following trap:

trap {exp_debug 1} SIGINT

The debugger trap can be changed by setting the environment variable EXPECT_DEBUG_INIT to a new trap command.

You can, of course, override both of these just by adding trap commands to your script. In particular, if you have your own «trap exit SIGINT", this will override the debugger trap. This is useful if you want to prevent users from getting to the debugger at all.

If you want to define your own trap on SIGINT but still trap to the debugger when it is running, use:

if ![exp_debug] {trap mystuff SIGINT}

Alternatively, you can trap to the debugger using some other signal.

trap will not let you override the action for SIGALRM as this is used internally to Expect. The disconnect command sets SIGALRM to SIG_IGN (ignore). You can reenable this as long as you disable it during subsequent spawn commands.

See signal(3) for more info.

wait [args]
delays until a spawned process (or the current process if none is named) terminates.

wait normally returns a list of four integers. The first integer is the pid of the process that was waited upon. The second integer is the corresponding spawn id. The third integer is -1 if an operating system error occurred, or 0 otherwise. If the third integer was 0, the fourth integer is the status returned by the spawned process. If the third integer was -1, the fourth integer is the value of errno set by the operating system. The global variable errorCode is also set.

Additional elements may appear at the end of the return value from wait. An optional fifth element identifies a class of information. Currently, the only possible value for this element is CHILDKILLED in which case the next two values are the C-style signal name and a short textual description.

The -i flag declares the process to wait corresponding to the named spawn_id (NOT the process id). Inside a SIGCHLD handler, it is possible to wait for any spawned process by using the spawn id -1.

The -nowait flag causes the wait to return immediately with the indication of a successful wait. When the process exits (later), it will automatically disappear without the need for an explicit wait.

The wait command may also be used wait for a forked process using the arguments «-i -1". Unlike its use with spawned processes, this command can be executed at any time. There is no control over which process is reaped. However, the return value can be checked for the process id.

Libraries

Expect automatically knows about two built-in libraries for Expect scripts. These are defined by the directories named in the variables exp_library and exp_exec_library. Both are meant to contain utility files that can be used by other scripts.

exp_library contains architecture-independent files. exp_exec_library contains architecture-dependent files. Depending on your system, both directories may be totally empty. The existence of the file $exp_exec_library/cat buffers describes whether your /bin/cat buffers by default.

Pretty-printing

A vgrind definition is available for pretty-printing Expect scripts. Assuming the vgrind definition supplied with the Expect distribution is correctly installed, you can use it as:

vgrind -lexpect file

Examples

It many not be apparent how to put everything together that the man page describes. I encourage you to read and try out the examples in the example directory of the Expect distribution. Some of them are real programs. Others are simply illustrative of certain techniques, and of course, a couple are just quick hacks. The INSTALL file has a quick overview of these programs.

The Expect papers (see SEE ALSO) are also useful. While some papers use syntax corresponding to earlier versions of Expect, the accompanying rationales are still valid and go into a lot more detail than this man page.

Caveats

Extensions may collide with Expect's command names. For example, send is defined by Tk for an entirely different purpose. For this reason, most of the Expect commands are also available as «exp_XXXX". Commands and variables beginning with «exp", «inter", «spawn", and «timeout» do not have aliases. Use the extended command names if you need this compatibility between environments.

Expect takes a rather liberal view of scoping. In particular, variables read by commands specific to the Expect program will be sought first from the local scope, and if not found, in the global scope. For example, this obviates the need to place «global timeout» in every procedure you write that uses expect. On the other hand, variables written are always in the local scope (unless a «global" command has been issued). The most common problem this causes is when spawn is executed in a procedure. Outside the procedure, spawn_id no longer exists, so the spawned process is no longer accessible simply because of scoping. Add a «global spawn_id» to such a procedure.

If you cannot enable the multispawning capability (i.e., your system supports neither select (BSD *.*), poll (SVR>2), nor something equivalent), Expect will only be able to control a single process at a time. In this case, do not attempt to set spawn_id, nor should you execute processes via exec while a spawned process is running.

Furthermore, you will not be able to expect from multiple processes (including the user as one) at the same time.

Terminal parameters can have a big effect on scripts. For example, if a script is written to look for echoing, it will misbehave if echoing is turned off. For this reason, Expect forces sane terminal parameters by default. Unfortunately, this can make things unpleasant for other programs. As an example, the emacs shell wants to change the «usual» mappings: newlines get mapped to newlines instead of carriage-return newlines, and echoing is disabled. This allows one to use emacs to edit the input line. Unfortunately, Expect cannot possibly guess this.

You can request that Expect not override its default setting of terminal parameters, but you must then be very careful when writing scripts for such environments. In the case of emacs, avoid depending upon things like echoing and end-of-line mappings.

The commands that accepted arguments braced into a single list (the expect variants and interact) use a heuristic to decide if the list is actually one argument or many. The heuristic can fail only in the case when the list actually does represent a single argument which has multiple embedded \n's with non-whitespace characters between them. This seems sufficiently improbable, however the argument «-nobrace» can be used to force a single argument to be handled as a single argument. This could conceivably be used with machine-generated Expect code.

Bugs

It was really tempting to name the program «sex» (for either «Smart EXec» or «Send-EXpect"), but good sense (or perhaps just Puritanism) prevailed.

On some systems, when a shell is spawned, it complains about not being able to access the tty but runs anyway. This means your system has a mechanism for gaining the controlling tty that Expect doesn't know about. Please find out what it is, and send this information back to me.

Ultrix 4.1 (at least the latest versions around here) considers timeouts of above 1000000 to be equivalent to 0.

Digital UNIX 4.0A (and probably other versions) refuses to allocate ptys if you define a SIGCHLD handler. See grantpt page for more info.

IRIX 6.0 does not handle pty permissions correctly so that if Expect attempts to allocate a pty previously used by someone else, it fails. Upgrade to IRIX 6.1.

Telnet (verified only under SunOS 4.1.2) hangs if TERM is not set. This is a problem under cron, at and in cgi scripts, which do not define TERM. Thus, you must set it explicitly - to what type is usually irrelevant. It just has to be set to something! The following probably suffices for most cases.

set env(TERM) vt100

Tip (verified only under BSDI BSD/OS 3.1 i386) hangs if SHELL and HOME are not set. This is a problem under cron, at and in cgi scripts, which do not define these environment variables. Thus, you must set them explicitly - to what type is usually irrelevant. It just has to be set to something! The following probably suffices for most cases.

set env(SHELL) /bin/sh
set env(HOME) /usr/local/bin

Some implementations of ptys are designed so that the kernel throws away any unread output after 10 to 15 seconds (actual number is implementation-dependent) after the process has closed the file descriptor. Thus Expect programs such as

spawn date
sleep 20
expect

will fail. To avoid this, invoke non-interactive programs with exec rather than spawn. While such situations are conceivable, in practice I have never encountered a situation in which the final output of a truly interactive program would be lost due to this behavior.

On the other hand, Cray UNICOS ptys throw away any unread output immediately after the process has closed the file descriptor. I have reported this to Cray and they are working on a fix.

Sometimes a delay is required between a prompt and a response, such as when a tty interface is changing UART settings or matching baud rates by looking for start/stop bits. Usually, all this is require is to sleep for a second or two. A more robust technique is to retry until the hardware is ready to receive input. The following example uses both strategies:

send «speed 9600\r";
sleep 1
expect {

timeout {send «\r"; exp_continue} $prompt
}

Expect Hints

There are a couple of things about Expect that may be nonintuitive. This section attempts to address some of these things with a couple of suggestions.

A common expect problem is how to recognize shell prompts. Since these are customized differently by differently people and different shells, portably automating rlogin can be difficult without knowing the prompt. A reasonable convention is to have users store a regular expression describing their prompt (in particular, the end of it) in the environment variable EXPECT_PROMPT. Code like the following can be used. If EXPECT_PROMPT doesn't exist, the code still has a good chance of functioning correctly.

set prompt «(%|#|\\$) $»
;# default prompt catch {set prompt $env(EXPECT_PROMPT)}

expect -re $prompt

I encourage you to write expect patterns that include the end of whatever you expect to see. This avoids the possibility of answering a question before seeing the entire thing. In addition, while you may well be able to answer questions before seeing them entirely, if you answer early, your answer may appear echoed back in the middle of the question. In other words, the resulting dialogue will be correct but look scrambled.

Most prompts include a space character at the end. For example, the prompt from ftp is `f', `t', `p', `>' and <blank>. To match this prompt, you must account for each of these characters. It is a common mistake not to include the blank. Put the blank in explicitly.

If you use a pattern of the form X*, the * will match all the output received from the end of X to the last thing received. This sounds intuitive but can be somewhat confusing because the phrase «last thing received» can vary depending upon the speed of the computer and the processing of I/O both by the kernel and the device driver.

In particular, humans tend to see program output arriving in huge chunks (atomically) when in reality most programs produce output one line at a time. Assuming this is the case, the * in the pattern of the previous paragraph may only match the end of the current line even though there seems to be more, because at the time of the match that was all the output that had been received.

expect has no way of knowing that further output is coming unless your pattern specifically accounts for it.

Even depending on line-oriented buffering is unwise. Not only do programs rarely make promises about the type of buffering they do, but system indigestion can break output lines up so that lines break at seemingly random places. Thus, if you can express the last few characters of a prompt when writing patterns, it is wise to do so.

If you are waiting for a pattern in the last output of a program and the program emits something else instead, you will not be able to detect that with the timeout keyword. The reason is that expect will not timeout - instead it will get an eof indication. Use that instead. Even better, use both. That way if that line is ever moved around, you won't have to edit the line itself.

Newlines are usually converted to carriage return, linefeed sequences when output by the terminal driver. Thus, if you want a pattern that explicitly matches the two lines, from, say, printf("foo\nbar"), you should use the pattern «foo\r\nbar".

A similar translation occurs when reading from the user, via expect_user. In this case, when you press return, it will be translated to a newline. If Expect then passes that to a program which sets its terminal to raw mode (like telnet), there is going to be a problem, as the program expects a true return. (Some programs are actually forgiving in that they will automatically translate newlines to returns, but most don't.) Unfortunately, there is no way to find out that a program put its terminal into raw mode.

Rather than manually replacing newlines with returns, the solution is to use the command «stty raw", which will stop the translation. Note, however, that this means that you will no longer get the cooked line-editing features.

interact implicitly sets your terminal to raw mode so this problem will not arise then.

It is often useful to store passwords (or other private information) in Expect scripts. This is not recommended since anything that is stored on a computer is susceptible to being accessed by anyone. Thus, interactively prompting for passwords from a script is a smarter idea than embedding them literally. Nonetheless, sometimes such embedding is the only possibility.

Unfortunately, the UNIX file system has no direct way of creating scripts which are executable but unreadable. Systems which support setgid shell scripts may indirectly simulate this as follows:

Create the Expect script (that contains the secret data) as usual. Make its permissions be 750 (-rwxr-x---) and owned by a trusted group, i.e., a group which is allowed to read it. If necessary, create a new group for this purpose. Next, create a /bin/sh script with permissions 2751 (-rwxr-s--x) owned by the same group as before.

The result is a script which may be executed (and read) by anyone. When invoked, it runs the Expect script.

See Also

Tcl(3) , libexpect(3)
«Exploring Expect: A Tcl-Based Toolkit for Automating Interactive Programs» by Don Libes, pp. 602, ISBN 1-56592-090-2, O'Reilly and Associates, 1995. «expect: Curing Those Uncontrollable Fits of Interactiv_ity" by Don Libes, Proceedings of the Summer 1990 USENIX Conference, Anaheim, California, June 11-15, 1990. «Using expect to Automate System Administration Tasks» by Don Libes, Proceedings of the 1990 USENIX Large Installation Systems Administration Conference, Colorado Springs, Colorado, October 17-19, 1990.
«Tcl: An Embeddable Command Language» by John Ousterhout, Proceedings of the Winter 1990 USENIX Conference, Washington, D.C., January 22-26, 1990.
«expect: Scripts for Controlling Interactive Programs» by Don Libes, Computing Systems, Vol. 4, No. 2, University of California Press Journals, November 1991. «Regression Testing and Conformance Testing Interactive Programs", by Don Libes, Proceedings of the Summer 1992 USENIX Conference, pp. 135-144, San Antonio, TX, June 12-15, 1992.
«Kibitz - Connecting Multiple Interactive Programs Together", by Don Libes, Software - Practice & Experience, John Wiley & Sons, West Sussex, England, Vol. 23, No. 5, May, 1993.
«A Debugger for Tcl Applications", by Don Libes, Proceedings of the 1993 Tcl/Tk Workshop, Berkeley, CA, June 10-11, 1993.

Author

Don Libes, National Institute of Standards and Technology

Acknowledgments

Thanks to John Ousterhout for Tcl, and Scott Paisley for inspiration. Thanks to Rob Savoye for Expect's autoconfiguration code.

The HISTORY file documents much of the evolution of expect. It makes interesting reading and might give you further insight to this software. Thanks to the people mentioned in it who sent me bug fixes and gave other assistance.

Design and implementation of Expect was paid for in part by the U.S. government and is therefore in the public domain. However the author and NIST would like credit if this program and documentation or portions of them are used.

Table of Contents

  • Name
  • Synopsis
  • Introduction
  • Usage
  • Commands
  • Libraries
  • Pretty-printing
  • Examples
  • Caveats
  • Bugs
  • Expect Hints
  • See Also
  • Author
  • Acknowledgments


expectk

 Table of Contents

Name

expectk - Expect with Tk support

Synopsis

expectk [ args ]

Introduction

Expectk is a combination of Expect with Tk. (See their respective man pages for a more comprehensive explanation of either.) Expectk should run any wish or Expect script (with minor changes - see below).

The differences between the Expectk and Expect environment follows.

The send command is Tk's. Expect's send command can be invoked by the name exp_send. (For compatibility, Expect allows either send or exp_send to be used.)

Scripts may be invoked implicitly on systems which support the #! notation by marking the script executable, and making the first line in your script:

#!/usr/local/bin/expectk -f

Of course, the path must accurately describe where Expectk lives. /usr/local/bin is just an example.

Table of Contents

  • Name
  • Synopsis
  • Introduction


libexpect

 Table of Contents

Name

libexpect - programmed dialogue with interactive programs - C functions

Description

This library contains functions that allow Expect to be used as a Tcl extension or to be used directly from C or C++ (without Tcl). Adding Expect as a Tcl extension is very short and simple, so that will be covered first.

Synopsis

#include expect_tcl.h
Expect_Init(interp);

cc files... -lexpect5.20 -ltcl7.5 -lm

Note: library versions may differ in the actual release.

The Expect_Init function adds expect commands to the named interpreter. It avoids overwriting commands that already exist, however aliases beginning with «exp_» are always created for expect commands. So for example, «send» can be used as «exp_send".

Generally, you should only call Expect commands via Tcl_Eval. Certain auxiliary functions may be called directly. They are summarized below. They may be useful in constructing your own main. Look at the file exp_main_exp.c in the Expect distribution as a prototype main. Another prototype is tclAppInit.c in the Tcl source distribution. A prototype for working with Tk is in exp_main_tk.c in the Expect distribution.

int exp_cmdlinecmds;
int exp_interactive;
FILE *exp_cmdfile;
char *exp_cmdfilename;
int exp_tcl_debugger_available;

void exp_parse_argv(Tcl_Interp *,int argc,char **argv);
int exp_interpreter(Tcl_Interp *);
void exp_interpret_cmdfile(Tcl_Interp *,FILE *);
void exp_interpret_cmdfilename(Tcl_Interp *,char *);
void exp_interpret_rcfiles(Tcl_Interp *,int my_rc,int sys_rc);

char *
   exp_cook(char *s,int *len);
void (*exp_app_exit)EXP_PROTO((Tcl_Interp *);
void exp_exit(Tcl_Interp *,int status);
void exp_exit_handlers(Tcl_Interp *);
void exp_error(Tcl_Interp,char *,...);

exp_cmdlinecmds is 1 if Expect has been invoked with commands on the program command-line (using «-c» for example). exp_interactive is 1 if Expect has been invoked with the -i flag or if no commands or script is being invoked. exp_cmdfile is a stream from which Expect will read commands. exp_cmdfilename is the name of a file which Expect will open and read commands from. exp_tcl_debugger_available is 1 if the debugger has been armed.

exp_parse_argv reads the representation of the command line. Based on what is found, any of the other variables listed here are initialized appropriately. exp_interpreter interactively prompts the user for commands and evaluates them. exp_interpret_cmdfile reads the given stream and evaluates any commands found. exp_interpret_cmdfilename opens the named file and evaluates any commands found. exp_interpret_rcfiles reads and evalutes the .rc files. If my_rc is zero, then ~/.expectrc is skipped. If sys_rc is zero, then the system-wide expectrc file is skipped. exp_cook returns a static buffer containing the argument reproduced with newlines replaced by carriage-return linefeed sequences. The primary purpose of this is to allow messages to be produced without worrying about whether the terminal is in raw mode or cooked mode. If length is zero, it is computed via strlen. exp_error is a printf-like function that writes the result to interp->result.

Synopsis

#include <expect.h>

int
exp_spawnl(file, arg0 [, arg1, ..., argn] (char *)0);
char *file;
char *arg0, *arg1, ... *argn;

int
exp_spawnv(file,argv);
char *file, *argv[ ];

int
exp_spawnfd(fd);
int fd;

FILE *
exp_popen(command); char *command;

extern int exp_pid;
extern int exp_ttyinit;
extern int exp_ttycopy;
extern int exp_console;
extern char *exp_stty_init;
extern void (*exp_close_in_child)();
extern void (*exp_child_exec_prelude)();
extern void exp_close_tcl_files();
cc files... -lexpect -ltcl -lm

Description

exp_spawnl and exp_spawnv fork a new process so that its stdin, stdout, and stderr can be written and read by the current process. file is the name of a file to be executed. The arg pointers are null-terminated strings. Following the style of execve(), arg0 (or argv[0]) is customarily a duplicate of the name of the file.

Four interfaces are available, exp_spawnl is useful when the number of arguments is known at compile time. exp_spawnv is useful when the number of arguments is not known at compile time. exp_spawnfd is useful when an open file descriptor is already available as a source. exp_popen is explained later on.

If the process is successfully created, a file descriptor is returned which corresponds to the process's stdin, stdout and stderr. A stream may be associated with the file descriptor by using fdopen(). (This should almost certainly be followed by setbuf() to unbuffer the I/O.)

Closing the file descriptor will typically be detected by the process as an EOF. Once such a process exits, it should be waited upon (via wait) in order to free up the kernel process slot. (Some systems allow you to avoid this if you ignore the SIGCHLD signal).

exp_popen is yet another interface, styled after popen(). It takes a Bourne shell command line, and returns a stream that corresponds to the process's stdin, stdout and stderr. The actual implementation of exp_popen below demonstrates exp_spawnl.

FILE *
exp_popen(program)

char *program;
{
FILE *fp;
int ec;

if (0 > (ec = exp_spawnl("sh","sh","-c",program,(char *)0)))
return(0);
if (NULL == (fp = fdopen(ec,"r+")) return(0);
setbuf(fp,(char *)0);
return(fp);
}

After a process is started, the variable exp_pid is set to the process-id of the new process. The variable exp_pty_slave_name is set to the name of the slave side of the pty.

The spawn functions uses a pty to communicate with the process. By default, the pty is initialized the same way as the user's tty (if possible, i.e., if the environment has a controlling terminal.) This initialization can be skipped by setting exp_ttycopy to 0.

The pty is further initialized to some system wide defaults if exp_ttyinit is non-zero. The default is generally comparable to «stty sane".

The tty setting can be further modified by setting the variable exp_stty_init. This variable is interpreted in the style of stty arguments. For example, exp_stty_init = «sane"; repeats the default initialization.

On some systems, it is possible to redirect console output to ptys. If this is supported, you can force the next spawn to obtain the console output by setting the variable exp_console to 1.

Between the time a process is started and the new program is given control, the spawn functions can clean up the environment by closing file descriptors. By default, the only file descriptors closed are ones internal to Expect and any marked «close-on-exec".

If needed, you can close additional file descriptors by creating an appropriate function and assigning it to exp_close_in_child. The function will be called after the fork and before the exec. (This also modifies the behavior of the spawn command in Expect.)

If you are also using Tcl, it may be convenient to use the function exp_close_tcl_files which closes all files between the default standard file descriptors and the highest descriptor known to Tcl. (Expect does this.)

The function exp_child_exec_prelude is the last function called prior to the actual exec in the child. You can redefine this for effects such as manipulating the uid or the signals.

If You Want to Allocate Your Own Pty

extern int exp_autoallocpty;
extern int exp_pty[2];

The spawn functions use a pty to communicate with the process. By default, a pty is automatically allocated each time a process is spawned. If you want to allocate ptys yourself, before calling one of the spawn functions, set exp_autoallocpty to 0, exp_pty[0] to the master pty file descriptor and exp_pty[1] to the slave pty file descriptor. The expect library will not do any pty initializations (e.g., exp_stty_init will not be used). The slave pty file descriptor will be automatically closed when the process is spawned. After the process is started, all further communication takes place with the master pty file descriptor.

exp_spawnl and exp_spawnv duplicate the shell's actions in searching for an executable file in a list of directories. The directory list is obtained from the environment.

Expect Processing

While it is possible to use read() to read information from a process spawned by exp_spawnl or exp_spawnv, more convenient functions are provided. They are as follows:

int
exp_expectl(fd,type1,pattern1,[re1,],value1,type2,...,exp_end);
int fd;
enum exp_type type;
char *pattern1, *pattern2, ...;
regexp *re1, *re2, ...;
int value1, value2, ...;

int
exp_fexpectl(fp,type1,pattern1,[re1,]value1,type2,...,exp_end);
FILE *fp;
enum exp_type type;
char *pattern1, *pattern2, ...;
regexp *re1, *re2, ...;
int value1, value2, ...;

enum exp_type {
exp_end,
exp_glob,
exp_exact,
exp_regexp,
exp_compiled,
exp_null,
};

struct exp_case {
char *pattern;
regexp *re;
enum exp_type type;
int value;
};

int
exp_expectv(fd,cases);
int fd;
struct exp_case *cases;

int
exp_fexpectv(fp,cases);

FILE *fp;
struct exp_case *cases;

extern int exp_timeout;
extern char *exp_match;
extern char *exp_match_end;
extern char *exp_buffer;
extern char *exp_buffer_end;
extern int exp_match_max;
extern int exp_full_buffer;
extern int exp_remove_nulls;

The functions wait until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen.

The first argument to each function is either a file descriptor or a stream. Successive sets of arguments describe patterns and associated integer values to return when the pattern matches.

The type argument is one of four values. exp_end indicates that no more patterns appear. exp_glob indicates that the pattern is a glob-style string pattern. exp_exact indicates that the pattern is an exact string. exp_regexp indicates that the pattern is a regexp-style string pattern. exp_compiled indicates that the pattern is a regexp-style string pattern, and that its compiled form is also provided. exp_null indicates that the pattern is a null (for debugging purposes, a string pattern must also follow).

If the compiled form is not provided with the functions exp_expectl and exp_fexpectl, any pattern compilation done internally is thrown away after the function returns. The functions exp_expectv and exp_fexpectv will automatically compile patterns and will not throw them away. Instead, they must be discarded by the user, by calling free on each pattern. It is only necessary to discard them, the last time the cases are used.

Regexp subpatterns matched are stored in the compiled regexp. Assuming «re» contains a compiled regexp, the matched string can be found in re->startp[0]. The match substrings (according to the parentheses) in the original pattern can be found in re->startp[1], re->startp[2], and so on, up to re->startp[9]. The corresponding strings ends are re->endp[x] where x is that same index as for the string start.

The type exp_null matches if a null appears in the input. The variable exp_remove_nulls must be set to 0 to prevent nulls from being automatically stripped. By default, exp_remove_nulls is set to 1 and nulls are automatically stripped.

exp_expectv and exp_fexpectv are useful when the number of patterns is not known in advance. In this case, the sets are provided in an array. The end of the array is denoted by a struct exp_case with type exp_end. For the rest of this discussion, these functions will be referred to generically as expect.

If a pattern matches, then the corresponding integer value is returned. Values need not be unique, however they should be positive to avoid being mistaken for EXP_EOF, EXP_TIMEOUT, or EXP_FULLBUFFER. Upon EOF or timeout, the value EXP_EOF or EXP_TIMEOUT is returned. The default timeout period is 10 seconds but may be changed by setting the variable exp_timeout. A value of -1 disables a timeout from occurring. A value of 0 causes the expect function to return immediately (i.e., poll) after one read(). However it must be preceded by a function such as select, poll, or an event manager callback to guarantee that there is data to be read.

If the variable exp_full_buffer is 1, then EXP_FULLBUFFER is returned if exp_buffer fills with no pattern having matched.

When the expect function returns, exp_buffer points to the buffer of characters that was being considered for matching. exp_buffer_end points to one past the last character in exp_buffer. If a match occurred, exp_match points into exp_buffer where the match began. exp_match_end points to one character past where the match ended.

Each time new input arrives, it is compared to each pattern in the order they are listed. Thus, you may test for absence of a match by making the last pattern something guaranteed to appear, such as a prompt. In situations where there is no prompt, you must check for EXP_TIMEOUT (just like you would if you were interacting manually). More philosophy and strategies on specifying expect patterns can be found in the documentation on the expect program itself. See SEE ALSO below.

Patterns are the usual C-shell-style regular expressions. For example, the following fragment looks for a successful login, such as from a telnet dialogue.

switch (exp_expectl(
exp_glob,"connected",CONN,
exp_glob,"busy",BUSY,
exp_glob,"failed",ABORT,
exp_glob,"invalid password",ABORT, exp_end)) {

case CONN:
/* logged in successfully */

break;

case BUSY:
/* couldn't log in at the moment */ break; case EXP_TIMEOUT:
case ABORT:
/* can't log in at any moment! */ break; default: /* problem with expect */ }

Asterisks (as in the example above) are a useful shorthand for omitting line-termination characters and other detail. Patterns must match the entire output of the current process (since the previous read on the descriptor or stream). More than 2000 bytes of output can force earlier bytes to be «forgotten". This may be changed by setting the variable exp_match_max. Note that excessively large values can slow down the pattern matcher.

Running in the Background

extern int exp_disconnected;
int exp_disconnect();

It is possible to move a process into the background after it has begun running. A typical use for this is to read passwords and then go into the background to sleep before using the passwords to do real work.

To move a process into the background, fork, call exp_disconnect() in the child process and exit() in the parent process. This disassociates your process from the controlling terminal. If you wish to move a process into the background in a different way, you must set the variable exp_disconnected to 1. This allows processes spawned after this point to be started correctly.

Multiplexing

By default, the expect functions block inside of a read on a single file descriptor. If you want to wait on patterns from multiple file descriptors, use select, poll, or an event manager. They will tell you what file descriptor is ready to read.

When a file descriptor is ready to read, you can use the expect functions to do one and only read by setting timeout to 0.

Slave Control

void
exp_slave_control(fd,enable)
int fd;
int enable;

Pty trapping is normally done automatically by the expect functions. However, if you want to issue an ioctl, for example, directly on the slave device, you should temporary disable trapping.

Pty trapping can be controlled with exp_slave_control. The first argument is the file descriptor corresponding to the spawned process. The second argument is a 0 if trapping is to be disabled and 1 if it is to be enabled.

Errors

All functions indicate errors by returning -1 and setting errno.

Errors that occur after the spawn functions fork (e.g., attempting to spawn a non-existent program) are written to the process's stderr, and will be read by the first expect.

Signals

extern int exp_reading;
extern jmp_buf exp_readenv;

expect uses alarm() to timeout, thus if you generate alarms during expect, it will timeout prematurely.

Internally, expect calls read() which can be interrupted by signals. If you define signal handlers, you can choose to restart or abort expect's internal read. The variable, exp_reading, is true if (and only if) expect's read has been interrupted. longjmp(exp_readenv,EXP_ABORT) will abort the read. longjmp(exp_readenv,EXP_RESTART) will restart the read.

Logging

extern int exp_loguser;
extern int exp_logfile_all
extern FILE *exp_logfile;

If exp_loguser is nonzero, expect sends any output from the spawned process to stdout. Since interactive programs typically echo their input, this usually suffices to show both sides of the conversation. If exp_logfile is also nonzero, this same output is written to the stream defined by exp_logfile. If exp_logfile_all is non-zero, exp_logfile is written regardless of the value of exp_loguser.

Debugging

While I consider the library to be easy to use, I think that the standalone expect program is much, much, easier to use than working with the C compiler and its usual edit, compile, debug cycle. Unlike typical C programs, most of the debugging isn't getting the C compiler to accept your programs - rather, it is getting the dialogue correct. Also, translating scripts from expect to C is usually not necessary. For example, the speed of interactive dialogues is virtually never an issue. So please try the standalone `expect' program first. I suspect it is a more appropriate solution for most people than the library.

Nonetheless, if you feel compelled to debug in C, here are some tools to help you.

extern int exp_is_debugging;
extern FILE *exp_debugfile;

While expect dialogues seem very intuitive, trying to codify them in a program can reveal many surprises in a program's interface. Therefore a variety of debugging aids are available. They are controlled by the above variables, all 0 by default.

Debugging information internal to expect is sent to stderr when exp_is_debugging is non-zero. The debugging information includes every character received, and every attempt made to match the current input against the patterns. In addition, non-printable characters are translated to a printable form. For example, a control-C appears as a caret followed by a C. If exp_logfile is non-zero, this information is also written to that stream.

If exp_debugfile is non-zero, all normal and debugging information is written to that stream, regardless of the value of exp_is_debugging.

Caveats

The stream versions of the expect functions are much slower than the file descriptor versions because there is no way to portably read an unknown number of bytes without the potential of timing out. Thus, characters are read one at a time. You are therefore strongly encouraged to use the file descriptor versions of expect (although, automated versions of interactive programs don't usually demand high speed anyway).

You can actually get the best of both worlds, writing with the usual stream functions and reading with the file descriptor versions of expect as long as you don't attempt to intermix other stream input functions (e.g., fgetc). To do this, pass fileno(stream) as the file descriptor each time. Fortunately, there is little reason to use anything but the expect functions when reading from interactive programs.

There is no matching exp_pclose to exp_popen (unlike popen and pclose). It only takes two functions to close down a connection (fclose() followed by waiting on the pid), but it is not uncommon to separate these two actions by large time intervals, so the function seems of little value.

If you are running on a Cray running Unicos (all I know for sure from experience), you must run your compiled program as root or setuid. The problem is that the Cray only allows root processes to open ptys. You should observe as much precautions as possible: If you don't need permissions, setuid(0) only immediately before calling one of the spawn functions and immediately set it back afterwards.

Normally, spawn takes little time to execute. If you notice spawn taking a significant amount of time, it is probably encountering ptys that are wedged. A number of tests are run on ptys to avoid entanglements with errant processes. (These take 10 seconds per wedged pty.) Running expect with the -d option will show if expect is encountering many ptys in odd states. If you cannot kill the processes to which these ptys are attached, your only recourse may be to reboot.

Bugs

The exp_fexpect functions don't work at all under HP-UX it appears to be a bug in getc. Follow the advice (above) about using the exp_expect functions (which doesn't need to call getc). If you fix the problem (before I do please check the latest release) let me know.

See Also

An alternative to this library is the expect program. expect interprets scripts written in a high-level language which direct the dialogue. In addition, the user can take control and interact directly when desired. If it is not absolutely necessary to write your own C program, it is much easier to use expect to perform the entire interaction. It is described further in the following references:

«expect: Curing Those Uncontrollable Fits of Interactiv_ity" by Don Libes, Proceedings of the Summer 1990 USENIX Conference, Anaheim, California, June 11-15, 1990.

«Using expect to Automate System Administration Tasks» by Don Libes, Proceedings of the 1990 USENIX Large Installation Systems Administration Conference, Colorado Springs, Colorado, October 17-19, 1990.

expect(1)
, alarm(3)
, read(2)
, write(2)
, fdopen(3)
,
execve(2)
, execvp(3)
, longjmp(3)
, pty(4)
.

There are several examples C programs in the test directory of expect's source distribution which use the expect library.

Author

Don Libes, libes@nist.gov, National Institute of Standards and Technology

Acknowledgements

Thanks to John Ousterhout (UCBerkeley) for supplying the pattern matcher.

Design and implementation of the expect library was paid for by the U.S. government and is therefore in the public domain. However the author and NIST would like credit if this program and documentation or portions of them are used.

Table of Contents

  • Name
  • Description
  • Synopsis
  • Synopsis
  • Description
  • If You Want to Allocate Your Own Pty
  • Expect Processing
  • Running in the Background
  • Multiplexing
  • Slave Control
  • Errors
  • Signals
  • Logging
  • Debugging
  • Caveats
  • Bugs
  • See Also
  • Author
  • Acknowledgements


Img Documentation

Img Manual

Introduction Installation Format handlers External libraries

Format handlers

The pixmap image type can be used as follows:
image create pixmap -file
or
image create pixmap -data ;#(in XPM format)
The photo image type works the same:
image create photo -file
or
image create photo -data ;#(base-64 encoding required with Tk8.2 and lower)

Valid format specifiers for reading photo's:

"bmp" |
"gif -index <n>" |
"jpeg -fast -grayscale" |
"png" |
"tiff" |
"xbm" |
"xpm" |
"postscript -index <n> -zoom <x> <y>" | (-index not yet implemented)
"window" | (works only with "-data", not "-file")

Valid format specifiers for writing photo's:

"bmp" |
"gif -interlaced <bool>" | (-interlaced not yet implemented)
"jpeg -quality <n> -smooth <n> -grayscale -optimize -progressive" |
"png Author <name> Title <title> Description ....." Each pair of arguments will add a named text chunk to the file. |
"tiff -compression <compression> -byteorder <byteorder>" |
"xbm" |
"xpm" |

The format options have the following meaning:

-background C: | use color C as background color for transparent parts of the image.
-byteorder: | Byteorder for TIFF file. Should be one of bigendian, littleendian, network, smallendian or {}. Default: {}
-compression: | Compression for TIFF file. Should be one of none, jpeg, packbits or deflate. Default: none.
-fast: | Fast, low-quality processing.
-grayscale: | Force incoming image to grayscale/ Create monochrome file.
-index N: | Select one of the sub-images (GIF and postscript only, not yet implemented for postscript). Default value: 0
-interlaced N: | N=1: interlaced. N=0: non-interlaced (not yet implemented).
-optimize: | Optimize Huffman table.
-progressive: | Create progressive file (JPEG only).
-quality N: | Compression quality (0..100; 5-95 is useful range). Default value: 75
-smooth N: | Perform smoothing (10-30 is enough for most GIF's). Default value: 0
-zoom X Y: | Multiply image size by given scale factors. If Y is missing, the default is the same as X. X and Y are allowed to be in floating point format, but they are rounded to the nearest practically possible value. For postscript this means the zoom factors should be multiples of 1/72.


Img Documentation

Img Manual

Introduction Installation Format handlers External libraries

Installation

For Windows, just run the executable.

For UNIX, you have to compile the sources yourself, but that shouldn't give you many problems. In the future, hopefully, binary distributions for various UNIX systems will become available as well.

Configure

The source distributions have "configure", which has the following possibilities:

 | configure ?options? |
Some possible options:
 | --prefix=<dir> | Install headers in <dir>/include. Default: "/usr/local"
 | --exec-prefix=<dir> | Install libraries in <dir>/lib. Default: "${prefix}"
 | --with-tcl=<dir> | Find Tcl libraries in <dir> and include files in <dir>/../include or <dir>/../generic. Default: "${exec-prefix}/lib" or a sibling directory of the Img build directory.
 | --with-tk=<dir> | Find Tk libraries in <dir> and include files in <dir>/../include or <dir>/../generic. Default: the same values as given by --with-tcl or a sibling directory of the Img build directory.
 | --disable-shared | Force the creation of static libraries.
 | --disable-stubs | Disable stub support. This is necessary if you want to run Img 1.2 with Tcl/Tk 8.0 up to 8.0.5.

Configuration of libz, libpng, libtiff, libjpeg and libttf will be done automatically.

make

By default only libimg1.2.so will be built. Further on:

make | build libimg1.2.so only
make z | build libz.so.1.1.3
make png | build libpng.so.2.1.0.7
make jpeg | build libjpeg.so.62.0.0
make tiff | build libtiff.so.3.5.5
make all | build all of above
make test | run tests for all image formats.

Best is to start with "make". If a test fails for one of the PNG, JPEG or TIFF formats, the error message will indicate what is wrong. If a library is missing in your system, you can always build it later. If a crash occurs, this might also indicate that you better upgrade one of these libraries.

If you prefer to use different versions numbers after the extension, you can manually adapt the Makefile. On Irix, you can use the "ifl" libraries which are already part of the operating system. The top of the Makefile shows which file names to use.

Install (source distributions only)

You can install whatever you like:

make install | install libimg1.2.so only
make install-z | install libz.so.1.1.3
make install-png | install libpng.so.2.1.0.7
make install-jpeg | install libjpeg.so.62.0.0
make install-tiff | install libtiff.so.3.5.5
make install-all | install all of above

Use

If you want to use the new image formats to be available in your own scripts, add the following line somewhere in your script:

package require Img

This will load the library into memory and register the format handlers into Tk.

As an example, have a look at the file "demo.tcl"


Img Documentation

Img Manual

Introduction Installation Format handlers External libraries

External libraries

Included in this distribution are the most recent versions (as of july 2000) of the libz, libpng, libjpeg and libtiff libraries. These are not required for compilation of libimg, unless you need support for the PNG, JPEG or TIFF formats. If your system already has shared libraries for these formats, probably it will already work with this package. Otherwise the tools are here to build it any time later.

If your system already has later versions than the ones distributed together with Img, it is recommended that you always use the latest available version. In the case of JPEG no promise is made that future versions of the JPEG library keep binary compatiblility, so it might be that you need to recompile Img using the latest JPEG header files. If you don't want the trouble of recompiling Img, it's problably best to stick with libjpeg 6b.

If you want more information about the external libraries, all of them have the latest information readily available on the internet. Img uses unmodified versions of those libraries, except that it provides its own set of makefiles. The reason for this is that not all libraries supply very good support for building them as a shared library. But if you already have them available as a shared library, there should be no need to rebuild them. Here is an overview.

zlib
http://www.info-zip.org/pub/infozip/zlib/
libpng
http://www.libpng.org/pub/png/
libtiff
http://www.libtiff.org/
libjpeg
ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz
ghostscript (needed for Postscipt reading)
http://www.cs.wisc.edu/~ghost/

If you have a problems with any of those libraries, please first try to recompile them using the makefiles supplied by Img. If that works, it's an indication that something is wrong with the original distribution of the libraries, and you better report it to the instance where you got it.


NAME

Snack_AddSubCmd - add a new sub-command to a Snack object command

SYNOPSIS

#include <snack.h>
Snack_AddSubCmd(snackCmd, cmdName, cmdProc, delCmdProc)

ARGUMENTS

int snackCmd (in)
A flag specifying which command category the new sub-command belongs to. Valid values are SNACK_SOUND_CMD, SNACK_MIXER_CMD, or SNACK_AUDIO_CMD.

char *cmdName (in)
Name of the new sub-command.

Snack_CmdProc *cmdProc (in)
Implementation of the new sub-command. cmdProc will be called whenever cmdName is invoked as a sub-command.

Snack_DelCmdProc *delCmdProc (in)
Procedure to invoke before deleting the object command.

DESCRIPTION

Snack_AddSubCmd defines a new sub-command for a Snack object command and associates with it procedure cmdProc, such that whenever cmdName is invoked as a sub-command (e.g., via a call to Tcl_EvalObj) the Tcl interpreter will call cmdProc to process the command. New sound sub-commands must call Snack_GetSound() to determine which sound they invoked on. delCmdProc is called during clean-up when unloading the extension.


Callback

NAME

Snack_AddCallback, Snack_RemoveCallback, Snack_ExecCallbacks - track changes to Snack sound objects

SYNOPSIS

#include <snack.h>
Snack_AddCallback(sound, procedure, clientData)
Snack_RemoveCallback(sound, id)
Snack_ExecCallbacks(sound, flag)

ARGUMENTS

Sound *sound (in)
Sound object to attach the callback to.
updateProc *procedure (in)
Procedure to invoke when the sound data changes.
ClientData *clientData (in)
Arbitrary one-word value to pass to procedure.
int id (in)
Unique identifer for the callback.
int flag (in)
Flag which specifies how the sound changed.

DESCRIPTION

Snack_AddCallback adds a callback procedure to sound, that will be called whenever its content changes. It returns an id number that can be used by Snack_RemoveCallback to remove the callback. The clientData parameter to procedure is a copy of the clientData argument given to Snack_AddCallback when
the callback was created. Typically, clientData points to a data structure containing application-specific
information about what to do in procedure.
Snack_ExecCallbacks is used in sub-commands so that changes to a sound can be tracked for example Snack´s canvas item types. The flag specifies whether all sound data has changed (SNACK_NEW_SOUND) or if new data has been appended (SNACK_MORE_DATA).


CreateFilter

NAME

Snack_CreateFilterType - define new filter type

SYNOPSIS

#include <snack.h>
Snack_CreateFilterType(filterType)

ARGUMENTS

Snack_FilterType *filterType

struct Snack_FilterType {
char
*name;
createProc    *createProc;
configProc     *configProc;
startProc       *startProc;
flowProc        *flowProc;
freeProc         *freeProc;
struct Snack_FilterType *nextPtr;
} Snack_FilterType;

char *name

Snack_Filter createProc (Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])

int configProc (Snack_Filter f, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])

int startProc (Snack_Filter f, Snack_StreamInfo si)

int flowProc (Snack_Filter f, Snack_StreamInfo si, float *inBuffer, float *outBuffer, int *inFrames, int *outFrames)

void freeProc (Snack_Filter f)

DESCRIPTION

Snack_CreateFilterType is used to define a new kind of filter type. Everything regarding filters is still under development. The source code itself is currently the only source of information.

Some helpful notes on the current implementation:

inFrames specifies how many samples exist in inBuffer. This value can be modified to specify how many samples were actually consumed.

outFrames is an upper bound on how many samples that may be written to outBuffer.

flowProc should start to drain out any samples as soon as inFrames < outFrames.

If the return value of outFrames is less than the original, the procedure will not be called again. Internal clean-up can be performed in this case.

The parameters inBuffer and outBuffer may point to the same memory. In some cases it might be neccessary to make local copies of samples during calculations.

configProc can be called at any time.

inBuffer can be NULL if inSize is 0.


FileFormat

NAME

Snack_CreateFileFormat - define new sound file format

SYNOPSIS

#include <snack.h>
Snack_CreateFileFormat(format)

ARGUMENTS

Snack_FileFormat *format

typedef struct Snack_FileFormat {
char
*name;
guessFileTypeProc      *guessProc;
getHeaderProc
*getHeaderProc;
extensionFileTypeProc *extProc;
putHeaderProc
*putHeaderProc;
openProc
*openProc;
closeProc
*closeProc;
readSamplesProc
*readProc;
writeSamplesProc
*writeProc;
seekProc
*seekProc;
freeHeaderProc
*freeHeaderProc;
configureProc            *configureProc;
struct Snack_FileFormat *nextPtr;
} Snack_FileFormat;

char *name

char *guessFileTypeProc (char *buf, int len)

int getHeaderProc (Sound *s, Tcl_Interp *interp, Tcl_Channel ch, Tcl_Obj *obj, char *buf)

char *extensionFileTypeProc (char *buf);

int putHeaderProc (Sound *s, Tcl_Interp *interp, Tcl_Channel ch, Tcl_Obj *obj, int objc, Tcl_Obj *CONST objv[], int length)

int openProc (Sound *s, Tcl_Interp *interp,Tcl_Channel *ch, char *mode)

int closeProc (Sound *s, Tcl_Interp *interp, Tcl_Channel *ch)

int readSamplesProc (Sound *s, Tcl_Interp *interp, Tcl_Channel ch, char *inBuffer, float *outBuffer, int length)

int writeSamplesProc (Sound *s, Tcl_Channel ch, Tcl_Obj *obj, int start, int length)

int seekProc (Sound *s, Tcl_Interp *interp, Tcl_Channel ch, int position)

void freeHeaderProc (Sound *s)

int configureProc(Sound *s, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])

DESCRIPTION

Snack_CreateFileFormat is used to define a new kind of sound file format. A number of procedures can be specified in a Snack_FileFormat structure to handle sound data I/O, header parsing, etc. The file SphereFile.c serves as good example of how these routines are intended to be used.

The string name will be returned as the result of a successful read command.

guessFileTypeProc is invoked by Snack in order to find out if the current file is of a type which this handler recognizes. guessFileTypeProc will receive buffer filled with bytes from the header up to length and if it recognizes the format is should return formatName. If it can't make a decision after seeing only length bytes it should return the string QUE_STRING. It will subsequently be invoked again with some more bytes for a new try. If the file is clearly in another format guessFileTypeProc should return NULL.

extensionFileTypeProc takes a filename string and returns formatName if its file name extension matches its format else it return NULL. This is used when saving a sound object using a filename to guess which format it should be saved with. If no save functionality is needed and extensionFileTypeProc is specified as NULL, a raw file will be saved using filename, which could be confusing. By providing an extensionFileTypeProc for the format Snack will be able to report "unsupported save format".

getHeaderProc is invoked in order to decode a sound file header. If the sound file resides on disk ch will be a a channel opened for reading, otherwise it will be NULL. If the sound resides in memory obj will point to a binary Tcl variable containing the data of the sound file, otherwise it will be NULL. The procedure should use these macros to specify the properties of the sound file
Snack_SetSampleRate()
Snack_SetNumChannels()
Snack_SetSampleEncoding()
Snack_SetBytesPerSample()
Snack_SetHeaderSize()
Snack_SetLength()
On success getHeaderProc should TCL_OK, otherwise it should return TCL_ERROR and leave an error message in the Tcl result.

putHeaderProc is invoked in order to decode a sound file header. If the sound file is to be written to disk, ch will point to a channel opened for writing, otherwise it will be NULL. If the sound file is to be written to a Tcl binary variable, obj will point to a Tcl Obj, otherwise it will be NULL. The length argument will contain the length of the sound data in sample frames.

openProc, closeProc, readSamplesProc, writeSamplesProc, and seekProc are modelled after their Tcl channel equivalents. readSamplesProc should read data either from ch or inBuffer which ever is not equal to NULL. The length argument is given in samples (not frames) and the return value is the number of samples read (or -1 if an error occurred). seekProc should seek in the sound file to the sample frame given by the position argument.

freeHeaderProc is called when a new file is read into a sound object or when it is destroyed. It is used to deallocate ant memory which might have been allocated earlier in, e.g., openProc.


SampConv

NAME

Snack_Mulaw2Lin, Snack_Alaw2Lin, Snack_Lin2Mulaw, Snack_Lin2Alaw, Snack_SwapShort - convert samples

SYNOPSIS

#include <snack.h>
Snack_Mulaw2Lin(u_val)
Snack_Lin2Mulaw(pcm_val)
Snack_Alaw2Lin(a_val)
Snack_Lin2Alaw(pcm_val)
Snack_SwapShort(short_val)

ARGUMENTS

unsigned char u_val (in)
unsigned char a_val (in)
int pcm_val (in)
short short_val (in)

DESCRIPTION

Snack_Mulaw2Lin converts an 8-bit MULAW sample into a 16-bit linear value (LIN16).
Snack_Lin2Mulaw converts a 16-bit linear value (LIN16) into an 8-bit MULAW sample.
Snack_Alaw2Lin converts an 8-bit ALAW sample into a 16-bit linear value (LIN16).
Snack_Lin2Alaw converts a 16-bit linear value (LIN16) into an 8-bit ALAW sample.
Snack_SwapShort swaps the high and low bytes of a 16-bit linear sample.


Snack library

Snack library functions

This is the public API of Snack to be used by C/C++-level extensions. The functions are contained in Snack's stub library, libsnackstub2.1.a (unix), snackstub21.lib (win). Linking with this will make your extension usable with different versions of Snack without recompilation.

Snack_AddCallback

Snack_AddSubCmd

Snack_Alaw2Lin

Snack_CreateFilterType

Snack_CreateFileFormat

Snack_DeleteSound

Snack_ExecCallbacks

Snack_GetBytesPerSample

Snack_GetFrequency

Snack_GetLength

Snack_GetNumChannels

Snack_GetSample

Snack_GetSampleFormat

Snack_GetSound

Snack_GetSoundData

Snack_GetSoundFilename

Snack_Lin2Alaw

Snack_Lin2Mulaw

Snack_Mulaw2Lin

Snack_NewSound

Snack_PutSoundData

Snack_RemoveCallback

Snack_ResizeSoundStorage

Snack_SetBytesPerSample

Snack_SetFrequency

Snack_SetHeaderSize

Snack_SetLength

Snack_SetNumChannels

Snack_SetSample

Snack_SetSampleFormat

Snack_SwapShort

Snack_UpdateExtremes

Snack home


SoundData

NAME

Snack_PutSoundData, Snack_GetSoundData - transfer sound data between a buffer and a Snack sound

SYNOPSIS

#include <snack.h>
Snack_PutSoundData(sound, position, buffer, nSamples)
Snack_GetSoundData(sound, position, buffer, nSamples)

ARGUMENTS

Sound *sound (in)
int position (in)
void *buffer (in)
int nSamples (in)

DESCRIPTION

Snack_PutSoundData transfers nSamples samples of sound data from buffer into a Snack sound at specified position. The buffer data is expected to be in float or double format depending on the precision of the Snack sound.
The sound must be of storage type SOUND_IN_MEMORY, i.e. the sound sample data must reside in memory. Snack_GetSoundData transfers data from the Snack sound to the buffer. These functions work both with memory resident sounds and sounds linked to disk files (SOUND_IN_MEMORY and SOUND_IN_FILE). The buffer data is returned in float or double format depending on the precision of the Snack sound.


SoundObj

NAME

Snack_NewSound, Snack_DeleteSound, Snack_GetSound, Snack_ResizeSoundStorage,
Snack_UpdateExtremes - manipulate Snack sound objects

SYNOPSIS

#include <snack.h>

Snack_NewSound(frequency, format, nChannels)
Snack_DeleteSound(sound)
Snack_GetSound(interp, name)
Snack_ResizeSoundStorage(sound, length)
Snack_UpdateExtremes(sound, start, end, flag)

ARGUMENTS

int frequency (in)
Sampling frequency of the new sound object
int format (in)
Sample encoding format of the new sound object
int nChannels (in)
Number of channels of the new sound object
Sound *sound (in)
Pointer to a Snack sound object
Tcl_Interp *interp (in)
char *name (in)
int length (in)
int start (in)
int end (in)
int flag (in)

DESCRIPTION

Snack_NewSound creates a new Snack sound object by allocating and initializing a sound struct. It takes the arguments frequency, sample encoding format and number of channels, nChannels. Snack_DeleteSound deallocates all storage associated with sound. Snack_GetSound returns a pointer to a Snack sound given its sound command name.
Snack_ResizeSoundStorage is used to set the storage associated with a sound to accomodate length samples. Memory is allocated or deallocated as necessary. Snack_UpdateExtremes scans the samples of sound from start to end and records the extremes in the sound struct. The flag is used to specify whether to reset the current recorded extremes before calculating new ones (SNACK_NEW_SOUND) or if they should be kept and possibly updated (SNACK_MORE_DATA).


SoundProp

NAME

Snack_GetSampleRate, Snack_SetSampleRate, Snack_GetSampleEncoding, Snack_SetSampleEncoding, Snack_GetNumChannels, Snack_SetNumChannels, Snack_GetBytesPerSample, Snack_SetBytesPerSample, Snack_GetSoundFilename, Snack_SetHeaderSize - macros to set/get properties of Snack sound objects

SYNOPSIS

#include <snack.h>
Snack_GetSampleRate(sound)
Snack_SetSampleRate(sound, frequency)
Snack_GetSampleEncoding(sound)
Snack_SetSampleEncoding(sound, format)
Snack_GetNumChannels(sound)
Snack_SetNumChannels(sound, numChannels)
Snack_GetBytesPerSample(sound)
Snack_SetBytesPerSample(sound, size)
Snack_SetHeaderSize(sound, size)
Snack_GetSoundFilename(sound)

ARGUMENTS

Sound *sound (in)
A pointer to a sound object to query or modify
int frequency (in)
A positive integer specifying the sample rate of the sound.
int format (in)
An integer used to specify sample encoding format. Use one of these definitions LIN16, MULAW, ALAW, LIN8OFFSET, LIN8, LIN24, LIN32, SNACK_FLOAT, or SNACK_DOUBLE
int numChannels (in)
A positive integer specifying the number of separate channels of a sound
int size (in)
A size specification measured in bytes

DESCRIPTION

The following functions are implemented as macros. Snack_GetLength returns the length of a sound in number of frames, for mono sounds this is equal to the number of samples. Snack_SetLength is used to specify the length of the sound. No storage is allocated/freed as a result of this, the function Snack_ResizeSoundStorage must be used to the perform actual storage management. Snack_GetFrequency and Snack_SetFrequency control the sampling frequency of a Snack sound object. Most audio devices only allow certain specific values for playback and recording. Common values are 8000, 11025, 16000, 22050, 32000, 44100, and 48000. Snack_GetNumChannels and Snack_SetNumChannels handle the number of channels of the sound, either a positive integer or MONO/STEREO/QUAD. Snack_GetSampleFormat and Snack_SetSampleFormat control the sample encoding format. Use the constants LIN16, MULAW, ALAW, LIN8OFFSET, LIN8, LIN24, LIN32, SNACK_FLOAT, or SNACK_DOUBLE. Snack_GetBytesPerSample and Snack_SetBytesPerSample should be used in conjunction with the previous pair. For LIN16 the number of bytes per sample is 2. No checks are performed for any arguments to these functions. Snack_GetSoundFilename is used to retrieve a pointer to the filename string which is or last was associated with the sound object. Snack_SetHeaderSize is used, in code that defines new sound file formats, to specify how large (in bytes) the header of the sound file is.


SoundSamp

NAME

Snack_GetSample, Snack_SetSample - macros to set/get sample values of Snack sound objects

SYNOPSIS

#include <snack.h>
Snack_GetSample(sound, channel, index)
Snack_SetSample(sound, channel, index, value)

ARGUMENTS

Sound *sound (in)
A pointer to a sound object to query or modify
int channel (in)
A positive index selecting a channel. 0 = left, 1 = right.
int index (in)
A positive index pointing to a sound sample
float value (in)
The sample value as a float.

DESCRIPTION

The following functions are implemented as macros for performance reasons. Snack_GetSample returns the sample value at index of channel. Snack_SetSample sets the sample at index of channel to value. No check is made that index, channel or value are valid values. These functions work only with memory resident sounds (SOUND_IN_MEMORY ). Block transfers can be accomplished more efficiently using the functions Snack_PutSoundData and Snack_GetSoundData.


Tcl/Tk Keywords - A

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

abort
break
above
Restack
absolute file name
filename
access mode
open
access point
OpenFileChnl
access position
seek, tell
add
incr, AddOption
alias
interp, safe, loadTk, CrtSlave
alloc
Alloc
allocation
Alloc
alpha
GetVersion
anchor
ConfigWidg, SetOptions
anchor position
GetAnchor
append
append, lappend, open, clipboard, DString, ListObj, SetResult, StringObj, Clipboard
application
dde, destroy, send, AppInit, Init, MainLoop, MainWin, SetAppName, Tk_Init
application name
tk
application-specific initialization
SourceRCFile, Tcl_Main, Tk_Main
argument
tclsh, proc, AppInit
arguments
ParseArgv
arithmetic
expr, tclvars
array
array, SetVar
aspect ratio
wm
association
AssocData
asynchronous event
Async
asynchronous I/O
fileevent
atom
winfo, GetUid, InternAtom
attributes
file, ConfigWind, WindowId
auto-exec
library
auto-load
library, packagens, pkgMkIndex
auto-loading
safe, loadTk
auto_mkindex
safe, loadTk
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - B

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

background
BackgdErr, DetachPids, 3DBorder
background error
bgerror, tkerror
backslash
Backslash, SplitList, Utf
backslash substitution
subst, ParseCmd
beep
bell
bell
bell
below
Restack
beta
GetVersion
bevel
GetJoinStl
bgerror
BackgdErr
binary
binary, fconfigure, FindExec
binary code
load
bind
socket, keysyms, CrtCommand, CrtObjCmd, CrtGenHdlr, EventHndlr
binding
bindtags, event, keysyms, BindTable
bisque
palette
bitmap
bitmap, dialog, CanvPsY, ConfigWidg, GetBitmap, SetOptions
blocking
close, fblocked, fconfigure, fcopy, fileevent, flush, gets, read, CrtChannel, CrtChnlHdlr, OpenFileChnl
boolean
expr, if, BoolObj, ExprLong, ExprLongObj, GetInt, LinkVar, ConfigWidg, SetOptions
boolean object
BoolObj
boolean type
BoolObj
boolean value
while
border
3DBorder, ConfigWidg, ConfigWind, SetOptions
braces
ParseCmd
break
break, return, AllowExc
buffer
flush
buffered I/O
OpenFileChnl
buffering
fconfigure
butt
GetCapStyl
button
button
byte array
fconfigure, ByteArrObj
bytecode
tclvars
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - C

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

cache
InternAtom
callback
CallDel, CrtChnlHdlr, CrtCloseHdlr, CrtFileHdlr, CrtTimerHdlr, DoOneEvent, DoWhenIdle, Exit, CrtErrHdlr, CrtGenHdlr, EventHndlr, HandleEvent, ManageGeom, QWinEvent
cancel
after
canvas
canvas, CanvPsY, CanvTkwin, CanvTxtInfo, CrtItemType
cap style
ConfigWidg, GetCapStyl
carriage return
fconfigure
case
ToUpper
case conversion
string
catch
catch
cell
grid
center
GetJustify
centimeters
GetPixels
channel
close, eof, fcopy, fileevent, flush, gets, puts, read, socket, tell, ChnlStack, CrtChnlHdlr, GetOpnFl, OpenFileChnl
channel closing
CrtCloseHdlr
channel driver
CrtChannel, OpenFileChnl
channel registration
CrtChannel
channel type
CrtChannel
checkbutton
checkbutton
child
DetachPids
children
winfo
class
options, winfo, AddOption, GetOption, SetClass
cleanup
Exit
clear
clipboard, selection, Clipboard, ClrSelect
client
OpenTcp
clientData
TraceVar
clipboard
clipboard, Clipboard
clock
clock, CrtTimerHdlr, QWinEvent
close
close
color
colors, palette, photo, 3DBorder, CanvPsY, ConfigWidg, ConfigWind, GetColor, SetOptions
color selection dialog
chooseColor
colormap
GetClrmap, GetVisual, SetVisual, WindowId
command
info, rename, AppInit, CrtCommand, CrtInterp, CrtObjCmd, CrtSlave, CrtTrace, ParseCmd, RecEvalObj, RecordEval, SetResult, WrongNumArgs
command line
ParseArgv
command substitution
subst
command-line arguments
Tcl_Main, Tk_Main
compare
expr, string
compiler
tclvars
complete command
CmdCmplt
compression
ChnlStack
concat
StringObj
concatenate
concat, eval, Concat, StringObj
condition variable
Thread
conditional
if
configuration option
SetOptions
configuration options
ConfigWidg
configure
ConfigWind
connection
socket
containing
CoordToWin
context
uplevel, upvar
continue
continue, return, AllowExc
conversion
GetInt, PrintDbl, GetDash
conversion specifier
format, scan
convert
Encoding, SplitList, GetPixels
coordinates
CoordToWin, GetRootCrd
copy files
file
create
open, CrtCommand, CrtInterp, CrtObjCmd, CrtTrace, CrtWindow
ctype
string
current directory
filename
cursor
cursors, ConfigWidg, GetCursor, SetOptions
custom
ConfigWidg
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - D

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

dash
GetDash
data
AssocData
database
option
date
clock
dde
dde, send
debug
memory, DumpActiveMemory, TCL_MEM_DEBUG
defer
DoWhenIdle
deferred creation
CrtWindow
define
event
deiconify
wm
delay
after, RestrictEv
delete
rename, CallDel, CrtCommand, CrtInterp, CrtObjCmd, CrtTrace
delete files
file
delete image
DeleteImg
deletion procedure
AssocData
depressed
3DBorder
depth
SetVisual, WindowId
destroy
destroy, CrtWindow
detach
DetachPids
dialog
dialog
directory
file
directory selection dialog
chooseDirectory
display
CrtWindow, InternAtom, WindowId
domain name
socket
double
DoubleObj, ExprLong, ExprLongObj, GetInt, ConfigWidg, SetOptions
double object
DoubleObj
double type
DoubleObj
double-precision
PrintDbl
dynamic loading
Exit
dynamic string
DString
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - E

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

element
join, lappend, lindex, linsert, list, llength, lrange, lreplace, lsort, SetResult, SplitList
element names
array
else
if
encoding
encoding, fconfigure, read, Encoding
end application
Exit
end of file
eof, fcopy, gets, read, OpenFileChnl
end of line
fconfigure, fcopy, gets, read
entry
entry
environment
tclvars
equal
string
errno
SetErrno
error
catch, error, return, tclvars, unknown, AddErrInfo, BackgdErr, CrtErrHdlr
error code
SetErrno
error message
WrongNumArgs
errorCode
error
errorInfo
error
evaluate
eval, ExprLong, ExprLongObj
event
history, update, vwait, bindtags, event, DoOneEvent, Notifier, RecEvalObj, RecordEval, BindTable, CrtErrHdlr, CrtGenHdlr, EventHndlr, HandleEvent, MainLoop, RestrictEv
event handler
fileevent
event queue
Notifier
event sources
Notifier
events
focus, CrtChnlHdlr
exception
AllowExc
executable file
FindExec
execute
exec, Eval, RecEvalObj, RecordEval
exist
glob
exit
exit, Exit
exported
namespace
exposed commands
CrtSlave
expression
expr, CrtMathFnc, ExprLong, ExprLongObj, ParseCmd
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - F

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

false
if
file
file, glob, open, pid, seek, source, CrtFileHdlr, Eval, SplitPath
file events
Notifier
file handle
GetOpnFl
file name
Translate
file selection dialog
getOpenFile
filename
SplitPath
fill
GetJustify
filter
fconfigure, RestrictEv
floating-point
GetInt, PrintDbl
flush
flush, update, OpenFileChnl
flushing
fconfigure
focus
focus, focusNext, CanvTkwin, CanvTxtInfo, CrtItemType, DrawFocHlt
focus model
wm
font
font, CanvPsY, ConfigWidg, FontId, GetFont, MeasureChar, SetOptions, TextLayout
for
for
foreach
foreach
form
bind
format
binary, format, clipboard, selection, Clipboard, CrtSelHdlr, GetSelect
frame
upvar, frame
free
Alloc, DString, Interp, Preserve
fuzzy comparison
expr
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - G

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

geometry
winfo, wm, GeomReq, GetVRoot, ManageGeom
geometry manager
grid, pack, place, MaintGeom, WindowId
get
GetSelect
get variable
SetVar
glob
glob
global
global, upvar, variable, Eval
global variables
SetErrno
grab
grab, Grab
graphics context
GetGC
grid
grid, wm, SetGrid
group
wm
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - H

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

handle
event
handler
update, selection, Async, CrtChnlHdlr, CrtFileHdlr, CrtTimerHdlr, DoOneEvent, CrtErrHdlr, CrtGenHdlr, CrtSelHdlr, EventHndlr, HandleEvent, QWinEvent
hash table
Hash
height
image, place, winfo, ConfigWind, GetVRoot, WindowId
hidden commands
CrtSlave
history
history, RecEvalObj, RecordEval
home directory
Translate
host
socket
hostname
GetHostName
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - I

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

i18n
msgcat
ICCCM
selection
icon
wm
iconify
wm
identifier
winfo, GetHINSTANCE, GetHWND, WindowId
idle
update, DoOneEvent, Notifier
idle callback
after, DoWhenIdle
if
if
illumination
3DBorder
image
bitmap, image, photo, FindPhoto
image file
CrtPhImgFmt
image manager
CrtImgType, DeleteImg, NameOfImg
image name
NameOfImg
image size changes
ImgChanged
image type
CrtImgType
images
GetImage, ImgChanged
inches
GetPixels
increment
incr
increments
wm
index
lindex, packagens, pkgMkIndex, string, GetIndex, ListObj
information
info, winfo
initialization
AppInit, Init, Tk_Init
initialization procedure
StaticPkg
initialized
Interp
input
OpenFileChnl
insert
linsert, ListObj
insertion cursor
CanvTxtInfo
instance
CrtImgType, GetHINSTANCE
integer
ExprLong, ExprLongObj, GetInt, IntObj, LinkVar, ConfigWidg, SetOptions
integer object
IntObj
integer type
IntObj
intensity
GetColor
internal
namespace
internal representation
BoolObj, DoubleObj, IntObj, ListObj, Object, ObjectType, StringObj
internal window
CrtWindow
internationalization
msgcat, ByteArrObj
interp
SaveResult
interpreter
tclsh, info, AllowExc, AppInit, AssocData, CallDel, CrtCommand, CrtInterp, CrtSlave, CrtTrace, Init, Interp, RecEvalObj, RecordEval, SetResult, SetVar
interpreters
winfo
invoke
CrtSlave
item type
CanvTkwin, CrtItemType
iteration
continue, for, foreach
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - J

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

join
concat, join, SplitPath
join style
ConfigWidg, GetJoinStl
justification
GetJustify
justify
ConfigWidg, SetOptions
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - K

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

key
AssocData, Hash
keyboard
focus
keyboard events
grab
keyboard traversal
focusNext
keysym
keysyms
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - L

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

l10n
msgcat
label
label
length
llength, ListObj
level
info, uplevel, upvar
library
library
line
gets
linemode
fconfigure
link
LinkVar
linked variable
UpVar
list
foreach, join, lappend, lindex, linsert, list, llength, lrange, lreplace, lsearch, lsort, split, ListObj, SetResult, SplitList
list object
ListObj
list type
ListObj
listbox
listbox
lists
concat
load
safe, loadTk, Tk_Init
loading
load
localization
msgcat
location
grid, pack, place, GetVRoot
lookup
Hash
loop
break, continue, while
looping
for, foreach
lower
lower
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - M

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

main loop
MainLoop
main program
SourceRCFile, Tcl_Main, Tk_Main
main window
MainWin, Tk_Init
major
GetVersion
malloc
Alloc, Interp
managed
ManageGeom
manual
bind
map
MaintGeom, MapWindow
mapped
winfo, WindowId
master
place, CrtSlave, CrtImgType, MaintGeom
master interpreter
interp, safe, loadTk
match
lsearch, re_syntax, regexp, regsub, string, switch, RegExp, StrMatch
mathematical function
CrtMathFnc
memory
memory, Alloc, DumpActiveMemory, TCL_MEM_DEBUG
menu
menu, popup
menubutton
menubutton
merge
SplitList
message
msgcat, message
message box
messageBox
millimeters
ConfigWidg, GetPixels
minor
GetVersion
miter
GetJoinStl
modal
dialog
modal timeout
QWinEvent
Motif compliance
StrictMotif
move files
file
mutex
Thread
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - N

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

name
dde, file, options, send, AddOption, GetOption, GetRelief, Name, SetAppName
namespace
global, info, rename, uplevel, upvar, variable, CrtCommand, CrtObjCmd
nesting depth
SetRecLmt
network address
socket
newline
fconfigure, puts
non-blocking
open
non-existent command
unknown
nonblocking
close, fblocked, fconfigure, fcopy, fileevent, flush, gets, read, CrtChannel, OpenFileChnl
nonblocking.
CrtChnlHdlr
notifier
Notifier
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - O

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

object
AddErrInfo, BoolObj, ByteArrObj, CrtObjCmd, DoubleObj, Eval, ExprLong, ExprLongObj, GetIndex, IntObj, ListObj, Object, ObjectType, RecEvalObj, SetResult, SetVar, StringObj, 3DBorder, BindTable, GetColor
object creation
Object
object result
AddErrInfo
object type
BoolObj, DoubleObj, IntObj, ListObj, Object, ObjectType, StringObj
obscure
lower, raise, Restack
open
open, resource
option
colors, cursors, option, AddOption, GetOption
option menu
optionMenu
options
ParseArgv
order
lsort
output
flush, puts, OpenFileChnl
own
selection, OwnSelect
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - P

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

pack
grid
package
package, packagens, pkgMkIndex, PkgRequire, StaticPkg
packer
pack
palette
palette
parcel
pack
parent
winfo, MaintGeom
parse
scan, Backslash, ParseCmd, GetScroll
partial command
CmdCmplt
patchlevel
GetVersion
path
SplitPath, CanvPsY
path name
winfo, Name
pattern
glob, lsearch, regsub, string, RegExp, StrMatch
permissions
open, GetOpnFl
photo
photo, FindPhoto
photo image
CrtPhImgFmt
pipeline
exec, open, pid, GetOpnFl
pixel
ConfigWind
pixel value
GetColor
pixels
ConfigWidg, GetPixels, SetOptions
pixmap
ConfigWind, GetBitmap, GetPixmap
place
place
platform
fconfigure
pointer events
grab
points
GetPixels
polygon
3DBorder
popup
popup
portability
filename
position
wm, MaintGeom, MoveToplev
POSIX
tclvars
Postscript
CanvPsY
precision
tclvars
present
PkgRequire
priority
option
procedure
global, info, proc, return, upvar, variable
process
exit, open, DetachPids
process identifier
pid
projecting
GetCapStyl
prompt
tclsh
propagation
grid, pack
provide
PkgRequire
pwd
GetCwd
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - Q

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - R

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

radiobutton
radiobutton
raise
raise
raised
3DBorder
range
lrange
rc file
SourceRCFile
read
fcopy, gets, read, set, trace, GetOpnFl, OpenFileChnl
read-only
LinkVar
readable
fileevent
real
LinkVar
realloc
Alloc
record
history, RecEvalObj, RecordEval
recursion
SetRecLmt
redirection
exec
redisplay
CanvTkwin, GetImage, ImgChanged
reference count
Preserve
reference counting
Object
register
SetAppName
registry
registry
regular expression
lsearch, re_syntax, regexp, regsub, switch, RegExp
relative file name
filename
release
GetVersion
relief
ConfigWidg, GetRelief, SetOptions
remote execution
dde, send
remove
unset
rename
rename
rename files
file
replace
lreplace, ListObj
reporting
bgerror, tkerror
request
GeomReq, ManageGeom
requested size
WindowId
require
PkgRequire
resource
resource
resource identifier
FreeXId, GetPixmap
restriction
RestrictEv
result
DString, Eval, Interp, SaveResult, SetResult
retrieve
option, GetOption
return
return
return value
SetResult
ring
bell
root window
CoordToWin, GetRootCrd
round
GetCapStyl, GetJoinStl
rubber sheet
place
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - S

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

safe
Tk_Init
safe interpreter
safe, loadTk
safe interpreter
interp, load
scalar
SetVar
scale
scale
scan
binary, scan
screen
winfo, CrtWindow, GetVisual, WindowId
screen distance
SetOptions
screen units
GetPixels
script
eval, fileevent, source, time, Eval, BindTable
script file
tclsh
scrollbar
scrollbar, GetScroll
scrolling command
GetScroll
search
array, lsearch, Hash
security
send
security policy
http
seek
seek, OpenFileChnl
seeking
tell
selection
clipboard, selection, CanvTkwin, CanvTxtInfo, ClrSelect, CrtItemType, CrtSelHdlr
selection anchor
CanvTxtInfo
selection owner
OwnSelect
selection retrieval
GetSelect
send
send, tk
send command
SetAppName
separator
join
serial
open
server
OpenTcp
service mode
Notifier
set
SetVar
shadow
3DBorder
shared library
load
shell
tclsh, wish
signal
Async
size
grid, pack, wm
slave
place, CrtSlave, MaintGeom
slave interpreter
interp, safe, loadTk
sleep
after, Sleep
slider
scale
socket
http, socket
sort
lsort
source
safe, loadTk
split
split, SplitList, SplitPath
sprintf
format
stack
AddErrInfo
stack frame
uplevel
stacking order
lower, raise, Restack
standard channel
GetStdChan
standard error
GetStdChan
standard input
GetStdChan
standard option
options
standard output
GetStdChan
stat
file
stat access
Access
state
SaveResult
static linking
StaticPkg
stipple
CanvPsY
storage
Preserve
string
format, lsearch, re_syntax, regexp, split, string, ExprLong, ExprLongObj, LinkVar, PrintDbl, RegExp, StrMatch, GetJustify, GetRelief
string object
StringObj
string representation
BoolObj, DoubleObj, IntObj, ListObj, Object, ObjectType, StringObj
string type
StringObj
strings
Concat, SplitList
stubs
InitStubs, TkInitStubs
subexpression
RegExp
sublist
lrange
subprocess
exec, tclvars
substitute
regsub
substitution
format
switch
switch, options
synonym
ConfigWidg, SetOptions
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - T

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

table lookup
GetIndex
tag
bindtags
target
selection, CrtSelHdlr
Tcl_RegExpIndices
RegExp
Tcl_RegExpInfo
RegExp
tcp
socket
TCP
OpenTcp
test
tcltest, while
test harness
tcltest
test suite
tcltest
text
msgcat, text, CanvTxtInfo
thread
Exit, Thread
thread local storage
Thread
threads
Notifier
three-dimensional effect
3DBorder
tilde
Translate
time
after, clock, time, Sleep
timer
CrtTimerHdlr, DoOneEvent, Notifier
title
wm
tk_strictMotif variable
StrictMotif
token
ParseCmd, Name
tolower
ToUpper
toolkit
wish
top-level
focus, focusNext, WindowId
top-level window
wm, CrtWindow, MoveToplev
toplevel
toplevel
totitle
ToUpper
toupper
ToUpper
trace
trace, AddErrInfo, CrtTrace, TraceVar
traces
LinkVar
translate
Translate
translation
fconfigure, fcopy, msgcat, read
traversal highlight
DrawFocHlt
trough
scale
true
if
type
clipboard, selection, SplitPath, Clipboard
type conversion
Object, ObjectType
type manager
CanvTkwin, CrtItemType
types of images
image
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - U

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

uid
ConfigWidg
unicode
ByteArrObj, StringObj, ToUpper, Utf
unique identifier
GetUid, SetClass
units
wm
unknown
library
unloading
Exit
unmanaged
ManageGeom
unmap
MaintGeom, MapWindow
unset
trace, SetVar
update
update
upvar
UpVar
user
Translate
utf
ByteArrObj, Encoding, ToUpper, Utf
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - V

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

value
incr, Hash
variable
append, global, incr, info, lappend, namespace, set, trace, unset, upvar, variable, vwait, tkwait, AddErrInfo, LinkVar, SetVar, TraceVar, UpVar
variable substitution
subst, ParseCmd
variables
tclvars, uplevel, tkvars
version
package, packagens, pkgMkIndex, tkvars, GetVersion, PkgRequire
virtual event
event
virtual root
winfo, GetVRoot
visibility
tkwait
visual
GetVisual, SetVisual, WindowId
volume-relative file name
filename
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - W

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

wait
vwait, tkwait, DetachPids, Sleep
while
while
whitespace
library
widget
button, canvas, checkbutton, entry, frame, label, listbox, menu, menubutton, message, radiobutton, scale, scrollbar, text, toplevel
width
image, place, winfo, ConfigWind, GetVRoot, WindowId
window
destroy, grab, tkwait, winfo, ConfigWind, CrtWindow, GetHWND, Grab, HandleEvent, MapWindow, Name, SetClass, SetGrid, WindowId
window manager
focus, wm, GetVRoot, MoveToplev, SetClass, SetGrid
Windows window id
HWNDToWindow
word
library, string
working directory
cd, pwd
writable.
fileevent
write
puts, set, trace, GetOpnFl, OpenFileChnl
wrong number of arguments
WrongNumArgs
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - X

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

x
ConfigWind, WindowId
X window id
IdToWindow
xview
GetScroll
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - Y

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

y
ConfigWind, WindowId
yview
GetScroll
Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl/Tk Keywords - Z

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1994 The Australian National University
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.
Copyright © 1997-2000 Scriptics Corporation.
Copyright © 1998 Mark Harrison.
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1998-1999 Scriptics Corportation


Tcl Built-In Commands - after manual page

NAME
after - Execute a command after a time delay
SYNOPSIS
after ms
after ms ?script script script ...?
after cancel id
after cancel script script script ...
after idle ?script script script ...?
after info ?id?
DESCRIPTION
after ms
after ms ?script script script ...?
after cancel id
after cancel script script ...
after idle script ?script script ...?
after info ?id?
SEE ALSO
KEYWORDS

NAME

after - Execute a command after a time delay

SYNOPSIS

after ms
after ms ?script script script ...?
after cancel id
after cancel script script script ...
after idle ?script script script ...?
after info ?id?

DESCRIPTION

This command is used to delay execution of the program or to execute a command in background sometime in the future. It has several forms, depending on the first argument to the command:

after ms
Ms must be an integer giving a time in milliseconds. The command sleeps for ms milliseconds and then returns. While the command is sleeping the application does not respond to events.

after ms ?script script script ...?
In this form the command returns immediately, but it arranges for a Tcl command to be executed ms milliseconds later as an event handler. The command will be executed exactly once, at the given time. The delayed command is formed by concatenating all the script arguments in the same fashion as the concat command. 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 bgerror mechanism is used to report the error. The after command returns an identifier that can be used to cancel the delayed command using after cancel.

after cancel id
Cancels the execution of a delayed command that was previously scheduled. Id indicates which command should be canceled; it must have been the return value from a previous after command. If the command given by id has already been executed then the after cancel command has no effect.

after cancel script script ...
This command also cancels the execution of a delayed command. The script arguments are concatenated together with space separators (just as in the concat command). If there is a pending command that matches the string, it is cancelled and will never be executed; if no such command is currently pending then the after cancel command has no effect.

after idle script ?script script ...?
Concatenates the script arguments together with space separators (just as in the concat command), and arranges for the resulting script to be evaluated later as an idle callback. The script will be run exactly once, the next time the event loop is entered and there are no events to process. The command returns an identifier that can be used to cancel the delayed command using after cancel. If an error occurs while executing the script then the bgerror mechanism is used to report the error.

after info ?id?
This command returns information about existing event handlers. If no id argument is supplied, the command returns a list of the identifiers for all existing event handlers created by the after command for this interpreter. If id is supplied, it specifies an existing handler; id must have been the return value from some previous call to after and it must not have triggered yet or been cancelled. In this case the command returns a list with two elements. The first element of the list is the script associated with id, and the second element is either idle or timer to indicate what kind of event handler it is.

The after ms and after idle forms of the command assume that the application is event driven: the delayed commands will not be executed unless the application enters the event loop. In applications that are not normally event-driven, such as tclsh, the event loop can be entered with the vwait and update commands.

SEE ALSO

bgerror, concat, update, vwait

KEYWORDS

cancel, delay, idle callback, sleep, time
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - append manual page

NAME

append - Append to variable

SYNOPSIS

append varName ?value value value ...?

DESCRIPTION

Append all of the value arguments to the current value of variable varName. If varName doesn't exist, it is given a value equal to the concatenation of all the value arguments. This command provides an efficient way to build up long variables incrementally. For example, ``append a $b'' is much more efficient than ``set a $a$b'' if $a is long.

SEE ALSO

concat, lappend

KEYWORDS

append, variable
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - array manual page

NAME
array - Manipulate array variables
SYNOPSIS
array option arrayName ?arg arg ...?
DESCRIPTION
array anymore arrayName searchId
array donesearch arrayName searchId
array exists arrayName
array get arrayName ?pattern?
array names arrayName ?pattern?
array nextelement arrayName searchId
array set arrayName list
array size arrayName
array startsearch arrayName
array unset arrayName ?pattern?
KEYWORDS

NAME

array - Manipulate array variables

SYNOPSIS

array option arrayName ?arg arg ...?

DESCRIPTION

This command performs one of several operations on the variable given by arrayName. Unless otherwise specified for individual commands below, arrayName must be the name of an existing array variable. The option argument determines what action is carried out by the command. The legal options (which may be abbreviated) are:

array anymore arrayName searchId
Returns 1 if there are any more elements left to be processed in an array search, 0 if all elements have already been returned. SearchId indicates which search on arrayName to check, and must have been the return value from a previous invocation of array startsearch. This option is particularly useful if an array has an element with an empty name, since the return value from array nextelement won't indicate whether the search has been completed.

array donesearch arrayName searchId
This command terminates an array search and destroys all the state associated with that search. SearchId indicates which search on arrayName to destroy, and must have been the return value from a previous invocation of array startsearch. Returns an empty string.

array exists arrayName
Returns 1 if arrayName is an array variable, 0 if there is no variable by that name or if it is a scalar variable.

array get arrayName ?pattern?
Returns a list containing pairs of elements. The first element in each pair is the name of an element in arrayName and the second element of each pair is the value of the array element. The order of the pairs is undefined. If pattern is not specified, then all of the elements of the array are included in the result. If pattern is specified, then only those elements whose names match pattern (using the matching rules of string match) are included. If arrayName isn't the name of an array variable, or if the array contains no elements, then an empty list is returned.

array names arrayName ?pattern?
Returns a list containing the names of all of the elements in the array that match pattern (using the matching rules of string match). If pattern is omitted then the command returns all of the element names in the array. If there are no (matching) elements in the array, or if arrayName isn't the name of an array variable, then an empty string is returned.

array nextelement arrayName searchId
Returns the name of the next element in arrayName, or an empty string if all elements of arrayName have already been returned in this search. The searchId argument identifies the search, and must have been the return value of an array startsearch command. Warning: if elements are added to or deleted from the array, then all searches are automatically terminated just as if array donesearch had been invoked; this will cause array nextelement operations to fail for those searches.

array set arrayName list
Sets the values of one or more elements in arrayName. list must have a form like that returned by array get, consisting of an even number of elements. Each odd-numbered element in list is treated as an element name within arrayName, and the following element in list is used as a new value for that array element. If the variable arrayName does not already exist and list is empty, arrayName is created with an empty array value.

array size arrayName
Returns a decimal string giving the number of elements in the array. If arrayName isn't the name of an array then 0 is returned.

array startsearch arrayName
This command initializes an element-by-element search through the array given by arrayName, such that invocations of the array nextelement command will return the names of the individual elements in the array. When the search has been completed, the array donesearch command should be invoked. The return value is a search identifier that must be used in array nextelement and array donesearch commands; it allows multiple searches to be underway simultaneously for the same array.

array unset arrayName ?pattern?
Unsets all of the elements in the array that match pattern (using the matching rules of string match). If arrayName isn't the name of an array variable or there are no matching elements in the array, then an empty string is returned. If pattern is omitted and is it an array variable, then the command unsets the entire array.

KEYWORDS

array, element names, search
Copyright © 1993-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - bgerror manual page

NAME

bgerror - Command invoked to process background errors

SYNOPSIS

bgerror message

DESCRIPTION

The bgerror command doesn't exist as built-in part of Tcl. Instead, individual applications or users can define a bgerror command (e.g. as a Tcl procedure) if they wish to handle background errors.

A background error is one that occurs in an event handler or some other command that didn't originate with the application. For example, if an error occurs while executing a command specified with the after command, then it is a background error. For a non-background error, the error can simply be returned up through nested Tcl command evaluations until it reaches the top-level code in the application; then the application can report the error in whatever way it wishes. When a background error occurs, the unwinding ends in the Tcl library and there is no obvious way for Tcl to report the error.

When Tcl detects a background error, it saves information about the error and invokes the bgerror command later as an idle event handler. Before invoking bgerror, Tcl restores the errorInfo and errorCode variables to their values at the time the error occurred, then it invokes bgerror with the error message as its only argument. Tcl assumes that the application has implemented the bgerror command, and that the command will report the error in a way that makes sense for the application. Tcl will ignore any result returned by the bgerror command as long as no error is generated.

If another Tcl error occurs within the bgerror command (for example, because no bgerror command has been defined) then Tcl reports the error itself by writing a message to stderr.

If several background errors accumulate before bgerror is invoked to process them, bgerror will be invoked once for each error, in the order they occurred. However, if bgerror returns with a break exception, then any remaining errors are skipped without calling bgerror.

Tcl has no default implementation for bgerror. However, in applications using Tk there is a default bgerror procedure which posts a dialog box containing the error message and offers the user a chance to see a stack trace showing where the error occurred. In addition to allowing the user to view the stack trace, the dialog provides an additional application configurable button which may be used, for example, to save the stack trace to a file. By default, this is the behavior associated with that button. This behavior can be redefined by setting the option database values *ErrorDialog.function.text, to specify the caption for the function button, and *ErrorDialog.function.command, to specify the command to be run. The text of the stack trace is appended to the command when it is evaluated. If either of these options is set to the empty string, then the additional button will not be displayed in the dialog.

SEE ALSO

after, tclvars

KEYWORDS

background error, reporting
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - binary manual page

NAME
binary - Insert and extract fields from binary strings
SYNOPSIS
binary format formatString ?arg arg ...?
binary scan string formatString ?varName varName ...?
DESCRIPTION
BINARY FORMAT
a
A
b
B
h
H
c
s
S
i
I
f
d
x
X
@
BINARY SCAN
a
A
b
B
h
H
c
s
S
i
I
f
d
x
X
@
PLATFORM ISSUES
SEE ALSO
KEYWORDS

NAME

binary - Insert and extract fields from binary strings

SYNOPSIS

binary format formatString ?arg arg ...?
binary scan string formatString ?varName varName ...?

DESCRIPTION

This command provides facilities for manipulating binary data. The first form, binary format, 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, binary scan, does the opposite: it extracts data from a binary string and returns it as ordinary Tcl string values.

BINARY FORMAT

The binary format command generates a binary string whose layout is specified by the formatString and whose contents come from the additional arguments. The resulting binary value is returned.

The formatString consists of a sequence of zero or more field specifiers separated by zero or more spaces. Each field specifier is a single type character followed by an optional numeric count. Most field specifiers consume one argument to obtain the value to be formatted. The type character specifies how the value is to be formatted. The count typically indicates how many items of the specified type are taken from the value. If present, the count is a non-negative decimal integer or *, which normally indicates that all of the items in the value are to be used. If the number of arguments does not match the number of fields in the format string that consume arguments, then an error is generated.

Each type-count pair moves an imaginary cursor through the binary data, storing bytes at the current position and advancing the cursor to just after the last byte stored. The cursor is initially at position 0 at the beginning of the data. The type may be any one of the following characters:

a
Stores a character string of length count in the output string. If arg has fewer than count bytes, then additional zero bytes are used to pad out the field. If arg is longer than the specified length, the extra characters will be ignored. If count is *, then all of the bytes in arg will be formatted. If count is omitted, then one character will be formatted. For example,
binary format a7a*a alpha bravo charlie
will return a string equivalent to alpha\000\000bravoc.

A
This form is the same as a except that spaces are used for padding instead of nulls. For example,
binary format A6A*A alpha bravo charlie
will return alpha bravoc.

b
Stores a string of count binary digits in low-to-high order within each byte in the output string. Arg must contain a sequence of 1 and 0 characters. The resulting bytes are emitted in first to last order with the bits being formatted in low-to-high order within each byte. If arg has fewer than count digits, then zeros will be used for the remaining bits. If arg has more than the specified number of digits, the extra digits will be ignored. If count is *, then all of the digits in arg will be formatted. If count is omitted, then one digit will be formatted. If the number of bits formatted does not end at a byte boundary, the remaining bits of the last byte will be zeros. For example,
binary format b5b* 11100 111000011010
will return a string equivalent to \x07\x87\x05.

B
This form is the same as b except that the bits are stored in high-to-low order within each byte. For example,
binary format B5B* 11100 111000011010
will return a string equivalent to \xe0\xe1\xa0.

h
Stores a string of count hexadecimal digits in low-to-high within each byte in the output string. Arg must contain a sequence of characters in the set ``0123456789abcdefABCDEF''. The resulting bytes are emitted in first to last order with the hex digits being formatted in low-to-high order within each byte. If arg has fewer than count digits, then zeros will be used for the remaining digits. If arg has more than the specified number of digits, the extra digits will be ignored. If count is *, then all of the digits in arg will be formatted. If count is omitted, then one digit will be formatted. If the number of digits formatted does not end at a byte boundary, the remaining bits of the last byte will be zeros. For example,
binary format h3h* AB def
will return a string equivalent to \xba\x00\xed\x0f.

H
This form is the same as h except that the digits are stored in high-to-low order within each byte. For example,
binary format H3H* ab DEF
will return a string equivalent to \xab\x00\xde\xf0.

c
Stores one or more 8-bit integer values in the output string. If no count is specified, then arg must consist of an integer value; otherwise arg must consist of a list containing at least count integer elements. The low-order 8 bits of each integer are stored as a one-byte value at the cursor position. If count is *, then all of the integers in the list are formatted. If the number of elements in the list is fewer than count, then an error is generated. If the number of elements in the list is greater than count, then the extra elements are ignored. For example,
binary format c3cc* {3 -3 128 1} 260 {2 5}
will return a string equivalent to \x03\xfd\x80\x04\x02\x05, whereas
binary format c {2 5}
will generate an error.

s
This form is the same as c except that it stores one or more 16-bit integers in little-endian byte order in the output string. The low-order 16-bits of each integer are stored as a two-byte value at the cursor position with the least significant byte stored first. For example,
binary format s3 {3 -3 258 1}
will return a string equivalent to \x03\x00\xfd\xff\x02\x01.

S
This form is the same as s except that it stores one or more 16-bit integers in big-endian byte order in the output string. For example,
binary format S3 {3 -3 258 1}
will return a string equivalent to \x00\x03\xff\xfd\x01\x02.

i
This form is the same as c except that it stores one or more 32-bit integers in little-endian byte order in the output string. The low-order 32-bits of each integer are stored as a four-byte value at the cursor position with the least significant byte stored first. For example,
binary format i3 {3 -3 65536 1}
will return a string equivalent to \x03\x00\x00\x00\xfd\xff\xff\xff\x00\x00\x01\x00

I
This form is the same as i except that it stores one or more one or more 32-bit integers in big-endian byte order in the output string. For example,
binary format I3 {3 -3 65536 1}
will return a string equivalent to \x00\x00\x00\x03\xff\xff\xff\xfd\x00\x01\x00\x00

f
This form is the same as c except that it stores one or more one or more single-precision floating in the machine's native representation in the output string. This representation is not portable across architectures, so it should not be used to communicate floating point numbers across the network. The size of a floating point number may vary across architectures, so the number of bytes that are generated may vary. If the value overflows the machine's native representation, then the value of FLT_MAX as defined by the system will be used instead. Because Tcl uses double-precision floating-point numbers internally, there may be some loss of precision in the conversion to single-precision. For example, on a Windows system running on an Intel Pentium processor,
binary format f2 {1.6 3.4}
will return a string equivalent to \xcd\xcc\xcc\x3f\x9a\x99\x59\x40.

d
This form is the same as f except that it stores one or more one or more double-precision floating in the machine's native representation in the output string. For example, on a Windows system running on an Intel Pentium processor,
binary format d1 {1.6}
will return a string equivalent to \x9a\x99\x99\x99\x99\x99\xf9\x3f.

x
Stores count null bytes in the output string. If count is not specified, stores one null byte. If count is *, generates an error. This type does not consume an argument. For example,
binary format a3xa3x2a3 abc def ghi
will return a string equivalent to abc\000def\000\000ghi.

X
Moves the cursor back count bytes in the output string. If count is * or is larger than the current cursor position, then the cursor is positioned at location 0 so that the next byte stored will be the first byte in the result string. If count is omitted then the cursor is moved back one byte. This type does not consume an argument. For example,
binary format a3X*a3X2a3 abc def ghi
will return dghi.

@
Moves the cursor to the absolute location in the output string specified by count. Position 0 refers to the first byte in the output string. If count refers to a position beyond the last byte stored so far, then null bytes will be placed in the unitialized locations and the cursor will be placed at the specified location. If count is *, then the cursor is moved to the current end of the output string. If count is omitted, then an error will be generated. This type does not consume an argument. For example,
binary format a5@2a1@*a3@10a1 abcde f ghi j
will return abfdeghi\000\000j.

BINARY SCAN

The binary scan command parses fields from a binary string, returning the number of conversions performed. String gives the input to be parsed and formatString indicates how to parse it. Each varName gives the name of a variable; when a field is scanned from string the result is assigned to the corresponding variable.

As with binary format, the formatString consists of a sequence of zero or more field specifiers separated by zero or more spaces. Each field specifier is a single type character followed by an optional numeric count. Most field specifiers consume one argument to obtain the variable into which the scanned values should be placed. The type character specifies how the binary data is to be interpreted. The count typically indicates how many items of the specified type are taken from the data. If present, the count is a non-negative decimal integer or *, which normally indicates that all of the remaining items in the data are to be used. If there are not enough bytes left after the current cursor position to satisfy the current field specifier, then the corresponding variable is left untouched and binary scan returns immediately with the number of variables that were set. If there are not enough arguments for all of the fields in the format string that consume arguments, then an error is generated.

It is important to note that the c, s, and S (and i and I on 64bit systems) will be scanned into long data size values. In doing this, values that have their high bit set (0x80 for chars, 0x8000 for shorts, 0x80000000 for ints), will be sign extended. Thus the following will occur:

set signShort [binary format s1 0x8000]
binary scan $signShort s1 val; # val == 0xFFFF8000
If you want to produce an unsigned value, then you can mask the return value to the desired size. For example, to produce an unsigned short value:
set val [expr {$val & 0xFFFF}]; # val == 0x8000

Each type-count pair moves an imaginary cursor through the binary data, reading bytes from the current position. The cursor is initially at position 0 at the beginning of the data. The type may be any one of the following characters:

a
The data is a character string of length count. If count is *, then all of the remaining bytes in string will be scanned into the variable. If count is omitted, then one character will be scanned. For example,
binary scan abcde\000fghi a6a10 var1 var2
will return 1 with the string equivalent to abcde\000 stored in var1 and var2 left unmodified.

A
This form is the same as a, except trailing blanks and nulls are stripped from the scanned value before it is stored in the variable. For example,
binary scan "abc efghi  \000" A* var1
will return 1 with abc efghi stored in var1.

b
The data is turned into a string of count binary digits in low-to-high order represented as a sequence of ``1'' and ``0'' characters. The data bytes are scanned in first to last order with the bits being taken in low-to-high order within each byte. Any extra bits in the last byte are ignored. If count is *, then all of the remaining bits in string will be scanned. If count is omitted, then one bit will be scanned. For example,
binary scan \x07\x87\x05 b5b* var1 var2
will return 2 with 11100 stored in var1 and 1110000110100000 stored in var2.

B
This form is the same as b, except the bits are taken in high-to-low order within each byte. For example,
binary scan \x70\x87\x05 B5B* var1 var2
will return 2 with 01110 stored in var1 and 1000011100000101 stored in var2.

h
The data is turned into a string of count hexadecimal digits in low-to-high order represented as a sequence of characters in the set ``0123456789abcdef''. The data bytes are scanned in first to last order with the hex digits being taken in low-to-high order within each byte. Any extra bits in the last byte are ignored. If count is *, then all of the remaining hex digits in string will be scanned. If count is omitted, then one hex digit will be scanned. For example,
binary scan \x07\x86\x05 h3h* var1 var2
will return 2 with 706 stored in var1 and 50 stored in var2.

H
This form is the same as h, except the digits are taken in high-to-low order within each byte. For example,
binary scan \x07\x86\x05 H3H* var1 var2
will return 2 with 078 stored in var1 and 05 stored in var2.

c
The data is turned into count 8-bit signed integers and stored in the corresponding variable as a list. If count is *, then all of the remaining bytes in string will be scanned. If count is omitted, then one 8-bit integer will be scanned. For example,
binary scan \x07\x86\x05 c2c* var1 var2
will return 2 with 7 -122 stored in var1 and 5 stored in var2. Note that the integers returned are signed, but they can be converted to unsigned 8-bit quantities using an expression like:
expr ( $num + 0x100 ) % 0x100

s
The data is interpreted as count 16-bit signed integers represented in little-endian byte order. The integers are stored in the corresponding variable as a list. If count is *, then all of the remaining bytes in string will be scanned. If count is omitted, then one 16-bit integer will be scanned. For example,
binary scan \x05\x00\x07\x00\xf0\xff s2s* var1 var2
will return 2 with 5 7 stored in var1 and -16 stored in var2. Note that the integers returned are signed, but they can be converted to unsigned 16-bit quantities using an expression like:
expr ( $num + 0x10000 ) % 0x10000

S
This form is the same as s except that the data is interpreted as count 16-bit signed integers represented in big-endian byte order. For example,
binary scan \x00\x05\x00\x07\xff\xf0 S2S* var1 var2
will return 2 with 5 7 stored in var1 and -16 stored in var2.

i
The data is interpreted as count 32-bit signed integers represented in little-endian byte order. The integers are stored in the corresponding variable as a list. If count is *, then all of the remaining bytes in string will be scanned. If count is omitted, then one 32-bit integer will be scanned. For example,
binary scan \x05\x00\x00\x00\x07\x00\x00\x00\xf0\xff\xff\xff i2i* var1 var2
will return 2 with 5 7 stored in var1 and -16 stored in var2. Note that the integers returned are signed and cannot be represented by Tcl as unsigned values.

I
This form is the same as I except that the data is interpreted as count 32-bit signed integers represented in big-endian byte order. For example,
binary \x00\x00\x00\x05\x00\x00\x00\x07\xff\xff\xff\xf0 I2I* var1 var2
will return 2 with 5 7 stored in var1 and -16 stored in var2.

f
The data is interpreted as count single-precision floating point numbers in the machine's native representation. The floating point numbers are stored in the corresponding variable as a list. If count is *, then all of the remaining bytes in string will be scanned. If count is omitted, then one single-precision floating point number will be scanned. The size of a floating point number may vary across architectures, so the number of bytes that are scanned may vary. If the data does not represent a valid floating point number, the resulting value is undefined and compiler dependent. For example, on a Windows system running on an Intel Pentium processor,
binary scan \x3f\xcc\xcc\xcd f var1
will return 1 with 1.6000000238418579 stored in var1.

d
This form is the same as f except that the data is interpreted as count double-precision floating point numbers in the machine's native representation. For example, on a Windows system running on an Intel Pentium processor,
binary scan \x9a\x99\x99\x99\x99\x99\xf9\x3f d var1
will return 1 with 1.6000000000000001 stored in var1.

x
Moves the cursor forward count bytes in string. If count is * or is larger than the number of bytes after the current cursor cursor position, then the cursor is positioned after the last byte in string. If count is omitted, then the cursor is moved forward one byte. Note that this type does not consume an argument. For example,
binary scan \x01\x02\x03\x04 x2H* var1
will return 1 with 0304 stored in var1.

X
Moves the cursor back count bytes in string. If count is * or is larger than the current cursor position, then the cursor is positioned at location 0 so that the next byte scanned will be the first byte in string. If count is omitted then the cursor is moved back one byte. Note that this type does not consume an argument. For example,
binary scan \x01\x02\x03\x04 c2XH* var1 var2
will return 2 with 1 2 stored in var1 and 020304 stored in var2.

@
Moves the cursor to the absolute location in the data string specified by count. Note that position 0 refers to the first byte in string. If count refers to a position beyond the end of string, then the cursor is positioned after the last byte. If count is omitted, then an error will be generated. For example,
binary scan \x01\x02\x03\x04 c2@1H* var1 var2
will return 2 with 1 2 stored in var1 and 020304 stored in var2.

PLATFORM ISSUES

Sometimes it is desirable to format or scan integer values in the native byte order for the machine. Refer to the byteOrder element of the tcl_platform array to decide which type character to use when formatting or scanning integers.

SEE ALSO

format, scan, tclvars

KEYWORDS

binary, format, scan
Copyright © 1997 by Sun Microsystems, Inc.


Built-In Commands - break manual page

NAME

break - Abort looping command

SYNOPSIS

break

DESCRIPTION

This command is typically invoked inside the body of a looping command such as for or foreach or while. It returns a TCL_BREAK 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 aborts its execution and returns normally. Break exceptions are also handled in a few other situations, such as the catch command, Tk event bindings, and the outermost scripts of procedure bodies.

SEE ALSO

catch, continue, for, foreach, while

KEYWORDS

abort, break, loop
Copyright © 1993-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - catch manual page

NAME

catch - Evaluate script and trap exceptional returns

SYNOPSIS

catch script ?varName?

DESCRIPTION

The catch command may be used to prevent errors from aborting command interpretation. Catch calls the Tcl interpreter recursively to execute script, and always returns without raising an error, regardless of any errors that might occur while executing script.

If script raises an error, catch will return a non-zero integer value corresponding to one of the exceptional return codes (see tcl.h for the definitions of code values). If the varName argument is given, then the variable it names is set to the error message from interpreting script.

If script does not raise an error, catch will return 0 (TCL_OK) and set the variable to the value returned from script.

Note that catch catches all exceptions, including those generated by break and continue as well as errors. The only errors that are not caught are syntax errors found when the script is compiled. This is because the catch command only catches errors during runtime. When the catch statement is compiled, the script is compiled as well and any syntax errors will generate a Tcl error.

EXAMPLES

The catch command may be used in an if to branch based on the success of a script.
if { [catch {open $someFile w} fid] } {
    puts stderr "Could not open $someFile for writing\n$fid"
    exit 1
}
The catch command will not catch compiled syntax errors. The first time proc foo is called, the body will be compiled and a Tcl error will be generated.
proc foo {} {
    catch {expr {1 +- }}
}

KEYWORDS

catch, error
Copyright © 1993-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - cd manual page

NAME

cd - Change working directory

SYNOPSIS

cd ?dirName?

DESCRIPTION

Change the current working directory to dirName, or to the home directory (as specified in the HOME environment variable) if dirName is not given. Returns an empty string.

SEE ALSO

filename, glob, pwd

KEYWORDS

working directory
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - clock manual page

NAME
clock - Obtain and manipulate time
SYNOPSIS
clock option ?arg arg ...?
DESCRIPTION
.VS 8.3
clock format clockValue ?-format string? ?-gmt boolean?
%%
%a
%A
%b
%B
%c
%d
%H
%I
%j
%m
%M
%p
%S
%U
%w
%W
%x
%X
%y
%Y
%Z
%D
%e
%h
%n
%r
%R
%t
%T
clock scan dateString ?-base clockVal? ?-gmt boolean?
time
date
ISO 8601 point-in-time
relative time
clock seconds
KEYWORDS

NAME

clock - Obtain and manipulate time

SYNOPSIS

clock option ?arg arg ...?

DESCRIPTION

This command performs one of several operations that may obtain or manipulate strings or values that represent some notion of time. The option argument determines what action is carried out by the command. The legal options (which may be abbreviated) are:

.VS 8.3
clock clicks ?-milliseconds? Return a high-resolution time value as a system-dependent integer value. The unit of the value is system-dependent but should be the highest resolution clock available on the system such as a CPU cycle counter. If -milliseconds is specified, then the value is guaranteed to be of millisecond granularity. This value should only be used for the relative measurement of elapsed time.

clock format clockValue ?-format string? ?-gmt boolean?
Converts an integer time value, typically returned by clock seconds, clock scan, or the atime, mtime, or ctime options of the file command, to human-readable form. If the -format argument is present the next argument is a string that describes how the date and time are to be formatted. Field descriptors consist of a % followed by a field descriptor character. All other characters are copied into the result. Valid field descriptors are:

%%
Insert a %.

%a
Abbreviated weekday name (Mon, Tue, etc.).

%A
Full weekday name (Monday, Tuesday, etc.).

%b
Abbreviated month name (Jan, Feb, etc.).

%B
Full month name.

%c
Locale specific date and time.

%d
Day of month (01 - 31).

%H
Hour in 24-hour format (00 - 23).

%I
Hour in 12-hour format (00 - 12).

%j
Day of year (001 - 366).

%m
Month number (01 - 12).

%M
Minute (00 - 59).

%p
AM/PM indicator.

%S
Seconds (00 - 59).

%U
Week of year (00 - 52), Sunday is the first day of the week.

%w
Weekday number (Sunday = 0).

%W
Week of year (00 - 52), Monday is the first day of the week.

%x
Locale specific date format.

%X
Locale specific time format.

%y
Year without century (00 - 99).

%Y
Year with century (e.g. 1990)

%Z
Time zone name.

In addition, the following field descriptors may be supported on some systems (e.g. Unix but not Windows):

%D
Date as %m/%d/%y.

%e
Day of month (1 - 31), no leading zeros.

%h
Abbreviated month name.

%n
Insert a newline.

%r
Time as %I:%M:%S %p.

%R
Time as %H:%M.

%t
Insert a tab.

%T
Time as %H:%M:%S.

If the -format argument is not specified, the format string "%a %b %d %H:%M:%S %Z %Y" is used. If the -gmt argument is present the next argument must be a boolean which if true specifies that the time will be formatted as Greenwich Mean Time. If false then the local timezone will be used as defined by the operating environment.

clock scan dateString ?-base clockVal? ?-gmt boolean?
Convert dateString to an integer clock value (see clock seconds). This command can parse and convert virtually any standard date and/or time string, which can include standard time zone mnemonics. If only a time is specified, the current date is assumed. If the string does not contain a time zone mnemonic, the local time zone is assumed, unless the -gmt argument is true, in which case the clock value is calculated assuming that the specified time is relative to Greenwich Mean Time. -gmt, if specified, affects only the computed time value; it does not impact the interpretation of -base.

If the -base flag is specified, the next argument should contain an integer clock value. Only the date in this value is used, not the time. This is useful for determining the time on a specific day or doing other date-relative conversions.

The dateString consists of zero or more specifications of the following form:

time
A time of day, which is of the form: hh?:mm?:ss?? ?meridian? ?zone? or hhmm ?meridian? ?zone?. If no meridian is specified, hh is interpreted on a 24-hour clock.

date
A specific month and day with optional year. The acceptable formats are mm/dd?/yy?, monthname dd ?, yy?, dd monthname ?yy?, day, dd monthname yy, ?CC?yymmdd, ?CC?yy-mm-dd, dd-monthname-?CC?yy. The default year is the current year. If the year is less than 100, we treat the years 00-68 as 2000-2068 and the years 69-99 as 1969-1999. Not all platforms can represent the years 38-70, so an error may result if these years are used.

ISO 8601 point-in-time
An ISO 8601 point-in-time specification, such as CCyymmddThhmmss, where T is the literal T, CCyymmdd hhmmss, or CCyymmddThh:mm:ss.

relative time
A specification relative to the current time. The format is number unit acceptable units are year, fortnight, month, week, day, hour, minute (or min), and second (or sec). The unit can be specified as a singular or plural, as in 3 weeks. These modifiers may also be specified: tomorrow, yesterday, today, now, last, this, next, ago.

The actual date is calculated according to the following steps. First, any absolute date and/or time is processed and converted. Using that time as the base, day-of-week specifications are added. Next, relative specifications are used. If a date or day is specified, and no absolute or relative time is given, midnight is used. Finally, a correction is applied so that the correct hour of the day is produced after allowing for daylight savings time differences and the correct date is given when going from the end of a long month to a short month.

Daylight savings time correction is applied only when the relative time is specified in units of days or more, ie, days, weeks, fortnights, months or years. This means that when crossing the daylight savings time boundary, different results will be given for clock scan "1 day" and clock scan "24 hours":

% clock scan "1 day" -base [clock scan 1999-10-31]
941443200
% clock scan "24 hours" -base [clock scan 1999-10-31]
941439600

clock seconds
Return the current date and time as a system-dependent integer value. The unit of the value is seconds, allowing it to be used for relative time calculations. The value is usually defined as total elapsed time from an ``epoch''. You shouldn't assume the value of the epoch.

KEYWORDS

clock, date, time
Copyright © 1992-1995 Karl Lehenbauer and Mark Diekhans.
Copyright © 1995-1997 Sun Microsystems, Inc.
Copyright © 1998-1999 Scriptics Corporation


Tcl Built-In Commands - close manual page

NAME

close - Close an open channel.

SYNOPSIS

close channelId

DESCRIPTION

Closes the channel given by channelId. ChannelId must be a channel identifier such as the return value from a previous open or socket command. All buffered output is flushed to the channel's output device, any buffered input is discarded, the underlying file or device is closed, and channelId becomes unavailable for use.

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.

If channelId is a blocking channel for a command pipeline then close waits for the child processes to complete.

If the channel is shared between interpreters, then close makes channelId 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 close, the cleanup actions described above occur. See the interp command for a description of channel sharing.

Channels are automatically 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.

The command returns an empty string, and may generate an error if an error occurs while flushing output.

SEE ALSO

file, open, socket, eof

KEYWORDS

blocking, channel, close, nonblocking
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - concat manual page

NAME

concat - Join lists together

SYNOPSIS

concat ?arg arg ...?

DESCRIPTION

This command treats each argument as a list and concatenates them into a single list. It also eliminates leading and trailing spaces in the arg's and adds a single separator space between arg's. It permits any number of arguments. For example, the command
concat a b {c d e} {f {g h}}
will return
a b c d e f {g h}
as its result.

If no args are supplied, the result is an empty string.

SEE ALSO

append, eval

KEYWORDS

concatenate, join, lists
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - continue manual page

NAME

continue - Skip to the next iteration of a loop

SYNOPSIS

continue

DESCRIPTION

This command is typically invoked inside the body of a looping command such as for or foreach or while. It returns a TCL_CONTINUE 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. Catch exceptions are also handled in a few other situations, such as the catch command and the outermost scripts of procedure bodies.

SEE ALSO

break, for, foreach, while

KEYWORDS

continue, iteration, loop
Copyright © 1993-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - dde manual page

NAME
dde - Execute a Dynamic Data Exchange command
SYNOPSIS
package require dde 1.1
dde servername ?topic?
dde ?-async? command service topic ?data?
DESCRIPTION
-async
DDE COMMANDS
dde servername ?topic?
dde execute service topic data
dde poke service topic item data
dde request service topic item
dde services service topic
dde eval topic cmd ?arg arg ...?
DDE AND TCL
SEE ALSO
KEYWORDS

NAME

dde - Execute a Dynamic Data Exchange command

SYNOPSIS

package require dde 1.1
dde servername ?topic?
dde ?-async? command service topic ?data?

DESCRIPTION

This command allows an application to send Dynamic Data Exchange (DDE) command when running under Microsoft Windows. Dynamic Data Exchange is a mechanism where applications can exchange raw data. Each DDE transaction needs a service name and a topic. Both the service name and topic are application defined; Tcl uses the service name TclEval, while the topic name is the name of the interpreter given by dde servername. Other applications have their own service names and topics. For instance, Microsoft Excel has the service name Excel.

The only option to the dde command is:

-async
Requests asynchronous invocation. This is valid only for the execute subcommand. Normally, the dde execute subcommand waits until the command completes, returning appropriate error messages. When the -async option is used, the command returns immediately, and no error information is available.

DDE COMMANDS

The following commands are a subset of the full Dynamic Data Exchange set of commands.

dde servername ?topic?
dde servername registers the interpreter as a DDE server with the service name TclEval and the topic name specified by topic. If no topic is given, dde servername returns the name of the current topic or the empty string if it is not registered as a service.

dde execute service topic data
dde execute takes the data and sends it to the server indicated by service with the topic indicated by topic. Typically, service is the name of an application, and topic is a file to work on. The data field is given to the remote application. Typically, the application treats the data field as a script, and the script is run in the application. The command returns an error if the script did not run. If the -async flag was used, the command returns immediately with no error.

dde poke service topic item data
dde poke passes the data to the server indicated by service using the topic and item specified. Typically, service is the name of an application. topic is application specific but can be a command to the server or the name of a file to work on. The item is also application specific and is often not used, but it must always be non-null. The data field is given to the remote application.

dde request service topic item
dde request is typically used to get the value of something; the value of a cell in Microsoft Excel or the text of a selection in Microsoft Word. service is typically the name of an application, topic is typically the name of the file, and item is application-specific. The command returns the value of item as defined in the application.

dde services service topic
dde services returns a list of service-topic pairs that currently exist on the machine. If service and topic are both null strings ({}), then all service-topic pairs currently available on the system are returned. If service is null and topic is not, then all services with the specified topic are returned. If service is not null and topic is, all topics for a given service are returned. If both are not null, if that service-topic pair currently exists, it is returned; otherwise, null is returned.

dde eval topic cmd ?arg arg ...?
dde eval evaluates a command and its arguments using the interpreter specified by topic. The DDE service must be the TclEval service. This command can be used to replace send on Windows.

DDE AND TCL

A Tcl interpreter always has a service name of TclEval. Each different interpreter of all running Tcl applications must be given a unique name specified by dde servername. Each interp is available as a DDE topic only if the dde servername command was used to set the name of the topic for each interp. So a dde services TclEval {} command will return a list of service-topic pairs, where each of the currently running interps will be a topic.

When Tcl processes a dde execute command, the data for the execute is run as a script in the interp named by the topic of the dde execute command.

When Tcl processes a dde request command, it returns the value of the variable given in the dde command in the context of the interp named by the dde topic. Tcl reserves the variable $TCLEVAL$EXECUTE$RESULT for internal use, and dde request commands for that variable will give unpredictable results.

An external application which wishes to run a script in Tcl should have that script store its result in a variable, run the dde execute command, and the run dde request to get the value of the variable.

When using DDE, be careful to ensure that the event queue is flushed using either update or vwait. This happens by default when using wish unless a blocking command is called (such as exec without adding the & to place the process in the background). 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.

SEE ALSO

tk, winfo, send

KEYWORDS

application, dde, name, remote execution
Copyright © 1997 Sun Microsystems, Inc.


Tcl Built-In Commands - encoding manual page

NAME
encoding - Manipulate encodings
SYNOPSIS
encoding option ?arg arg ...?
INTRODUCTION
DESCRIPTION
encoding convertfrom ?encoding? data
encoding convertto ?encoding? string
encoding names
encoding system ?encoding?
EXAMPLE
SEE ALSO
KEYWORDS

NAME

encoding - Manipulate encodings

SYNOPSIS

encoding option ?arg arg ...?

INTRODUCTION

Strings in Tcl are encoded using 16-bit Unicode characters. Different operating system interfaces or applications may generate strings in other encodings such as Shift-JIS. The encoding command helps to bridge the gap between Unicode and these other formats.

DESCRIPTION

Performs one of several encoding related operations, depending on option. The legal options are:

encoding convertfrom ?encoding? data
Convert data to Unicode from the specified encoding. The characters in data are treated as binary data where the lower 8-bits of each character is taken as a single byte. The resulting sequence of bytes is treated as a string in the specified encoding. If encoding is not specified, the current system encoding is used.

encoding convertto ?encoding? string
Convert string from Unicode to the specified encoding. The result is a sequence of bytes that represents the converted string. Each byte is stored in the lower 8-bits of a Unicode character. If encoding is not specified, the current system encoding is used.

encoding names
Returns a list containing the names of all of the encodings that are currently available.

encoding system ?encoding?
Set the system encoding to encoding. If encoding is omitted then the command returns the current system encoding. The system encoding is used whenever Tcl passes strings to system calls.

EXAMPLE

It is common practice to write script files using a text editor that produces output in the euc-jp encoding, which represents the ASCII characters as singe bytes and Japanese characters as two bytes. This makes it easy to embed literal strings that correspond to non-ASCII characters by simply typing the strings in place in the script. However, because the source command always reads files using the ISO8859-1 encoding, Tcl will treat each byte in the file as a separate character that maps to the 00 page in Unicode. The resulting Tcl strings will not contain the expected Japanese characters. Instead, they will contain a sequence of Latin-1 characters that correspond to the bytes of the original string. The encoding command can be used to convert this string to the expected Japanese Unicode characters. For example,
set s [encoding convertfrom euc-jp "\xA4\xCF"]
would return the Unicode string "\u306F", which is the Hiragana letter HA.

SEE ALSO

Tcl_GetEncoding

KEYWORDS

encoding
Copyright © 1998 by Scriptics Corporation.


Tcl Built-In Commands - eof manual page

NAME

eof - Check for end of file condition on channel

SYNOPSIS

eof channelId

DESCRIPTION

Returns 1 if an end of file condition occurred during the most recent input operation on channelId (such as gets), 0 otherwise.

SEE ALSO

file, open, close, fblocked

KEYWORDS

channel, end of file
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - error manual page

NAME

error - Generate an error

SYNOPSIS

error message ?info? ?code?

DESCRIPTION

Returns a TCL_ERROR code, which causes command interpretation to be unwound. Message is a string that is returned to the application to indicate what went wrong.

If the info argument is provided and is non-empty, it is used to initialize the global variable errorInfo. errorInfo is used to accumulate a stack trace of what was in progress when an error occurred; as nested commands unwind, the Tcl interpreter adds information to errorInfo. If the info argument is present, it is used to initialize errorInfo and the first increment of unwind information will not be added by the Tcl interpreter. In other words, the command containing the error command will not appear in errorInfo; in its place will be info. This feature is most useful in conjunction with the catch command: if a caught error cannot be handled successfully, info can be used to return a stack trace reflecting the original point of occurrence of the error:

catch {...} errMsg
set savedInfo $errorInfo
    ...
error $errMsg $savedInfo

If the code argument is present, then its value is stored in the errorCode global variable. This variable is intended to hold a machine-readable description of the error in cases where such information is available; see the tclvars manual page for information on the proper format for the variable. If the code argument is not present, then errorCode is automatically reset to ``NONE'' by the Tcl interpreter as part of processing the error generated by the command.

SEE ALSO

catch, tclvars

KEYWORDS

error, errorCode, errorInfo
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - eval manual page

NAME

eval - Evaluate a Tcl script

SYNOPSIS

eval arg ?arg ...?

DESCRIPTION

Eval takes one or more arguments, which together comprise a Tcl script containing one or more commands. Eval concatenates all its arguments in the same fashion as the concat command, passes the concatenated string to the Tcl interpreter recursively, and returns the result of that evaluation (or any error generated by it).

KEYWORDS

concatenate, evaluate, script

SEE ALSO

catch, concat, error, subs, tclvars
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - exec manual page

NAME
exec - Invoke subprocess(es)
SYNOPSIS
exec ?switches? arg ?arg ...?
DESCRIPTION
-keepnewline
- -
|
|&
< fileName
<@ fileId
<< value
> fileName
2> fileName
>& fileName
>> fileName
2>> fileName
>>& fileName
>@ fileId
2>@ fileId
>&@ fileId
PORTABILITY ISSUES
Windows (all versions)
Windows NT
Windows 95
Macintosh
Unix
SEE ALSO
KEYWORDS

NAME

exec - Invoke subprocess(es)

SYNOPSIS

exec ?switches? arg ?arg ...?

DESCRIPTION

This command treats its arguments as the specification of one or more subprocesses to execute. The arguments take the form of a standard shell pipeline where each arg becomes one word of a command, and each distinct command becomes a subprocess.

If the initial arguments to exec start with - then they are treated as command-line switches and are not part of the pipeline specification. The following switches are currently supported:

-keepnewline
Retains a trailing newline in the pipeline's output. Normally a trailing newline will be deleted.

- -
Marks the end of switches. The argument following this one will be treated as the first arg even if it starts with a -.

If an arg (or pair of arg's) has one of the forms described below then it is used by exec to control the flow of input and output among the subprocess(es). Such arguments will not be passed to the subprocess(es). In forms such as ``< fileName'' fileName may either be in a separate argument from ``<'' or in the same argument with no intervening space (i.e. ``<fileName'').

|
Separates distinct commands in the pipeline. The standard output of the preceding command will be piped into the standard input of the next command.

|&
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 >&.

< fileName
The file named by fileName is opened and used as the standard input for the first command in the pipeline.

<@ fileId
FileId must be the identifier for an open file, such as the return value from a previous call to open. It is used as the standard input for the first command in the pipeline. FileId must have been opened for reading.

<< value
Value is passed to the first command as its standard input.

> fileName
Standard output from the last command is redirected to the file named fileName, overwriting its previous contents.

2> fileName
Standard error from all commands in the pipeline is redirected to the file named fileName, overwriting its previous contents.

>& fileName
Both standard output from the last command and standard error from all commands are redirected to the file named fileName, overwriting its previous contents.

>> fileName
Standard output from the last command is redirected to the file named fileName, appending to it rather than overwriting it.

2>> fileName
Standard error from all commands in the pipeline is redirected to the file named fileName, appending to it rather than overwriting it.

>>& fileName
Both standard output from the last command and standard error from all commands are redirected to the file named fileName, appending to it rather than overwriting it.

>@ fileId
FileId must be the identifier for an open file, such as the return value from a previous call to open. Standard output from the last command is redirected to fileId's file, which must have been opened for writing.

2>@ fileId
FileId must be the identifier for an open file, such as the return value from a previous call to open. Standard error from all commands in the pipeline is redirected to fileId's file. The file must have been opened for writing.

>&@ fileId
FileId must be the identifier for an open file, such as the return value from a previous call to open. Both standard output from the last command and standard error from all commands are redirected to fileId's file. The file must have been opened for writing.

If standard output has not been redirected then the exec command returns the standard output from the last command in the pipeline. If any of the commands in the pipeline exit abnormally or are killed or suspended, then exec will return an error and the error message will include the pipeline's output followed by error messages describing the abnormal terminations; the errorCode variable will contain additional information about the last abnormal termination encountered. If any of the commands writes to its standard error file and that standard error isn't redirected, then exec 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 output.

If the last character of the result or error message is a newline then that character is normally deleted from the result or error message. This is consistent with other Tcl return values, which don't normally end with newlines. However, if -keepnewline is specified then the trailing newline is retained.

If standard input isn't redirected with ``<'' or ``<<'' or ``<@'' then the standard input for the first command in the pipeline is taken from the application's current standard input.

If the last arg is ``&'' then the pipeline will be executed in background. In this case the exec command will return a list whose elements are the process identifiers for all of the subprocesses in the pipeline. The standard output from the last command in the pipeline will go to the application's standard output if it hasn't been redirected, and error output from all of the commands in the pipeline will go to the application's standard error file unless redirected.

The first word in each command is taken as the command name; tilde-substitution is performed on it, and if the result contains no slashes then the directories in the PATH environment variable are searched for an executable by the given name. If the name contains a slash then it must refer to an executable reachable from the current directory. No ``glob'' expansion or other shell-like substitutions are performed on the arguments to commands.

PORTABILITY ISSUES

Windows (all versions)
Reading from or writing to a socket, using the ``@ fileId'' notation, does not work. When reading from a socket, a 16-bit DOS application will hang and a 32-bit application will return immediately with end-of-file. When either type of application writes to a socket, the information is instead sent to the console, if one is present, or is discarded.

The Tk console text widget does not provide real standard IO capabilities. Under Tk, when redirecting from standard input, all applications will see an immediate end-of-file; information redirected to standard output or standard error will be discarded.

Either forward or backward slashes are accepted as path separators for arguments to Tcl commands. When executing an application, the path name specified for the application may also contain forward or backward slashes as path separators. Bear in mind, however, that most Windows applications accept arguments with forward slashes only as option delimiters and backslashes only in paths. Any arguments to an application that specify a path name with forward slashes will not automatically be converted to use the backslash character. If an argument contains forward slashes as the path separator, it may or may not be recognized as a path name, depending on the program.

Additionally, when calling a 16-bit DOS or Windows 3.X application, all path names must use the short, cryptic, path format (e.g., using ``applba~1.def'' instead of ``applbakery.default'').

Two or more forward or backward slashes in a row in a path refer to a network path. For example, a simple concatenation of the root directory c:/ with a subdirectory /windows/system will yield c://windows/system (two slashes together), which refers to the mount point called system on the machine called windows (and the c:/ is ignored), and is not equivalent to c:/windows/system, which describes a directory on the current computer. The file join command should be used to concatenate path components.

Windows NT
When attempting to execute an application, exec first searches for the name as it was specified. Then, in order, .com, .exe, and .bat are appended to the end of the specified name and it searches 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:

The directory from which the Tcl executable was loaded.
The current directory.
The Windows NT 32-bit system directory.
The Windows NT 16-bit system directory.
The Windows NT home directory.
The directories listed in the path.

In order to execute the shell builtin commands like dir and copy, the caller must prepend ``cmd.exe /c '' to the desired command.

Windows 95
When attempting to execute an application, exec first searches for the name as it was specified. Then, in order, .com, .exe, and .bat are appended to the end of the specified name and it searches 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:

The directory from which the Tcl executable was loaded.
The current directory.
The Windows 95 system directory.
The Windows 95 home directory.
The directories listed in the path.

In order to execute the shell builtin commands like dir and copy, the caller must prepend ``command.com /c '' to the desired command.

Once a 16-bit DOS application has read standard input from a console and then quit, all subsequently run 16-bit DOS applications will see the standard input as already closed. 32-bit applications do not have this problem and will run correctly, even after a 16-bit DOS application thinks that standard input is closed. There is no known workaround for this bug at this time.

Redirection between the NUL: device and a 16-bit application does not always work. When redirecting from NUL:, some applications may hang, others will get an infinite stream of ``0x01'' bytes, and some will actually correctly get an immediate end-of-file; the behavior seems to depend upon something compiled into the application itself. When redirecting greater than 4K or so to NUL:, some applications will hang. The above problems do not happen with 32-bit applications.

All DOS 16-bit applications are run synchronously. All standard input from a pipe to a 16-bit DOS application is collected into a temporary file; the other end of the pipe must be closed before the 16-bit DOS application begins executing. All standard output or error from a 16-bit DOS application to a pipe is collected into temporary files; the application must terminate before the temporary files are redirected to the next stage of the pipeline. This is due to a workaround for a Windows 95 bug in the implementation of pipes, and is how the standard Windows 95 DOS shell handles pipes itself.

Certain applications, such as command.com, should not be executed interactively. Applications which directly access the console window, rather than reading from their standard input and writing to their standard output may fail, hang Tcl, or even hang the system if their own private console window is not available to them.

Macintosh
The exec command is not implemented and does not exist under Macintosh.

Unix
The exec command is fully functional and works as described.

SEE ALSO

error, open

KEYWORDS

execute, pipeline, redirection, subprocess
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - exit manual page

NAME

exit - End the application

SYNOPSIS

exit ?returnCode?

DESCRIPTION

Terminate the process, returning returnCode to the system as the exit status. If returnCode isn't specified then it defaults to 0.

SEE ALSO

exec, tclvars

KEYWORDS

exit, process
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - expr manual page

NAME
expr - Evaluate an expression
SYNOPSIS
expr arg ?arg arg ...?
DESCRIPTION
OPERANDS
OPERATORS
- + ~ !
* / %
+ -
<< >>
< > <= >=
== !=
&
^
|
&&
||
x?y:z
MATH FUNCTIONS
abs(arg)
acos(arg)
asin(arg)
atan(arg)
atan2(x, y)
ceil(arg)
cos(arg)
cosh(arg)
double(arg)
exp(arg)
floor(arg)
fmod(x, y)
hypot(x, y)
int(arg)
log(arg)
log10(arg)
pow(x, y)
rand()
round(arg)
sin(arg)
sinh(arg)
sqrt(arg)
srand(arg)
tan(arg)
tanh(arg)
TYPES, OVERFLOW, AND PRECISION
STRING OPERATIONS
PERFORMANCE CONSIDERATIONS
KEYWORDS

NAME

expr - Evaluate an expression

SYNOPSIS

expr arg ?arg arg ...?

DESCRIPTION

Concatenates arg's (adding separator spaces between them), evaluates the result as a Tcl expression, and returns the value. The operators permitted in Tcl expressions are a subset of the operators permitted in C expressions, and they have the same meaning and precedence as the corresponding C operators. Expressions almost always yield numeric results (integer or floating-point values). For example, the expression
expr 8.2 + 6
evaluates to 14.2. Tcl expressions differ from C expressions in the way that operands are specified. Also, Tcl expressions support non-numeric operands and string comparisons.

OPERANDS

A Tcl expression consists of a combination of operands, operators, 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. Integer values may be specified in decimal (the normal case), in octal (if the first character of the operand is 0), or in hexadecimal (if the first two characters of the operand are 0x). If an operand does not have one of the integer formats given above, then it is treated as a floating-point number if that is possible. Floating-point numbers may be specified in any of the ways accepted by an ANSI-compliant C compiler (except that the f, F, l, and L suffixes will not be permitted in most installations). For example, all of the following are valid floating-point numbers: 2.1, 3., 6e4, 7.91e+16. If no numeric interpretation is possible, then an operand is left as a string (and only a limited set of operators may be applied to it).

Operands may be specified in any of the following ways:

[1]
As an numeric value, either integer or floating-point.

[2]
As a Tcl variable, using standard $ notation. The variable's value will be used as the operand.

[3]
As a string enclosed in double-quotes. The expression parser will perform backslash, variable, and command substitutions on the information between the quotes, and use the resulting value as the operand

[4]
As a string enclosed in braces. The characters between the open brace and matching close brace will be used as the operand without any substitutions.

[5]
As a Tcl command enclosed in brackets. The command will be executed and its result will be used as the operand.

[6]
As a mathematical function whose arguments have any of the above forms for operands, such as sin($x). See below for a list of defined functions.

Where substitutions occur above (e.g. inside quoted strings), they are performed by the expression's instructions. However, an additional layer of substitution may already have been performed by the command parser before the expression processor was called. As discussed below, it is usually best to enclose expressions in braces to prevent the command parser from performing substitutions on the contents.

For some examples of simple expressions, suppose the variable a has the value 3 and the variable b 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:

expr 3.1 + $a	6.1
expr 2 + "$a.$b"	5.6
expr 4*[llength "6 2"]	8
expr {{word one} < "word $a"}	0

OPERATORS

The valid operators are listed below, grouped in decreasing order of precedence:

- + ~ !
Unary minus, unary plus, bit-wise NOT, logical NOT. None of these operands may be applied to string operands, and bit-wise NOT may be applied only to integers.

* / %
Multiply, divide, remainder. None of these operands may be applied to string operands, and remainder may be applied only to integers. The remainder will always have the same sign as the divisor and an absolute value smaller than the divisor.

+ -
Add and subtract. Valid for any numeric operands.

<< >>
Left and right shift. Valid for integer operands only. A right shift always propagates the sign bit.

< > <= >=
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.

== !=
Boolean equal and not equal. Each operator produces a zero/one result. Valid for all operand types.

&
Bit-wise AND. Valid for integer operands only.

^
Bit-wise exclusive OR. Valid for integer operands only.

|
Bit-wise OR. Valid for integer operands only.

&&
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.

||
Logical OR. Produces a 0 result if both operands are zero, 1 otherwise. Valid for boolean and numeric (integers or floating-point) operands only.

x?y:z
If-then-else, as in C. If x evaluates to non-zero, then the result is the value of y. Otherwise the result is the value of z. The x operand must have a numeric value.

See the C manual for more details on the results produced by each operator. All of the binary operators group left-to-right within the same precedence level. For example, the command

expr 4*2 < 7
returns 0.

The &&, ||, and ?: operators have ``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

expr {$v ? [a] : [b]}
only one of [a] or [b] will actually be evaluated, depending on the value of $v. Note, however, that this is only true if the entire expression is enclosed in braces; otherwise the Tcl parser will evaluate both [a] and [b] before invoking the expr command.

MATH FUNCTIONS

Tcl supports the following mathematical functions in expressions:
abs	cosh	log	sqrt
acos	double	log10	srand
asin	exp	pow	tan
atan	floor	rand	tanh
atan2	fmod	round
ceil	hypot	sin
cos	int	sinh

abs(arg)
Returns the absolute value of arg. Arg may be either integer or floating-point, and the result is returned in the same form.

acos(arg)
Returns the arc cosine of arg, in the range [0,pi] radians. Arg should be in the range [-1,1].

asin(arg)
Returns the arc sine of arg, in the range [-pi/2,pi/2] radians. Arg should be in the range [-1,1].

atan(arg)
Returns the arc tangent of arg, in the range [-pi/2,pi/2] radians.

atan2(x, y)
Returns the arc tangent of y/x, in the range [-pi,pi] radians. x and y cannot both be 0.

ceil(arg)
Returns the smallest integer value not less than arg.

cos(arg)
Returns the cosine of arg, measured in radians.

cosh(arg)
Returns the hyperbolic cosine of arg. If the result would cause an overflow, an error is returned.

double(arg)
If arg is a floating value, returns arg, otherwise converts arg to floating and returns the converted value.

exp(arg)
Returns the exponential of arg, defined as e**arg. If the result would cause an overflow, an error is returned.

floor(arg)
Returns the largest integral value not greater than arg.

fmod(x, y)
Returns the floating-point remainder of the division of x by y. If y is 0, an error is returned.

hypot(x, y)
Computes the length of the hypotenuse of a right-angled triangle (x*x+y*y).

int(arg)
If arg is an integer value, returns arg, otherwise converts arg to integer by truncation and returns the converted value.

log(arg)
Returns the natural logarithm of arg. Arg must be a positive value.

log10(arg)
Returns the base 10 logarithm of arg. Arg must be a positive value.

pow(x, y)
Computes the value of x raised to the power y. If x is negative, y must be an integer value.

rand()
Returns a floating point number from zero to just less than one or, in mathematical terms, the range [0,1). The seed comes from the internal clock of the machine or may be set manual with the srand function.

round(arg)
If arg is an integer value, returns arg, otherwise converts arg to integer by rounding and returns the converted value.

sin(arg)
Returns the sine of arg, measured in radians.

sinh(arg)
Returns the hyperbolic sine of arg. If the result would cause an overflow, an error is returned.

sqrt(arg)
Returns the square root of arg. Arg must be non-negative.

srand(arg)
The arg, which must be an integer, is used to reset the seed for the random number generator. Returns the first random number from that seed. Each interpreter has it's own seed.

tan(arg)
Returns the tangent of arg, measured in radians.

tanh(arg)
Returns the hyperbolic tangent of arg.

In addition to these predefined functions, applications may define additional functions using Tcl_CreateMathFunc().

TYPES, OVERFLOW, AND PRECISION

All internal computations involving integers are done with the C type long, and all internal computations involving floating-point are done with the C type double. When converting a string to floating-point, exponent overflow is detected and results in a Tcl error. For conversion to integer from string, detection of overflow depends on the behavior of some routines in the local C library, so it should be regarded as unreliable. In any case, integer overflow and underflow are generally not detected reliably for intermediate results. Floating-point overflow and underflow are detected to the degree supported by the hardware, which is generally pretty reliable.

Conversion among internal representations for integer, floating-point, 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,

expr 5 / 4
returns 1, while
expr 5 / 4.0
expr 5 / ( [string length "abcd"] + 0.0 )
both return 1.25. Floating-point values are always returned with a ``.'' or an e so that they will not look like integer values. For example,
expr 20.0/5.0
returns 4.0, not 4.

STRING OPERATIONS

String values may be used as operands of the comparison operators, although the expression evaluator tries to do comparisons as integer or floating-point when it can. If one of the operands of a comparison is a string and the other has a numeric value, the numeric operand is converted back to a string using the C sprintf format specifier %d for integers and %g for floating-point values. For example, the commands
expr {"0x03" > "2"}
expr {"0y" < "0x12"}
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 18. Because of Tcl's tendency to treat values as numbers whenever possible, it isn't generally a good idea to use operators like == when you really want string comparison and the values of the operands could be arbitrary; it's better in these cases to use the string command instead.

PERFORMANCE CONSIDERATIONS

Enclose expressions in braces for the best speed and the smallest storage requirements. 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 expr command. For example, the commands

set a 3
set b {$a + 2}
expr $b*4
return 11, not a multiple of 4. This is because the Tcl parser will first substitute $a + 2 for the variable b, then the expr command will evaluate the expression $a + 2*4.

Most expressions do not require a second round of substitutions. Either they are enclosed in braces or, if not, their variable and command substitutions yield numbers or strings that don't themselves require substitutions. However, because a few unbraced expressions need two rounds of substitutions, the bytecode compiler must emit additional instructions to handle this situation. 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.

KEYWORDS

arithmetic, boolean, compare, expression, fuzzy comparison
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-2000 Sun Microsystems, Inc.


Tcl Built-In Commands - fblocked manual page

NAME

fblocked - Test whether the last input operation exhausted all available input

SYNOPSIS

fblocked channelId

DESCRIPTION

The fblocked command returns 1 if the most recent input operation on channelId returned less information than requested because all available input was exhausted. For example, if gets is invoked when there are only three characters available for input and no end-of-line sequence, gets returns an empty string and a subsequent call to fblocked will return 1.

SEE ALSO

gets, open, read

KEYWORDS

blocking, nonblocking
Copyright © 1996 Sun Microsystems, Inc.


Tcl Built-In Commands - fconfigure manual page

NAME
fconfigure - Set and get options on a channel
SYNOPSIS
fconfigure channelId
fconfigure channelId name
fconfigure channelId name value ?name value ...?
DESCRIPTION
-blocking boolean
-buffering newValue
-buffersize newSize
-encoding name
-eofchar char
-eofchar {inChar outChar}
-translation mode
-translation {inMode outMode}
auto
binary
cr
crlf
lf
SEE ALSO
KEYWORDS

NAME

fconfigure - Set and get options on a channel

SYNOPSIS

fconfigure channelId
fconfigure channelId name
fconfigure channelId name value ?name value ...?

DESCRIPTION

The fconfigure command sets and retrieves options for channels. ChannelId identifies the channel for which to set or query an option. If no name or value arguments are supplied, the command returns a list containing alternating option names and values for the channel. If name is supplied but no value then the command returns the current value of the given option. If one or more pairs of name and value are supplied, the command sets each of the named options to the corresponding value; in this case the return value is an empty string.

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 socket command for its additional options.

-blocking boolean
The -blocking option determines whether I/O operations on the channel can cause the process to block indefinitely. The value of the option must be a proper boolean value. Channels are normally in blocking mode; if a channel is placed into nonblocking mode it will affect the operation of the gets, read, puts, flush, and close commands; see the documentation for those commands for details. For nonblocking mode to work correctly, the application must be using the Tcl event loop (e.g. by calling Tcl_DoOneEvent or invoking the vwait command).

-buffering newValue
If newValue is full then the I/O system will buffer output until its internal buffer is full or until the flush command is invoked. If newValue is line, then the I/O system will automatically flush output for the channel whenever a newline character is output. If newValue is none, the I/O system will flush automatically after every output operation. The default is for -buffering to be set to full except for channels that connect to terminal-like devices; for these channels the initial setting is line. Additionally, stdin and stdout are intially set to line, and stderr is set to none.

-buffersize newSize
Newvalue must be an integer; its value is used to set the size of buffers, in bytes, subsequently allocated for this channel to store input or output. Newvalue must be between ten and one million, allowing buffers of ten to one million bytes in size.

-encoding name
This option is used to specify the encoding of the channel, so that the data can be converted to and from Unicode for use in Tcl. For instance, in order for Tcl to read characters from a Japanese file in shiftjis and properly process and display the contents, the encoding would be set to shiftjis. Thereafter, when reading from the channel, the bytes in the Japanese file would be converted to Unicode as they are read. Writing is also supported - as Tcl strings are written to the channel they will automatically be converted to the specified encoding on output.

If a file contains pure binary data (for instance, a JPEG image), the encoding for the channel should be configured to be binary. Tcl will then assign no interpretation to the data in the file and simply read or write raw bytes. The Tcl binary command can be used to manipulate this byte-oriented data.

The default encoding for newly opened channels is the same platform- and locale-dependent system encoding used for interfacing with the operating system.

-eofchar char

-eofchar {inChar outChar}
This option supports DOS file systems that use Control-z (\x1a) as an end of file marker. If char is not an empty string, then this character signals end-of-file when it is encountered during input. For output, the end-of-file character is output when the channel is closed. If char is the empty string, then there is no special end of file character marker. For read-write channels, a two-element list specifies the end of file marker for input and output, respectively. As a convenience, when setting the end-of-file character for a read-write channel you can specify a single value that will apply to both reading and writing. When querying the end-of-file character of a read-write channel, a two-element list will always be returned. The default value for -eofchar is the empty string in all cases except for files under Windows. In that case the -eofchar is Control-z (\x1a) for reading and the empty string for writing.

-translation mode

-translation {inMode outMode}
In Tcl scripts the end of a line is always represented using a single newline character (\n). However, in actual files and devices the end of a line may be represented differently on different platforms, or even for different devices on the same platform. For example, under UNIX newlines are used in files, whereas carriage-return-linefeed sequences are normally used in network connections. On input (i.e., with gets and read) the Tcl I/O system automatically translates the external end-of-line representation into newline characters. Upon output (i.e., with puts), the I/O system translates newlines to the external end-of-line representation. The default translation mode, auto, handles all the common cases automatically, but the -translation option provides explicit control over the end of line translations.

The value associated with -translation is a single item for read-only and write-only channels. The value is a two-element list for read-write channels; the read translation mode is the first element of the list, and the write translation mode is the second element. As a convenience, when setting the translation mode for a read-write channel you can specify a single value that will apply to both reading and writing. When querying the translation mode of a read-write channel, a two-element list will always be returned. The following values are currently supported:

auto
As the input translation mode, auto treats any of newline (lf), carriage return (cr), or carriage return followed by a newline (crlf) as the end of line representation. The end of line representation can even change from line-to-line, and all cases are translated to a newline. As the output translation mode, auto chooses a platform specific representation; for sockets on all platforms Tcl chooses crlf, for all Unix flavors, it chooses lf, for the Macintosh platform it chooses cr and for the various flavors of Windows it chooses crlf. The default setting for -translation is auto for both input and output.

binary
No end-of-line translations are performed. This is nearly identical to lf mode, except that in addition binary mode also sets the end-of-file character to the empty string (which disables it) and sets the encoding to binary (which disables encoding filtering). See the description of -eofchar and -encoding for more information.

cr
The end of a line in the underlying file or device is represented by a single carriage return character. As the input translation mode, cr mode converts carriage returns to newline characters. As the output translation mode, cr mode translates newline characters to carriage returns. This mode is typically used on Macintosh platforms.

crlf
The end of a line in the underlying file or device is represented by a carriage return character followed by a linefeed character. As the input translation mode, crlf mode converts carriage-return-linefeed sequences to newline characters. As the output translation mode, crlf mode translates newline characters to carriage-return-linefeed sequences. This mode is typically used on Windows platforms and for network connections.

lf
The end of a line in the underlying file or device is represented by a single newline (linefeed) character. In this mode no translations occur during either input or output. This mode is typically used on UNIX platforms.

SEE ALSO

close, flush, gets, puts, read, socket

KEYWORDS

blocking, buffering, carriage return, end of line, flushing, linemode, newline, nonblocking, platform, translation, encoding, filter, byte array, binary
Copyright © 1995-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - fcopy manual page

NAME

fcopy - Copy data from one channel to another.

SYNOPSIS

fcopy inchan outchan ?-size size? ?-command callback?

DESCRIPTION

The fcopy command copies data from one I/O channel, inchan to another I/O channel, outchan. The fcopy command leverages the buffering in the Tcl I/O system to avoid extra copies and to avoid buffering too much data in main memory when copying large files to slow destinations like network sockets.

The fcopy command transfers data from inchan until end of file or size bytes have been transferred. If no -size argument is given, then the copy goes until end of file. All the data read from inchan is copied to outchan. Without the -command option, fcopy blocks until the copy is complete and returns the number of bytes written to outchan.

The -command argument makes fcopy work in the background. In this case it returns immediately and the callback is invoked later when the copy completes. The callback is called with one or two additional arguments that indicates how many bytes were written to outchan. If an error occurred during the background copy, the second argument is the error string associated with the error. With a background copy, it is not necessary to put inchan or outchan into non-blocking mode; the fcopy command takes care of that automatically. However, it is necessary to enter the event loop by using the vwait command or by using Tk.

You are not allowed to do other I/O operations with inchan or outchan during a background fcopy. If either inchan or outchan get closed while the copy is in progress, the current copy is stopped and the command callback is not made. If inchan is closed, then all data already queued for outchan is written out.

Note that inchan can become readable during a background copy. You should turn off any fileevent handlers during a background copy so those handlers do not interfere with the copy. Any I/O attempted by a fileevent handler will get a "channel busy" error.

Fcopy translates end-of-line sequences in inchan and outchan according to the -translation option for these channels. See the manual entry for fconfigure for details on the -translation option. The translations mean that the number of bytes read from inchan can be different than the number of bytes written to outchan. Only the number of bytes written to outchan is reported, either as the return value of a synchronous fcopy or as the argument to the callback for an asynchronous fcopy.

EXAMPLE

This first example shows how the callback gets 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.
proc Cleanup {in out bytes {error {}}} {
    global total
    set total $bytes
    close $in
    close $out
    if {[string length $error] != 0} {
    # error occurred during the copy
    }
}
set in [open $file1]
set out [socket $server $port]
fcopy $in $out -command [list Cleanup $in $out]
vwait total

The second example copies in chunks and tests for end of file in the command callback

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
    } else {
    fcopy $in $out -command [list CopyMore $in $out $chunk] \
        -size $chunk
    }
}
set in [open $file1]
set out [socket $server $port]
set chunk 1024
set total 0
fcopy $in $out -command [list CopyMore $in $out $chunk] -size $chunk
vwait done

SEE ALSO

eof, fblocked, fconfigure

KEYWORDS

blocking, channel, end of line, end of file, nonblocking, read, translation
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Built-In Commands - file manual page

NAME
file - Manipulate file names and attributes
SYNOPSIS
file option name ?arg arg ...?
DESCRIPTION
file atime name ?time?
file attributes name
file channels ?pattern?
file copy ?-force? ?- -? source target
file delete ?-force? ?- -? pathname ?pathname ... ?
file dirname name
file executable name
file exists name
file extension name
file isdirectory name
file isfile name
file join name ?name ...?
file lstat name varName
file mkdir dir ?dir ...?
file mtime name ?time?
file nativename name
file owned name
file pathtype name
file readable name
file readlink name
file rename ?-force? ?- -? source target
file rename ?-force? ?- -? source ?source ...? targetDir
file rootname name
file size name
file split name
file stat name varName
file tail name
file type name
file volume
file writable name
PORTABILITY ISSUES
Unix
SEE ALSO
KEYWORDS

NAME

file - Manipulate file names and attributes

SYNOPSIS

file option name ?arg arg ...?

DESCRIPTION

This command provides several operations on a file's name or attributes. Name is the name of a file; if it starts with a tilde, then tilde substitution is done before executing the command (see the manual entry for filename for details). Option indicates what to do with the file name. Any unique abbreviation for option is acceptable. The valid options are:

file atime name ?time?
Returns a decimal string giving the time at which file name was last accessed. If time is specified, it is an access time to set for the file. The time is measured in the standard POSIX fashion as seconds from a fixed starting time (often January 1, 1970). If the file doesn't exist or its access time cannot be queried or set then an error is generated. On Windows, FAT file systems do not support access time.

file attributes name

file attributes name ?option?
file attributes name ?option value option value...?

This subcommand returns or sets platform specific values associated with a file. The first form returns a list of the platform specific flags and their values. The second form returns the value for the specific option. The third form sets one or more of the values. The values are as follows:

On Unix, -group gets or sets the group name for the file. A group id can be given to the command, but it returns a group name. -owner gets or sets the user name of the owner of the file. The command returns the owner name, but the numerical id can be passed when setting the owner. -permissions sets or retrieves the octal code that chmod(1) uses. This command does also has limited support for setting using the symbolic attributes for chmod(1), of the form [ugo]?[[+-=][rwxst],[...]], where multiple symbolic attributes can be separated by commas (example: u+s,go-rw add sticky bit for user, remove read and write permissions for group and other). A simplified ls style string, of the form rwxrwxrwx (must be 9 characters), is also supported (example: rwxr-xr-t is equivalent to 01755).

On Windows, -archive gives the value or sets or clears the archive attribute of the file. -hidden gives the value or sets or clears the hidden attribute of the file. -longname will expand each path element to its long version. This attribute cannot be set. -readonly gives the value or sets or clears the readonly attribute of the file. -shortname gives a string where every path element is replaced with its short (8.3) version of the name. This attribute cannot be set. -system gives or sets or clears the value of the system attribute of the file.

On Macintosh, -creator gives or sets the Finder creator type of the file. -hidden gives or sets or clears the hidden attribute of the file. -readonly gives or sets or clears the readonly attribute of the file. Note that directories can only be locked if File Sharing is turned on. -type gives or sets the Finder file type for the file.

file channels ?pattern?
If pattern isn't specified, returns a list of names of all registered open channels in this interpreter. If pattern is specified, only those names matching pattern are returned. Matching is determined using the same rules as for string match.

file copy ?-force? ?- -? source target

file copy ?-force? ?- -? source ?source ...? targetDir

The first form makes a copy of the file or directory source under the pathname target. If target is an existing directory, then the second form is used. The second form makes a copy inside targetDir of each source file listed. If a directory is specified as a source, then the contents of the directory will be recursively copied into targetDir. Existing files will not be overwritten unless the -force option is specified. Trying to overwrite a non-empty directory, overwrite a directory with a file, or a file with a directory will all result in errors even if -force was specified. Arguments are processed in the order specified, halting at the first error, if any. A - - marks the end of switches; the argument following the - - will be treated as a source even if it starts with a -.

file delete ?-force? ?- -? pathname ?pathname ... ?
Removes the file or directory specified by each pathname argument. Non-empty directories will be removed only if the -force option is specified. Trying to delete a non-existant file is not considered an error. Trying to delete a read-only file will cause the file to be deleted, even if the -force flags is not specified. Arguments are processed in the order specified, halting at the first error, if any. A - - marks the end of switches; the argument following the - - will be treated as a pathname even if it starts with a -.

file dirname name
Returns a name comprised of all of the path components in name excluding the last element. If name is a relative file name and only contains one path element, then returns ``.'' (or ``:'' on the Macintosh). If name refers to a root directory, then the root directory is returned. For example,
file dirname c:/
returns c:/.

Note that tilde substitution will only be performed if it is necessary to complete the command. For example,

file dirname ~/src/foo.c
returns ~/src, whereas
file dirname ~
returns /home (or something similar).

file executable name
Returns 1 if file name is executable by the current user, 0 otherwise.

file exists name
Returns 1 if file name exists and the current user has search privileges for the directories leading to it, 0 otherwise.

file extension name
Returns all of the characters in name after and including the last dot in the last element of name. If there is no dot in the last element of name then returns the empty string.

file isdirectory name
Returns 1 if file name is a directory, 0 otherwise.

file isfile name
Returns 1 if file name is a regular file, 0 otherwise.

file join name ?name ...?
Takes one or more file names and combines them, using the correct path separator for the current platform. If a particular name is 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,
file join a b /foo bar
returns /foo/bar.

Note that any of the names can contain separators, and that the result is always canonical for the current platform: / for Unix and Windows, and : for Macintosh.

file lstat name varName
Same as stat option (see below) except uses the lstat kernel call instead of stat. This means that if name refers to a symbolic link the information returned in varName is for the link rather than the file it refers to. On systems that don't support symbolic links this option behaves exactly the same as the stat option.

file mkdir dir ?dir ...?
Creates each directory specified. For each pathname dir specified, this command will create all non-existing parent directories as well as dir itself. If an existing directory is specified, then no action is taken and no error is returned. Trying to overwrite an existing file with a directory will result in an error. Arguments are processed in the order specified, halting at the first error, if any.

file mtime name ?time?
Returns a decimal string giving the time at which file name was last modified. If time is specified, it is a modification time to set for the file (equivalent to Unix touch). The time is measured in the standard POSIX fashion as seconds from a fixed starting time (often January 1, 1970). If the file doesn't exist or its modified time cannot be queried or set then an error is generated.

file nativename name
Returns the platform-specific name of the file. This is useful if the filename is needed to pass to a platform-specific call, such as exec under Windows or AppleScript on the Macintosh.

file owned name
Returns 1 if file name is owned by the current user, 0 otherwise.

file pathtype name
Returns one of absolute, relative, volumerelative. If name refers to a specific file on a specific volume, the path type will be absolute. If name refers to a file relative to the current working directory, then the path type will be relative. If name refers to a file relative to the current working directory on a specified volume, or to a specific file on the current working volume, then the file type is volumerelative.

file readable name
Returns 1 if file name is readable by the current user, 0 otherwise.

file readlink name
Returns the value of the symbolic link given by name (i.e. the name of the file it points to). If name isn't a symbolic link or its value cannot be read, then an error is returned. On systems that don't support symbolic links this option is undefined.

file rename ?-force? ?- -? source target
file rename ?-force? ?- -? source ?source ...? targetDir
The first form takes the file or directory specified by pathname source and renames it to target, moving the file if the pathname target specifies a name in a different directory. If target is an existing directory, then the second form is used. The second form moves each source file or directory into the directory targetDir. Existing files will not be overwritten unless the -force option is specified. Trying to overwrite a non-empty directory, overwrite a directory with a file, or a file with a directory will all result in errors. Arguments are processed in the order specified, halting at the first error, if any. A - - marks the end of switches; the argument following the - - will be treated as a source even if it starts with a -.

file rootname name
Returns all of the characters in name up to but not including the last ``.'' character in the last component of name. If the last component of name doesn't contain a dot, then returns name.

file size name
Returns a decimal string giving the size of file name in bytes. If the file doesn't exist or its size cannot be queried then an error is generated.

file split name
Returns a list whose elements are the path components in name. The first element of the list will have the same path type as name. All other elements will be relative. Path separators will be discarded unless they are needed ensure that an element is unambiguously relative. For example, under Unix
file split /foo/~bar/baz
returns / foo ./~bar baz to ensure that later commands that use the third component do not attempt to perform tilde substitution.

file stat name varName
Invokes the stat kernel call on name, and uses the variable given by varName to hold information returned from the kernel call. VarName is treated as an array variable, and the following elements of that variable are set: atime, ctime, dev, gid, ino, mode, mtime, nlink, size, type, uid. Each element except type is a decimal string with the value of the corresponding field from the stat return structure; see the manual entry for stat for details on the meanings of the values. The type element gives the type of the file in the same form returned by the command file type. This command returns an empty string.

file tail name
Returns all of the characters in name after the last directory separator. If name contains no separators then returns name.

file type name
Returns a string giving the type of file name, which will be one of file, directory, characterSpecial, blockSpecial, fifo, link, or socket.

file volume
Returns the absolute paths to the volumes mounted on the system, as a proper Tcl list. On the Macintosh, this will be a list of the mounted drives, both local and network. N.B. if two drives have the same name, they will both appear on the volume list, but there is currently no way, from Tcl, to access any but the first of these drives. On UNIX, the command will always return "/", since all filesystems are locally mounted. On Windows, it will return a list of the available local drives (e.g. {a:/ c:/}).

file writable name
Returns 1 if file name is writable by the current user, 0 otherwise.

PORTABILITY ISSUES

Unix
These commands always operate using the real user and group identifiers, not the effective ones.

SEE ALSO

filename

KEYWORDS

attributes, copy files, delete files, directory, file, move files, name, rename files, stat
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - fileevent manual page

NAME

fileevent - Execute a script when a channel becomes readable or writable

SYNOPSIS

fileevent channelId readable ?script?
fileevent channelId writable ?script?

DESCRIPTION

This command is used to create file event handlers. A file event handler is a binding between a channel and a script, such that the script is evaluated whenever the channel becomes readable or writable. File event handlers are most commonly used to allow data to be received from another process on an event-driven basis, so that the receiver can continue to interact with the user while waiting for the data to arrive. If an application invokes gets or read on a blocking channel when there is no input data available, the process will block; until the input data arrives, it will not be able to service other events, so it will appear to the user to ``freeze up''. With fileevent, the process can tell when data is present and only invoke gets or read when they won't block.

The channelId argument to fileevent refers to an open channel, such as the return value from a previous open or socket command. If the script argument is specified, then fileevent creates a new event handler: script will be evaluated whenever the channel becomes readable or writable (depending on the second argument to fileevent). In this case fileevent returns an empty string. The readable and writable event handlers for a file are independent, and may be created and deleted separately. However, there may be at most one readable and one writable handler for a file at a given time in a given interpreter. If fileevent is called when the specified handler already exists in the invoking interpreter, the new script replaces the old one.

If the script argument is not specified, fileevent returns the current script for channelId, or an empty string if there is none. If the script argument is specified as an empty string then the event handler is deleted, so that no script will be invoked. A file event handler is also deleted automatically whenever its channel is closed or its interpreter is deleted.

A channel is considered to be readable if there is unread data available on the underlying device. A channel is also considered to be readable if there is unread data in an input buffer, except in the special case where the most recent attempt to read from the channel was a gets call that could not find a complete line in the input buffer. This feature allows a file to be read a line at a time in nonblocking mode using events. A channel is also considered to be readable if an end of file or error condition is present on the underlying file or device. It is important for script to check for these conditions and handle them appropriately; for example, if there is no special check for end of file, an infinite loop may occur where script reads no data, returns, and is immediately invoked again.

A channel is considered to be writable if at least one byte of data can be written to the underlying file or device without blocking, or if an error condition is present on the underlying file or device.

Event-driven I/O works best for channels that have been placed into nonblocking mode with the fconfigure command. In blocking mode, a puts command may block if you give it more data than the underlying file or device can accept, and a gets or read command will block if you attempt to read more data than is ready; no events will be processed while the commands block. In nonblocking mode puts, read, and gets never block. See the documentation for the individual commands for information on how they handle blocking and nonblocking channels.

The script for a file event is executed at global level (outside the context of any Tcl procedure) in the interpreter in which the fileevent command was invoked. If an error occurs while executing the script then the bgerror mechanism is used to report the error. 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.

CREDITS

fileevent is based on the addinput command created by Mark Diekhans.

SEE ALSO

bgerror, fconfigure, gets, puts, read

KEYWORDS

asynchronous I/O, blocking, channel, event handler, nonblocking, readable, script, writable.
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - filename manual page

NAME
filename - File name conventions supported by Tcl commands
INTRODUCTION
PATH TYPES
PATH SYNTAX
mac
:
MyFile
MyDisk:MyFile
:MyDir:MyFile
::MyFile
:::MyFile
/MyDisk/MyFile
../MyFile
unix
/
/etc/passwd
.
foo
foo/bar
../foo
windows
\\Host\share/file
c:foo
c:/foo
foo\bar
\foo
TILDE SUBSTITUTION
PORTABILITY ISSUES
KEYWORDS
SEE ALSO

NAME

filename - File name conventions supported by Tcl commands

INTRODUCTION

All Tcl commands and C procedures that take file names as arguments expect the file names to be in one of three forms, depending on the current platform. On each platform, Tcl supports file names in the standard forms(s) for that platform. In addition, on all platforms, Tcl supports a Unix-like syntax intended to provide a convenient way of constructing simple file names. However, scripts that are intended to be portable should not assume a particular form for file names. Instead, portable scripts must use the file split and file join commands to manipulate file names (see the file manual entry for more details).

PATH TYPES

File names are grouped into three general types based on the starting point for the path used to specify the file: absolute, relative, and volume-relative. Absolute names are completely qualified, giving a path to the file relative to a particular volume and the root directory on that volume. Relative names are unqualified, giving a path to the file relative to the current working directory. Volume-relative names are partially qualified, either giving the path relative to the root directory on the current volume, or relative to the current directory of the specified volume. The file pathtype command can be used to determine the type of a given path.

PATH SYNTAX

The rules for native names depend on the value reported in the Tcl array element tcl_platform(platform):

mac
On Apple Macintosh systems, Tcl supports two forms of path names. The normal Mac style names use colons as path separators. Paths may be relative or absolute, and file names may contain any character other than colon. A leading colon causes the rest of the path to be interpreted relative to the current directory. If a path contains a colon that is not at the beginning, then the path is interpreted as an absolute path. Sequences of two or more colons anywhere in the path are used to construct relative paths where :: refers to the parent of the current directory, ::: refers to the parent of the parent, and so forth.

In addition to Macintosh style names, Tcl also supports a subset of Unix-like names. If a path contains no colons, then it is interpreted like a Unix path. Slash is used as the path separator. The file name . refers to the current directory, and .. refers to the parent of the current directory. However, some names like / or /.. have no mapping, and are interpreted as Macintosh names. In general, commands that generate file names will return Macintosh style names, but commands that accept file names will take both Macintosh and Unix-style names.

The following examples illustrate various forms of path names:

:
Relative path to the current folder.

MyFile
Relative path to a file named MyFile in the current folder.

MyDisk:MyFile
Absolute path to a file named MyFile on the device named MyDisk.

:MyDir:MyFile
Relative path to a file name MyFile in a folder named MyDir in the current folder.

::MyFile
Relative path to a file named MyFile in the folder above the current folder.

:::MyFile
Relative path to a file named MyFile in the folder two levels above the current folder.

/MyDisk/MyFile
Absolute path to a file named MyFile on the device named MyDisk.

../MyFile
Relative path to a file named MyFile in the folder above the current folder.

unix
On Unix platforms, Tcl uses path names where the components are separated by slashes. Path names may be relative or absolute, and file names may contain any character other than slash. The file names . and .. are special and refer to the current directory and the parent of the current directory respectively. Multiple adjacent slash characters are interpreted as a single separator. The following examples illustrate various forms of path names:

/
Absolute path to the root directory.

/etc/passwd
Absolute path to the file named passwd in the directory etc in the root directory.

.
Relative path to the current directory.

foo
Relative path to the file foo in the current directory.

foo/bar
Relative path to the file bar in the directory foo in the current directory.

../foo
Relative path to the file foo in the directory above the current directory.

windows
On Microsoft Windows platforms, Tcl supports both drive-relative and UNC style names. Both / and \ may be used as directory separators in either type of name. Drive-relative names consist of an optional drive specifier followed by an absolute or relative path. UNC paths follow the general form \\servername\sharename\path\file. In both forms, the file names . and .. are special and refer to the current directory and the parent of the current directory respectively. The following examples illustrate various forms of path names:

\\Host\share/file
Absolute UNC path to a file called file in the root directory of the export point share on the host Host.

c:foo
Volume-relative path to a file foo in the current directory on drive c.

c:/foo
Absolute path to a file foo in the root directory of drive c.

foo\bar
Relative path to a file bar in the foo directory in the current directory on the current volume.

\foo
Volume-relative path to a file foo in the root directory of the current volume.

TILDE SUBSTITUTION

In addition to the file name rules described above, Tcl also supports csh-style tilde substitution. If a file name starts with a tilde, then the file name will be interpreted as if the first element is replaced with the location of the home directory for the given user. If the tilde is followed immediately by a separator, then the $HOME environment variable is substituted. Otherwise the characters between the tilde and the next separator are taken as a user name, which is used to retrieve the user's home directory for substitution.

The Macintosh and Windows platforms do not support tilde substitution when a user name follows the tilde. On these platforms, attempts to use a tilde followed by a user name will generate an error. File names that have a tilde without a user name will be substituted using the $HOME environment variable, just like for Unix.

PORTABILITY ISSUES

Not all file systems are case sensitive, so scripts should avoid code that depends on the case of characters in a file name. In addition, the character sets allowed on different devices may differ, so scripts should choose file names that do not contain special characters like: <>:"/\|. The safest approach is to use names consisting of alphanumeric characters only. Also Windows 3.1 only supports file names with a root of no more than 8 characters and an extension of no more than 3 characters.

KEYWORDS

current directory, absolute file name, relative file name, volume-relative file name, portability

SEE ALSO

file, glob
Copyright © 1995-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - flush manual page

NAME

flush - Flush buffered output for a channel

SYNOPSIS

flush channelId

DESCRIPTION

Flushes any output that has been buffered for channelId. ChannelId must be a channel identifier such as returned by a previous open or socket command, and it must have been opened for writing. If the channel is in blocking mode the command does not return until all the buffered output has been flushed to the channel. If the channel is in 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.

SEE ALSO

file, open, socket

KEYWORDS

blocking, buffer, channel, flush, nonblocking, output
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - for manual page

NAME

for - ``For'' loop

SYNOPSIS

for start test next body

DESCRIPTION

For is a looping command, similar in structure to the C for statement. The start, next, and body arguments must be Tcl command strings, and test is an expression string. The for command first invokes the Tcl interpreter to execute start. Then it repeatedly evaluates test as an expression; if the result is non-zero it invokes the Tcl interpreter on body, then invokes the Tcl interpreter on next, then repeats the loop. The command terminates when test evaluates to 0. If a continue command is invoked within body then any remaining commands in the current execution of body are skipped; processing continues by invoking the Tcl interpreter on next, then evaluating test, and so on. If a break command is invoked within body or next, then the for command will return immediately. The operation of break and continue are similar to the corresponding statements in C. For returns an empty string.

Note: test should almost always be enclosed in braces. If not, variable substitutions will be made before the for command starts executing, which means that variable changes made by the loop body will not be considered in the expression. This is likely to result in an infinite loop. If test is enclosed in braces, variable substitutions are delayed until the 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 $x<10:

for {set x 0} {$x<10} {incr x} {
    puts "x is $x"
}

SEE ALSO

break, continue, foreach, while

KEYWORDS

for, iteration, looping
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Built-In Commands - foreach manual page

NAME

foreach - Iterate over all elements in one or more lists

SYNOPSIS

foreach varname list body
foreach varlist1 list1 ?varlist2 list2 ...? body

DESCRIPTION

The foreach command implements a loop where the loop variable(s) take on values from one or more lists. In the simplest case there is one loop variable, varname, and one list, list, that is a list of values to assign to varname. The body argument is a Tcl script. For each element of list (in order from first to last), foreach assigns the contents of the element to varname as if the lindex command had been used to extract the element, then calls the Tcl interpreter to execute body.

In the general case there can be more than one value list (e.g., list1 and list2), and each value list can be associated with a list of loop variables (e.g., varlist1 and varlist2). During each iteration of the loop the variables of each varlist are assigned consecutive values from the corresponding list. Values in each list are used in order from first to last, and each value is used exactly once. The total number of loop iterations is large enough to use up all the values from all the value lists. If a value list does not contain enough elements for each of its loop variables in each iteration, empty values are used for the missing elements.

The break and continue statements may be invoked inside body, with the same effect as in the for command. Foreach returns an empty string.

EXAMPLES

The following loop uses i and j as loop variables to iterate over pairs of elements of a single list.
set x {}
foreach {i j} {a b c d e f} {
    lappend x $j $i
}
# The value of x is "b a d c f e"
# There are 3 iterations of the loop.

The next loop uses i and j to iterate over two lists in parallel.

set x {}
foreach i {a b c} j {d e f g} {
    lappend x $i $j
}
# The value of x is "a d b e c f {} g"
# There are 4 iterations of the loop.

The two forms are combined in the following example.

set x {}
foreach i {a b c} {j k} {d e f g} {
    lappend x $i $j $k
}
# The value of x is "a d e b f g c {} {}"
# There are 3 iterations of the loop.

SEE ALSO

for, while, break, continue

KEYWORDS

foreach, iteration, list, looping
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - format manual page

NAME
format - Format a string in the style of sprintf
SYNOPSIS
format formatString ?arg arg ...?
INTRODUCTION
DETAILS ON FORMATTING
-
+
space
0
#
d
u
i
o
x or X
c
s
f
e or e
g or G
%
DIFFERENCES FROM ANSI SPRINTF
SEE ALSO
KEYWORDS

NAME

format - Format a string in the style of sprintf

SYNOPSIS

format formatString ?arg arg ...?

INTRODUCTION

This command generates a formatted string in the same way as the ANSI C sprintf procedure (it uses sprintf in its implementation). FormatString indicates how to format the result, using % conversion specifiers as in sprintf, and the additional arguments, if any, provide values to be substituted into the result. The return value from format is the formatted string.

DETAILS ON FORMATTING

The command operates by scanning formatString from left to right. Each character from the format string is appended to the result string unless it is a percent sign. If the character is a % then it is not copied to the result string. Instead, the characters following the % character are treated as a conversion specifier. The conversion specifier controls the conversion of the next successive arg to a particular format and the result is appended to the result string in place of the conversion specifier. If there are multiple conversion specifiers in the format string, then each one controls the conversion of one additional arg. The format command must be given enough args to meet the needs of all of the conversion specifiers in formatString.

Each conversion specifier may contain up to six different parts: an XPG3 position specifier, a set of flags, a minimum field width, a precision, a length modifier, 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.

If the % is followed by a decimal number and a $, as in ``%2$d'', then the value to convert is not taken from the next sequential argument. Instead, it is taken from the argument indicated by the number, where 1 corresponds to the first arg. If the conversion specifier requires multiple arguments because of * characters in the specifier then successive arguments are used, starting with the argument given by the number. This follows the XPG3 conventions for positional specifiers. If there are any positional specifiers in formatString then all of the specifiers must be positional.

The second portion of a conversion specifier may contain any of the following flag characters, in any order:

-
Specifies that the converted argument should be left-justified in its field (numbers are normally right-justified with leading spaces if needed).

+
Specifies that a number should always be printed with a sign, even if positive.

space
Specifies that a space should be added to the beginning of the number if the first character isn't a sign.

0
Specifies that the number should be padded on the left with zeroes instead of spaces.

#
Requests an alternate output form. For o and O conversions it guarantees that the first digit is always 0. For x or X conversions, 0x or 0X (respectively) will be added to the beginning of the result unless it is zero. For all floating-point conversions (e, E, f, g, and G) it guarantees that the result always has a decimal point. For g and G conversions it specifies that trailing zeroes should not be removed.

The third portion of a conversion specifier is a number giving a minimum field width for this conversion. It is typically used to make columns line up in tabular printouts. If the converted argument contains fewer characters than the minimum field width then it will be padded so that it is as wide as the minimum field width. Padding normally occurs by adding extra spaces on the left of the converted argument, but the 0 and - flags may be used to specify padding with zeroes on the left or with spaces on the right, respectively. If the minimum field width is specified as * rather than a number, then the next argument to the format command determines the minimum field width; it must be a numeric string.

The fourth portion of a conversion specifier is a precision, which consists of a period followed by a number. The number is used in different ways for different conversions. For e, E, and f conversions it specifies the number of digits to appear to the right of the decimal point. For g and G conversions it specifies the total number of digits to appear, including those on both sides of the decimal point (however, trailing zeroes after the decimal point will still be omitted unless the # flag has been specified). For integer conversions, it specifies a minimum number of digits to print (leading zeroes will be added if necessary). For s conversions it specifies the maximum number of characters to be printed; if the string is longer than this then the trailing characters will be dropped. If the precision is specified with * rather than a number then the next argument to the format command determines the precision; it must be a numeric string.

The fifth part of a conversion specifier is a length modifier, which must be h or l. If it is h it specifies that the numeric value should be truncated to a 16-bit value before converting. This option is rarely useful. The l modifier is ignored.

The last thing in a conversion specifier is an alphabetic character that determines what kind of conversion to perform. The following conversion characters are currently supported:

d
Convert integer to signed decimal string.

u
Convert integer to unsigned decimal string.

i
Convert integer to signed decimal string; the integer may either be in decimal, in octal (with a leading 0) or in hexadecimal (with a leading 0x).

o
Convert integer to unsigned octal string.

x or X
Convert integer to unsigned hexadecimal string, using digits ``0123456789abcdef'' for x and ``0123456789ABCDEF'' for X).

c
Convert integer to the Unicode character it represents.

s
No conversion; just insert string.

f
Convert floating-point number to signed decimal string of the form xx.yyy, where the number of y's is determined by the precision (default: 6). If the precision is 0 then no decimal point is output.

e or e
Convert floating-point number to scientific notation in the form x.yyy e±zz, where the number of y's is determined by the precision (default: 6). If the precision is 0 then no decimal point is output. If the E form is used then E is printed instead of e.

g or G
If the exponent is less than -4 or greater than or equal to the precision, then convert floating-point number as for %e or %E. Otherwise convert as for %f. Trailing zeroes and a trailing decimal point are omitted.

%
No conversion: just insert %.

For the numerical conversions the argument being converted must be an integer or floating-point string; format converts the argument to binary and then converts it back to a string according to the conversion specifier.

DIFFERENCES FROM ANSI SPRINTF

The behavior of the format command is the same as the ANSI C sprintf procedure except for the following differences:

[1]
%p and %n specifiers are not currently supported.

[2]
For %c conversions the argument must be a decimal string, which will then be converted to the corresponding character value.

[3]
The l modifier is ignored; integer values are always converted as if there were no modifier present and real values are always converted as if the l modifier were present (i.e. type double is used for the internal representation). If the h modifier is specified then integer values are truncated to short before conversion.

SEE ALSO

sprintf, string

KEYWORDS

conversion specifier, format, sprintf, string, substitution
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - gets manual page

NAME

gets - Read a line from a channel

SYNOPSIS

gets channelId ?varName?

DESCRIPTION

This command reads the next line from channelId, returns everything in the line up to (but not including) the end-of-line character(s), and discards the end-of-line character(s). If varName is omitted the line is returned as the result of the command. If varName is specified then the line is placed in the variable by that name and the return value is a count of the number of characters returned.

If end of file occurs while scanning for an end of line, the command returns whatever input is available up to the end of file. If channelId is in nonblocking mode and there is not a full line of input available, the command returns an empty string and does not consume any input. If varName is specified and an empty string is returned in varName because of end-of-file or because of insufficient data in nonblocking mode, then the return count is -1. Note that if varName is not specified then the end-of-file and no-full-line-available cases can produce the same results as if there were an input line consisting only of the end-of-line character(s). The eof and fblocked commands can be used to distinguish these three cases.

SEE ALSO

file, eof, fblocked

KEYWORDS

blocking, channel, end of file, end of line, line, nonblocking, read
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - glob manual page

NAME
glob - Return names of files that match patterns
SYNOPSIS
glob ?switches? pattern ?pattern ...?
DESCRIPTION
-directory directory
-join
-nocomplain
-path pathPrefix
-types typeList
- -
?
*
[chars]
\x
{a,b,...}
PORTABILITY ISSUES
Windows
Macintosh
SEE ALSO
KEYWORDS

NAME

glob - Return names of files that match patterns

SYNOPSIS

glob ?switches? pattern ?pattern ...?

DESCRIPTION

This command performs file name ``globbing'' in a fashion similar to the csh shell. It returns a list of the files whose names match any of the pattern arguments.

If the initial arguments to glob start with - then they are treated as switches. The following switches are currently supported:

-directory directory
Search for files which match the given patterns starting in the given directory. 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 -path.

-join
The remaining pattern arguments are treated as a single pattern obtained by joining the arguments with directory separators.

-nocomplain
Allows an empty list to be returned without error; without this switch an error is returned if the result list would be empty.

-path pathPrefix
Search for files with the given pathPrefix where the rest of the name matches the given patterns. This allows searching for files with names similar to a given file even when the names contain glob-sensitive characters. This option may not be used in conjunction with -directory.

-types typeList
Only list files or directories which match typeList, where the items in the list have two forms. The first form is like the -type option of the Unix find command: b (block special file), c (character special file), d (directory), f (plain file), l (symbolic link), p (named pipe), or s (socket), where multiple types may be specified in the list. Glob will return all files which match at least one of the types given.

The second form specifies types where all the types given must match. These are r, w, x as file permissions, and readonly, hidden 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. TEXT). Items which are of the form {macintosh type XXXX} or {macintosh creator XXXX} will match types or creators respectively. Unrecognised types, or specifications of multiple MacOS types/creators will signal an error.

The two forms may be mixed, so -types {d f r w} will find all regular files OR directories that have both read AND write permissions. The following are equivalent:

glob -type d *
glob */
except that the first case doesn't return the trailing ``/'' and is more platform independent.

- -
Marks the end of switches. The argument following this one will be treated as a pattern even if it starts with a -.

The pattern arguments may contain any of the following special characters:

?
Matches any single character.

*
Matches any sequence of zero or more characters.

[chars]
Matches any single character in chars. If chars contains a sequence of the form a-b then any character between a and b (inclusive) will match.

\x
Matches the character x.

{a,b,...}
Matches any of the strings a, b, etc.

As with csh, a ``.'' at the beginning of a file's name or just after a ``/'' must be matched explicitly or with a {} construct. In addition, all ``/'' characters must be matched explicitly.

If the first character in a pattern is ``~'' then it refers to the home directory for the user whose name follows the ``~''. If the ``~'' is followed immediately by ``/'' then the value of the HOME environment variable is used.

The glob command differs from csh globbing in two ways. First, it does not sort its result list (use the lsort command if you want the list sorted). Second, glob only returns the names of files that actually exist; in csh no check for existence is made unless a pattern contains a ?, *, or [] construct.

PORTABILITY ISSUES

Unlike other Tcl commands that will accept both network and native style names (see the filename manual entry for details on how native and network names are specified), the glob command only accepts native names.

Windows
For Windows UNC names, the servername and sharename components of the path may not contain ?, *, or [] constructs. On Windows NT, if pattern is of the form ``~username@domain'' 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, glob accepts patterns like ``.../'' and ``..../'' for successively higher up parent directories.

Macintosh
When using the options, -dir, -join or -path, glob assumes the directory separator for the entire pattern is the standard ``:''. When not using these options, glob examines each pattern argument and uses ``/'' unless the pattern contains a ``:''.

SEE ALSO

file

KEYWORDS

exist, file, glob, pattern
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - global manual page

NAME

global - Access global variables

SYNOPSIS

global varname ?varname ...?

DESCRIPTION

This command is ignored unless a Tcl procedure is being interpreted. If so then it declares the given varname's to be global variables rather than local ones. Global variables are variables in the global namespace. For the duration of the current procedure (and only while executing in the current procedure), any reference to any of the varnames will refer to the global variable by the same name.

Please note that this is done by creating local variables that are linked to the global variables, and therefore that these variables will be listed by info locals like all other local variables.

SEE ALSO

namespace, upvar, variable

KEYWORDS

global, namespace, procedure, variable
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Built-In Commands - history manual page

NAME
history - Manipulate the history list
SYNOPSIS
history ?option? ?arg arg ...?
DESCRIPTION
history
history add command ?exec?
history change newValue ?event?
history clear
history event ?event?
history info ?count?
history keep ?count?
history nextid
history redo ?event?
HISTORY REVISION
KEYWORDS

NAME

history - Manipulate the history list

SYNOPSIS

history ?option? ?arg arg ...?

DESCRIPTION

The history command performs one of several operations related to recently-executed commands recorded in a history list. Each of these recorded commands is referred to as an ``event''. When specifying an event to the history command, the following forms may be used:

[1]
A number: if positive, it refers to the event with that number (all events are numbered starting at 1). If the number is negative, it selects an event relative to the current event (-1 refers to the previous event, -2 to the one before that, and so on). Event 0 refers to the current event.

[2]
A string: selects the most recent event that matches the string. An event is considered to match the string either if the string is the same as the first characters of the event, or if the string matches the event in the sense of the string match command.

The history command can take any of the following forms:

history
Same as history info, described below.

history add command ?exec?
Adds the command argument to the history list as a new event. If exec is specified (or abbreviated) then the command is also executed and its result is returned. If exec isn't specified then an empty string is returned as result.

history change newValue ?event?
Replaces the value recorded for an event with newValue. Event specifies the event to replace, and defaults to the current event (not event -1). This command is intended for use in commands that implement new forms of history substitution and wish to replace the current event (which invokes the substitution) with the command created through substitution. The return value is an empty string.

history clear
Erase the history list. The current keep limit is retained. The history event numbers are reset.

history event ?event?
Returns the value of the event given by event. Event defaults to -1.

history info ?count?
Returns a formatted string (intended for humans to read) giving the event number and contents for each of the events in the history list except the current event. If count is specified then only the most recent count events are returned.

history keep ?count?
This command may be used to change the size of the history list to count events. Initially, 20 events are retained in the history list. If count is not specified, the current keep limit is returned.

history nextid
Returns the number of the next event to be recorded in the history list. It is useful for things like printing the event number in command-line prompts.

history redo ?event?
Re-executes the command indicated by event and return its result. Event defaults to -1. This command results in history revision: see below for details.

HISTORY REVISION

Pre-8.0 Tcl had a complex history revision mechanism. The current mechanism is more limited, and the old history operations substitute and words have been removed. (As a consolation, the clear operation was added.)

The history option redo results in much simpler ``history revision''. When this option is invoked then the most recent event is modified to eliminate the history command and replace it with the result of the history command. If you want to redo an event without modifying history, then use the event operation to retrieve some event, and the add operation to add it to history and execute it.

KEYWORDS

event, history, record
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Built-In Commands - Http manual page

NAME
Http - Client-side implementation of the HTTP/1.0 protocol.
SYNOPSIS
package require http ?2.4?
::http::config ?options?
::http::geturl url ?options?
::http::formatQuery list
::http::reset token
::http::wait token
::http::status token
::http::size token
::http::code token
::http::ncode token
::http::data token
::http::error token
::http::cleanup token
::http::register proto port command
::http::unregister proto
DESCRIPTION
COMMANDS
::http::config ?options?
-accept mimetypes
-proxyhost hostname
-proxyport number
-proxyfilter command
-useragent string
::http::geturl url ?options?
-binary boolean
-blocksize size
-channel name
-command callback
-handler callback
-headers keyvaluelist
-progress callback
-query query
-queryblocksize size
-querychannel channelID
-queryprogress callback
-timeout milliseconds
-type mime-type
-validate boolean
::http::formatQuery key value ?key value ...?
::http::reset token ?why?
::http::wait token
::http::data token
::http::error token
::http::status token
::http::code token
::http::ncode token
::http::size token
::http::cleanup token
::http::register proto port command
::http::unregister proto
ERRORS
ok
eof
error
STATE ARRAY
body
charset
coding
currentsize
error
http
meta
Content-Type
Content-Length
Location
posterror
status
totalsize
type
url
EXAMPLE
SEE ALSO
KEYWORDS

NAME

Http - Client-side implementation of the HTTP/1.0 protocol.

SYNOPSIS

package require http ?2.4?
::http::config ?options?
::http::geturl url ?options?
::http::formatQuery list
::http::reset token
::http::wait token
::http::status token
::http::size token
::http::code token
::http::ncode token
::http::data token
::http::error token
::http::cleanup token
::http::register proto port command
::http::unregister proto

DESCRIPTION

The http package provides the client side of the HTTP/1.0 protocol. The package implements the GET, POST, and HEAD operations of HTTP/1.0. It allows configuration of a proxy host to get through firewalls. The package is compatible with the Safesock security policy, so it can be used by untrusted applets to do URL fetching from a restricted set of hosts. This package can be extened to support additional HTTP transport protocols, such as HTTPS, by providing a custom socket command, via http::register.

The ::http::geturl procedure does a HTTP transaction. Its options determine whether a GET, POST, or HEAD transaction is performed. The return value of ::http::geturl is a token for the transaction. The value is also the name of an array in the ::http namespace that contains state information about the transaction. The elements of this array are described in the STATE ARRAY section.

If the -command option is specified, then the HTTP operation is done in the background. ::http::geturl returns immediately after generating the HTTP request and the callback is invoked when the transaction completes. For this to work, the Tcl event loop must be active. In Tk applications this is always true. For pure-Tcl applications, the caller can use ::http::wait after calling ::http::geturl to start the event loop.

COMMANDS

::http::config ?options?
The ::http::config 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 is returned. If a single argument is specified, then it should be one of the flags described below. In this case the current value of that setting is returned. Otherwise, the options should be a set of flags and values that define the configuration:

-accept mimetypes
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 willing to receive. For example, "image/gif, image/jpeg, text/*".

-proxyhost hostname
The name of the proxy host, if any. If this value is the empty string, the URL host is contacted directly.

-proxyport number
The proxy port number.

-proxyfilter command
The command is a callback that is made during ::http::geturl to determine if a proxy is required for a given host. One argument, a host name, is added to command when it is invoked. If a proxy is required, the callback should return a two element list containing the proxy server and proxy port. Otherwise the filter should return an empty list. The default filter returns the values of the -proxyhost and -proxyport settings if they are non-empty.

-useragent string
The value of the User-Agent header in the HTTP request. The default is "Tcl http client package 2.2."

::http::geturl url ?options?
The ::http::geturl command is the main procedure in the package. The -query option causes a POST operation and the -validate option causes a HEAD operation; otherwise, a GET operation is performed. The ::http::geturl command returns a token value that can be used to get information about the transaction. See the STATE ARRAY and ERRORS section for details. The ::http::geturl command blocks until the operation completes, unless the -command option specifies a callback that is invoked when the HTTP transaction completes. ::http::geturl takes several options:

-binary boolean
Specifies whether to force interpreting the url data as binary. Normally this is auto-detected (anything not beginning with a text content type or whose content encoding is gzip or compress is considered binary data).

-blocksize size
The blocksize used when reading the URL. At most size bytes are read at once. After each block, a call to the -progress callback is made (if that option is specified).

-channel name
Copy the URL contents to channel name instead of saving it in state(body).

-command callback
Invoke callback after the HTTP transaction completes. This option causes ::http::geturl to return immediately. The callback gets an additional argument that is the token returned from ::http::geturl. This token is the name of an array that is described in the STATE ARRAY section. Here is a template for the callback:
proc httpCallback {token} {
    upvar #0 $token state
    # Access state as a Tcl array
}

-handler callback
Invoke callback 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 token returned from ::http::geturl. The token is the name of a global array that is described in the STATE ARRAY section. The procedure is expected to return the number of bytes read from the socket. Here is a template for the callback:
proc httpHandlerCallback {socket token} {
    upvar #0 $token state
    # Access socket, and state as a Tcl array
    ...
    (example: set data [read $socket 1000];set nbytes [string length $data])
    ...
    return nbytes
}

-headers keyvaluelist
This option is used to add extra headers to the HTTP request. The keyvaluelist argument must be a list with an even number of elements that alternate between keys and values. The keys become header field names. Newlines are stripped from the values so the header cannot be corrupted. For example, if keyvaluelist is Pragma no-cache then the following header is included in the HTTP request:
Pragma: no-cache

-progress callback
The callback is made after each transfer of data from the URL. The callback gets three additional arguments: the token from ::http::geturl, the expected total size of the contents from the Content-Length meta-data, and the current number of bytes 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:
proc httpProgress {token total current} {
    upvar #0 $token state
}

-query query
This flag causes ::http::geturl to do a POST request that passes the query to the server. The query must be a x-url-encoding formatted query. The ::http::formatQuery procedure can be used to do the formatting.

-queryblocksize size
The blocksize used when posting query data to the URL. At most size bytes are written at once. After each block, a call to the -queryprogress callback is made (if that option is specified).

-querychannel channelID
This flag causes ::http::geturl to do a POST request that passes the data contained in channelID to the server. The data contained in channelID must be a x-url-encoding formatted query unless the -type option below is used. If a Content-Length header is not specified via the -headers options, ::http::geturl attempts to determine the size of the post data in order to create that header. If it is unable to determine the size, it returns an error.

-queryprogress callback
The callback is made after each transfer of data to the URL (i.e. POST) and acts exactly like the -progress option (the callback format is the same).

-timeout milliseconds
If milliseconds is non-zero, then ::http::geturl sets up a timeout to occur after the specified number of milliseconds. A timeout results in a call to ::http::reset and to the -command callback, if specified. The return value of ::http::status is timeout after a timeout has occurred.

-type mime-type
Use mime-type as the Content-Type value, instead of the default value (application/x-www-form-urlencoded) during a POST operation.

-validate boolean
If boolean is non-zero, then ::http::geturl 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 state(meta) variable after the transaction. See the STATE ARRAY section for details.

::http::formatQuery key value ?key value ...?
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 proper & and = separators. The result is suitable for the -query value passed to ::http::geturl.

::http::reset token ?why?
This command resets the HTTP transaction identified by token, if any. This sets the state(status) value to why, which defaults to reset, and then calls the registered -command callback.

::http::wait token
This is a convenience procedure that blocks and waits for the transaction to complete. This only works in trusted code because it uses vwait. Also, it's not useful for the case where ::http::geturl is called without the -command option because in this case the ::http::geturl call doesn't return until the HTTP transaction is complete, and thus there's nothing to wait for.

::http::data token
This is a convenience procedure that returns the body element (i.e., the URL data) of the state array.

::http::error token
This is a convenience procedure that returns the error element of the state array.

::http::status token
This is a convenience procedure that returns the status element of the state array.

::http::code token
This is a convenience procedure that returns the http element of the state array.

::http::ncode token
This is a convenience procedure that returns just the numeric return code (200, 404, etc.) from the http element of the state array.

::http::size token
This is a convenience procedure that returns the currentsize element of the state array, which represents the number of bytes received from the URL in the ::http::geturl call.

::http::cleanup token
This procedure cleans up the state associated with the connection identified by token. After this call, the procedures like ::http::data cannot be used to get information about the operation. It is strongly recommended that you call this function after you're done with a given HTTP request. Not doing so will result in memory not being freed, and if your app calls ::http::geturl enough times, the memory leak could cause a performance hit...or worse.

::http::register proto port command
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 channel. E.g.:
package require http
package require tls

http::register https 443 ::tls::socket

set token [http::geturl https://my.secure.site/]

::http::unregister proto
This procedure unregisters a protocol handler that was previously registered via http::register.

ERRORS

The http::geturl procedure will raise errors in the following cases: invalid command line options, an invalid URL, a URL on a non-existent host, or a URL at a bad port on an existing host. These errors mean that it cannot even start the network transaction. It will also raise an error if it gets an I/O error while writing out the HTTP request header. For synchronous ::http::geturl calls (where -command is not specified), it will raise an error if it gets an I/O error while reading the HTTP reply headers or data. Because ::http::geturl doesn't return a token in these cases, it does all the required cleanup and there's no issue of your app having to call ::http::cleanup.

For asynchronous ::http::geturl calls, all of the above error situations apply, except that if there's any error while reading the HTTP reply headers or data, no exception is thrown. This is because after writing the HTTP headers, ::http::geturl returns, and the rest of the HTTP transaction occurs in the background. The command callback can check if any error occurred during the read by calling ::http::status to check the status and if it's error, calling ::http::error to get the error message.

Alternatively, if the main program flow reaches a point where it needs to know the result of the asynchronous HTTP request, it can call ::http::wait and then check status and error, just as the callback does.

In any case, you must still call http::cleanup to delete the state array when you're done.

There are other possible results of the HTTP transaction determined by examining the status from http::status. These are described below.

ok
If the HTTP transaction completes entirely, then status will be ok. However, you should still check the http::code value to get the HTTP status. The http::ncode procedure provides just the numeric error (e.g., 200, 404 or 500) while the http::code procedure returns a value like "HTTP 404 File not found".

eof
If the server closes the socket without replying, then no error is raised, but the status of the transaction will be eof.

error
The error message will also be stored in the error status array element, accessible via ::http::error.

Another error possibility is that http::geturl is unable to write all the post query data to the server before the server responds and closes the socket. The error message is saved in the posterror status array element and then http::geturl attempts to complete the transaction. If it can read the server's response it will end up with an ok status, otherwise it will have an eof status.

STATE ARRAY

The ::http::geturl procedure returns a token 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:
upvar #0 $token state
Once the data associated with the url is no longer needed, the state array should be unset to free up storage. The http::cleanup procedure is provided for that purpose. The following elements of the array are supported:

body
The contents of the URL. This will be empty if the -channel option has been specified. This value is returned by the ::http::data command.

charset
The value of the charset attribute from the Content-Type meta-data value. If none was specified, this defaults to the RFC standard iso8859-1, or the value of $::http::defaultCharset. Incoming text data will be automatically converted from this charset to utf-8.

coding
A copy of the Content-Encoding meta-data value.

currentsize
The current number of bytes fetched from the URL. This value is returned by the ::http::size command.

error
If defined, this is the error string seen when the HTTP transaction was aborted.

http
The HTTP status reply from the server. This value is returned by the ::http::code command. The format of this value is:
HTTP/1.0 code string
The code 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 Location meta-data specifies a new URL that contains the requested information.

meta
The HTTP protocol returns meta-data that describes the URL contents. The meta 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:
array set meta $state(meta)
Some of the meta-data keys are listed below, but the HTTP standard defines more, and servers are free to add their own.

Content-Type
The type of the URL contents. Examples include text/html, image/gif, application/postscript and application/x-tcl.

Content-Length
The advertised size of the contents. The actual size obtained by ::http::geturl is available as state(size).

Location
An alternate URL that contains the requested data.

posterror
The error, if any, that occurred while writing the post query data to the server.

status
Either ok, for successful completion, reset for user-reset, timeout if a timeout occurred before the transaction could complete, or error for an error condition. During the transaction this value is the empty string.

totalsize
A copy of the Content-Length meta-data value.

type
A copy of the Content-Type meta-data value.

url
The requested URL.

EXAMPLE

# Copy a URL to a file and print meta-data
proc ::http::copy { url file {chunk 4096} } {
    set out [open $file w]
    set token [geturl $url -channel $out -progress ::http::Progress \
    -blocksize $chunk]
    close $out
    # This ends the line started by http::Progress
    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 [copy [string trim $value] $file $chunk]
    }
    }
    incr max
    foreach {name value} $state(meta) {
    puts [format "%-*s %s" $max $name: $value]
    }

    return $token
}
proc ::http::Progress {args} {
    puts -nonewline stderr . ; flush stderr
}

SEE ALSO

safe, socket, safesock

KEYWORDS

security policy, socket
Copyright © 1995-1997 Sun Microsystems, Inc.
Copyright © 1998-2000 by Ajuba Solutions.


Built-In Commands - if manual page

NAME

if - Execute scripts conditionally

SYNOPSIS

if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?

DESCRIPTION

The if command evaluates expr1 as an expression (in the same way that expr evaluates its argument). The value of the expression must be a boolean (a numeric value, where 0 is false and anything is true, or a string value such as true or yes for true and false or no for false); if it is true then body1 is executed by passing it to the Tcl interpreter. Otherwise expr2 is evaluated as an expression and if it is true then body2 is executed, and so on. If none of the expressions evaluates to true then bodyN is executed. The then and else arguments are optional ``noise words'' to make the command easier to read. There may be any number of elseif clauses, including zero. BodyN may also be omitted as long as else is omitted too. 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 bodyN.

SEE ALSO

expr, for, foreach

KEYWORDS

boolean, conditional, else, false, if, true
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - incr manual page

NAME

incr - Increment the value of a variable

SYNOPSIS

incr varName ?increment?

DESCRIPTION

Increments the value stored in the variable whose name is varName. The value of the variable must be an integer. If increment is supplied then its value (which must be an integer) is added to the value of variable varName; otherwise 1 is added to varName. The new value is stored as a decimal string in variable varName and also returned as result.

SEE ALSO

expr

KEYWORDS

add, increment, variable, value
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - info manual page

NAME
info - Return information about the state of the Tcl interpreter
SYNOPSIS
info option ?arg arg ...?
DESCRIPTION
info args procname
info body procname
info cmdcount
info commands ?pattern?
info complete command
info default procname arg varname
info exists varName
info globals ?pattern?
info hostname
info level ?number?
info library
info loaded ?interp?
info locals ?pattern?
info nameofexecutable
info patchlevel
info procs ?pattern?
info script
info sharedlibextension
info tclversion
info vars ?pattern?
KEYWORDS

NAME

info - Return information about the state of the Tcl interpreter

SYNOPSIS

info option ?arg arg ...?

DESCRIPTION

This command provides information about various internals of the Tcl interpreter. The legal option's (which may be abbreviated) are:

info args procname
Returns a list containing the names of the arguments to procedure procname, in order. Procname must be the name of a Tcl command procedure.

info body procname
Returns the body of procedure procname. Procname must be the name of a Tcl command procedure.

info cmdcount
Returns a count of the total number of commands that have been invoked in this interpreter.

info commands ?pattern?
If pattern isn't specified, returns a list of names of all the Tcl commands in the current namespace, including both the built-in commands written in C and the command procedures defined using the proc command. If pattern is specified, only those names matching pattern are returned. Matching is determined using the same rules as for string match. pattern can be a qualified name like Foo::print*. That is, it may specify a particular namespace using a sequence of namespace names separated by ::s, and may have pattern matching special characters at the end to specify a set of commands in that namespace. If pattern is a qualified name, the resulting list of command names has each one qualified with the name of the specified namespace.

info complete command
Returns 1 if command is a complete Tcl command in the sense of having no unclosed quotes, braces, brackets or array element names, If the command doesn't appear to be complete then 0 is returned. This command is typically used in line-oriented input environments to allow users to type in commands that span multiple lines; if the command isn't complete, the script can delay evaluating it until additional lines have been typed to complete the command.

info default procname arg varname
Procname must be the name of a Tcl command procedure and arg must be the name of an argument to that procedure. If arg doesn't have a default value then the command returns 0. Otherwise it returns 1 and places the default value of arg into variable varname.

info exists varName
Returns 1 if the variable named varName exists in the current context (either as a global or local variable) and has been defined by being given a value, returns 0 otherwise.

info globals ?pattern?
If pattern isn't specified, returns a list of all the names of currently-defined global variables. Global variables are variables in the global namespace. If pattern is specified, only those names matching pattern are returned. Matching is determined using the same rules as for string match.

info hostname
Returns the name of the computer on which this invocation is being executed.

info level ?number?
If number 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 number is specified, then the result is a list consisting of the name and arguments for the procedure call at level number on the stack. If number is positive then it selects a particular stack level (1 refers to the top-most active procedure, 2 to the procedure it called, and so on); otherwise it gives a level relative to the current level (0 refers to the current procedure, -1 to its caller, and so on). See the uplevel command for more information on what stack levels mean.

info library
Returns the name of the library directory in which standard Tcl scripts are stored. This is actually the value of the tcl_library variable and may be changed by setting tcl_library. See the tclvars manual entry for more information.

info loaded ?interp?
Returns a list describing all of the packages that have been loaded into interp with the load command. Each list element is a sub-list with two elements consisting of the name of the file from which the package was loaded and the name of the package. For statically-loaded packages the file name will be an empty string. If interp is omitted then information is returned for all packages loaded in any interpreter in the process. To get a list of just the packages in the current interpreter, specify an empty string for the interp argument.

info locals ?pattern?
If pattern isn't specified, returns a list of all the names of currently-defined local variables, including arguments to the current procedure, if any. Variables defined with the global and upvar commands will not be returned. If pattern is specified, only those names matching pattern are returned. Matching is determined using the same rules as for string match.

info nameofexecutable
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.

info patchlevel
Returns the value of the global variable tcl_patchLevel; see the tclvars manual entry for more information.

info procs ?pattern?
If pattern isn't specified, returns a list of all the names of Tcl command procedures in the current namespace. If pattern is specified, only those procedure names in the current namespace matching pattern are returned. Matching is determined using the same rules as for string match.

info script
If a Tcl script file is currently being evaluated (i.e. there is a call to Tcl_EvalFile active or there is an active invocation of the source command), then this command returns the name of the innermost file being processed. Otherwise the command returns an empty string.

info sharedlibextension
Returns the extension used on this platform for the names of files containing shared libraries (for example, .so under Solaris). If shared libraries aren't supported on this platform then an empty string is returned.

info tclversion
Returns the value of the global variable tcl_version; see the tclvars manual entry for more information.

info vars ?pattern?
If pattern isn't specified, returns a list of all the names of currently-visible variables. This includes locals and currently-visible globals. If pattern is specified, only those names matching pattern are returned. Matching is determined using the same rules as for string match. pattern can be a qualified name like Foo::option*. That is, it may specify a particular namespace using a sequence of namespace names separated by ::s, and may have pattern matching special characters at the end to specify a set of variables in that namespace. If pattern is a qualified name, the resulting list of variable names has each matching namespace variable qualified with the name of its namespace.

KEYWORDS

command, information, interpreter, level, namespace, procedure, variable
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies


Tcl Built-In Commands - interp manual page

NAME
interp - Create and manipulate Tcl interpreters
SYNOPSIS
interp option ?arg arg ...?
DESCRIPTION
THE INTERP COMMAND
interp alias srcPath srcCmd
interp alias srcPath srcCmd {}
interp alias srcPath srcCmd targetPath targetCmd ?arg arg ...?
interp aliases ?path?
interp create ?-safe? ?- -? ?path?
interp delete ?path ...?
interp eval path arg ?arg ...?
interp exists path
interp expose path hiddenName ?exposedCmdName?
interp hide path exposedCmdName ?hiddenCmdName?
interp hidden path
interp invokehidden path ?-global? hiddenCmdName ?arg ...?
interp issafe ?path?
interp marktrusted path
interp share srcPath channelId destPath
interp slaves ?path?
interp target path alias
interp transfer srcPath channelId destPath
SLAVE COMMAND
slave aliases
slave alias srcCmd
slave alias srcCmd {}
slave alias srcCmd targetCmd ?arg ..?
slave eval arg ?arg ..?
slave expose hiddenName ?exposedCmdName?
slave hide exposedCmdName ?hiddenCmdName?
slave hidden
slave invokehidden ?-global hiddenName ?arg ..?
slave issafe
slave marktrusted
SAFE INTERPRETERS
ALIAS INVOCATION
HIDDEN COMMANDS
CREDITS
SEE ALSO
KEYWORDS

NAME

interp - Create and manipulate Tcl interpreters

SYNOPSIS

interp option ?arg arg ...?

DESCRIPTION

This command makes it possible to create one or more new Tcl interpreters that co-exist with the creating interpreter in the same application. The creating interpreter is called the master and the new interpreter is called a slave. A master can create any number of slaves, and each slave can itself create additional slaves for which it is master, resulting in a hierarchy of interpreters.

Each interpreter is independent from the others: it has its own name space for commands, procedures, and global variables. A master interpreter may create connections between its slaves and itself using a mechanism called an alias. An alias is a command in a slave interpreter which, when invoked, causes a command to be invoked in its master interpreter or in another slave interpreter. The only other connections between interpreters are through environment variables (the env variable), which are normally shared among all interpreters in the application. Note that the name space for files (such as the names returned by the open command) is no longer shared between interpreters. Explicit commands are provided to share files and to transfer references to open files from one interpreter to another.

The interp command also provides support for safe interpreters. A safe interpreter is a slave whose functions have been greatly restricted, so that it is safe to execute untrusted scripts without fear of them damaging other interpreters or the application's environment. For example, all IO channel creation commands and subprocess creation commands are made inaccessible to safe interpreters. See SAFE INTERPRETERS below for more information on what features are present in a safe interpreter. The dangerous functionality is not removed from the safe interpreter; instead, it is hidden, so that only trusted interpreters can obtain access to it. For a detailed explanation of hidden commands, see HIDDEN COMMANDS, below. The alias mechanism can be used for protected communication (analogous to a kernel call) between a slave interpreter and its master. See ALIAS INVOCATION, below, for more details 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 a is a slave of the current interpreter and it has a slave a1, which in turn has a slave a11, the qualified name of a11 in a is the list a1 a11.

The interp command, described below, accepts qualified interpreter names as arguments; the interpreter in which the command is being evaluated can always be referred to as {} (the empty list or string). Note that it is impossible to refer to a master (ancestor) interpreter by name in a slave interpreter except through aliases. Also, there is no global name by which one can refer to the first interpreter created in an application. Both restrictions are motivated by safety concerns.

THE INTERP COMMAND

The interp command is used to create, delete, and manipulate slave interpreters, and to share or transfer channels between interpreters. It can have any of several forms, depending on the option argument:

interp alias srcPath srcCmd
Returns a Tcl list whose elements are the targetCmd and args associated with the alias named srcCmd (all of these are the values specified when the alias was created; it is possible that the actual source command in the slave is different from srcCmd if it was renamed).

interp alias srcPath srcCmd {}
Deletes the alias for srcCmd in the slave interpreter identified by srcPath. srcCmd refers to the name under which the alias was created; if the source command has been renamed, the renamed command will be deleted.

interp alias srcPath srcCmd targetPath targetCmd ?arg arg ...?
This command creates an alias between one slave and another (see the alias slave command below for creating aliases between a slave and its master). In this command, either of the slave interpreters may be anywhere in the hierarchy of interpreters under the interpreter invoking the command. SrcPath and srcCmd identify the source of the alias. SrcPath is a Tcl list whose elements select a particular interpreter. For example, ``a b'' identifies an interpreter b, which is a slave of interpreter a, which is a slave of the invoking interpreter. An empty list specifies the interpreter invoking the command. srcCmd gives the name of a new command, which will be created in the source interpreter. TargetPath and targetCmd specify a target interpreter and command, and the arg arguments, if any, specify additional arguments to targetCmd which are prepended to any arguments specified in the invocation of srcCmd. TargetCmd may be undefined at the time of this call, or it may already exist; it is not created by this command. The alias arranges for the given target command to be invoked in the target interpreter whenever the given source command is invoked in the source interpreter. See ALIAS INVOCATION below for more details.

interp aliases ?path?
This command returns a Tcl list of the names of all the source commands for aliases defined in the interpreter identified by path.

interp create ?-safe? ?- -? ?path?
Creates a slave interpreter identified by path and a new command, called a slave command. The name of the slave command is the last component of path. The new slave interpreter and the slave command are created in the interpreter identified by the path obtained by removing the last component from path. For example, if path is a b c then a new slave interpreter and slave command named c are created in the interpreter identified by the path a b. The slave command may be used to manipulate the new interpreter as described below. If path is omitted, Tcl creates a unique name of the form interp x, where x is an integer, and uses it for the interpreter and the slave command. If the -safe switch is specified (or if the master interpreter is a safe interpreter), the new slave interpreter will be created as a safe interpreter with limited functionality; otherwise the slave will include the full set of Tcl built-in commands and variables. The - - switch can be used to mark the end of switches; it may be needed if path is an unusual value such as -safe. The result of the command is the name of the new interpreter. The name of a slave interpreter must be unique among all the slaves for its master; an error occurs if a slave interpreter by the given name already exists in this master.

interp delete ?path ...?
Deletes zero or more interpreters given by the optional path arguments, and for each interpreter, it also deletes its slaves. The command also deletes the slave command for each interpreter deleted. For each path argument, if no interpreter by that name exists, the command raises an error.

interp eval path arg ?arg ...?
This command concatenates all of the arg arguments in the same fashion as the concat command, then evaluates the resulting string as a Tcl script in the slave interpreter identified by path. The result of this evaluation (including error information such as the errorInfo and errorCode variables, if an error occurs) is returned to the invoking interpreter.

interp exists path
Returns 1 if a slave interpreter by the specified path exists in this master, 0 otherwise. If path is omitted, the invoking interpreter is used.

interp expose path hiddenName ?exposedCmdName?
Makes the hidden command hiddenName exposed, eventually bringing it back under a new exposedCmdName name (this name is currently accepted only if it is a valid global name space name without any ::), in the interpreter denoted by path. If an exposed command with the targetted name already exists, this command fails. Hidden commands are explained in more detail in HIDDEN COMMANDS, below.

interp hide path exposedCmdName ?hiddenCmdName?
Makes the exposed command exposedCmdName hidden, renaming it to the hidden command hiddenCmdName, or keeping the same name if hiddenCmdName is not given, in the interpreter denoted by path. If a hidden command with the targetted name already exists, this command fails. Currently both exposedCmdName and hiddenCmdName can not contain namespace qualifiers, or an error is raised. Commands to be hidden by interp hide are looked up in the global 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. Hidden commands are explained in more detail in HIDDEN COMMANDS, below.

interp hidden path
Returns a list of the names of all hidden commands in the interpreter identified by path.

interp invokehidden path ?-global? hiddenCmdName ?arg ...?
Invokes the hidden command hiddenCmdName with the arguments supplied in the interpreter denoted by path. No substitutions or evaluation are applied to the arguments. If the -global flag is present, the hidden command is invoked at the global level in the target interpreter; otherwise it is invoked at the current call frame and can access local variables in that and outer call frames. Hidden commands are explained in more detail in HIDDEN COMMANDS, below.

interp issafe ?path?
Returns 1 if the interpreter identified by the specified path is safe, 0 otherwise.

interp marktrusted path
Marks the interpreter identified by path as trusted. Does not expose the hidden commands. This command can only be invoked from a trusted interpreter. The command has no effect if the interpreter identified by path is already trusted.

interp share srcPath channelId destPath
Causes the IO channel identified by channelId to become shared between the interpreter identified by srcPath and the interpreter identified by destPath. Both interpreters have the same permissions on the IO channel. Both interpreters must close it to close the underlying IO channel; IO channels accessible in an interpreter are automatically closed when an interpreter is destroyed.

interp slaves ?path?
Returns a Tcl list of the names of all the slave interpreters associated with the interpreter identified by path. If path is omitted, the invoking interpreter is used.

interp target path alias
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 interp alias above. The name of the target interpreter is returned as an interpreter path, relative to the invoking interpreter. If the target interpreter for the alias is the invoking interpreter then an empty list is returned. If the target interpreter for the alias is not the 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.

interp transfer srcPath channelId destPath
Causes the IO channel identified by channelId to become available in the interpreter identified by destPath and unavailable in the interpreter identified by srcPath.

SLAVE COMMAND

For each slave interpreter created with the interp command, a 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:
slave command ?arg arg ...?
Slave is the name of the interpreter, and command and the args determine the exact behavior of the command. The valid forms of this command are:

slave aliases
Returns a Tcl list whose elements are the names of all the aliases in slave. The names returned are the srcCmd values used when the aliases were created (which may not be the same as the current names of the commands, if they have been renamed).

slave alias srcCmd
Returns a Tcl list whose elements are the targetCmd and args associated with the alias named srcCmd (all of these are the values specified when the alias was created; it is possible that the actual source command in the slave is different from srcCmd if it was renamed).

slave alias srcCmd {}
Deletes the alias for srcCmd in the slave interpreter. srcCmd refers to the name under which the alias was created; if the source command has been renamed, the renamed command will be deleted.

slave alias srcCmd targetCmd ?arg ..?
Creates an alias such that whenever srcCmd is invoked in slave, targetCmd is invoked in the master. The arg arguments will be passed to targetCmd as additional arguments, prepended before any arguments passed in the invocation of srcCmd. See ALIAS INVOCATION below for details.

slave eval arg ?arg ..?
This command concatenates all of the arg arguments in the same fashion as the concat command, then evaluates the resulting string as a Tcl script in slave. The result of this evaluation (including error information such as the errorInfo and errorCode variables, if an error occurs) is returned to the invoking interpreter.

slave expose hiddenName ?exposedCmdName?
This command exposes the hidden command hiddenName, eventually bringing it back under a new exposedCmdName name (this name is currently accepted only if it is a valid global name space name without any ::), in slave. If an exposed command with the targetted name already exists, this command fails. For more details on hidden commands, see HIDDEN COMMANDS, below.

slave hide exposedCmdName ?hiddenCmdName?
This command hides the exposed command exposedCmdName, renaming it to the hidden command hiddenCmdName, or keeping the same name if the the argument is not given, in the slave interpreter. If a hidden command with the targetted name already exists, this command fails. Currently both exposedCmdName and hiddenCmdName can not contain namespace qualifiers, or an error is raised. Commands to be hidden are looked up in the global 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. For more details on hidden commands, see HIDDEN COMMANDS, below.

slave hidden
Returns a list of the names of all hidden commands in slave.

slave invokehidden ?-global hiddenName ?arg ..?
This command invokes the hidden command hiddenName with the supplied arguments, in slave. No substitutions or evaluations are applied to the arguments. If the -global flag is given, the command is invoked at the global level in the slave; otherwise it is invoked at the current call frame and can access local variables in that or outer call frames. For more details on hidden commands, see HIDDEN COMMANDS, below.

slave issafe
Returns 1 if the slave interpreter is safe, 0 otherwise.

slave marktrusted
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.

SAFE INTERPRETERS

A safe interpreter is one with restricted functionality, so that is safe to execute an arbitrary script from your worst enemy without fear of that script damaging the enclosing application or the rest of your computing environment. In order to make an interpreter safe, certain commands and variables are removed from the interpreter. For example, commands to create files on disk are removed, and the exec command is removed, since it could be used to cause damage through subprocesses. Limited access to these facilities can be provided, by creating aliases to the master interpreter which check their arguments carefully and provide restricted access to a safe subset of facilities. For example, file creation might be allowed in a particular subdirectory and subprocess invocation might be allowed for a carefully selected and fixed set of programs.

A safe interpreter is created by specifying the -safe switch to the interp create command. Furthermore, any slave created by a safe interpreter will also be safe.

A safe interpreter is created with exactly the following set of built-in commands:

after	append	array	binary
break	case	catch	clock
close	concat	continue	eof
error	eval	expr	fblocked
fcopy	fileevent	flush	for
foreach	format	gets	global
history	if	incr	info
interp	join	lappend	lindex
linsert	list	llength	lrange
lreplace	lsearch	lsort	namespace
package	pid	proc	puts
read	regexp	regsub	rename
return	scan	seek	set
split	string	subst	switch
tell	trace	unset	update
uplevel	upvar	variable	vwait
while
The following commands are hidden by interp create when it creates a safe interpreter:
cd	exec	exit	fconfigure
file	glob	load	open
pwd	socket	source	vwait
These commands can be recreated later as Tcl procedures or aliases, or re-exposed by interp expose.

In addition, the env variable is not present in a safe interpreter, so it cannot share environment variables with other interpreters. The env variable poses a security risk, because users can store sensitive information in an environment variable. For example, the PGP manual recommends storing the PGP private key protection password in the environment variable PGPPASS. Making this variable available to untrusted code executing in a safe interpreter would incur a security risk.

If extensions are loaded into a safe interpreter, they may also restrict their own functionality to eliminate unsafe commands. For a discussion of management of extensions for safety see the manual entries for Safe-Tcl and the load Tcl command.

ALIAS INVOCATION

The alias mechanism has been carefully designed so that it can be used safely when an untrusted script is executing in a safe slave and the target of the alias is a trusted master. The most important thing in guaranteeing safety is to ensure that information passed from the slave to the master is never evaluated or substituted in the master; if this were to occur, it would enable an evil script in the slave to invoke arbitrary functions in the master, which would compromise security.

When the source for an alias is invoked in the slave interpreter, the usual Tcl substitutions are performed when parsing that command. These substitutions are carried out in the source interpreter just as they would be for any other command invoked in that interpreter. The command procedure for the source command takes its arguments and merges them with the targetCmd and args for the alias to create a new array of arguments. If the words of srcCmd were ``srcCmd arg1 arg2 ... argN'', the new set of words will be ``targetCmd arg arg ... arg arg1 arg2 ... argN'', where targetCmd and args are the values supplied when the alias was created. TargetCmd is then used to locate a command procedure in the target interpreter, and that command procedure is invoked with the new set of arguments. An error occurs if there is no command named targetCmd in the target interpreter. No additional substitutions are performed on the words: the target command procedure is invoked directly, without going through the normal Tcl evaluation mechanism. Substitutions are thus performed on each word exactly once: targetCmd and args were substituted when parsing the command that created the alias, and arg1 - argN are substituted when the alias's source command is parsed in the source interpreter.

When writing the targetCmds for aliases in safe interpreters, it is very important that the arguments to that command never be evaluated or substituted, since this would provide an escape mechanism whereby the slave interpreter could execute arbitrary code in the master. This in turn would compromise the security of the system.

HIDDEN COMMANDS

Safe interpreters greatly restrict the functionality available to Tcl programs executing within them. Allowing the untrusted Tcl program to have direct access to this functionality is unsafe, because it can be used for a variety of attacks on the environment. However, there are times when there is a legitimate need to use the dangerous functionality in the context of the safe interpreter. For example, sometimes a program must be sourced into the interpreter. Another example is Tk, where windows are bound to the hierarchy of windows for a specific interpreter; some potentially dangerous functions, e.g. window management, must be performed on these windows within the interpreter context.

The interp command provides a solution to this problem in the form of hidden commands. Instead of removing the dangerous commands entirely from a safe interpreter, these commands are hidden so they become unavailable to Tcl scripts executing in the interpreter. However, such hidden commands can be invoked by any trusted ancestor of the safe interpreter, in the context of the safe interpreter, using interp invoke. Hidden commands and exposed commands reside in separate name spaces. It is possible to define a hidden command and an exposed command by the same name within one interpreter.

Hidden commands in a slave interpreter can be invoked in the body of procedures called in the master during alias invocation. For example, an alias for source could be created in a slave interpreter. When it is invoked in the slave interpreter, a procedure is called in the master interpreter to check that the operation is allowable (e.g. it asks to source a file that the slave interpreter is allowed to access). The procedure then it invokes the hidden source command in the slave interpreter to actually source in the contents of the file. Note that two commands named source exist in the slave interpreter: the alias, and the hidden command.

Because a master interpreter may invoke a hidden command as part of handling an alias invocation, great care must be taken to avoid evaluating any arguments passed in through the alias invocation. Otherwise, malicious slave interpreters could cause a trusted master interpreter to execute dangerous commands on their behalf. See the section on ALIAS INVOCATION for a more complete discussion of this topic. To help avoid this problem, no substitutions or evaluations are applied to arguments of interp invokehidden.

Safe interpreters are not allowed to invoke hidden commands in themselves or in their descendants. This prevents safe slaves from gaining access to hidden functionality in themselves or their descendants.

The set of hidden commands in an interpreter can be manipulated by a trusted interpreter using interp expose and interp hide. The interp expose command moves a hidden command to the set of exposed commands in the interpreter identified by path, potentially renaming the command in the process. If an exposed command by the targetted name already exists, the operation fails. Similarly, interp hide moves an exposed command to the set of hidden commands in that interpreter. Safe interpreters are not allowed to move commands between the set of hidden and exposed commands, in either themselves or their descendants.

Currently, the names of hidden commands cannot contain namespace qualifiers, and you must first rename a command in a namespace to the global namespace before you can hide it. Commands to be hidden by interp hide are looked up in the global 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.

CREDITS

This mechanism is based on the Safe-Tcl prototype implemented by Nathaniel Borenstein and Marshall Rose.

SEE ALSO

load, safe, Tcl_CreateSlave

KEYWORDS

alias, master interpreter, safe interpreter, slave interpreter
Copyright © 1995-1996 Sun Microsystems, Inc.


Built-In Commands - join manual page

NAME

join - Create a string by joining together list elements

SYNOPSIS

join list ?joinString?

DESCRIPTION

The list argument must be a valid Tcl list. This command returns the string formed by joining all of the elements of list together with joinString separating each adjacent pair of elements. The joinString argument defaults to a space character.

SEE ALSO

list, lappend

KEYWORDS

element, join, list, separator
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - lappend manual page

NAME

lappend - Append list elements onto a variable

SYNOPSIS

lappend varName ?value value value ...?

DESCRIPTION

This command treats the variable given by varName as a list and appends each of the value arguments to that list as a separate element, with spaces between elements. If varName doesn't exist, it is created as a list with elements given by the value arguments. Lappend is similar to append except that the values are appended as list elements rather than raw text. This command provides a relatively efficient way to build up large lists. For example, ``lappend a $b'' is much more efficient than ``set a [concat $a [list $b]]'' when $a is long.

SEE ALSO

list, lindex, linsert, llength, lsort, lrange

KEYWORDS

append, element, list, variable
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - library manual page

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
SYNOPSIS
auto_execok cmd
auto_import pattern
auto_load cmd
auto_mkindex dir pattern pattern ...
auto_mkindex_old dir pattern pattern ...
auto_qualify command namespace
auto_reset
tcl_findLibrary basename version patch initScript enVarName varName
parray arrayName
tcl_endOfWord str start
tcl_startOfNextWord str start
tcl_startOfPreviousWord str start
tcl_wordBreakAfter str start
tcl_wordBreakBefore str start
INTRODUCTION
COMMAND PROCEDURES
auto_execok cmd
auto_import pattern
auto_load cmd
auto_mkindex dir pattern pattern ...
auto_reset
auto_qualify command namespace
tcl_findLibrary basename version patch initScript enVarName varName
parray arrayName
tcl_endOfWord str start
tcl_startOfNextWord str start
tcl_startOfPreviousWord str start
tcl_wordBreakAfter str start
tcl_wordBreakBefore str start
VARIABLES
auto_execs
auto_index
auto_noexec
auto_noload
auto_path
env(TCL_LIBRARY)
env(TCLLIBPATH)
tcl_nonwordchars
tcl_wordchars
unknown_pending
SEE ALSO
KEYWORDS

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

SYNOPSIS

auto_execok cmd
auto_import pattern
auto_load cmd
auto_mkindex dir pattern pattern ...
auto_mkindex_old dir pattern pattern ...
auto_qualify command namespace
auto_reset
tcl_findLibrary basename version patch initScript enVarName varName
parray arrayName
tcl_endOfWord str start
tcl_startOfNextWord str start
tcl_startOfPreviousWord str start
tcl_wordBreakAfter str start
tcl_wordBreakBefore str start

INTRODUCTION

Tcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library.

To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command

source [file join [info library] init.tcl]
If the library procedure Tcl_Init is invoked from an application's Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below.

COMMAND PROCEDURES

The following procedures are provided in the Tcl library:

auto_execok cmd
Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information.

auto_import pattern
Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import.

auto_load cmd
This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path 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 tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn't actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk.

auto_mkindex dir pattern pattern ...
Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command
auto_mkindex foo *.tcl

will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex.

Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) 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.

Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc 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 don't appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old.

auto_reset
Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they're used.

auto_qualify command namespace
Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace.

Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime.

tcl_findLibrary basename version patch initScript enVarName varName
This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree.

parray arrayName
Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global.

tcl_endOfWord str start
Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters.

tcl_startOfNextWord str start
Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point.

tcl_startOfPreviousWord str start
Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point.

tcl_wordBreakAfter str start
Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary.

tcl_wordBreakBefore str start
Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary.

VARIABLES

The following global variables are defined or used by the procedures in the Tcl library:

auto_execs
Used by auto_execok to record information about whether particular commands exist as executable files.

auto_index
Used by auto_load to save the index information read from disk.

auto_noexec
If set to any value, then unknown will not attempt to auto-exec any commands.

auto_noload
If set to any value, then unknown will not attempt to auto-load any commands.

auto_path
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.

env(TCL_LIBRARY)
If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn't set then a default value is used.

env(TCLLIBPATH)
If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable.

tcl_nonwordchars
This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters.

tcl_wordchars
This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is 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.

unknown_pending
Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns.

SEE ALSO

info, re_syntax

KEYWORDS

auto-exec, auto-load, library, unknown, word, whitespace
Copyright © 1991-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - lindex manual page

NAME

lindex - Retrieve an element from a list

SYNOPSIS

lindex list index

DESCRIPTION

This command treats list as a Tcl list and returns the index'th element from it (0 refers to the first element of the list). In extracting the element, lindex observes the same rules concerning braces and quotes and backslashes as the Tcl command interpreter; however, variable substitution and command substitution do not occur. If index is negative or greater than or equal to the number of elements in value, then an empty string is returned. If index has the value end, it refers to the last element in the list, and end-integer refers to the last element in the list minus the specified integer offset.

SEE ALSO

list, lappend, linsert, llength, lsearch, lsort, lrange, lreplace

KEYWORDS

element, index, list
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - linsert manual page

NAME

linsert - Insert elements into a list

SYNOPSIS

linsert list index element ?element element ...?

DESCRIPTION

This command produces a new list from list by inserting all of the element arguments just before the indexth element of list. Each element argument will become a separate element of the new list. If index is less than or equal to zero, then the new elements are inserted at the beginning of the list. If index has the value end, or if it is greater than or equal to the number of elements in the list, then the new elements are appended to the list. end-integer refers to the last element in the list minus the specified integer offset.

SEE ALSO

list, lappend, llength

KEYWORDS

element, insert, list
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - list manual page

NAME

list - Create a list

SYNOPSIS

list ?arg arg ...?

DESCRIPTION

This command returns a list comprised of all the args, or an empty string if no args are specified. Braces and backslashes get added as necessary, so that the index command may be used on the result to re-extract the original arguments, and also so that eval may be used to execute the resulting list, with arg1 comprising the command's name and the other args comprising its arguments. List produces slightly different results than concat: concat removes one level of grouping before forming the list, while list works directly from the original arguments. For example, the command
list a b {c d e} {f {g h}}
will return
a b {c d e} {f {g h}}
while concat with the same arguments will return
a b c d e f {g h}

SEE ALSO

lappend, lindex, linsert, llength, lsearch, lsort, lrange, lreplace

KEYWORDS

element, list
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - llength manual page

NAME

llength - Count the number of elements in a list

SYNOPSIS

llength list

DESCRIPTION

Treats list as a list and returns a decimal string giving the number of elements in it.

SEE ALSO

list, lindex, lrange

KEYWORDS

element, list, length
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - load manual page

NAME
load - Load machine code and initialize new commands.
SYNOPSIS
load fileName
load fileName packageName
load fileName packageName interp
DESCRIPTION
PORTABILITY ISSUES
Windows
BUGS
SEE ALSO
KEYWORDS

NAME

load - Load machine code and initialize new commands.

SYNOPSIS

load fileName
load fileName packageName
load fileName packageName interp

DESCRIPTION

This command loads binary code from a file into the application's address space and calls an initialization procedure in the package to incorporate it into an interpreter. fileName is the name of the file containing the code; its exact form varies from system to system but on most systems it is a shared library, such as a .so file under Solaris or a DLL under Windows. packageName is the name of the package, and is used to compute the name of an initialization procedure. interp is the path name of the interpreter into which to load the package (see the interp manual entry for details); if interp is omitted, it defaults to the interpreter in which the load command was invoked.

Once the file has been loaded into the application's address space, one of two initialization procedures will be invoked in the new code. Typically the initialization procedure will add new commands to a Tcl interpreter. The name of the initialization procedure is determined by packageName and whether or not the target interpreter is a safe one. For normal interpreters the name of the initialization procedure will have the form pkg_Init, where pkg is the same as packageName except that the first letter is converted to upper case and all other letters are converted to lower case. For example, if packageName is foo or FOo, the initialization procedure's name will be Foo_Init.

If the target interpreter is a safe interpreter, then the name of the initialization procedure will be pkg_SafeInit instead of pkg_Init. The pkg_SafeInit function should be written carefully, so that it initializes the safe interpreter only with partial functionality provided by the package that is safe for use by untrusted code. For more information on Safe-Tcl, see the safe manual entry.

The initialization procedure must match the following prototype:

typedef int Tcl_PackageInitProc(Tcl_Interp *interp);
The interp argument identifies the interpreter in which the package is to be loaded. The initialization procedure must return TCL_OK or TCL_ERROR to indicate whether or not it completed successfully; in the event of an error it should set the interpreter's result to point to an error message. The result of the load command will be the result returned by the initialization procedure.

The actual loading of a file will only be done once for each fileName in an application. If a given fileName is loaded into multiple interpreters, then the first load will load the code and call the initialization procedure; subsequent loads will call the initialization procedure without loading the code again. It is not possible to unload or reload a package.

The load command also supports packages that are statically linked with the application, if those packages have been registered by calling the Tcl_StaticPackage procedure. If fileName is an empty string, then packageName must be specified.

If packageName is omitted or specified as an empty string, Tcl tries to guess the name of the package. This may be done differently on different platforms. The default guess, which is used on most UNIX platforms, is to take the last element of fileName, strip off the first three characters if they are lib, and use any following alphabetic and underline characters as the module name. For example, the command load libxyz4.2.so uses the module name xyz and the command load bin/last.so {} uses the module name last.

If fileName is an empty string, then packageName must be specified. The load command first searches for a statically loaded package (one that has been registered by calling the Tcl_StaticPackage procedure) by that name; if one is found, it is used. Otherwise, the load command searches for a dynamically loaded package by that name, and uses it if it is found. If several different files have been loaded with different versions of the package, Tcl picks the file that was loaded first.

PORTABILITY ISSUES

Windows
When a load fails with "library not found" error, it is also possible that a dependent library was not found. To see the dependent libraries, type ``dumpbin -imports <dllname>'' in a DOS console to see what the library must import. When loading a DLL in the current directory, Windows will ignore ``./'' as a path specifier and use a search heuristic to find the DLL instead. To avoid this, load the DLL with
load [file join [pwd] mylib.DLL]

BUGS

If the same file is loaded by different fileNames, it will 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).

SEE ALSO

info sharedlibextension, Tcl_StaticPackage, safe

KEYWORDS

binary code, loading, safe interpreter, shared library
Copyright © 1995-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - lrange manual page

NAME

lrange - Return one or more adjacent elements from a list

SYNOPSIS

lrange list first last

DESCRIPTION

List must be a valid Tcl list. This command will return a new list consisting of elements first through last, inclusive. First or last may be end (or any abbreviation of it) to refer to the last element of the list. If first is less than zero, it is treated as if it were zero. If last is greater than or equal to the number of elements in the list, then it is treated as if it were end. If first is greater than last then an empty string is returned. Note: ``lrange list first first'' does not always produce the same result as ``lindex list first'' (although it often does for simple fields that aren't enclosed in braces); it does, however, produce exactly the same results as ``list [lindex list first]''

SEE ALSO

lappend, lindex, linsert, list, llength, lreplace

KEYWORDS

element, list, range, sublist
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - lreplace manual page

NAME

lreplace - Replace elements in a list with new elements

SYNOPSIS

lreplace list first last ?element element ...?

DESCRIPTION

lreplace returns a new list formed by replacing one or more elements of list with the element arguments. first and last specify the first and last index of the range of elements to replace. 0 refers to the first element of the list, and end (or any abbreviation of it) may be used to refer to the last element of the list. If list is empty, then first and last are ignored. If first is less than zero, it is considered to refer to the first element of the list. For non-empty lists, the element indicated by first must exist. If last is less than zero but greater than first, then any specified elements will be prepended to the list. If last is less than first then no elements are deleted; the new elements are simply inserted before first. The element arguments specify zero or more new arguments to be added to the list in place of those that were deleted. Each element argument will become a separate element of the list. If no element arguments are specified, then the elements between first and last are simply deleted. If list is empty, any element arguments are added to the end of the list.

SEE ALSO

lappend, lindex, linsert, list, llength, lrange, lsearch, lsort

KEYWORDS

element, list, replace
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - lsearch manual page

NAME

lsearch - See if a list contains a particular element

SYNOPSIS

lsearch ?mode? list pattern

DESCRIPTION

This command searches the elements of list to see if one of them matches pattern. If so, the command returns the index of the first matching element. If not, the command returns -1. The mode argument indicates how the elements of the list are to be matched against pattern and it must have one of the following values:

-exact
The list element must contain exactly the same string as pattern.

-glob
Pattern is a glob-style pattern which is matched against each list element using the same rules as the string match command.

-regexp
Pattern is treated as a regular expression and matched against each list element using the rules described in the re_syntax reference page.

If mode is omitted then it defaults to -glob.

KEYWORDS

list, match, pattern, regular expression, search, string
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - lsort manual page

NAME
lsort - Sort the elements of a list
SYNOPSIS
lsort ?options? list
DESCRIPTION
-ascii
-dictionary
-integer
-real
-command command
-increasing
-decreasing
-index index
-unique
NOTES
EXAMPLES
SEE ALSO
KEYWORDS

NAME

lsort - Sort the elements of a list

SYNOPSIS

lsort ?options? list

DESCRIPTION

This command sorts the elements of list, returning a new list in sorted order. The implementation of the lsort command uses the merge-sort algorithm which is a stable sort that has O(n log n) performance characteristics.

By default ASCII sorting is used with the result returned in increasing order. However, any of the following options may be specified before list to control the sorting process (unique abbreviations are accepted):

-ascii
Use string comparison with ASCII collation order. This is the default.

-dictionary
Use dictionary-style comparison. This is the same as -ascii 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 -dictionary mode, bigBoy sorts between bigbang and bigboy, and x10y sorts between x9y and x11y.

-integer
Convert list elements to integers and use integer comparison.

-real
Convert list elements to floating-point values and use floating comparison.

-command command
Use command as a comparison command. To compare two elements, evaluate a Tcl script consisting of command with the two elements appended as additional 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.

-increasing
Sort the list in increasing order (``smallest'' items first). This is the default.

-decreasing
Sort the list in decreasing order (``largest'' items first).

-index index
If this option is specified, each of the elements of list must itself be a proper Tcl sublist. Instead of sorting based on whole sublists, lsort will extract the index'th element from each sublist and sort based on the given element. The keyword end is allowed for the index to sort on the last sublist element, and end-index sorts on a sublist element offset from the end. For example,
lsort -integer -index 1 {{First 24} {Second 18} {Third 30}}
returns {Second 18} {First 24} {Third 30}, and
lsort -index end-1 {{a 1 e i} {b 2 3 f g} {c 4 5 6 d h}}
returns {c 4 5 6 d h} {a 1 e i} {b 2 3 f g}. This option is much more efficient than using -command to achieve the same effect.

-unique
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 -index 0 is used, {1 a} and {1 b} would be considered duplicates and only the second element, {1 b}, would be retained.

NOTES

The options to lsort only control what sort of comparison is used, and do not necessarily constrain what the values themselves actually are. This distinction is only noticeable when the list to be sorted has fewer than two elements.

The lsort command is reentrant, meaning it is safe to use as part of the implementation of a command used in the -command option.

EXAMPLES

Sorting a list using ASCII sorting:
% lsort {a10 B2 b1 a1 a2}
B2 a1 a10 a2 b1

Sorting a list using Dictionary sorting:

% lsort -dictionary {a10 B2 b1 a1 a2}
a1 a2 a10 b1 B2

Sorting lists of integers:

% lsort -integer {5 3 1 2 11 4}
1 2 3 4 5 11
% lsort -integer {1 2 0x5 7 0 4 -1}
-1 0 1 2 4 0x5 7

Sorting lists of floating-point numbers:

% lsort -real {5 3 1 2 11 4}
1 2 3 4 5 11
% lsort -real {.5 0.07e1 0.4 6e-1}
0.4 .5 6e-1 0.07e1

Sorting using indices:

% # Note the space character before the c
% lsort {{a 5} { c 3} {b 4} {e 1} {d 2}}
{ c 3} {a 5} {b 4} {d 2} {e 1}
% lsort -index 0 {{a 5} { c 3} {b 4} {e 1} {d 2}}
{a 5} {b 4} { c 3} {d 2} {e 1}
% lsort -index 1 {{a 5} { c 3} {b 4} {e 1} {d 2}}
{e 1} {d 2} { c 3} {b 4} {a 5}

Stripping duplicate values using sorting:

% lsort -unique {a b c a b c a b c}
a b c

More complex sorting using a comparison function:

% proc compare {a b} {
    set a0 [lindex $a 0]
    set b0 [lindex $b 0]
    if {$a0 < $b0} {
        return -1
    } elseif {$a0 > $b0} {
        return 1
    }
    return [string compare [lindex $a 1] [lindex $b 1]]
}
% lsort -command compare \
        {{3 apple} {0x2 carrot} {1 dingo} {2 banana}}
{1 dingo} {2 banana} {0x2 carrot} {3 apple}

SEE ALSO

lappend, lindex, linsert, list, llength, lrange, lreplace, lsearch

KEYWORDS

element, list, order, sort
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
Copyright © 1999 Scriptics Corporation
Copyright © 1995-1997 Roger E. Critchlow Jr.


Tcl Built-In Commands - memory manual page

NAME
memory - Control Tcl memory debugging capabilities.
SYNOPSIS
memory option ?arg arg ...?
DESCRIPTION
memory info
memory trace [on|off]
memory validate [on|off]
memory trace_on_at_malloc count
memory break_on_malloc count
memory display file
SEE ALSO
KEYWORDS

NAME

memory - Control Tcl memory debugging capabilities.

SYNOPSIS

memory option ?arg arg ...?

DESCRIPTION

The memory command gives the Tcl developer control of Tcl's memory debugging capabilities. The memory command has several suboptions, which are described below. It is only available when Tcl has been compiled with memory debugging enabled (when TCL_MEM_DEBUG is defined at compile time).

memory info
Produces a report containing the total allocations and frees since Tcl began, the current packets allocated (the current number of calls to ckalloc not met by a corresponding call to ckfree), the current bytes allocated, and the maximum number of packets and bytes allocated.

memory trace [on|off]

Turns memory tracing on or off. When memory tracing is on, every call to ckalloc causes a line of trace information to be written to stderr, consisting of the word ckalloc, followed by the address returned, the amount of memory allocated, and the C filename and line number of the code performing the allocation. For example:
ckalloc 40e478 98 tclProc.c 1406
Calls to ckfree are traced in the same manner.

memory validate [on|off]
Turns memory validation on or off. When memory validation is enabled, on every call to ckalloc or ckfree, the guard zones are checked for every piece of memory currently in existence that was allocated by ckalloc. This has a large performance impact and should only be used when overwrite problems are strongly suspected. The advantage of enabling memory validation is that a guard zone overwrite can be detected on the first call to ckalloc or ckfree after the overwrite occurred, rather than when the specific memory with the overwritten guard zone(s) is freed, which may occur long after the overwrite occurred.

memory trace_on_at_malloc count
Enable memory tracing after count ckalloc's have been performed. For example, if you enter memory trace_on_at_malloc 100, after the 100th call to ckalloc, memory trace information will begin being displayed for all allocations and frees. Since there can be a lot of memory activity before a problem occurs, judicious use of this option can reduce the slowdown caused by tracing (and the amount of trace information produced), if you can identify a number of allocations that occur before the problem sets in. The current number of memory allocations that have occurred since Tcl started is printed on a guard zone failure.

memory break_on_malloc count
After the count allocations have been performed, ckalloc's output a message to this effect and that it is now attempting to enter the C debugger. Tcl will then issue a SIGINT signal against itself. If you are running Tcl under a C debugger, it should then enter the debugger command mode.

memory display file
Write a list of all currently allocated memory to the specified file.

SEE ALSO

ckalloc, ckfree, Tcl_ValidateAllMemory, Tcl_DumpActiveMemory, TCL_MEM_DEBUG

KEYWORDS

memory, debug
Copyright © 1992-1999 by Karl Lehenbauer and Mark Diekhans
Copyright © 2000 by Scriptics Corporation.


Tcl Built-In Commands - msgcat manual page

NAME
msgcat - Tcl message catalog
SYNOPSIS
::msgcat::mc src-string
::msgcat::mclocale ?newLocale?
::msgcat::mcpreferences
::msgcat::mcload dirname
::msgcat::mcset locale src-string ?translate-string?
::msgcat::mcunknown locale src-string
DESCRIPTION
COMMANDS
::msgcat::mc src-string ?arg arg ...?
::msgcat::mclocale ?newLocale?
::msgcat::mcpreferences
::msgcat::mcload dirname
::msgcat::mcset locale src-string ?translate-string?
::msgcat::mcunknown locale src-string
LOCALE AND SUBLOCALE SPECIFICATION
NAMESPACES AND MESSAGE CATALOGS
LOCATION AND FORMAT OF MESSAGE FILES
RECOMMENDED MESSAGE SETUP FOR PACKAGES
POSTITIONAL CODES FOR FORMAT AND SCAN COMMANDS
CREDITS
SEE ALSO
KEYWORDS

NAME

msgcat - Tcl message catalog

SYNOPSIS

::msgcat::mc src-string
::msgcat::mclocale ?newLocale?
::msgcat::mcpreferences
::msgcat::mcload dirname
::msgcat::mcset locale src-string ?translate-string?
::msgcat::mcunknown locale src-string

DESCRIPTION

The msgcat package provides a set of functions that can be used to manage multi-lingual user interfaces. Text strings are defined in a ``message catalog'' which is independent from the application, and which can be edited or localized without modifying the application source code. New languages or locales are provided by adding a new file to the message catalog.

Use of the message catalog is optional by any application or package, but is encouraged if the application or package wishes to be enabled for multi-lingual applications.

COMMANDS

::msgcat::mc src-string ?arg arg ...?
Returns a translation of src-string according to the user's current locale. If additional arguments past src-string are given, the format command is used to substitute the additional arguments in the translation of src-string. ::msgcat::mc will search the messages defined in the current namespace for a translation of src-string; if none is found, it will search in the parent of the current namespace, and so on until it reaches the global namespace. If no translation string exists, ::msgcat::mcunknown is called and the string returned from ::msgcat::mcunknown is returned.

::msgcat::mc is the main function used to localize an application. Instead of using an English string directly, an applicaton can pass the English string through ::msgcat::mc and use the result. If an application is written for a single language in this fashion, then it is easy to add support for additional languages later simply by defining new message catalog entries.

::msgcat::mclocale ?newLocale?
This function sets the locale to newLocale. If newLocale is omitted, the current locale is returned, otherwise the current locale is set to newLocale. The initial locale defaults to the locale specified in the user's environment. See LOCALE AND SUBLOCALE SPECIFICATION below for a description of the locale string format.

::msgcat::mcpreferences
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 preference. If the user has specified LANG=en_US_funky, this procedure would return {en_US_funky en_US en}.

::msgcat::mcload dirname
Searches the specified directory for files that match the language specifications returned by ::msgcat::mcpreferences. Each file located is sourced. The file extension is ``.msg''. The number of message files which matched the specification and were loaded is returned.

::msgcat::mcset locale src-string ?translate-string?
Sets the translation for src-string to translate-string in the specified locale. If translate-string is not specified, src-string is used for both. The function returns translate-string.

::msgcat::mcunknown locale src-string
This routine is called by ::msgcat::mc in the case when a translation for src-string is not defined in the current locale. The default action is to return src-string. This procedure can be redefined by the application, for example to log error messages for each unknown string. The ::msgcat::mcunknown procedure is invoked at the same stack context as the call to ::msgcat::mc. The return vaue of ::msgcat::mcunknown is used as the return vaue for the call to ::msgcat::mc.

LOCALE AND SUBLOCALE SPECIFICATION

The locale is specified by a locale string. The locale string consists of a language code, an optional country code, and an optional system-specific code, each separated by ``_''. The country and language codes are specified in standards ISO-639 and ISO-3166. For example, the locale ``en'' specifies English and ``en_US'' specifes U.S. English.

The locale defaults to the value in env(LANG) at the time the msgcat package is loaded. If env(LANG) is not defined, then the locale defaults to ``C''.

When a locale is specified by the user, a ``best match'' search is performed during string translation. For example, if a user specifies en_UK_Funky, the locales ``en_UK_Funky'', ``en_UK'', and ``en'' are searched in order until a matching translation string is found. If no translation string is available, then ::msgcat::unknown is called.

NAMESPACES AND MESSAGE CATALOGS

Strings stored in the message catalog are stored relative to the namespace from which they were added. This allows multiple packages to use the same strings without fear of collisions with other packages. It also allows the source string to be shorter and less prone to typographical error.

For example, executing the code

mcset en hello "hello from ::"
namespace eval foo {mcset en hello "hello from ::foo"}
puts [mc hello]
namespace eval foo {puts [mc hello]}
will print
hello from ::
hello from ::foo

When searching for a translation of a message, the message catalog will search first the current namespace, then the parent of the current namespace, and so on until the global namespace is reached. This allows child namespaces to "inherit" messages from their parent namespace.

For example, executing the code

mcset en m1 ":: message1"
mcset en m2 ":: message2"
mcset en m3 ":: message3"
namespace eval ::foo {
    mcset en m2 "::foo message2"
    mcset en m3 "::foo message3"
}
namespace eval ::foo::bar {
    mcset en m3 "::foo::bar message3"
}
puts "[mc m1]; [mc m2]; [mc m3]"
namespace eval ::foo {puts "[mc m1]; [mc m2]; [mc m3]"}
namespace eval ::foo::bar {puts "[mc m1]; [mc m2]; [mc m3]"}
will print
:: message1; :: message2; :: message3
:: message1; ::foo message2; ::foo message3
:: message1; ::foo message2; ::foo::bar message3

LOCATION AND FORMAT OF MESSAGE FILES

Message files can be located in any directory, subject to the following conditions:

[1]
All message files for a package are in the same directory.

[2]
The message file name is a locale specifier followed by ``.msg''. For example:
es.msg    -- spanish
en_UK.msg -- UK English

[3]
The file contains a series of calls to mcset, setting the necessary translation strings for the language. For example:
::msgcat::mcset es "Free Beer!" "Cerveza Gracias!"

RECOMMENDED MESSAGE SETUP FOR PACKAGES

If a package is installed into a subdirectory of the tcl_pkgPath and loaded via package require, the following procedure is recommended.

[1]
During package installation, create a subdirectory msgs under your package directory.

[2]
Copy your *.msg files into that directory.

[3]
Add the following command to your package initialization script:
# load language files, stored in msgs subdirectory
::msgcat::mcload [file join [file dirname [info script]] msgs]

POSTITIONAL CODES FOR FORMAT AND SCAN COMMANDS

It is possible that a message string used as an argument to format 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.
format "We produced %d units in location %s" $num $city
format "In location %s we produced %d units" $city $num

This can be handled by using the positional parameters:

format "We produced %1\$d units in location %2\$s" $num $city
format "In location %2\$s we produced %1\$d units" $num $city

Similarly, positional parameters can be used with scan to extract values from internationalized strings.

CREDITS

The message catalog code was developed by Mark Harrison.

SEE ALSO

format, scan, namespace, package

KEYWORDS

internationalization, i18n, localization, l10n, message, text, translation
Copyright © 1998 Mark Harrison.


Tcl Built-In Commands - namespace manual page

NAME
namespace - create and manipulate contexts for commands and variables
SYNOPSIS
namespace ?option? ?arg ...?
DESCRIPTION
namespace children ?namespace? ?pattern?
namespace code script
namespace current
namespace delete ?namespace namespace ...?
namespace eval namespace arg ?arg ...?
namespace export ?-clear? ?pattern pattern ...?
namespace forget ?pattern pattern ...?
namespace import ?-force? ?pattern pattern ...?
namespace inscope namespace arg ?arg ...?
namespace origin command
namespace parent ?namespace?
namespace qualifiers string
namespace tail string
namespace which ?-command? ?-variable? name
WHAT IS A NAMESPACE?
QUALIFIED NAMES
NAME RESOLUTION
IMPORTING COMMANDS
EXPORTING COMMANDS
SEE ALSO
KEYWORDS

NAME

namespace - create and manipulate contexts for commands and variables

SYNOPSIS

namespace ?option? ?arg ...?

DESCRIPTION

The namespace command lets you create, access, and destroy separate contexts for commands and variables. See the section WHAT IS A NAMESPACE? below for a brief overview of namespaces. The legal option's are listed below. Note that you can abbreviate the option's.

namespace children ?namespace? ?pattern?
Returns a list of all child namespaces that belong to the namespace namespace. If namespace is not specified, then the children are returned for the current namespace. This command returns fully-qualified names, which start with ::. If the optional pattern is given, then this command returns only the names that match the glob-style pattern. The actual pattern used is determined as follows: a pattern that starts with :: is used directly, otherwise the namespace namespace (or the fully-qualified name of the current namespace) is prepended onto the the pattern.

namespace code script
Captures the current namespace context for later execution of the script script. It returns a new script in which script has been wrapped in a namespace code command. The new script has two important properties. First, it can be evaluated in any namespace and will cause script to be evaluated in the current namespace (the one where the namespace code command was invoked). Second, additional arguments can be appended to the resulting script and they will be passed to script as additional arguments. For example, suppose the command set script [namespace code {foo bar}] is invoked in namespace ::a::b. Then eval "$script x y" can be executed in any namespace (assuming the value of script has been passed in properly) and will have the same effect as the command namespace eval ::a::b {foo bar x y}. This command is needed because extensions like Tk normally execute callback scripts in the global namespace. A scoped command captures a command together with its namespace context in a way that allows it to be executed properly later. See the section SCOPED VALUES for some examples of how this is used to create callback scripts.

namespace current
Returns the fully-qualified name for the current namespace. The actual name of the global namespace is ``'' (i.e., an empty string), but this command returns :: for the global namespace as a convenience to programmers.

namespace delete ?namespace namespace ...?
Each namespace namespace is deleted and all variables, procedures, and child namespaces contained in the namespace are deleted. If a procedure is currently executing inside the namespace, the namespace will be kept alive until the procedure returns; however, the namespace is marked to prevent other code from looking it up by name. If a namespace doesn't exist, this command returns an error. If no namespace names are given, this command does nothing.

namespace eval namespace arg ?arg ...?
Activates a namespace called namespace and evaluates some code in that context. If the namespace does not already exist, it is created. If more than one arg argument is specified, the arguments are concatenated together with a space between each one in the same fashion as the eval command, and the result is evaluated.

If namespace has leading namespace qualifiers and any leading namespaces do not exist, they are automatically created.

namespace export ?-clear? ?pattern pattern ...?
Specifies which commands are exported from a namespace. The exported commands are those that can be later imported into another namespace using a namespace import command. Both commands defined in a namespace and commands the namespace has previously imported can be exported by a namespace. The commands do not have to be defined at the time the namespace export command is executed. Each pattern may contain glob-style special characters, but it may not include any namespace qualifiers. That is, the pattern can only specify commands in the current (exporting) namespace. Each pattern is appended onto the namespace's list of export patterns. If the -clear flag is given, the namespace's export pattern list is reset to empty before any pattern arguments are appended. If no patterns are given and the -clear flag isn't given, this command returns the namespace's current export list.

namespace forget ?pattern pattern ...?
Removes previously imported commands from a namespace. Each pattern is a qualified name such as foo::x or a::b::p*. Qualified names contain ::s and qualify a name with the name of one or more namespaces. Each pattern is qualified with 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. This command first finds the matching exported commands. It then checks whether any of those those commands were previously imported by the current namespace. If so, this command deletes the corresponding imported commands. In effect, this un-does the action of a namespace import command.

namespace import ?-force? ?pattern pattern ...?
Imports commands into a namespace. Each pattern is a qualified name like foo::x or a::p*. 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. All the commands that match a pattern string and which are currently exported from their namespace are added to the current namespace. This is done by creating a new command in the current namespace 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 -force option is given, imported commands will silently replace existing commands. The namespace import command has snapshot semantics: that is, only requested commands that are currently defined in the exporting namespace are imported. In other words, you can import only the commands that are in a namespace at the time when the namespace import command is executed. If another command is defined and exported in this namespace later on, it will not be imported.

namespace inscope namespace arg ?arg ...?
Executes a script in the context of a particular namespace. This command is not expected to be used directly by programmers; calls to it are generated implicitly when applications use namespace code commands to create callback scripts that the applications then register with, e.g., Tk widgets. The namespace inscope command is much like the namespace eval command except that it has lappend semantics and the namespace must already exist. It treats the first argument as a list, and appends any arguments after the first onto the end as proper list elements. namespace inscope ::foo a x y z is equivalent to namespace eval ::foo [concat a [list x y z]] This lappend semantics is important because many callback scripts are actually prefixes.

namespace origin command
Returns the fully-qualified name of the original command to which the imported command command refers. When a command is imported into a namespace, a new command is created in that namespace that points to the actual command in the exporting namespace. If a command is imported into a sequence of namespaces a, b,...,n where each successive namespace just imports the command from the previous namespace, this command returns the fully-qualified name of the original command in the first namespace, a. If command does not refer to an imported command, the command's own fully-qualified name is returned.

namespace parent ?namespace?
Returns the fully-qualified name of the parent namespace for namespace namespace. If namespace is not specified, the fully-qualified name of the current namespace's parent is returned.

namespace qualifiers string
Returns any leading namespace qualifiers for string. Qualifiers are namespace names separated by ::s. For the string ::foo::bar::x, this command returns ::foo::bar, and for :: it returns an empty string. This command is the complement of the namespace tail command. Note that it does not check whether the namespace names are, in fact, the names of currently defined namespaces.

namespace tail string
Returns the simple name at the end of a qualified string. Qualifiers are namespace names separated by ::s. For the string ::foo::bar::x, this command returns x, and for :: it returns an empty string. This command is the complement of the namespace qualifiers command. It does not check whether the namespace names are, in fact, the names of currently defined namespaces.

namespace which ?-command? ?-variable? name
Looks up name as either a command or variable and returns its fully-qualified name. For example, if name does not exist in the current namespace but does exist in the global namespace, this command returns a fully-qualified name in the global namespace. If the command or variable does not exist, this command returns an empty string. If the variable has been created but not defined, such as with the variable command or through a trace on the variable, this command will return the fully-qualified name of the variable. If no flag is given, name is treated as a command name. See the section NAME RESOLUTION below for an explanation of the rules regarding name resolution.

WHAT IS A NAMESPACE?

A namespace is a collection of commands and variables. It encapsulates the commands and variables to ensure that they won't interfere with the commands and variables of other namespaces. Tcl has always had one such collection, which we refer to as the global namespace. The global namespace holds all global variables and commands. The namespace eval command lets you create new namespaces. For example,
namespace eval Counter {
    namespace export bump
    variable num 0

    proc bump {} {
        variable num
        incr num
    }
}
creates a new namespace containing the variable num and the procedure bump. The commands and variables in this namespace are separate from other commands and variables in the same program. If there is a command named bump in the global namespace, for example, it will be different from the command bump in the Counter namespace.

Namespace variables resemble global variables in Tcl. They exist outside of the procedures in a namespace but can be accessed in a procedure via the variable command, as shown in the example above.

Namespaces are dynamic. You can add and delete commands and variables at any time, so you can build up the contents of a namespace over time using a series of namespace eval commands. For example, the following series of commands has the same effect as the namespace definition shown above:

namespace eval Counter {
    variable num 0
    proc bump {} {
        variable num
        return [incr num]
    }
}
namespace eval Counter {
    proc test {args} {
        return $args
    }
}
namespace eval Counter {
    rename test ""
}
Note that the test procedure is added to the Counter namespace, and later removed via the rename command.

Namespaces can have other namespaces within them, so they nest hierarchically. A nested namespace is encapsulated inside its parent namespace and can not interfere with other namespaces.

QUALIFIED NAMES

Each namespace has a textual name such as history or ::safe::interp. Since namespaces may nest, qualified names are used to refer to commands, variables, and child namespaces contained inside namespaces. Qualified names are similar to the hierarchical path names for Unix files or Tk widgets, except that :: is used as the separator instead of / or .. The topmost or global namespace has the name ``'' (i.e., an empty string), although :: is a synonym. As an example, the name ::safe::interp::create refers to the command create in the namespace interp that is a child of of namespace ::safe, which in turn is a child of the global namespace ::.

If you want to access commands and variables from another namespace, you must use some extra syntax. Names must be qualified by the namespace that contains them. From the global namespace, we might access the Counter procedures like this:

Counter::bump 5
Counter::Reset
We could access the current count like this:
puts "count = $Counter::num"
When one namespace contains another, you may need more than one qualifier to reach its elements. If we had a namespace Foo that contained the namespace Counter, you could invoke its bump procedure from the global namespace like this:
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 Foo namespace like this:

proc Foo::Test {args} {return $args}
And you could move the same procedure to another namespace like this:
rename Foo::Test Bar::Test

There are a few remaining points about qualified names that we should cover. Namespaces have nonempty names except for the global namespace. :: is disallowed in simple command, variable, and namespace names except as a namespace separator. Extra :s in a qualified name are ignored; that is, two or more :s are treated as a namespace separator. A trailing :: in a qualified variable or command name refers to the variable or command named {}. However, a trailing :: in a qualified namespace name is ignored.

NAME RESOLUTION

In general, all Tcl commands that take variable and command names support qualified names. This means you can give qualified names to such commands as set, proc, rename, and interp alias. If you provide a fully-qualified name that starts with a ::, there is no question about what command, variable, or namespace you mean. However, if the name does not start with a :: (i.e., is relative), Tcl follows a fixed rule for looking it up: Command and variable names are always resolved by looking first in the current namespace, and then in the global namespace. Namespace names, on the other hand, are always resolved by looking in only the current namespace.

In the following example,

set traceLevel 0
namespace eval Debug {
    printTrace $traceLevel
}
Tcl looks for traceLevel in the namespace Debug and then in the global namespace. It looks up the command printTrace 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:
set traceLevel 0
namespace eval Foo {
    variable traceLevel 3

    namespace eval Debug {
        printTrace $traceLevel
    }
}
Here Tcl looks for traceLevel first in the namespace Foo::Debug. Since it is not found there, Tcl then looks for it in the global namespace. The variable Foo::traceLevel is completely ignored during the name resolution process.

You can use the namespace which command to clear up any question about name resolution. For example, the command:

namespace eval Foo::Debug {namespace which -variable traceLevel}
returns ::traceLevel. On the other hand, the command,
namespace eval Foo {namespace which -variable traceLevel}
returns ::Foo::traceLevel.

As mentioned above, namespace names are looked up differently than the names of variables and commands. Namespace names are always resolved in the current namespace. This means, for example, that a namespace eval command that creates a new namespace always creates a child of the current namespace unless the new namespace name begins with a ::.

Tcl has no access control to limit what variables, commands, or namespaces you can reference. If you provide a qualified name that resolves to an element by the name resolution rule above, you can access the element.

You can access a namespace variable from a procedure in the same namespace by using the variable command. Much like the global command, this creates a local link to the namespace variable. If necessary, it also creates the variable in the current namespace and initializes it. Note that the global command only creates links to variables in the global namespace. It is not necessary to use a variable command if you always refer to the namespace variable using an appropriate qualified name.

IMPORTING COMMANDS

Namespaces are often used to represent libraries. Some library commands are used so frequently 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 Blt. Then you might access these commands like this:
Blt::graph .g -background red
Blt::table . .g 0,0
If you use the graph and table commands frequently, you may want to access them without the Blt:: prefix. You can do this by importing the commands into the current namespace, like this:
namespace import Blt::*
This adds all exported commands from the Blt namespace into the current namespace context, so you can write code like this:
graph .g -background red
table . .g 0,0
The namespace import command only imports commands from a namespace that that namespace exported with a namespace export command.

Importing every command from a namespace is generally a bad idea since you don't know what you will get. It is better to import just the specific commands you need. For example, the command

namespace import Blt::graph Blt::table
imports only the graph and table commands into the current context.

If you try to import a command that already exists, you will get an error. This prevents you from importing the same command from two different packages. But from time to time (perhaps when debugging), you may want to get around this restriction. You may want to reissue the namespace import command to pick up new commands that have appeared in a namespace. In that case, you can use the -force option, and existing commands will be silently overwritten:

namespace import -force Blt::graph Blt::table
If for some reason, you want to stop using the imported commands, you can remove them with an namespace forget command, like this:
namespace forget Blt::*
This searches the current namespace for any commands imported from Blt. If it finds any, it removes them. Otherwise, it does nothing. After this, the Blt commands must be accessed with the Blt:: prefix.

When you delete a command from the exporting namespace like this:

rename Blt::graph ""
the command is automatically removed from all namespaces that import it.

EXPORTING COMMANDS

You can export commands from a namespace like this:
namespace eval Counter {
    namespace export 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!"
        }
    }
}
The procedures bump and reset are exported, so they are included when you import from the Counter namespace, like this:
namespace import Counter::*
However, the Check procedure is not exported, so it is ignored by the import operation.

The namespace import command only imports commands that were declared as exported by their namespace. The namespace export command specifies what commands may be imported by other namespaces. If a namespace import command specifies a command that is not exported, the command is not imported.

SEE ALSO

variable

KEYWORDS

exported, internal, variable
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1997 Sun Microsystems, Inc.


Tcl Built-In Commands - open manual page

NAME
open - Open a file-based or command pipeline channel
SYNOPSIS
open fileName
open fileName access
open fileName access permissions
DESCRIPTION
r
r+
w
w+
a
a+
RDONLY
WRONLY
RDWR
APPEND
CREAT
EXCL
NOCTTY
NONBLOCK
TRUNC
COMMAND PIPELINES
SERIAL COMMUNICATIONS
CONFIGURATION OPTIONS
-mode baud,parity,data,stop
-pollinterval msec
-lasterror
PORTABILITY ISSUES
Windows (all versions)
Windows NT
Windows 95
Macintosh
Unix
SEE ALSO
KEYWORDS

NAME

open - Open a file-based or command pipeline channel

SYNOPSIS

open fileName
open fileName access
open fileName access permissions

DESCRIPTION

This command opens a file, serial port, or command pipeline and returns a channel identifier that may be used in future invocations of commands like read, puts, and close. If the first character of fileName is not | then the command opens a file: fileName gives the name of the file to open, and it must conform to the conventions described in the filename manual entry.

The access argument, if present, indicates the way in which the file (or command pipeline) is to be accessed. In the first form access may have any of the following values:

r
Open the file for reading only; the file must already exist. This is the default value if access is not specified.

r+
Open the file for both reading and writing; the file must already exist.

w
Open the file for writing only. Truncate it if it exists. If it doesn't exist, create a new file.

w+
Open the file for reading and writing. Truncate it if it exists. If it doesn't exist, create a new file.

a
Open the file for writing only. If the file doesn't exist, create a new empty file. Set the initial access position to the end of the file.

a+
Open the file for reading and writing. If the file doesn't exist, create a new empty file. Set the initial access position to the end of the file.

In the second form, access 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 RDONLY, WRONLY or RDWR.

RDONLY
Open the file for reading only.

WRONLY
Open the file for writing only.

RDWR
Open the file for both reading and writing.

APPEND
Set the file pointer to the end of the file prior to each write.

CREAT
Create the file if it doesn't already exist (without this flag it is an error for the file not to exist).

EXCL
If CREAT is also specified, an error is returned if the file already exists.

NOCTTY
If the file is a terminal device, this flag prevents the file from becoming the controlling terminal of the process.

NONBLOCK
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 (it is better to use the fconfigure command to put a file in nonblocking mode). For details refer to your system documentation on the open system call's O_NONBLOCK flag.

TRUNC
If the file exists it is truncated to zero length.

If a new file is created as part of opening it, permissions (an integer) is used to set the permissions for the new file in conjunction with the process's file mode creation mask. Permissions defaults to 0666.

Note that if you are going to be reading or writing binary data from the channel created by this command, you should use the fconfigure command to change the -translation option of the channel to binary before transferring any binary data. This is in contrast to the ``b'' character passed as part of the equivalent of the access parameter to some versions of the C library fopen() function.

COMMAND PIPELINES

If the first character of fileName is ``|'' then the remaining characters of fileName are treated as a list of arguments that describe a command pipeline to invoke, in the same style as the arguments for exec. In this case, the channel identifier returned by open may be used to write to the command's input pipe or read from its output pipe, depending on the value of access. If write-only access is used (e.g. access is w), 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. access is r), standard input for the pipeline is taken from the current standard input unless overridden by the command.

SERIAL COMMUNICATIONS

If fileName refers to a serial port, then the specified serial port is opened and initialized in a platform-dependent manner. Acceptable values for the fileName to use to open a serial port are described in the PORTABILITY ISSUES section.

CONFIGURATION OPTIONS

The fconfigure command can be used to query and set the following configuration option for open serial ports:

-mode baud,parity,data,stop
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 baud rate is a simple integer that specifies the connection speed. Parity is one of the following letters: n, o, e, m, s; respectively signifying the parity options of ``none'', ``odd'', ``even'', ``mark'', or ``space''. Data is the number of data bits and should be an integer from 5 to 8, while stop is the number of stop bits and should be the integer 1 or 2.

-pollinterval msec
This option, available only on Windows for serial ports, is used to set the maximum time between polling for fileevents. This affects the time interval between checking for events throughout the Tcl interpreter (the smallest value always wins). Use this option only if you want to poll the serial port more often than 10 msec (the default).

-lasterror
This option is available only on Windows for serial ports, and is query only (will only be reported when directly requested). In case of a serial communication error, read or puts returns a general Tcl file I/O error. fconfigure -lasterror can be called to get a list of error details (e.g. FRAME RXOVER).

PORTABILITY ISSUES

Windows (all versions)
Valid values for fileName to open a serial port are of the form com X:, where X is a number, generally from 1 to 4. This notation only works for serial ports from 1 to 9, if the system happens to have more than four. An attempt to open a serial port that does not exist or has a number greater than 9 will fail. An alternate form of opening serial ports is to use the filename \\.\comX, 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.

Windows NT
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 of the lines entered at the console will be sent to the command pipeline and some will be sent to the Tcl evaluator. If a command pipeline is opened for writing, keystrokes entered into the console are not visible until the the pipe is closed. This behavior occurs whether the command pipeline is executing 16-bit or 32-bit applications. These problems only occur because both Tcl and the child application are competing for the console at the same time. If the command pipeline is started from a script, so that Tcl is not accessing the console, or if the command pipeline does not use standard input or output, but is redirected from or to a file, then the above problems do not occur.

Windows 95
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 synchronously. Command pipelines that do not execute 16-bit DOS applications run asynchronously and can be opened for both reading and writing.

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 from a 32-bit application, some of the keystrokes entered at the console will be sent to the command pipeline and some will be sent to the Tcl evaluator. If a command pipeline is opened for writing to a 32-bit application, no output is visible on the console until the the pipe is closed. These problems only occur because both Tcl and the child application are competing for the console at the same time. If the command pipeline is started from a script, so that Tcl is not accessing the console, or if the command pipeline does not use standard input or output, but is redirected from or to a file, then the above problems do not occur.

Whether or not Tcl is running interactively, if a command pipeline is opened for reading from a 16-bit DOS application, the call to open will not return until end-of-file has been received from the command pipeline's standard output. If a command pipeline is opened for writing to a 16-bit DOS application, no data will be sent to the command pipeline's standard output until the pipe is actually closed. This problem occurs because 16-bit DOS applications are run synchronously, as described above.

Macintosh
Opening a serial port is not currently implemented under Macintosh.

Opening a command pipeline is not supported under Macintosh, since applications do not support the concept of standard input or output.

Unix
Valid values for fileName to open a serial port are generally of the form /dev/tty X, where X is a or b, but the name of any pseudo-file that maps to a serial port may be used.

When running Tcl interactively, there may be some strange interactions between the console, if one is present, and a command pipeline that uses standard input. If a command pipeline is opened for reading, some of the lines entered at the console will be sent to the command pipeline and some will be sent to the Tcl evaluator. This problem only occurs because both Tcl and the child application are competing for the console at the same time. If the command pipeline is started from a script, so that Tcl is not accessing the console, or if the command pipeline does not use standard input, but is redirected from a file, then the above problem does not occur.

See the PORTABILITY ISSUES section of the exec command for additional information not specific to command pipelines about executing applications on the various platforms

SEE ALSO

file, close, filename, fconfigure, gets, read, puts, exec, fopen

KEYWORDS

access mode, append, create, file, non-blocking, open, permissions, pipeline, process, serial
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - package manual page

NAME
package - Facilities for package loading and version control
SYNOPSIS
package forget ?package package ...?
package ifneeded package version ?script?
package names
package present ?-exact? package ?version?
package provide package ?version?
package require ?-exact? package ?version?
package unknown ?command?
package vcompare version1 version2
package versions package
package vsatisfies version1 version2
DESCRIPTION
package forget ?package package ...?
package ifneeded package version ?script?
package names
package present ?-exact? package ?version?
package provide package ?version?
package require ?-exact? package ?version?
package unknown ?command?
package vcompare version1 version2
package versions package
package vsatisfies version1 version2
VERSION NUMBERS
PACKAGE INDICES
SEE ALSO
KEYWORDS

NAME

package - Facilities for package loading and version control

SYNOPSIS

package forget ?package package ...?
package ifneeded package version ?script?
package names
package present ?-exact? package ?version?
package provide package ?version?
package require ?-exact? package ?version?
package unknown ?command?
package vcompare version1 version2
package versions package
package vsatisfies version1 version2

DESCRIPTION

This command keeps a simple database of the packages available for use by the current interpreter and how to load them into the interpreter. It supports multiple versions of each package and arranges for the correct version of a package to be loaded based on what is needed by the application. This command also detects and reports version clashes. Typically, only the package require and package provide commands are invoked in normal Tcl scripts; the other commands are used primarily by system scripts that maintain the package database.

The behavior of the package command is determined by its first argument. The following forms are permitted:

package forget ?package package ...?
Removes all information about each specified package from this interpreter, including information provided by both package ifneeded and package provide.

package ifneeded package version ?script?
This command typically appears only in system configuration scripts to set up the package database. It indicates that a particular version of a particular package is available if needed, and that the package can be added to the interpreter by executing script. The script is saved in a database for use by subsequent package require commands; typically, script sets up auto-loading for the commands in the package (or calls load and/or source directly), then invokes package provide to indicate that the package is present. There may be information in the database for several different versions of a single package. If the database already contains information for package and version, the new script replaces the existing one. If the script argument is omitted, the current script for version version of package package is returned, or an empty string if no package ifneeded command has been invoked for this package and version.

package names
Returns a list of the names of all packages in the interpreter for which a version has been provided (via package provide) or for which a package ifneeded script is available. The order of elements in the list is arbitrary.

package present ?-exact? package ?version?
This command is equivalent to package require except that it does not try and load the package if it is not already loaded.

package provide package ?version?
This command is invoked to indicate that version version of package package is now present in the interpreter. It is typically invoked once as part of an ifneeded script, and again by the package itself when it is finally loaded. An error occurs if a different version of package has been provided by a previous package provide command. If the version argument is omitted, then the command returns the version number that is currently provided, or an empty string if no package provide command has been invoked for package in this interpreter.

package require ?-exact? package ?version?
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 a suitable version of the package is loaded into the interpreter. If the command succeeds, it returns the version number that is loaded; otherwise it generates an error. If both the -exact switch and the version argument are specified then only the given version is acceptable. If -exact is omitted but version is specified, then versions later than version are also acceptable as long as they have the same major version number as version. If both -exact and version are omitted then any version whatsoever is acceptable. If a version of package has already been provided (by invoking the package provide command), then its version number must satisfy the criteria given by -exact and version and the command returns immediately. Otherwise, the command searches the database of information provided by previous package ifneeded commands to see if an acceptable version of the package is available. If so, the script for the highest acceptable version number is invoked; it must do whatever is necessary to load the package, including calling package provide for the package. If the package ifneeded database does not contain an acceptable version of the package and a package unknown command has been specified for the interpreter then that command is invoked; when it completes, Tcl checks again to see if the package is now provided or if there is a package ifneeded script for it. If all of these steps fail to provide an acceptable version of the package, then the command returns an error.

package unknown ?command?
This command supplies a ``last resort'' command to invoke during package require if no suitable version of a package can be found in the package ifneeded database. If the command argument is supplied, it contains the first part of a command; when the command is invoked during a package require command, Tcl appends two additional arguments giving the desired package name and version. For example, if command is foo bar and later the command package require test 2.4 is invoked, then Tcl will execute the command foo bar test 2.4 to load the package. If no version number is supplied to the package require command, then the version argument for the invoked command will be an empty string. If the package unknown command is invoked without a command argument, then the current package unknown script is returned, or an empty string if there is none. If command is specified as an empty string, then the current package unknown script is removed, if there is one.

package vcompare version1 version2
Compares the two version numbers given by version1 and version2. Returns -1 if version1 is an earlier version than version2, 0 if they are equal, and 1 if version1 is later than version2.

package versions package
Returns a list of all the version numbers of package for which information has been provided by package ifneeded commands.

package vsatisfies version1 version2
Returns 1 if scripts written for version2 will work unchanged with version1 (i.e. version1 is equal to or greater than version2 and they both have the same major version number), 0 otherwise.

VERSION NUMBERS

Version numbers consist of one or more decimal numbers separated by dots, such as 2 or 1.162 or 3.1.13.1. The first number is called the major version number. Larger numbers correspond to later versions of a package, with leftmost numbers having greater significance. For example, version 2.1 is later than 1.3 and version 3.4.6 is later than 3.3.5. Missing fields are equivalent to zeroes: version 1.3 is the same as version 1.3.0 and 1.3.0.0, so it is earlier than 1.3.1 or 1.3.0.2. A later version number is assumed to be upwards compatible with an earlier version number as long as both versions have the same major version number. For example, Tcl scripts written for version 2.3 of a package should work unchanged under versions 2.3.2, 2.4, and 2.5.1. Changes in the major version number signify incompatible changes: if code is written to use version 2.1 of a package, it is not guaranteed to work unmodified with either version 1.7.3 or version 3.1.

PACKAGE INDICES

The recommended way to use packages in Tcl is to invoke package require and package provide commands in scripts, and use the procedure pkg_mkIndex to create package index files. Once you've done this, packages will be loaded automatically in response to package require commands. See the documentation for pkg_mkIndex for details.

SEE ALSO

msgcat, packagens, pkgMkIndex

KEYWORDS

package, version
Copyright © 1996 Sun Microsystems, Inc.


Tcl Built-In Commands - pkg::create manual page

NAME
pkg::create - Construct an appropriate package ifneeded command for a given package specification
SYNOPSIS
::pkg::create -name packageName -version packageVersion ?-load filespec? ... ?-source filespec? ...
DESCRIPTION
OPTIONS
-name packageName
-version packageVersion
-load filespec
-source filespec
SEE ALSO
KEYWORDS

NAME

pkg::create - Construct an appropriate package ifneeded command for a given package specification

SYNOPSIS

::pkg::create -name packageName -version packageVersion ?-load filespec? ... ?-source filespec? ...

DESCRIPTION

::pkg::create is a utility procedure that is part of the standard Tcl library. It is used to create an appropriate package ifneeded command for a given package specification. It can be used to construct a pkgIndex.tcl file for use with the package mechanism.

OPTIONS

The parameters supported are:

-name packageName
This parameter specifies the name of the package. It is required.

-version packageVersion
This parameter specifies the version of the package. It is required.

-load filespec
This parameter specifies a binary library that must be loaded with the load command. filespec is a list with two elements. The first element is the name of the file to load. The second, optional element is a list of commands supplied by loading that file. If the list of procedures is empty or omitted, ::pkg::create will set up the library for direct loading (see pkg_mkIndex). Any number of -load parameters may be specified.

-source filespec
This parameter is similar to the -load parameter, except that it specifies a Tcl library that must be loaded with the source command. Any number of -source parameters may be specified.

At least one -load or -source paramter must be given.

SEE ALSO

package

KEYWORDS

auto-load, index, package, version
Copyright © 1998-2000 by Scriptics Corporation.


Tcl Built-In Commands - pid manual page

NAME

pid - Retrieve process id(s)

SYNOPSIS

pid ?fileId?

DESCRIPTION

If the fileId argument is given then it should normally refer to a process pipeline created with the open command. In this case the pid command will return a list whose elements are the process identifiers of all the processes in the pipeline, in order. The list will be empty if fileId refers to an open file that isn't a process pipeline. If no fileId argument is given then pid returns the process identifier of the current process. All process identifiers are returned as decimal strings.

SEE ALSO

exec, open

KEYWORDS

file, pipeline, process identifier
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - pkg_mkIndex manual page

NAME
pkg_mkIndex - Build an index for automatic loading of packages
SYNOPSIS
pkg_mkIndex ?-direct? ?-lazy? ?-load pkgPat? ?-verbose? dir ?pattern pattern ...?
DESCRIPTION
OPTIONS
-direct
-lazy
-load pkgPat
-verbose
--
PACKAGES AND THE AUTO-LOADER
HOW IT WORKS
DIRECT LOADING
COMPLEX CASES
SEE ALSO
KEYWORDS

NAME

pkg_mkIndex - Build an index for automatic loading of packages

SYNOPSIS

pkg_mkIndex ?-direct? ?-lazy? ?-load pkgPat? ?-verbose? dir ?pattern pattern ...?

DESCRIPTION

Pkg_mkIndex is a utility procedure that is part of the standard Tcl library. It is used to create index files that allow packages to be loaded automatically when package require commands are executed. To use pkg_mkIndex, follow these steps:

[1]
Create the package(s). Each package may consist of one or more Tcl script files or binary files. Binary files must be suitable for loading with the load command with a single argument; for example, if the file is test.so it must be possible to load this file with the command load test.so. Each script file must contain a package provide command to declare the package and version number, and each binary file must contain a call to Tcl_PkgProvide.

[2]
Create the index by invoking pkg_mkIndex. The dir argument gives the name of a directory and each pattern argument is a glob-style pattern that selects script or binary files in dir. The default pattern is *.tcl and *.[info sharedlibextension].
Pkg_mkIndex will create a file pkgIndex.tcl in dir with package information about all the files given by the pattern arguments. It does this by loading each file into a slave interpreter and seeing what packages and new commands appear (this is why it is essential to have package provide commands or Tcl_PkgProvide calls in the files, as described above). If you have a package split among scripts and binary files, or if you have dependencies among files, you may have to use the -load option or adjust the order in which pkg_mkIndex processes the files. See COMPLEX CASES below.

[3]
Install the package as a subdirectory of one of the directories given by the tcl_pkgPath variable. If $tcl_pkgPath contains more than one directory, machine-dependent packages (e.g., those that contain binary shared libraries) should normally be installed under the first directory and machine-independent packages (e.g., those that contain only Tcl scripts) should be installed under the second directory. The subdirectory should include the package's script and/or binary files as well as the pkgIndex.tcl file. As long as the package is installed as a subdirectory of a directory in $tcl_pkgPath it will automatically be found during package require commands.
If you install the package anywhere else, then you must ensure that the directory containing the package is in the auto_path global variable or an immediate subdirectory of one of the directories in auto_path. Auto_path contains a list of directories that are searched by both the auto-loader and the package loader; by default it includes $tcl_pkgPath. The package loader also checks all of the subdirectories of the directories in auto_path. You can add a directory to auto_path explicitly in your application, or you can add the directory to your TCLLIBPATH environment variable: if this environment variable is present, Tcl initializes auto_path from it during application startup.

[4]
Once the above steps have been taken, all you need to do to use a package is to invoke package require. For example, if versions 2.1, 2.3, and 3.1 of package Test have been indexed by pkg_mkIndex, the command package require Test will make version 3.1 available and the command package require -exact Test 2.1 will make version 2.1 available. There may be many versions of a package in the various index files in auto_path, but only one will actually be loaded in a given interpreter, based on the first call to package require. Different versions of a package may be loaded in different interpreters.

OPTIONS

The optional switches are:

-direct
The generated index will implement direct loading of the package upon package require. This is the default.

-lazy
The generated index will manage to delay loading the package until the use of one of the commands provided by the package, instead of loading it immediately upon package require.

-load pkgPat
The index process will pre-load any packages that exist in the current interpreter and match pkgPat into the slave interpreter used to generate the index. The pattern match uses string match rules. See COMPLEX CASES below.

-verbose
Generate output during the indexing process. Output is via the tclLog procedure, which by default prints to stderr.

--
End of the flags, in case dir begins with a dash.

PACKAGES AND THE AUTO-LOADER

The package management facilities overlap somewhat with the auto-loader, in that both arrange for files to be loaded on-demand. However, package management is a higher-level mechanism that uses the auto-loader for the last step in the loading process. It is generally better to index a package with pkg_mkIndex rather than auto_mkindex because the package mechanism provides version control: several versions of a package can be made available in the index files, with different applications using different versions based on package require commands. In contrast, auto_mkindex does not understand versions so it can only handle a single version of each package. It is probably not a good idea to index a given package with both pkg_mkIndex and auto_mkindex. If you use pkg_mkIndex to index a package, its commands cannot be invoked until package require has been used to select a version; in contrast, packages indexed with auto_mkindex can be used immediately since there is no version control.

HOW IT WORKS

Pkg_mkIndex depends on the package unknown command, the package ifneeded command, and the auto-loader. The first time a package require command is invoked, the package unknown script is invoked. This is set by Tcl initialization to a script that evaluates all of the pkgIndex.tcl files in the auto_path. The pkgIndex.tcl files contain package ifneeded commands for each version of each available package; these commands invoke package provide commands to announce the availability of the package, and they setup auto-loader information to load the files of the package. If the -lazy flag was provided when the pkgIndex.tcl was generated, a given file of a given version of a given package isn't actually loaded until the first time one of its commands is invoked. Thus, after invoking package require you may not see the package's commands in the interpreter, but you will be able to invoke the commands and they will be auto-loaded.

DIRECT LOADING

Some packages, for instance packages which use namespaces and export commands or those which require special initialization, might select that their package files be loaded immediately upon package require 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 -lazy argument.

COMPLEX CASES

Most complex cases of dependencies among scripts and binary files, and packages being split among scripts and binary files are handled OK. However, you may have to adjust the order in which files are processed by pkg_mkIndex. These issues are described in detail below.

If each script or file contains one package, and packages are only contained in one file, then things are easy. You simply specify all files to be indexed in any order with some glob patterns.

In general, it is OK for scripts to have dependencies on other packages. If scripts contain package require commands, these are stubbed out in the interpreter used to process the scripts, so these do not cause problems. If scripts call into other packages in global code, these calls are handled by a stub unknown command. However, if scripts make variable references to other package's variables in global code, these will cause errors. That is also bad coding style.

If binary files have dependencies on other packages, things can become tricky because it is not possible to stub out C-level API's such as Tcl_PkgRequire API when loading a binary file. For example, suppose the BLT package requires Tk, and expresses this with a call to Tcl_PkgRequire in its Blt_Init routine. To support this, you must run pkg_mkIndex in an interpreter that has Tk loaded. You can achieve this with the -load pkgPat option. If you specify this option, pkg_mkIndex will load any packages listed by info loaded and that match pkgPat into the interpreter used to process files. In most cases this will satisfy the Tcl_PkgRequire calls made by binary files.

If you are indexing two binary files and one depends on the other, you should specify the one that has dependencies last. This way the one without dependencies will get loaded and indexed, and then the package it provides will be available when the second file is processed. You may also need to load the first package into the temporary interpreter used to create the index by using the -load flag; it won't hurt to specify package patterns that are not yet loaded.

If you have a package that is split across scripts and a binary file, then you should avoid the -load flag. The problem is that if you load a package before computing the index it masks any other files that provide part of the same package. If you must use -load, then you must specify the scripts first; otherwise the package loaded from the binary file may mask the package defined by the scripts.

SEE ALSO

package

KEYWORDS

auto-load, index, package, version
Copyright © 1996 Sun Microsystems, Inc.


Built-In Commands - proc manual page

NAME

proc - Create a Tcl procedure

SYNOPSIS

proc name args body

DESCRIPTION

The proc command creates a new Tcl procedure named name, replacing any existing command or procedure there may have been by that name. Whenever the new command is invoked, the contents of body will be executed by the Tcl interpreter. Normally, name is unqualified (does not include the names of any containing namespaces), and the new procedure is created in the current namespace. If name includes any namespace qualifiers, the procedure is created in the specified namespace. Args specifies the formal arguments to the procedure. It consists of a list, possibly empty, each of whose elements specifies one argument. Each argument specifier is also a list with either one or two fields. If there is only a single field in the specifier then it is the name of the argument; if there are two fields, then the first is the argument name and the second is its default value.

When name is invoked a local variable will be created for each of the formal arguments to the procedure; its value will be the value of corresponding argument in the invoking command or the argument's default value. Arguments with default values need not be specified in a procedure invocation. However, there must be enough actual arguments for all the formal arguments that don't have defaults, and there must not be any extra actual arguments. There is one special case to permit procedures with variable numbers of arguments. If the last formal argument has the name args, then a call to the procedure may contain more actual arguments than the procedure has formals. In this case, all of the actual arguments starting at the one that would be assigned to args are combined into a list (as if the list command had been used); this combined value is assigned to the local variable args.

When body is being executed, variable names normally refer to local variables, which are created automatically when referenced and deleted when the procedure returns. One local variable is automatically created for each of the procedure's arguments. Global variables can only be accessed by invoking the global command or the upvar command. Namespace variables can only be accessed by invoking the variable command or the upvar command.

The proc command returns an empty string. When a procedure is invoked, the procedure's return value is the value specified in a return command. If the procedure doesn't execute an explicit return, then its return value is the value of the last command 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.

SEE ALSO

info, unknown

KEYWORDS

argument, procedure
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - puts manual page

NAME

puts - Write to a channel

SYNOPSIS

puts ?-nonewline? ?channelId? string

DESCRIPTION

Writes the characters given by string to the channel given by channelId. ChannelId must be a channel identifier such as returned from a previous invocation of open or socket. It must have been opened for output. If no channelId is specified then it defaults to stdout. Puts normally outputs a newline character after string, but this feature may be suppressed by specifying the -nonewline switch.

Newline characters in the output are translated by puts to platform-specific end-of-line sequences according to the current value of the -translation option for the channel (for example, on PCs newlines are normally replaced with carriage-return-linefeed sequences; on Macintoshes newlines are normally replaced with carriage-returns). See the fconfigure manual entry for a discussion on ways in which fconfigure will alter output.

Tcl buffers output internally, so characters written with puts may not appear immediately on the output file or device; Tcl will normally delay output until the buffer is full or the channel is closed. You can force output to appear immediately with the flush command.

When the output buffer fills up, the puts command will normally block until all the buffered data has been accepted for output by the operating system. If channelId is in nonblocking mode then the puts command will not block even if the operating system cannot accept the data. Instead, Tcl continues to buffer the data and writes it in the background as fast as the underlying file or device can accept it. The application must use the Tcl event loop for nonblocking output to work; otherwise Tcl never finds out that the file or device is ready for more output data. It is possible for an arbitrarily large amount of data to be buffered for a channel in nonblocking mode, which could consume a large amount of memory. To avoid wasting memory, nonblocking I/O should normally be used in an event-driven fashion with the fileevent command (don't invoke puts unless you have recently been notified via a file event that the channel is ready for more output data).

SEE ALSO

file, fileevent

KEYWORDS

channel, newline, output, write
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - pwd manual page

NAME

pwd - Return the current working directory

SYNOPSIS

pwd

DESCRIPTION

Returns the path name of the current working directory.

SEE ALSO

file, cd, glob, filename

KEYWORDS

working directory
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - re_syntax manual page

NAME
re_syntax - Syntax of Tcl regular expressions.
DESCRIPTION
DIFFERENT FLAVORS OF REs
REGULAR EXPRESSION SYNTAX
*
+
?
{m}
{m,}
{m,n}
*? +? ?? {m}? {m,}? {m,n}?
(re)
(?:re)
()
(?:)
[chars]
.
\k
\c
{
x
^
$
(?=re)
(?!re)
BRACKET EXPRESSIONS
ESCAPES
\a
\b
\B
\c X
\e
\f
\n
\r
\t
\u wxyz
\U stuvwxyz
\v
\x hhh
\0
\xy
\xyz
\d
\s
\w
\D
\S
\W
\A
\m
\M
\y
\Y
\Z
\m
\mnn
METASYNTAX
b
c
e
i
m
n
p
q
s
t
w
x
MATCHING
LIMITS AND COMPATIBILITY
BASIC REGULAR EXPRESSIONS
SEE ALSO
KEYWORDS

NAME

re_syntax - Syntax of Tcl regular expressions.

DESCRIPTION

A regular expression describes strings of characters. It's a pattern that matches certain strings and doesn't match others.

DIFFERENT FLAVORS OF REs

Regular expressions (``RE''s), as defined by POSIX, come in two flavors: extended REs (``EREs'') and basic REs (``BREs''). EREs are roughly those of the traditional egrep, while BREs are roughly those of the traditional ed. This implementation adds a third flavor, advanced REs (``AREs''), basically EREs with some significant extensions.

This manual page primarily describes AREs. BREs mostly exist for backward compatibility in some old programs; they will be discussed at the end. POSIX EREs are almost an exact subset of AREs. Features of AREs that are not present in EREs will be indicated.

REGULAR EXPRESSION SYNTAX

Tcl regular expressions are implemented using the package written by Henry Spencer, based on the 1003.2 spec and some (not quite all) of the Perl5 extensions (thanks, Henry!). Much of the description of regular expressions below is copied verbatim from his manual entry.

An ARE is one or more branches, separated by `|', matching anything that matches any of the branches.

A branch is zero or more constraints or quantified atoms, concatenated. It matches a match for the first, followed by a match for the second, etc; an empty branch matches the empty string.

A quantified atom is an atom possibly followed by a single quantifier. Without a quantifier, it matches a match for the atom. The quantifiers, and what a so-quantified atom matches, are:

*
a sequence of 0 or more matches of the atom

+
a sequence of 1 or more matches of the atom

?
a sequence of 0 or 1 matches of the atom

{m}
a sequence of exactly m matches of the atom

{m,}
a sequence of m or more matches of the atom

{m,n}
a sequence of m through n (inclusive) matches of the atom; m may not exceed n

*? +? ?? {m}? {m,}? {m,n}?
non-greedy quantifiers, which match the same possibilities, but prefer the smallest number rather than the largest number of matches (see MATCHING)

The forms using { and } are known as bounds. The numbers m and n are unsigned decimal integers with permissible values from 0 to 255 inclusive.

An atom is one of:

(re)
(where re is any regular expression) matches a match for re, with the match noted for possible reporting

(?:re)
as previous, but does no reporting (a ``non-capturing'' set of parentheses)

()
matches an empty string, noted for possible reporting

(?:)
matches an empty string, without reporting

[chars]
a bracket expression, matching any one of the chars (see BRACKET EXPRESSIONS for more detail)

.
matches any single character

\k
(where k is a non-alphanumeric character) matches that character taken as an ordinary character, e.g. \\ matches a backslash character

\c
where c is alphanumeric (possibly followed by other characters), an escape (AREs only), see ESCAPES below

{
when followed by a character other than a digit, matches the left-brace character `{'; when followed by a digit, it is the beginning of a bound (see above)

x
where x is a single character with no other significance, matches that character.

A constraint matches an empty string when specific conditions are met. A constraint may not be followed by a quantifier. The simple constraints are as follows; some more constraints are described later, under ESCAPES.

^
matches at the beginning of a line

$
matches at the end of a line

(?=re)
positive lookahead (AREs only), matches at any point where a substring matching re begins

(?!re)
negative lookahead (AREs only), matches at any point where no substring matching re begins

The lookahead constraints may not contain back references (see later), and all parentheses within them are considered non-capturing.

An RE may not end with `\'.

BRACKET EXPRESSIONS

A bracket expression is a list of characters enclosed in `[ ]'. It normally matches any single character from the list (but see below). If the list begins with `^', it matches any single character (but see below) not from the rest of the list.

If two characters in the list are separated by `-', this is shorthand for the full range of characters between those two (inclusive) in the collating sequence, e.g. [0-9] in ASCII matches any decimal digit. Two ranges may not share an endpoint, so e.g. a-c-e is illegal. Ranges are very collating-sequence-dependent, and portable programs should avoid relying on them.

To include a literal ] or - in the list, the simplest method is to enclose it in [. and .] to make it a collating element (see below). Alternatively, make it the first character (following a possible `^'), or (AREs only) precede it with `\'. Alternatively, for `-', make it the last character, or the second endpoint of a range. To use a literal - as the first endpoint of a range, make it a collating element or (AREs only) precede it with `\'. With the exception of these, some combinations using [ (see next paragraphs), and escapes, all other special characters lose their special significance within a bracket expression.

Within a bracket expression, a collating element (a character, a multi-character sequence that collates as if it were a single character, or a collating-sequence name for either) enclosed in [. and .] stands for the sequence of characters of that collating element. The sequence is a single element of the bracket expression's list. A bracket expression in a locale that has multi-character collating elements can thus match more than one character. So (insidiously), a bracket expression that starts with ^ can match multi-character collating elements even if none of them appear in the bracket expression! (Note: Tcl currently has no multi-character collating elements. This information is only for illustration.)

For example, assume the collating sequence includes a ch multi-character collating element. Then the RE [[.ch.]]*c (zero or more ch's followed by c) matches the first five characters of `chchcc'. Also, the RE [^c]b matches all of `chb' (because [^c] matches the multi-character ch).

Within a bracket expression, a collating element enclosed in [= and =] is an equivalence class, standing for the sequences of characters of all collating elements equivalent to that one, including itself. (If there are no other equivalent collating elements, the treatment is as if the enclosing delimiters were `[.' and `.]'.) For example, if o and ô are the members of an equivalence class, then `[[=o=]]', `[[=ô=]]', and `[oô]' are all synonymous. An equivalence class may not be an endpoint of a range. (Note: Tcl currently implements only the Unicode locale. It doesn't define any equivalence classes. The examples above are just illustrations.)

Within a bracket expression, the name of a character class enclosed in [: and :] stands for the list of all characters (not all collating elements!) belonging to that class. Standard character classes are:

alpha A letter. upper An upper-case letter. lower A lower-case letter. digit A decimal digit. xdigit A hexadecimal digit. alnum An alphanumeric (letter or digit). print An alphanumeric (same as alnum). blank A space or tab character. space A character producing white space in displayed text. punct A punctuation character. graph A character with a visible representation. cntrl A control character.

A locale may provide others. (Note that the current Tcl implementation has only one locale: the Unicode locale.) A character class may not be used as an endpoint of a range.

There are two special cases of bracket expressions: the bracket expressions [[:<:]] and [[:>:]] are constraints, matching empty strings at the beginning and end of a word respectively. A word is defined as a sequence of word characters that is neither preceded nor followed by word characters. A word character is an alnum character or an underscore (_). These special bracket expressions are deprecated; users of AREs should use constraint escapes instead (see below).

ESCAPES

Escapes (AREs only), which begin with a \ followed by an alphanumeric character, come in several varieties: character entry, class shorthands, constraint escapes, and back references. A \ followed by an alphanumeric character but not constituting a valid escape is illegal in AREs. In EREs, there are no escapes: outside a bracket expression, a \ followed by an alphanumeric character merely stands for that character as an ordinary character, and inside a bracket expression, \ is an ordinary character. (The latter is the one actual incompatibility between EREs and AREs.)

Character-entry escapes (AREs only) exist to make it easier to specify non-printing and otherwise inconvenient characters in REs:

\a
alert (bell) character, as in C

\b
backspace, as in C

\B
synonym for \ to help reduce backslash doubling in some applications where there are multiple levels of backslash processing

\c X
(where X is any character) the character whose low-order 5 bits are the same as those of X, and whose other bits are all zero

\e
the character whose collating-sequence name is `ESC', or failing that, the character with octal value 033

\f
formfeed, as in C

\n
newline, as in C

\r
carriage return, as in C

\t
horizontal tab, as in C

\u wxyz
(where wxyz is exactly four hexadecimal digits) the Unicode character U+wxyz in the local byte ordering

\U stuvwxyz
(where stuvwxyz is exactly eight hexadecimal digits) reserved for a somewhat-hypothetical Unicode extension to 32 bits

\v
vertical tab, as in C are all available.

\x hhh
(where hhh is any sequence of hexadecimal digits) the character whose hexadecimal value is 0x hhh (a single character no matter how many hexadecimal digits are used).

\0
the character whose value is 0

\xy
(where xy is exactly two octal digits, and is not a back reference (see below)) the character whose octal value is 0 xy

\xyz
(where xyz is exactly three octal digits, and is not a back reference (see below)) the character whose octal value is 0 xyz

Hexadecimal digits are `0'-`9', `a'-`f', and `A'-`F'. Octal digits are `0'-`7'.

The character-entry escapes are always taken as ordinary characters. For example, \135 is ] in ASCII, but \135 does not terminate a bracket expression. Beware, however, that some applications (e.g., C compilers) interpret such sequences themselves before the regular-expression package gets to see them, which may require doubling (quadrupling, etc.) the `\'.

Class-shorthand escapes (AREs only) provide shorthands for certain commonly-used character classes:

\d
[[:digit:]]

\s
[[:space:]]

\w
[[:alnum:]_] (note underscore)

\D
[^[:digit:]]

\S
[^[:space:]]

\W
[^[:alnum:]_] (note underscore)

Within bracket expressions, `\d', `\s', and `\w' lose their outer brackets, and `\D', `\S', and `\W' are illegal. (So, for example, [a-c\d] is equivalent to [a-c[:digit:]]. Also, [a-c\D], which is equivalent to [a-c^[:digit:]], is illegal.)

A constraint escape (AREs only) is a constraint, matching the empty string if specific conditions are met, written as an escape:

\A
matches only at the beginning of the string (see MATCHING, below, for how this differs from `^')

\m
matches only at the beginning of a word

\M
matches only at the end of a word

\y
matches only at the beginning or end of a word

\Y
matches only at a point that is not the beginning or end of a word

\Z
matches only at the end of the string (see MATCHING, below, for how this differs from `$')

\m
(where m is a nonzero digit) a back reference, see below

\mnn
(where m is a nonzero digit, and nn is some more digits, and the decimal value mnn is not greater than the number of closing capturing parentheses seen so far) a back reference, see below

A word is defined as in the specification of [[:<:]] and [[:>:]] above. Constraint escapes are illegal within bracket expressions.

A back reference (AREs only) matches the same string matched by the parenthesized subexpression specified by the number, so that (e.g.) ([bc])\1 matches bb or cc but not `bc'. The subexpression must entirely precede the back reference in the RE. Subexpressions are numbered in the order of their leading parentheses. Non-capturing parentheses do not define subexpressions.

There is an inherent historical ambiguity between octal character-entry escapes and back references, which is resolved by heuristics, as hinted at above. A leading zero always indicates an octal escape. A single non-zero digit, not followed by another digit, is always taken as a back reference. A multi-digit sequence not starting with a zero is taken as a back reference if it comes after a suitable subexpression (i.e. the number is in the legal range for a back reference), and otherwise is taken as octal.

METASYNTAX

In addition to the main syntax described above, there are some special forms and miscellaneous syntactic facilities available.

Normally the flavor of RE being used is specified by application-dependent means. However, this can be overridden by a director. If an RE of any flavor begins with `***:', the rest of the RE is an ARE. If an RE of any flavor begins with `***=', the rest of the RE is taken to be a literal string, with all characters considered ordinary characters.

An ARE may begin with embedded options: a sequence (?xyz) (where xyz is one or more alphabetic characters) specifies options affecting the rest of the RE. These supplement, and can override, any options specified by the application. The available option letters are:

b
rest of RE is a BRE

c
case-sensitive matching (usual default)

e
rest of RE is an ERE

i
case-insensitive matching (see MATCHING, below)

m
historical synonym for n

n
newline-sensitive matching (see MATCHING, below)

p
partial newline-sensitive matching (see MATCHING, below)

q
rest of RE is a literal (``quoted'') string, all ordinary characters

s
non-newline-sensitive matching (usual default)

t
tight syntax (usual default; see below)

w
inverse partial newline-sensitive (``weird'') matching (see MATCHING, below)

x
expanded syntax (see below)

Embedded options take effect at the ) terminating the sequence. They are available only at the start of an ARE, and may not be used later within it.

In addition to the usual (tight) RE syntax, in which all characters are significant, there is an expanded syntax, available in all flavors of RE with the -expanded switch, or in AREs with the embedded x option. In the expanded syntax, white-space characters are ignored and all characters between a # and the following newline (or the end of the RE) are ignored, permitting paragraphing and commenting a complex RE. There are three exceptions to that basic rule:

a white-space character or `#' preceded by `\' is retained

white space or `#' within a bracket expression is retained

white space and comments are illegal within multi-character symbols like the ARE `(?:' or the BRE `\('

Expanded-syntax white-space characters are blank, tab, newline, and any character that belongs to the space character class.

Finally, in an ARE, outside bracket expressions, the sequence `(?#ttt)' (where ttt is any text not containing a `)') is a comment, completely ignored. Again, this is not allowed between the characters of multi-character symbols like `(?:'. Such comments are more a historical artifact than a useful facility, and their use is deprecated; use the expanded syntax instead.

None of these metasyntax extensions is available if the application (or an initial ***= director) has specified that the user's input be treated as a literal string rather than as an RE.

MATCHING

In the event that an RE could match more than one substring of a given string, the RE matches the one starting earliest in the string. If the RE could match more than one substring starting at that point, its choice is determined by its preference: either the longest substring, or the shortest.

Most atoms, and all constraints, have no preference. A parenthesized RE has the same preference (possibly none) as the RE. A quantified atom with quantifier {m} or {m}? has the same preference (possibly none) as the atom itself. A quantified atom with other normal quantifiers (including {m,n} with m equal to n) prefers longest match. A quantified atom with other non-greedy quantifiers (including {m,n}? with m equal to n) prefers shortest match. A branch has the same preference as the first quantified atom in it which has a preference. An RE consisting of two or more branches connected by the | operator prefers longest match.

Subject to the constraints imposed by the rules for matching the whole RE, subexpressions also match the longest or shortest possible substrings, based on their preferences, with subexpressions starting earlier in the RE taking priority over ones starting later. Note that outer subexpressions thus take priority over their component subexpressions.

Note that the quantifiers {1,1} and {1,1}? can be used to force longest and shortest preference, respectively, on a subexpression or a whole RE.

Match lengths are measured in characters, not collating elements. An empty string is considered longer than no match at all. For example, bb* matches the three middle characters of `abbbc', (week|wee)(night|knights) matches all ten characters of `weeknights', when (.*).* is matched against abc the parenthesized subexpression matches all three characters, and when (a*)* is matched against bc both the whole RE and the parenthesized subexpression match an empty string.

If case-independent matching is specified, the effect is much as if all case distinctions had vanished from the alphabet. When an alphabetic that exists in multiple cases appears as an ordinary character outside a bracket expression, it is effectively transformed into a bracket expression containing both cases, so that x becomes `[xX]'. When it appears inside a bracket expression, all case counterparts of it are added to the bracket expression, so that [x] becomes [xX] and [^x] becomes `[^xX]'.

If newline-sensitive matching is specified, . and bracket expressions using ^ will never match the newline character (so that matches will never cross newlines unless the RE explicitly arranges it) and ^ and $ will match the empty string after and before a newline respectively, in addition to matching at beginning and end of string respectively. ARE \A and \Z continue to match beginning or end of string only.

If partial newline-sensitive matching is specified, this affects . and bracket expressions as with newline-sensitive matching, but not ^ and `$'.

If inverse partial newline-sensitive matching is specified, this affects ^ and $ as with newline-sensitive matching, but not . and bracket expressions. This isn't very useful but is provided for symmetry.

LIMITS AND COMPATIBILITY

No particular limit is imposed on the length of REs. Programs intended to be highly portable should not employ REs longer than 256 bytes, as a POSIX-compliant implementation can refuse to accept such REs.

The only feature of AREs that is actually incompatible with POSIX EREs is that \ does not lose its special significance inside bracket expressions. All other ARE features use syntax which is illegal or has undefined or unspecified effects in POSIX EREs; the *** syntax of directors likewise is outside the POSIX syntax for both BREs and EREs.

Many of the ARE extensions are borrowed from Perl, but some have been changed to clean them up, and a few Perl extensions are not present. Incompatibilities of note include `\b', `\B', the lack of special treatment for a trailing newline, the addition of complemented bracket expressions to the things affected by newline-sensitive matching, the restrictions on parentheses and back references in lookahead constraints, and the longest/shortest-match (rather than first-match) matching semantics.

The matching rules for REs containing both normal and non-greedy quantifiers have changed since early beta-test versions of this package. (The new rules are much simpler and cleaner, but don't work as hard at guessing the user's real intentions.)

Henry Spencer's original 1986 regexp package, still in widespread use (e.g., in pre-8.1 releases of Tcl), implemented an early version of today's EREs. There are four incompatibilities between regexp's near-EREs (`RREs' for short) and AREs. In roughly increasing order of significance:

In AREs, \ followed by an alphanumeric character is either an escape or an error, while in RREs, it was just another way of writing the alphanumeric. This should not be a problem because there was no reason to write such a sequence in RREs.

{ followed by a digit in an ARE is the beginning of a bound, while in RREs, { was always an ordinary character. Such sequences should be rare, and will often result in an error because following characters will not look like a valid bound.

In AREs, \ remains a special character within `[ ]', so a literal \ within [ ] must be written `\\'. \\ also gives a literal \ within [ ] in RREs, but only truly paranoid programmers routinely doubled the backslash.

AREs report the longest/shortest match for the RE, rather than the first found in a specified search order. This may affect some RREs which were written in the expectation that the first match would be reported. (The careful crafting of RREs to optimize the search order for fast matching is obsolete (AREs examine all possible matches in parallel, and their performance is largely insensitive to their complexity) but cases where the search order was exploited to deliberately find a match which was not the longest/shortest will need rewriting.)

BASIC REGULAR EXPRESSIONS

BREs differ from EREs in several respects. `|', `+', and ? are ordinary characters and there is no equivalent for their functionality. The delimiters for bounds are \{ and `\}', with { and } by themselves ordinary characters. The parentheses for nested subexpressions are \( and `\)', with ( and ) by themselves ordinary characters. ^ is an ordinary character except at the beginning of the RE or the beginning of a parenthesized subexpression, $ is an ordinary character except at the end of the RE or the end of a parenthesized subexpression, and * is an ordinary character if it appears at the beginning of the RE or the beginning of a parenthesized subexpression (after a possible leading `^'). Finally, single-digit back references are available, and \< and \> are synonyms for [[:<:]] and [[:>:]] respectively; no other escapes are available.

SEE ALSO

RegExp, regexp, regsub, lsearch, switch, text

KEYWORDS

match, regular expression, string
Copyright © 1998 Sun Microsystems, Inc.
Copyright © 1999 Scriptics Corporation
Copyright © 1995-1997 Roger E. Critchlow Jr.


Tcl Built-In Commands - read manual page

NAME

read - Read from a channel

SYNOPSIS

read ?-nonewline? channelId
read channelId numChars

DESCRIPTION

In the first form, the read command reads all of the data from channelId up to the end of the file. If the -nonewline switch is specified then the last character of the file is discarded if it is a newline. In the second form, the extra argument specifies how many characters to read. Exactly that many characters will be read and returned, unless there are fewer than numChars left in the file; in this case all the remaining characters are returned. If the channel is configured to use a multi-byte encoding, then the number of characters read may not be the same as the number of bytes read.

If channelId is in nonblocking mode, the command may not read as many characters as requested: once all available input has been read, the command will return the data that is available rather than blocking for more input. If the channel is configured to use a multi-byte encoding, then there may actually be some bytes remaining in the internal buffers that do not form a complete character. These bytes will not be returned until a complete character is available or end-of-file is reached. The -nonewline switch is ignored if the command returns before reaching the end of the file.

Read translates end-of-line sequences in the input into newline characters according to the -translation option for the channel. See the fconfigure manual entry for a discussion on ways in which fconfigure will alter input.

SEE ALSO

file, eof, fblocked, fconfigure

KEYWORDS

blocking, channel, end of line, end of file, nonblocking, read, translation, encoding
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - regexp manual page

NAME
regexp - Match a regular expression against a string
SYNOPSIS
regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?
DESCRIPTION
-about
-expanded
-indices
-line
-linestop
-lineanchor
-nocase
-all
-inline
-start index
- -
SEE ALSO
KEYWORDS

NAME

regexp - Match a regular expression against a string

SYNOPSIS

regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?

DESCRIPTION

Determines whether the regular expression exp matches part or all of string and returns 1 if it does, 0 if it doesn't, unless -inline is specified (see below). (Regular expression matching is described in the re_syntax reference page.)

If additional arguments are specified after string then they are treated as the names of variables in which to return information about which part(s) of string matched exp. MatchVar will be set to the range of string that matched all of exp. The first subMatchVar will contain the characters in string that matched the leftmost parenthesized subexpression within exp, the next subMatchVar will contain the characters that matched the next parenthesized subexpression to the right in exp, and so on.

If the initial arguments to regexp start with - then they are treated as switches. The following switches are currently supported:

-about
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 list of property names that describe various attributes of the regular expression. This switch is primarily intended for debugging purposes.

-expanded
Enables use of the expanded regular expression syntax where whitespace and comments are ignored. This is the same as specifying the (?x) embedded option (see METASYNTAX, below).

-indices
Changes what is stored in the subMatchVars. Instead of storing the matching characters from string, each variable will contain a list of two decimal strings giving the indices in string of the first and last characters in the matching range of characters.

-line
Enables newline-sensitive matching. By default, newline is a completely ordinary character with no special meaning. With this flag, `[^' bracket expressions and `.' never match newline, `^' matches an empty string after any newline in addition to its normal function, and `$' matches an empty string before any newline in addition to its normal function. This flag is equivalent to specifying both -linestop and -lineanchor, or the (?n) embedded option (see METASYNTAX, below).

-linestop
Changes the behavior of `[^' bracket expressions and `.' so that they stop at newlines. This is the same as specifying the (?p) embedded option (see METASYNTAX, below).

-lineanchor
Changes the behavior of `^' and `$' (the ``anchors'') so they match the beginning and end of a line respectively. This is the same as specifying the (?w) embedded option (see METASYNTAX, below).

-nocase
Causes upper-case characters in string to be treated as lower case during the matching process.

-all
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 continue information for the last match only.

-inline
Causes the command to return, as a list, the data that would otherwise be placed in match variables. When using -inline, match variables may not be specified. If used with -all, the 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:
regexp -inline -- {\w(\w)} " inlined "
 => {in n}
    regexp -all -inline -- {\w(\w)} " inlined "
 => {in n li i ne e}

-start index
Specifies a character index offset into the string to start matching the regular expression at. When using this switch, `^' will not match the beginning of the line, and \A will still match the start of the string at index. If -indices is specified, the indices will be indexed starting from the absolute beginning of the input string. index will be constrained to the bounds of the input string.

- -
Marks the end of switches. The argument following this one will be treated as exp even if it starts with a -.

If there are more subMatchVar's than parenthesized subexpressions within exp, or if a particular subexpression in exp doesn't match the string (e.g. because it was in a portion of the expression that wasn't matched), then the corresponding subMatchVar will be set to ``-1 -1'' if -indices has been specified or to an empty string otherwise.

SEE ALSO

re_syntax, regsub

KEYWORDS

match, regular expression, string
Copyright © 1998 Sun Microsystems, Inc.


Tcl Built-In Commands - registry manual page

NAME
registry - Manipulate the Windows registry
SYNOPSIS
package require registry 1.0
registry option keyName ?arg arg ...?
DESCRIPTION
registry delete keyName ?valueName?
registry get keyName valueName
registry keys keyName ?pattern?
registry set keyName ?valueName data ?type??
registry type keyName valueName
registry values keyName ?pattern?
SUPPORTED TYPES
binary
none
sz
expand_sz
dword
dword_big_endian
link
multi_sz
resource_list
PORTABILITY ISSUES
KEYWORDS

NAME

registry - Manipulate the Windows registry

SYNOPSIS

package require registry 1.0
registry option keyName ?arg arg ...?

DESCRIPTION

The registry package provides a general set of operations for manipulating the Windows registry. The package implements the registry Tcl command. This command is only supported on the Windows platform. Warning: this command should be used with caution as a corrupted registry can leave your system in an unusable state.

KeyName is the name of a registry key. Registry keys must be one of the following forms:

\\hostname\rootname\keypath

rootname\keypath

rootname

Hostname specifies the name of any valid Windows host that exports its registry. The rootname component must be one of HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_CURRENT_CONFIG, HKEY_PERFORMANCE_DATA, or HKEY_DYN_DATA. The keypath can be one or more registry key names separated by backslash (\) characters.

Option indicates what to do with the registry key name. Any unique abbreviation for option is acceptable. The valid options are:

registry delete keyName ?valueName?
If the optional valueName argument is present, the specified value under keyName will be deleted from the registry. If the optional valueName is omitted, the specified key and any subkeys or values beneath it in the registry heirarchy will be deleted. If the key could not be deleted then an error is generated. If the key did not exist, the command has no effect.

registry get keyName valueName
Returns the data associated with the value valueName under the key keyName. If either the key or the value does not exist, then an error is generated. For more details on the format of the returned data, see SUPPORTED TYPES, below.

registry keys keyName ?pattern?
If pattern isn't specified, returns a list of names of all the subkeys of keyName. If pattern is specified, only those names matching pattern are returned. Matching is determined using the same rules as for string match. If the specified keyName does not exist, then an error is generated.

registry set keyName ?valueName data ?type??
If valueName isn't specified, creates the key keyName if it doesn't already exist. If valueName is specified, creates the key keyName and value valueName if necessary. The contents of valueName are set to data with the type indicated by type. If type isn't specified, the type sz is assumed. For more details on the data and type arguments, see SUPPORTED TYPES below.

registry type keyName valueName
Returns the type of the value valueName in the key keyName. For more information on the possible types, see SUPPORTED TYPES, below.

registry values keyName ?pattern?
If pattern isn't specified, returns a list of names of all the values of keyName. If pattern is specified, only those names matching pattern are returned. Matching is determined using the same rules as for string match.

SUPPORTED TYPES

Each value under a key in the registry contains some data of a particular type in a type-specific representation. The registry command converts between this internal representation and one that can be manipulated by Tcl scripts. In most cases, the data is simply returned as a Tcl string. The type indicates the intended use for the data, but does not actually change the representation. For some types, the registry command returns the data in a different form to make it easier to manipulate. The following types are recognized by the registry command:

binary
The registry value contains arbitrary binary data. The data is represented exactly in Tcl, including any embedded nulls.

none
The registry value contains arbitrary binary data with no defined type. The data is represented exactly in Tcl, including any embedded nulls.

sz
The registry value contains a null-terminated string. The data is represented in Tcl as a string.

expand_sz
The registry value contains a null-terminated string that contains unexpanded references to environment variables in the normal Windows style (for example, "%PATH%"). The data is represented in Tcl as a string.

dword
The registry value contains a little-endian 32-bit number. The data is represented in Tcl as a decimal string.

dword_big_endian
The registry value contains a big-endian 32-bit number. The data is represented in Tcl as a decimal string.

link
The registry value contains a symbolic link. The data is represented exactly in Tcl, including any embedded nulls.

multi_sz
The registry value contains an array of null-terminated strings. The data is represented in Tcl as a list of strings.

resource_list
The registry value contains a device-driver resource list. The data is represented exactly in Tcl, including any embedded nulls.

In addition to the symbolically named types listed above, unknown types are identified using a 32-bit integer that corresponds to the type code returned by the system interfaces. In this case, the data is represented exactly in Tcl, including any embedded nulls.

PORTABILITY ISSUES

The registry command is only available on Windows.

KEYWORDS

registry
Copyright © 1997 Sun Microsystems, Inc.


Tcl Built-In Commands - regsub manual page

NAME
regsub - Perform substitutions based on regular expression pattern matching
SYNOPSIS
regsub ?switches? exp string subSpec varName
DESCRIPTION
-all
-expanded
-line
-linestop
-lineanchor
-nocase
-start index
- -
SEE ALSO
KEYWORDS

NAME

regsub - Perform substitutions based on regular expression pattern matching

SYNOPSIS

regsub ?switches? exp string subSpec varName

DESCRIPTION

This command matches the regular expression exp against string, and it copies string to the variable whose name is given by varName. (Regular expression matching is described in the re_syntax reference page.) If there is a match, then while copying string to varName the portion of string that matched exp is replaced with subSpec. If subSpec contains a ``&'' or ``\0'', then it is replaced in the substitution with the portion of string that matched exp. If subSpec contains a ``\n'', where n is a digit between 1 and 9, then it is replaced in the substitution with the portion of string that matched the n-th parenthesized subexpression of exp. Additional backslashes may be used in subSpec to prevent special interpretation of ``&'' or ``\0'' or ``\n'' or backslash. The use of backslashes in subSpec tends to interact badly with the Tcl parser's use of backslashes, so it's generally safest to enclose subSpec in braces if it includes backslashes.

If the initial arguments to regexp start with - then they are treated as switches. The following switches are currently supported:

-all
All ranges in string that match exp are found and substitution is performed for each of these ranges. Without this switch only the first matching range is found and substituted. If -all is specified, then ``&'' and ``\n'' sequences are handled for each substitution using the information from the corresponding match.

-expanded
Enables use of the expanded regular expression syntax where whitespace and comments are ignored. This is the same as specifying the (?x) embedded option (see METASYNTAX, below).

-line
Enables newline-sensitive matching. By default, newline is a completely ordinary character with no special meaning. With this flag, `[^' bracket expressions and `.' never match newline, `^' matches an empty string after any newline in addition to its normal function, and `$' matches an empty string before any newline in addition to its normal function. This flag is equivalent to specifying both -linestop and -lineanchor, or the (?n) embedded option (see METASYNTAX, below).

-linestop
Changes the behavior of `[^' bracket expressions and `.' so that they stop at newlines. This is the same as specifying the (?p) embedded option (see METASYNTAX, below).

-lineanchor
Changes the behavior of `^' and `$' (the ``anchors'') so they match the beginning and end of a line respectively. This is the same as specifying the (?w) embedded option (see METASYNTAX, below).

-nocase
Upper-case characters in string will be converted to lower-case before matching against exp; however, substitutions specified by subSpec use the original unconverted form of string.

-start index
Specifies a character index offset into the string to start matching the regular expression at. When using this switch, `^' will not match the beginning of the line, and \A will still match the start of the string at index. index will be constrained to the bounds of the input string.

- -
Marks the end of switches. The argument following this one will be treated as exp even if it starts with a -.

The command returns a count of the number of matching ranges that were found and replaced. See the manual entry for regexp for details on the interpretation of regular expressions.

SEE ALSO

regexp, re_syntax

KEYWORDS

match, pattern, regular expression, substitute
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
Copyright © 2000 Scriptics Corporation.


Built-In Commands - rename manual page

NAME

rename - Rename or delete a command

SYNOPSIS

rename oldName newName

DESCRIPTION

Rename the command that used to be called oldName so that it is now called newName. If newName is an empty string then oldName is deleted. oldName and newName may include namespace qualifiers (names of containing namespaces). If a command is renamed into a different namespace, future invocations of it will execute in the new namespace. The rename command returns an empty string as result.

SEE ALSO

namespace, proc

KEYWORDS

command, delete, namespace, rename
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Built-In Commands - resource manual page

NAME
resource - Manipulate Macintosh resources
SYNOPSIS
resource option ?arg arg ...?
DESCRIPTION
resource close rsrcRef
resource delete ?options? resourceType
-id resourceId
-name resourceName
-file resourceRef
resource files ?resourceRef?
resource list resourceType ?resourceRef?
resource open fileName ?access?
resource read resourceType resourceId ?resourceRef?
resource types ?resourceRef?
resource write ?options? resourceType data
-id resourceId
-name resourceName
-file resourceRef
-force
RESOURCE TYPES
RESOURCE IDS
PORTABILITY ISSUES
SEE ALSO
KEYWORDS

NAME

resource - Manipulate Macintosh resources

SYNOPSIS

resource option ?arg arg ...?

DESCRIPTION

The resource command provides some generic operations for dealing with Macintosh resources. This command is only supported on the Macintosh platform. Each Macintosh file consists of two forks: a data fork and a resource fork. You use the normal open, puts, close, etc. commands to manipulate the data fork. You must use this command, however, to interact with the resource fork. Option indicates what resource command to perform. Any unique abbreviation for option is acceptable. The valid options are:

resource close rsrcRef
Closes the given resource reference (obtained from resource open). Resources from that resource file will no longer be available.

resource delete ?options? resourceType
This command will delete the resource specified by options and type resourceType (see RESOURCE TYPES below). The options give you several ways to specify the resource to be deleted.

-id resourceId
If the -id option is given the id resourceId (see RESOURCE IDS below) is used to specify the resource to be deleted. The id must be a number - to specify a name use the -name option.

-name resourceName
If -name is specified, the resource named resourceName will be deleted. If the -id is also provided, then there must be a resource with BOTH this name and this id. If no name is provided, then the id will be used regardless of the name of the actual resource.

-file resourceRef
If the -file option is specified then the resource will be deleted from the file pointed to by resourceRef. Otherwise the first resource with the given resourceName and or resourceId which is found on the resource file path will be deleted. To inspect the file path, use the resource files command.

resource files ?resourceRef?
If resourceRefis not provided, this command returns a Tcl list of the resource references for all the currently open resource files. The list is in the normal Macintosh search order for resources. If resourceRef is specified, the command will return the path to the file whose resource fork is represented by that token.

resource list resourceType ?resourceRef?
List all of the resources ids of type resourceType (see RESOURCE TYPES below). If resourceRef is specified then the command will limit the search to that particular resource file. Otherwise, all resource files currently opened by the application will be searched. A Tcl list of either the resource name's or resource id's of the found resources will be returned. See the RESOURCE IDS section below for more details about what a resource id is.

resource open fileName ?access?
Open the resource for the file fileName. Standard file access permissions may also be specified (see the manual entry for open for details). A resource reference (resourceRef) is returned that can be used by the other resource commands. An error can occur if the file doesn't exist or the file does not have a resource fork. However, if you open the file with write permissions the file and/or resource fork will be created instead of generating an error.

resource read resourceType resourceId ?resourceRef?
Read the entire resource of type resourceType (see RESOURCE TYPES below) and the name or id of resourceId (see RESOURCE IDS below) into memory and return the result. If resourceRef is specified we limit our search to that resource file, otherwise we search all open resource forks in the application. It is important to note that most Macintosh resource use a binary format and the data returned from this command may have embedded NULLs or other non-ASCII data.

resource types ?resourceRef?
This command returns a Tcl list of all resource types (see RESOURCE TYPES below) found in the resource file pointed to by resourceRef. If resourceRef is not specified it will return all the resource types found in every resource file currently opened by the application.

resource write ?options? resourceType data
This command will write the passed in data as a new resource of type resourceType (see RESOURCE TYPES below). Several options are available that describe where and how the resource is stored.

-id resourceId
If the -id option is given the id resourceId (see RESOURCE IDS below) is used for the new resource, otherwise a unique id will be generated that will not conflict with any existing resource. However, the id must be a number - to specify a name use the -name option.

-name resourceName
If -name is specified the resource will be named resourceName, otherwise it will have the empty string as the name.

-file resourceRef
If the -file option is specified then the resource will be written in the file pointed to by resourceRef, otherwise the most resently open resource will be used.

-force
If the target resource already exists, then by default Tcl will not overwrite it, but raise an error instead. Use the -force flag to force overwriting the extant resource.

RESOURCE TYPES

Resource types are defined as a four character string that is then mapped to an underlying id. For example, TEXT refers to the Macintosh resource type for text. The type STR# is a list of counted strings. All Macintosh resources must be of some type. See Macintosh documentation for a more complete list of resource types that are commonly used.

RESOURCE IDS

For this command the notion of a resource id actually refers to two ideas in Macintosh resources. Every place you can use a resource Id you can use either the resource name or a resource number. Names are always searched or returned in preference to numbers. For example, the resource list command will return names if they exist or numbers if the name is NULL.

PORTABILITY ISSUES

The resource command is only available on Macintosh.

SEE ALSO

open

KEYWORDS

open, resource
Copyright © 1997 Sun Microsystems, Inc.


Tcl Built-In Commands - return manual page

NAME
return - Return from a procedure
SYNOPSIS
return ?-code code? ?-errorinfo info? ?-errorcode code? ?string?
DESCRIPTION
EXCEPTIONAL RETURNS
ok
error
return
break
continue
value
SEE ALSO
KEYWORDS

NAME

return - Return from a procedure

SYNOPSIS

return ?-code code? ?-errorinfo info? ?-errorcode code? ?string?

DESCRIPTION

Return immediately from the current procedure (or top-level command or source command), with string as the return value. If string is not specified then an empty string will be returned as result.

EXCEPTIONAL RETURNS

In the usual case where the -code option isn't specified the procedure will return normally (its completion code will be TCL_OK). However, the -code option may be used to generate an exceptional return from the procedure. Code may have any of the following values:

ok
Normal return: same as if the option is omitted.

error
Error return: same as if the error command were used to terminate the procedure, except for handling of errorInfo and errorCode variables (see below).

return
The current procedure will return with a completion code of TCL_RETURN, so that the procedure that invoked it will return also.

break
The current procedure will return with a completion code of TCL_BREAK, which will terminate the innermost nested loop in the code that invoked the current procedure.

continue
The current procedure will return with a completion code of TCL_CONTINUE, which will terminate the current iteration of the innermost nested loop in the code that invoked the current procedure.

value
Value must be an integer; it will be returned as the completion code for the current procedure.

The -code option is rarely used. It is provided so that procedures that implement new control structures can reflect exceptional conditions back to their callers.

Two additional options, -errorinfo and -errorcode, may be used to provide additional information during error returns. These options are ignored unless code is error.

The -errorinfo option specifies an initial stack trace for the errorInfo variable; if it is not specified then the stack trace left in errorInfo will include the call to the procedure and higher levels on the stack but it will not include any information about the context of the error within the procedure. Typically the info value is supplied from the value left in errorInfo after a catch command trapped an error within the procedure.

If the -errorcode option is specified then code provides a value for the errorCode variable. If the option is not specified then errorCode will default to NONE.

SEE ALSO

break, continue, error, proc

KEYWORDS

break, continue, error, procedure, return
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Tcl Built-In Commands - Safe manual page

NAME
Safe Base - A mechanism for creating and manipulating safe interpreters.
SYNOPSIS
::safe::interpCreate ?slave? ?options...?
::safe::interpInit slave ?options...?
::safe::interpConfigure slave ?options...?
::safe::interpDelete slave
::safe::interpAddToAccessPath slave directory
::safe::interpFindInAccessPath slave directory
::safe::setLogCmd ?cmd arg...?
OPTIONS
DESCRIPTION
COMMANDS
::safe::interpCreate ?slave? ?options...?
::safe::interpInit slave ?options...?
::safe::interpConfigure slave ?options...?
::safe::interpDelete slave
::safe::interpFindInAccessPath slave directory
::safe::interpAddToAccessPath slave directory
::safe::setLogCmd ?cmd arg...?
OPTIONS
-accessPath directoryList
-statics boolean
-noStatics
-nested boolean
-nestedLoadOk
-deleteHook script
ALIASES
source fileName
load fileName
file ?subCmd args...?
encoding ?subCmd args...?
exit
SECURITY
SEE ALSO
KEYWORDS

NAME

Safe Base - A mechanism for creating and manipulating safe interpreters.

SYNOPSIS

::safe::interpCreate ?slave? ?options...?
::safe::interpInit slave ?options...?
::safe::interpConfigure slave ?options...?
::safe::interpDelete slave
::safe::interpAddToAccessPath slave directory
::safe::interpFindInAccessPath slave directory
::safe::setLogCmd ?cmd arg...?

OPTIONS

?-accessPath pathList? ?-statics boolean? ?-noStatics? ?-nested boolean? ?-nestedLoadOk? ?-deleteHook script?

DESCRIPTION

Safe Tcl is a mechanism for executing untrusted Tcl scripts safely and for providing mediated access by such scripts to potentially dangerous functionality.

The Safe Base ensures that untrusted Tcl scripts cannot harm the hosting application. The Safe Base 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.

The Safe Base allows a master interpreter to create safe, restricted interpreters that contain a set of predefined aliases for the source, load, file, encoding, and exit commands and are able to use the auto-loading and package mechanisms.

No knowledge of the file system structure is leaked to the safe interpreter, because it has access only to a virtualized path containing tokens. When the safe interpreter requests to source a file, it uses the token in the virtual path as part of the file name to source; the master interpreter transparently translates the token into a real directory name and executes the requested operation (see the section SECURITY below for details). Different levels of security can be selected by using the optional flags of the commands described below.

All commands provided in the master interpreter by the Safe Base reside in the safe namespace:

COMMANDS

The following commands are provided in the master interpreter:

::safe::interpCreate ?slave? ?options...?
Creates a safe interpreter, installs the aliases described in the section ALIASES and initializes the auto-loading and package mechanism as specified by the supplied options. See the OPTIONS section below for a description of the optional arguments. If the slave argument is omitted, a name will be generated. ::safe::interpCreate always returns the interpreter name.

::safe::interpInit slave ?options...?
This command is similar to interpCreate except it that does not create the safe interpreter. slave must have been created by some other means, like interp create -safe.

::safe::interpConfigure slave ?options...?
If no options are given, returns the settings for all options for the named safe interpreter as a list of options and their current values for that slave. If a single additional argument is provided, it will return a list of 2 elements name and value where name is the full name of that option and value the current value for that option and the slave. If more than two additional arguments are provided, it will reconfigure the safe interpreter and change each and only the provided options. See the section on OPTIONS below for options description. Example of use:
# Create a new interp with the same configuration as "$i0" :
set i1 [eval safe::interpCreate [safe::interpConfigure $i0]]
# Get the current deleteHook
set dh [safe::interpConfigure $i0  -del]
# Change (only) the statics loading ok attribute of an interp
# and its deleteHook (leaving the rest unchanged) :
safe::interpConfigure $i0  -delete {foo bar} -statics 0 ;

::safe::interpDelete slave
Deletes the safe interpreter and cleans up the corresponding master interpreter data structures. If a deleteHook script was specified for this interpreter it is evaluated before the interpreter is deleted, with the name of the interpreter as an additional argument.

::safe::interpFindInAccessPath slave directory
This command finds and returns the token for the real directory directory in the safe interpreter's current virtual access path. It generates an error if the directory is not found. Example of use:
$slave eval [list set tk_library [::safe::interpFindInAccessPath $name $tk_library]]

::safe::interpAddToAccessPath slave directory
This command adds directory to the virtual path maintained for the safe interpreter in the master, and returns the token that can be used in the safe interpreter to obtain access to files in that directory. If the directory is already in the virtual path, it only returns the token without adding the directory to the virtual path again. Example of use:
$slave eval [list set tk_library [::safe::interpAddToAccessPath $name $tk_library]]

::safe::setLogCmd ?cmd arg...?
This command installs a script that will be called when interesting life cycle events occur for a safe interpreter. When called with no arguments, it returns the currently installed script. When called with one argument, an empty string, the currently installed script is removed and logging is turned off. The script will be invoked with one additional argument, a string describing the event of interest. The main purpose is to help in debugging safe interpreters. Using this facility you can get complete error messages while the safe interpreter gets only generic error messages. This prevents a safe interpreter from seeing messages about failures and other events that might contain sensitive information such as real directory names.

Example of use:
::safe::setLogCmd puts stderr
Below is the output of a sample session in which a safe interpreter attempted to source a file not found in its virtual access path. Note that the safe interpreter only received an error message saying that the file was not found:
NOTICE for slave interp10 : Created
NOTICE for slave interp10 : Setting accessPath=(/foo/bar) staticsok=1 nestedok=0 deletehook=()
NOTICE for slave interp10 : auto_path in interp10 has been set to {$p(:0:)}
ERROR for slave interp10 : /foo/bar/init.tcl: no such file or directory

OPTIONS

The following options are common to ::safe::interpCreate, ::safe::interpInit, and ::safe::interpConfigure. Any option name can be abbreviated to its minimal non-ambiguous name. Option names are not case sensitive.

-accessPath directoryList
This option sets the list of directories from which the safe interpreter can source and load files. If this option is not specified, or if it is given as the empty list, the safe interpreter will use the same directories as its master for auto-loading. See the section SECURITY below for more detail about virtual paths, tokens and access control.

-statics boolean
This option specifies if the safe interpreter will be allowed to load statically linked packages (like load {} Tk). The default value is true : safe interpreters are allowed to load statically linked packages.

-noStatics
This option is a convenience shortcut for -statics false and thus specifies that the safe interpreter will not be allowed to load statically linked packages.

-nested boolean
This option specifies if the safe interpreter will be allowed to load packages into its own sub-interpreters. The default value is false : safe interpreters are not allowed to load packages into their own sub-interpreters.

-nestedLoadOk
This option is a convenience shortcut for -nested true and thus specifies the safe interpreter will be allowed to load packages into its own sub-interpreters.

-deleteHook script
When this option is given an non empty script, it will be evaluated in the master with the name of the safe interpreter as an additional argument just before actually deleting the safe interpreter. Giving an empty value removes any currently installed deletion hook script for that safe interpreter. The default value ({}) is not to have any deletion call back.

ALIASES

The following aliases are provided in a safe interpreter:

source fileName
The requested file, a Tcl source file, is sourced into the safe interpreter if it is found. The source alias can only source files from directories in the virtual path for the safe interpreter. The source alias requires the safe interpreter to use one of the token names in its virtual path to denote the directory in which the file to be sourced can be found. See the section on SECURITY for more discussion of restrictions on valid filenames.

load fileName
The requested file, a shared object file, is dynamically loaded into the safe interpreter if it is found. The filename must contain a token name mentioned in the virtual path for the safe interpreter for it to be found successfully. Additionally, the shared object file must contain a safe entry point; see the manual page for the load command for more details.

file ?subCmd args...?
The file alias provides access to a safe subset of the subcommands of the file command; it allows only dirname, join, extension, root, tail, pathname and split subcommands. For more details on what these subcommands do see the manual page for the file command.

encoding ?subCmd args...?
The enconding alias provides access to a safe subset of the subcommands of the encoding command; it disallows setting of the system encoding, but allows all other subcommands including system to check the current encoding.

exit
The calling interpreter is deleted and its computation is stopped, but the Tcl process in which this interpreter exists is not terminated.

SECURITY

The Safe Base 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 is to prevent.

The commands available in a safe interpreter, in addition to the safe set as defined in interp manual page, are mediated aliases for source, load, exit, and safe subsets of file and encoding. The safe interpreter can also auto-load code and it can request that packages be loaded.

Because some of these commands access the local file system, there is a potential for information leakage about its directory structure. To prevent this, commands that take file names as arguments in a safe interpreter use tokens instead of the real directory names. These tokens are translated to the real directory name while a request to, e.g., source a file is mediated by the master interpreter. This virtual path system is maintained in the master interpreter for each safe interpreter created by ::safe::interpCreate or initialized by ::safe::interpInit and the path maps tokens accessible in the safe interpreter into real path names on the local file system thus preventing safe interpreters from gaining knowledge about the structure of the file system of the host on which the interpreter is executing. The only valid file names arguments for the source and load aliases provided to the slave are path in the form of [file join token filename] (ie, when using the native file path formats: token/filename on Unix, token\filename on Windows, and token:filename on the Mac), where token is representing one of the directories of the accessPath list and filename is one file in that directory (no sub directories access are allowed).

When a token is used in a safe interpreter in a request to source or load a file, the token is checked and translated to a real path name and the file to be sourced or loaded is located on the file system. The safe interpreter never gains knowledge of the actual path name under which the file is stored on the file system.

To further prevent potential information leakage from sensitive files that are accidentally included in the set of files that can be sourced by a safe interpreter, the source alias restricts access to files meeting the following constraints: the file name must fourteen characters or shorter, must not contain more than one dot ("."), must end up with the extension .tcl or be called tclIndex.

Each element of the initial access path list will be assigned a token that will be set in the slave auto_path and the first element of that list will be set as the tcl_library for that slave.

If the access path argument is not given or is the empty list, the default behavior is to let the slave access the same packages as the master has access to (Or to be more precise: only packages written in Tcl (which by definition can't be dangerous as they run in the slave interpreter) and C extensions that provides a Safe_Init entry point). For that purpose, the master's auto_path will be used to construct the slave access path. In order that the slave successfully loads the Tcl library files (which includes the auto-loading mechanism itself) the tcl_library will be added or moved to the first position if necessary, in the slave access path, so the slave tcl_library will be the same as the master's (its real path will still be invisible to the slave though). In order that auto-loading works the same for the slave and the master in this by default case, the first-level sub directories of each directory in the master auto_path will also be added (if not already included) to the slave access path. You can always specify a more restrictive path for which sub directories will never be searched by explicitly specifying your directory list with the -accessPath flag instead of relying on this default mechanism.

When the accessPath is changed after the first creation or initialization (ie through interpConfigure -accessPath list), an auto_reset is automatically evaluated in the safe interpreter to synchronize its auto_index with the new token list.

SEE ALSO

interp, library, load, package, source, unknown

KEYWORDS

alias, auto-loading, auto_mkindex, load, master interpreter, safe interpreter, slave interpreter, source
Copyright © 1995-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - scan manual page

NAME
scan - Parse string using conversion specifiers in the style of sscanf
SYNOPSIS
scan string format ?varName varName ...?
INTRODUCTION
DETAILS ON SCANNING
d
o
x
u
i
c
s
e or f or g
[chars]
[^chars]
n
DIFFERENCES FROM ANSI SSCANF
SEE ALSO
KEYWORDS

NAME

scan - Parse string using conversion specifiers in the style of sscanf

SYNOPSIS

scan string format ?varName varName ...?

INTRODUCTION

This command parses fields from an input string in the same fashion as the ANSI C sscanf procedure and returns a count of the number of conversions performed, or -1 if the end of the input string is reached before any conversions have been performed. String gives the input to be parsed and format indicates how to parse it, using % conversion specifiers as in sscanf. Each varName gives the name of a variable; when a field is scanned from string the result is converted back into a string and assigned to the corresponding variable. If no varName variables are specified, then scan works in an inline manner, returning the data that would otherwise be stored in the variables as a list. In the inline case, an empty string is returned when the end of the input string is reached before any conversions have been performed.

DETAILS ON SCANNING

Scan operates by scanning string and format together. If the next character in format is a blank or tab then it matches any number of white space characters in string (including zero). Otherwise, if it isn't a % character then it must match the next character of string. When a % is encountered in format, it indicates the start of a conversion specifier. A conversion specifier contains up to four fields after the %: a *, which indicates that the converted value is to be discarded instead of assigned to a variable; a XPG3 position specifier; a number indicating a maximum field width; and a conversion character. All of these fields are optional except for the conversion character. The fields that are present must appear in the order given above.

When scan finds a conversion specifier in format, it first skips any white-space characters in string (unless the specifier is [ or c). 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 scan.

If the % is followed by a decimal number and a $, as in ``%2$d'', then the variable to use is not taken from the next sequential argument. Instead, it is taken from the argument indicated by the number, where 1 corresponds to the first varName. If there are any positional specifiers in format then all of the specifiers must be positional. Every varName 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.

The following conversion characters are supported:

d
The input field must be a decimal integer. It is read in and the value is stored in the variable as a decimal string.

o
The input field must be an octal integer. It is read in and the value is stored in the variable as a decimal string. If the value exceeds MAX_INT (017777777777 on platforms using 32-bit integers), it will be truncated to a signed integer. Hence, 037777777777 will appear as -1 on a 32-bit machine.

x
The input field must be a hexadecimal integer. It is read in and the value is stored in the variable as a decimal string. If the value exceeds MAX_INT (0x7FFFFFFF on platforms using 32-bit integers), it will be truncated to a signed integer. Hence, 0xFFFFFFFF will appear as -1 on a 32-bit machine.

u
The input field must be a decimal integer. The value is stored in the variable as an unsigned decimal integer string.

i
The input field must be an integer. The base (i.e. decimal, octal, or hexadecimal) is determined in the same fashion as described in expr. The value is stored in the variable as a decimal string.

c
A single character is read in and its binary value is stored in the variable as a decimal string. Initial white space is not skipped in this case, so the input field may be a white-space character. This conversion is different from the ANSI standard in that the input field always consists of a single character and no field width may be specified.

s
The input field consists of all the characters up to the next white-space character; the characters are copied to the variable.

e or f or g
The input field 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 e or E followed by an optional sign and a string of decimal digits. It is read in and stored in the variable as a floating-point string.

[chars]
The input field consists of any number of characters in chars. The matching string is stored in the variable. If the first character between the brackets is a ] then it is treated as part of chars rather than the closing bracket for the set. If chars contains a sequence of the form a-b then any character between a and b (inclusive) will match. If the first or last character between the brackets is a -, then it is treated as part of chars rather than indicating a range.

[^chars]
The input field consists of any number of characters not in chars. The matching string is stored in the variable. If the character immediately following the ^ is a ] then it is treated as part of the set rather than the closing bracket for the set. If chars contains a sequence of the form a-b then any character between a and b (inclusive) will be excluded from the set. If the first or last character between the brackets is a -, then it is treated as part of chars rather than indicating a range.

n
No input is consumed from the input string. Instead, the total number of chacters scanned from the input string so far is stored in the variable.

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 %d, as many octal digits as possible for %o, and so on). The input field for a given conversion terminates either when a white-space character is encountered or when the maximum field width has been reached, whichever comes first. If a * is present in the conversion specifier then no variable is assigned and the next scan argument is not consumed.

DIFFERENCES FROM ANSI SSCANF

The behavior of the scan command is the same as the behavior of the ANSI C sscanf procedure except for the following differences:

[1]
%p conversion specifier is not currently supported.

[2]
For %c conversions a single character value is converted to a decimal string, which is then assigned to the corresponding varName; no field width may be specified for this conversion.

[3]
The l, h, and L modifiers are ignored; integer values are always converted as if there were no modifier present and real values are always converted as if the l modifier were present (i.e. type double is used for the internal representation).

[4]
If the end of the input string is reached before any conversions have been performed and no variables are given, and empty string is returned.

SEE ALSO

format, sscanf

KEYWORDS

conversion specifier, parse, scan
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
Copyright © 2000 Scriptics Corporation.


Tcl Built-In Commands - seek manual page

NAME

seek - Change the access position for an open channel

SYNOPSIS

seek channelId offset ?origin?

DESCRIPTION

Changes the current access position for channelId. ChannelId must be a channel identifier such as returned from a previous invocation of open or socket. The offset and origin arguments specify the position at which the next read or write will occur for channelId. Offset must be an integer (which may be negative) and origin must be one of the following:

start
The new access position will be offset bytes from the start of the underlying file or device.

current
The new access position will be offset bytes from the current access position; a negative offset moves the access position backwards in the underlying file or device.

end
The new access position will be offset bytes from the end of the file or device. A negative offset places the access position before the end of file, and a positive offset places the access position after the end of file.

The origin argument defaults to start.

The command flushes all buffered output for the channel before the command returns, even if the channel is in nonblocking mode. It also discards any buffered and unread input. This command returns an empty string. An error occurs if this command is applied to channels whose underlying file or device does not support seeking.

Note that offset values are byte offsets, not character offsets. Both seek and tell operate in terms of bytes, not characters, unlike read.

SEE ALSO

file, open, close, gets, tell

KEYWORDS

access position, file, seek
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - set manual page

NAME

set - Read and write variables

SYNOPSIS

set varName ?value?

DESCRIPTION

Returns the value of variable varName. If value is specified, then set the value of varName to value, creating a new variable if one doesn't already exist, and return its value. If varName contains an open parenthesis and ends with a close parenthesis, then it refers to an array element: the characters before the first open parenthesis are the name of the array, and the characters between the parentheses are the index within the array. Otherwise varName refers to a scalar variable. Normally, varName is unqualified (does not include the names of any containing namespaces), and the variable of that name in the current namespace is read or written. If varName includes namespace qualifiers (in the array name if it refers to an array element), the variable in the specified namespace is read or written.

If no procedure is active, then varName refers to a namespace variable (global variable if the current namespace is the global namespace). If a procedure is active, then varName refers to a parameter or local variable of the procedure unless the global command was invoked to declare varName to be global, or unless a variable command was invoked to declare varName to be a namespace variable.

SEE ALSO

expr, proc, trace, unset

KEYWORDS

read, write, variable
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - socket manual page

NAME
socket - Open a TCP network connection
SYNOPSIS
socket ?options? host port
socket -server command ?options? port
DESCRIPTION
CLIENT SOCKETS
-myaddr addr
-myport port
-async
SERVER SOCKETS
-myaddr addr
CONFIGURATION OPTIONS
-error
-sockname
-peername
SEE ALSO
KEYWORDS

NAME

socket - Open a TCP network connection

SYNOPSIS

socket ?options? host port
socket -server command ?options? port

DESCRIPTION

This command opens a network socket and returns a channel identifier that may be used in future invocations of commands like read, puts and flush. At present only the TCP network protocol is supported; future releases may include support for additional protocols. The socket command may be used to open either the client or server side of a connection, depending on whether the -server switch is specified.

CLIENT SOCKETS

If the -server option is not specified, then the client side of a connection is opened and the command returns a channel identifier that can be used for both reading and writing. Port and host specify a port to connect to; there must be a server accepting connections on this port. Port is an integer port number and host is either a domain-style name such as www.sunlabs.com or a numerical IP address such as 127.0.0.1. Use localhost to refer to the host on which the command is invoked.

The following options may also be present before host to specify additional information about the connection:

-myaddr addr
Addr 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 interfaces. If the option is omitted then the client-side interface will be chosen by the system software.

-myport port
Port specifies an integer port number to use for the client's side of the connection. If this option is omitted, the client's port number will be chosen at random by the system software.

-async
The -async 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 socket returns. When a gets or flush 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 gets or flush is done on the socket before the connection attempt succeeds or fails, the operation returns immediately and fblocked on the socket returns 1.

SERVER SOCKETS

If the -server option is specified then the new socket will be a server for the port given by port. 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 command 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.

The following additional option may also be specified before host:

-myaddr addr
Addr 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.

Server channels cannot be used for input or output; their sole use is to accept new client connections. The channels created for each incoming client connection are opened for input and output. Closing the server channel shuts down the server so that no new connections will be accepted; however, existing connections will be unaffected.

Server sockets depend on the Tcl event mechanism to find out when new connections are opened. If the application doesn't enter the event loop, for example by invoking the vwait command or calling the C procedure Tcl_DoOneEvent, then no connections will be accepted.

CONFIGURATION OPTIONS

The fconfigure command can be used to query several readonly configuration options for socket channels:

-error
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 returned. If there was no error, an empty string is returned.

-sockname
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.

-peername
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 or bound. If the host name cannot be computed, the second element of the list is identical to the address, its first element.

SEE ALSO

flush, open, read

KEYWORDS

bind, channel, connection, domain name, host, network address, socket, tcp
Copyright © 1996 Sun Microsystems, Inc.
Copyright © 1998-1999 by Scriptics Corporation.


Built-In Commands - source manual page

NAME

source - Evaluate a file or resource as a Tcl script

SYNOPSIS

source fileName
source -rsrc resourceName ?fileName?
source -rsrcid resourceId ?fileName?

DESCRIPTION

This command takes the contents of the specified file or resource and passes it to the Tcl interpreter as a text script. The return value from source is the return value of the last command executed in the script. If an error occurs in evaluating the contents of the script then the source command will return that error. If a return command is invoked from within the script then the remainder of the file will be skipped and the source command will return normally with the result from the return command. The -rsrc and -rsrcid forms of this command are only available on Macintosh computers. These versions of the command allow you to source a script from a TEXT resource. You may specify what TEXT resource to source by either name or id. By default Tcl searches all open resource files, which include the current application and any loaded C extensions. Alternatively, you may specify the fileName where the TEXT resource can be found.

KEYWORDS

file, script
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - split manual page

NAME

split - Split a string into a proper Tcl list

SYNOPSIS

split string ?splitChars?

DESCRIPTION

Returns a list created by splitting string at each character that is in the splitChars argument. Each element of the result list will consist of the characters from string that lie between instances of the characters in splitChars. Empty list elements will be generated if string contains adjacent characters in splitChars, or if the first or last character of string is in splitChars. If splitChars is an empty string then each character of string becomes a separate element of the result list. SplitChars defaults to the standard white-space characters. For example,
split "comp.unix.misc" .
returns "comp unix misc" and
split "Hello world" {}
returns "H e l l o { } w o r l d".

SEE ALSO

join, list, string

KEYWORDS

list, split, string
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - string manual page

NAME
string - Manipulate strings
SYNOPSIS
string option arg ?arg ...?
DESCRIPTION
string bytelength string
string compare ?-nocase? ?-length int? string1 string2
string equal ?-nocase? ?-length int? string1 string2
string first string1 string2 ?startIndex?
string index string charIndex
integer
end
end-integer
string is class ?-strict? ?-failindex varname? string
alnum
alpha
ascii
boolean
control
digit
double
false
graph
integer
lower
print
punct
space
true
upper
wordchar
xdigit
string last string1 string2 ?startIndex?
string length string
string map ?-nocase? charMap string
string match ?-nocase? pattern string
*
?
[chars]
\x
string range string first last
string repeat string count
string replace string first last ?newstring?
string tolower string ?first? ?last?
string totitle string ?first? ?last?
string toupper string ?first? ?last?
string trim string ?chars?
string trimleft string ?chars?
string trimright string ?chars?
string wordend string charIndex
string wordstart string charIndex
SEE ALSO
KEYWORDS

NAME

string - Manipulate strings

SYNOPSIS

string option arg ?arg ...?

DESCRIPTION

Performs one of several string operations, depending on option. The legal options (which may be abbreviated) are:

string bytelength string
Returns a decimal string giving the number of bytes used to represent string in memory. Because UTF-8 uses one to three bytes to represent Unicode characters, the byte length will not be the same as the character length in general. The cases where a script cares about the byte length are rare. In almost all cases, you should use the string length operation. Refer to the Tcl_NumUtfChars manual entry for more details on the UTF-8 representation.

string compare ?-nocase? ?-length int? string1 string2
Perform a character-by-character comparison of strings string1 and string2. Returns -1, 0, or 1, depending on whether string1 is lexicographically less than, equal to, or greater than string2. If -length is specified, then only the first length characters are used in the comparison. If -length is negative, it is ignored. If -nocase is specified, then the strings are compared in a case-insensitive manner.

string equal ?-nocase? ?-length int? string1 string2
Perform a character-by-character comparison of strings string1 and string2. Returns 1 if string1 and string2 are identical, or 0 when not. If -length is specified, then only the first length characters are used in the comparison. If -length is negative, it is ignored. If -nocase is specified, then the strings are compared in a case-insensitive manner.

string first string1 string2 ?startIndex?
Search string2 for a sequence of characters that exactly match the characters in string1. If found, return the index of the first character in the first such match within string2. If not found, return -1. If startIndex is specified (in any of the forms accepted by the index method), then the search is constrained to start with the character in string2 specified by the index. For example,
string first a 0a23456789abcdef 5
will return 10, but
string first a 0123456789abcdef 11
will return -1.

string index string charIndex
Returns the charIndex'th character of the string argument. A charIndex of 0 corresponds to the first character of the string. charIndex may be specified as follows:

integer
The char specified at this integral index

end
The last char of the string.

end-integer
The last char of the string minus the specified integer offset (e.g. end-1 would refer to the "c" in "abcd").

If charIndex is less than 0 or greater than or equal to the length of the string then an empty string is returned.

string is class ?-strict? ?-failindex varname? string
Returns 1 if string is a valid member of the specified character class, otherwise returns 0. If -strict is specified, then an empty string returns 0, otherwise and empty string will return 1 on any class. If -failindex 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 varname. The varname will not be set if the function returns 1. The following character classes are recognized (the class name can be abbreviated):

alnum
Any Unicode alphabet or digit character.

alpha
Any Unicode alphabet character.

ascii
Any character with a value less than \u0080 (those that are in the 7-bit ascii range).

boolean
Any of the forms allowed to Tcl_GetBoolean.

control
Any Unicode control character.

digit
Any Unicode digit character. Note that this includes characters outside of the [0-9] range.

double
Any of the valid forms for a double in Tcl, with optional surrounding whitespace. In case of under/overflow in the value, 0 is returned and the varname will contain -1.

false
Any of the forms allowed to Tcl_GetBoolean where the value is false.

graph
Any Unicode printing character, except space.

integer
Any of the valid forms for an integer in Tcl, with optional surrounding whitespace. In case of under/overflow in the value, 0 is returned and the varname will contain -1.

lower
Any Unicode lower case alphabet character.

print
Any Unicode printing character, including space.

punct
Any Unicode punctuation character.

space
Any Unicode space character.

true
Any of the forms allowed to Tcl_GetBoolean where the value is true.

upper
Any upper case alphabet character in the Unicode character set.

wordchar
Any Unicode word character. That is any alphanumeric character, and any Unicode connector punctuation characters (e.g. underscore).

xdigit
Any hexadecimal digit character ([0-9A-Fa-f]).

In the case of boolean, true and false, if the function will return 0, then the varname will always be set to 0, due to the varied nature of a valid boolean value.

string last string1 string2 ?startIndex?
Search string2 for a sequence of characters that exactly match the characters in string1. If found, return the index of the first character in the last such match within string2. If there is no match, then return -1. If startIndex is specified (in any of the forms accepted by the index method), then only the characters in string2 at or before the specified startIndex will be considered by the search. For example,
string last a 0a23456789abcdef 15
will return 10, but
string last a 0a23456789abcdef 9
will return 1.

string length string
Returns a decimal string giving the number of characters in string. Note that this is not necessarily the same as the number of bytes used to store the string.

string map ?-nocase? charMap string
Replaces characters in string based on the key-value pairs in charMap. charMap is a list of key value key value ... as in the form returned by array get. Each instance of a key in the string will be replaced with its corresponding value. If -nocase is specified, then matching is done without regard to case differences. Both key and value may be multiple characters. Replacement is done in an ordered manner, so the key appearing first in the list will be checked first, and so on. string is only iterated over once, so earlier key replacements will have no affect for later key matches. For example,
string map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc
will return the string 01321221.

string match ?-nocase? pattern string
See if pattern matches string; return 1 if it does, 0 if it doesn't. If -nocase is specified, then the pattern attempts to match against the string in a case insensitive manner. For the two strings to match, their contents must be identical except that the following special sequences may appear in pattern:

*
Matches any sequence of characters in string, including a null string.

?
Matches any single character in string.

[chars]
Matches any character in the set given by chars. If a sequence of the form x-y appears in chars, then any character between x and y, inclusive, will match. When used with -nocase, the end points of the range are converted to lower case first. Whereas {[A-z]} matches '_' when matching case-sensitively ('_' falls between the 'Z' and 'a'), with -nocase this is considered like {[A-Za-z]} (and probably what was meant in the first place).

\x
Matches the single character x. This provides a way of avoiding the special interpretation of the characters *?[]\ in pattern.

string range string first last
Returns a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string. first and last may be specified as for the index method. If first is less than zero then it is treated as if it were zero, and if last is greater than or equal to the length of the string then it is treated as if it were end. If first is greater than last then an empty string is returned.

string repeat string count
Returns string repeated count number of times.

string replace string first last ?newstring?
Removes a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string. First and last may be specified as for the index method. If newstring is specified, then it is placed in the removed character range. If first is less than zero then it is treated as if it were zero, and if last is greater than or equal to the length of the string then it is treated as if it were end. If first is greater than last or the length of the initial string, or last is less than 0, then the initial string is returned untouched.

string tolower string ?first? ?last?
Returns a value equal to string except that all upper (or title) case letters have been converted to lower case. If first is specified, it refers to the first char index in the string to start modifying. If last is specified, it refers to the char index in the string to stop at (inclusive). first and last may be specified as for the index method.

string totitle string ?first? ?last?
Returns a value equal to string except that the first character in string 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 first is specified, it refers to the first char index in the string to start modifying. If last is specified, it refers to the char index in the string to stop at (inclusive). first and last may be specified as for the index method.

string toupper string ?first? ?last?
Returns a value equal to string except that all lower (or title) case letters have been converted to upper case. If first is specified, it refers to the first char index in the string to start modifying. If last is specified, it refers to the char index in the string to stop at (inclusive). first and last may be specified as for the index method.

string trim string ?chars?
Returns a value equal to string except that any leading or trailing characters from the set given by chars are removed. If chars is not specified then white space is removed (spaces, tabs, newlines, and carriage returns).

string trimleft string ?chars?
Returns a value equal to string except that any leading characters from the set given by chars are removed. If chars is not specified then white space is removed (spaces, tabs, newlines, and carriage returns).

string trimright string ?chars?
Returns a value equal to string except that any trailing characters from the set given by chars are removed. If chars is not specified then white space is removed (spaces, tabs, newlines, and carriage returns).

string wordend string charIndex
Returns the index of the character just after the last one in the word containing character charIndex of string. charIndex may be specified as for the index 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.

string wordstart string charIndex
Returns the index of the first character in the word containing character charIndex of string. charIndex may be specified as for the index 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.

SEE ALSO

expr, list

KEYWORDS

case conversion, compare, index, match, pattern, string, word, equal, ctype
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - subst manual page

NAME

subst - Perform backslash, command, and variable substitutions

SYNOPSIS

subst ?-nobackslashes? ?-nocommands? ?-novariables? string

DESCRIPTION

This command performs variable substitutions, command substitutions, and backslash substitutions on its string argument and returns the fully-substituted result. The substitutions are performed in exactly the same way as for Tcl commands. As a result, the string argument is actually substituted twice, once by the Tcl parser in the usual fashion for Tcl commands, and again by the subst command.

If any of the -nobackslashes, -nocommands, or -novariables are specified, then the corresponding substitutions are not performed. For example, if -nocommands is specified, no command substitution is performed: open and close brackets are treated as ordinary characters with no special interpretation.

Note: when it performs its substitutions, subst does not give any special treatment to double quotes or curly braces. For example, the script

set a 44
subst {xyz {$a}}
returns ``xyz {44}'', not ``xyz {$a}''.

SEE ALSO

eval

KEYWORDS

backslash substitution, command substitution, variable substitution
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - switch manual page

NAME
switch - Evaluate one of several scripts, depending on a given value
SYNOPSIS
switch ?options? string pattern body ?pattern body ...?
switch ?options? string {pattern body ?pattern body ...?}
DESCRIPTION
-exact
-glob
-regexp
- -
SEE ALSO
KEYWORDS

NAME

switch - Evaluate one of several scripts, depending on a given value

SYNOPSIS

switch ?options? string pattern body ?pattern body ...?
switch ?options? string {pattern body ?pattern body ...?}

DESCRIPTION

The switch command matches its string argument against each of the pattern arguments in order. As soon as it finds a pattern that matches string it evaluates the following body argument by passing it recursively to the Tcl interpreter and returns the result of that evaluation. If the last pattern argument is default then it matches anything. If no pattern argument matches string and no default is given, then the switch command returns an empty string.

If the initial arguments to switch start with - then they are treated as options. The following options are currently supported:

-exact
Use exact matching when comparing string to a pattern. This is the default.

-glob
When matching string to the patterns, use glob-style matching (i.e. the same as implemented by the string match command).

-regexp
When matching string to the patterns, use regular expression matching (as described in the re_syntax reference page).

- -
Marks the end of options. The argument following this one will be treated as string even if it starts with a -.

Two syntaxes are provided for the pattern and body arguments. The first uses a separate argument for each of the patterns and commands; this form is convenient if substitutions are desired on some of the patterns or commands. The second form places all of the patterns and commands together into a single argument; the argument must have proper list structure, with the elements of the list being the patterns and commands. The second form makes it easy to construct multi-line switch commands, since the braces around the whole list make it unnecessary to include a backslash at the end of each line. Since the pattern arguments are in braces in the second form, no command or variable substitutions are performed on them; this makes the behavior of the second form different than the first form in some cases.

If a body is specified as ``-'' it means that the body for the next pattern should also be used as the body for this pattern (if the next pattern also has a body of ``-'' then the body after that is used, and so on). This feature makes it possible to share a single body among several patterns.

Beware of how you place comments in switch commands. Comments should only be placed inside the execution body of one of the patterns, and not intermingled with the patterns.

Below are some examples of switch commands:

switch abc a - b {format 1} abc {format 2} default {format 3}
will return 2,
switch -regexp aaab {
    ^a.*b$ -
    b {format 1}
    a* {format 2}
    default {format 3}
}
will return 1, and
switch xyz {
    a
        -
    b
        {
        # Correct Comment Placement
        format 1
    }
    a*
        {format 2}
    default
        {format 3}
}
will return 3.

SEE ALSO

for, if, regexp

KEYWORDS

switch, match, regular expression
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Built-In Commands - Tcl manual page

NAME
Tcl - Summary of Tcl language syntax.
DESCRIPTION
$name
$name(index)
${name}
\a
\b
\f
\n
\r
\t
\v
\<newline>whiteSpace
\\
\ooo
\x hh
\u hhhh

NAME

Tcl - Summary of Tcl language syntax.

DESCRIPTION

The following rules define the syntax and semantics of the Tcl language:

[1]
A Tcl script is a string containing one or more commands. Semi-colons and newlines are command separators unless quoted as described below. Close brackets are command terminators during command substitution (see below) unless quoted.

[2]
A command is evaluated in two steps. First, the Tcl interpreter breaks the command into words and performs substitutions as described below. These substitutions are performed in the same way for all commands. The first word is used to locate a command procedure to carry out the command, then all of the words of the command are passed to the command procedure. The command procedure is free to interpret each of its words in any way it likes, such as an integer, variable name, list, or Tcl script. Different commands interpret their words differently.

[3]
Words of a command are separated by white space (except for newlines, which are command separators).

[4]
If the first character of a word is double-quote (``"'') then the word is terminated by the next double-quote character. If semi-colons, close brackets, or white space characters (including newlines) appear between the quotes then they are treated 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.

[5]
If the first character of a word is an open brace (``{'') then the word is terminated by the matching close brace (``}''). Braces nest within the word: for each additional open brace there must be an additional close brace (however, if an open brace or close brace within the word is quoted with a backslash then it is not counted in locating the matching close brace). No substitutions are performed on the characters between the braces except for backslash-newline substitutions described below, nor do semi-colons, newlines, close brackets, or white space receive any special interpretation. The word will consist of exactly the characters between the outer braces, not including the braces themselves.

[6]
If a word contains an open bracket (``['') then Tcl performs command substitution. To do this it invokes the Tcl interpreter recursively to process the characters following the open bracket as a Tcl script. The script may contain any number of commands and must be terminated by a close bracket (``]''). The result of the script (i.e. the result of its last command) is substituted into the word in place of the brackets and all of the characters between them. There may be any number of command substitutions in a single word. Command substitution is not performed on words enclosed in braces.

[7]
If a word contains a dollar-sign (``$'') then Tcl performs variable substitution: the dollar-sign and the following characters are replaced in the word by the value of a variable. Variable substitution may take any of the following forms:

$name
Name is the name of a scalar variable; the name is terminated by any character that isn't a letter, digit, or underscore.

$name(index)
Name gives the name of an array variable and index gives the name of an element within that array. Name must contain only letters, digits, and underscores. Command substitutions, variable substitutions, and backslash substitutions are performed on the characters of index.

${name}
Name is the name of a scalar variable. It may contain any characters whatsoever except for close braces.

There may be any number of variable substitutions in a single word. Variable substitution is not performed on words enclosed in braces.

[8]
If a backslash (``\'') appears within a word then backslash substitution occurs. In all cases but those described below the backslash is dropped and the following character is treated as an ordinary character and included in the word. This allows characters such as double quotes, close brackets, and dollar signs to be included in words without triggering special processing. The following table lists the backslash sequences that are handled specially, along with the value that replaces each sequence.

\a
Audible alert (bell) (0x7).

\b
Backspace (0x8).

\f
Form feed (0xc).

\n
Newline (0xa).

\r
Carriage-return (0xd).

\t
Tab (0x9).

\v
Vertical tab (0xb).

\<newline>whiteSpace
A single space character replaces the backslash, newline, and all spaces and tabs after the newline. This backslash sequence is unique in that it is replaced in a separate pre-pass before the command is actually parsed. This means that it will be replaced even when it occurs between braces, and the resulting space will be treated as a word separator if it isn't in braces or quotes.

\\
Backslash (``\'').

\ooo
The digits ooo (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.

\x hh
The hexadecimal digits hh 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.

\u hhhh
The hexadecimal digits hhhh (one, two, three, or four of them) give a sixteen-bit hexadecimal value for the Unicode character that will be inserted.

Backslash substitution is not performed on words enclosed in braces, except for backslash-newline as described above.

[9]
If a hash character (``#'') appears at a point where Tcl is expecting the first character of the first word of a command, then the hash character and the characters that follow it, up through the next newline, are treated as a comment and ignored. The comment character only has significance when it appears at the beginning of a command.

[10]
Each character is processed exactly once by the Tcl interpreter as part of creating the words of a command. For example, if variable substitution occurs then no further substitutions are performed on the value of the variable; the value is inserted into the word verbatim. If command substitution occurs then the nested command is processed entirely by the recursive call to the Tcl interpreter; no substitutions are performed before making the recursive call and no additional substitutions are performed on the result of the nested script.

[11]
Substitutions do not affect the word boundaries of a command. 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.

Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - Tcltest manual page

NAME
Tcltest - Test harness support code and utilities
SYNOPSIS
package require tcltest ?1.0?
::tcltest::test name desc ?constraint? script expectedAnswer
::tcltest::cleanupTests ?runningMultipleTests?
::tcltest::getMatchingTestFiles
::tcltest::loadTestedCommands
::tcltest::makeFile contents name
::tcltest::removeFile name
::tcltest::makeDirectory name
::tcltest::removeDirectory name
::tcltest::viewFile name
::tcltest::normalizeMsg msg
::tcltest::bytestring string
::tcltest::saveState
::tcltest::restoreState
::tcltest::threadReap
DESCRIPTION
COMMANDS
::tcltest::test name desc ?constraints? script expectedAnswer
::tcltest::cleanupTests ?runningMultipleTests?
::tcltest::getMatchingTestFiles
::tcltest::loadTestedCommands
::tcltest::makeFile contents name
::tcltest::removeFile name
::tcltest::makeDirectory name
::tcltest::removeDirectory name
::tcltest::viewFile file
::tcltest::normalizeMsg msg
::tcltest::bytestring string
::tcltest::saveState
::tcltest::threadReap
TESTS
TCLTEST NAMEPSACE VARIABLES
::tcltest::outputChannel
::tcltest::errorChannel
::tcltest::mainThread
::tcltest::originalEnv
::tcltest::workingDirectory
::tcltest::temporaryDirectory
::tcltest::testsDirectory
::tcltest::tcltest
::tcltest::loadScript
TEST CONSTRAINTS
unix
pc
nt
95
98
mac
unixOrPc
macOrPc
macOrUnix
tempNotPc
tempNotMac
unixCrash
pcCrash
macCrash
emptyTest
knownBug
nonPortable
userInteraction
interactive
nonBlockFiles
asyncPipeClose
unixExecs
hasIsoLocale
root
notRoot
eformat
stdio
RUNNING TEST FILES
-help
-verbose <level>
-match <matchList>
-skip <skipList>
-file <globPatternList>
-notfile <globPatternList>
-constraints <list>
-limitconstraints <bool>
-load <script>
-loadfile <scriptfile>
-tmpdir <directoryName>
-testdir <directoryName>
-preservecore <level>
0
1
2
-debug <debugLevel>
0
1
2
3
-outfile <filename>
-errfile <filename>
TEST OUTPUT
CONTENTS OF A TEST FILE
SELECTING TESTS FOR EXECUTION WITHIN A FILE
HOW TO CUSTOMIZE THE TEST HARNESS
::tcltest::PrintUsageInfoHook
::tcltest::processCmdLineArgsFlagHook
::tcltest::processCmdLineArgsHook flags
::tcltest::initConstraintsHook
::tcltest::cleanupTestsHook
EXAMPLES
KEYWORDS

NAME

Tcltest - Test harness support code and utilities

SYNOPSIS

package require tcltest ?1.0?
::tcltest::test name desc ?constraint? script expectedAnswer
::tcltest::cleanupTests ?runningMultipleTests?
::tcltest::getMatchingTestFiles
::tcltest::loadTestedCommands
::tcltest::makeFile contents name
::tcltest::removeFile name
::tcltest::makeDirectory name
::tcltest::removeDirectory name
::tcltest::viewFile name
::tcltest::normalizeMsg msg
::tcltest::bytestring string
::tcltest::saveState
::tcltest::restoreState
::tcltest::threadReap

DESCRIPTION

The tcltest package provides the user with utility tools for writing and running tests in the Tcl test suite. It can also be used to create a customized test harness for an extension.

The Tcl test suite consists of multiple .test files, each of which contains multiple test cases. Each test case consists of a call to the test command, which specifies the name of test, a short description, any constraints that apply to the test case, the script to be run, and expected results. See the sections "Tests," "Test Constraints," and "Test Files and How to Run Them" for more details.

It is also possible to add to this test harness to create your own customized test harness implementation. For more defails, see the section "How to Customize the Test Harness".

This approach to testing was designed and initially implemented by Mary Ann May-Pumphrey of Sun Microsystems in the early 1990's. Many thanks to her for donating her work back to the public Tcl release.

COMMANDS

::tcltest::test name desc ?constraints? script expectedAnswer
The ::tcltest::test command runsscript and compares its result to expectedAnswer. It prints an error message if the two do not match. If ::tcltest::verbose contains "p" or "s", it also prints out a message if the test passed or was skipped. The test will be skipped if it doesn't match the ::tcltest::match variable, if it matches an element in ::tcltest::skip, or if one of the elements of constraint turns out not to be true. The ::tcltest::test command has no defined return values. See the "Writing a new test" section for more details on this command.

::tcltest::cleanupTests ?runningMultipleTests?
This command should be called at the end of a test file. It prints statistics about the tests run and removes files that were created by ::tcltest::makeDirectory and ::tcltest::makeFile. Names of files and directories created outside of ::tcltest::makeFile and ::tcltest::makeDirectory and never deleted are printed to ::tcltest::outputChannel. This command also restores the original shell environment, as described by the ::env array. calledFromAll should be specified when ::tcltest::cleanupTests is called from an "all.tcl" file. Tcl files files are generally used to run multiple tests. For more details on how to run multiple tests, please see the section "Running test files". This proc has no defined return value.

::tcltest::getMatchingTestFiles
This command is used when you want to run multiple test files. It returns the list of tests that should be sourced in an 'all.tcl' file. See the section "Running test files" for more information.

::tcltest::loadTestedCommands
This command uses the script specified via the -load or -loadfile to load the commands checked by the test suite. Allowed to be empty, as the tested commands could have been compiled into the interpreter running the test suite.

::tcltest::makeFile contents name
Create a file that will be automatically be removed by ::tcltest::cleanupTests at the end of a test file. This proc has no defined return value.

::tcltest::removeFile name
Force the file referenced by name to be removed. This file name should be relative to ::tcltest::temporaryDirectory. This proc has no defined return values.

::tcltest::makeDirectory name
Create a directory named name that will automatically be removed by ::tcltest::cleanupTests at the end of a test file. This proc has no defined return value.

::tcltest::removeDirectory name
Force the directory referenced by name to be removed. This proc has no defined return value.

::tcltest::viewFile file
Returns the contents of file.

::tcltest::normalizeMsg msg
Remove extra newlines from msg.

::tcltest::bytestring string
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 string. 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.

::tcltest::saveState
::tcltest::restoreState Save and restore the procedure and global variable names. A test file might contain calls to ::tcltest::saveState and ::tcltest:restoreState if it creates or deletes global variables or procs.

::tcltest::threadReap
::tcltest::threadReap only works if testthread is defined, generally by compiling tcltest. If testthread is defined, ::tcltest::threadReap kills all threads except for the main thread. It gets the ID of the main thread by calling testthread names during initialization. This value is stored in ::tcltest::mainThread. ::tcltest::threadReap returns the number of existing threads at completion.

TESTS

The test procedure runs a test script and prints an error message if the script's result does not match the expected result. The following is the spec for the test command:
test <name> <description> ?<constraint>? <script> <expectedAnswer>
The <name> argument should follow the pattern:
<target>-<majorNum>.<minorNum>
For white-box (regression) tests, the target should be the name of the C function or Tcl procedure being tested. For black-box tests, the target should be the name of the feature being tested. Related tests should share a major number.

The <description> argument is a short textual description of the test, to help humans understand what it tests. The name of a Tcl or C function being tested should be included for regression tests. If the test case exists to reproduce a bug, include the bug ID in the description.

The optional <constraints> argument can be list of one or more keywords or an expression. If the <constraints> argument consists of keywords, each of these keywords must be the name of an element in the array ::tcltest::testConstraints. If any of these elements is false or does not exist, the test is skipped. If the <constraints> argument consists of an expression, that expression is evaluated. If the expression evaluates to true, then the test is run.

Add appropriate constraints (e.g., unixOnly) to any tests that should not always be run. For example, a test that should only be run on Unix should look like the following:

test getAttribute-1.1 {testing file permissions} {unixOnly} {
    lindex [file attributes foo.tcl] 5
} {00644}

An example of a test that contains an expression:

test unixNotfy-1.1 {Tcl_DeleteFileHandler} {unixOnly && !testthread} {
    catch {vwait x}
    set f [open foo w]
    fileevent $f writable {set x 1}
    vwait x
    close $f
    list [catch {vwait x} msg] $msg
} {1 {can't wait for variable "x":  would wait forever}}

See the "Test Constraints" section for a list of built-in constraints and information on how to add your own constraints.

The <script> argument contains the script to run to carry out the test. It must return a result that can be checked for correctness. If your script requires that a file be created on the fly, please use the ::tcltest::makeFile procedure. If your test requires that a small file (<50 lines) be checked in, please consider creating the file on the fly using the ::tcltest::makeFile procedure. Files created by the ::tcltest::makeFile procedure will automatically be removed by the ::tcltest::cleanupTests call at the end of each test file.

The <expectedAnswer> argument will be compared against the result of evaluating the <script> argument. If they match, the test passes, otherwise the test fails.

TCLTEST NAMEPSACE VARIABLES

The following variables are also defined in the tcltest namespace and can be used by tests:

::tcltest::outputChannel
output file ID - defaults to stdout and can be specified using -outfile on the command line. Any test that prints test related output should send that output to ::tcltest::outputChannel rather than letting that output default to stdout.

::tcltest::errorChannel
error file ID - defaults to stderr and can be specified using -errfile on the command line. Any test that prints error messages should send that output to ::tcltest::errorChannel rather than printing directly to stderr.

::tcltest::mainThread
main thread ID - defaults to 1. This is the only thread that is not killed by ::tcltest::threadReap and is set according to the return value of testthread names at initialization.

::tcltest::originalEnv
copy of the global "env" array at the beginning of the test run. This array is used to restore the "env" array to its original state when ::tcltest::cleanupTests is called.

::tcltest::workingDirectory
the directory in which the test suite was launched.

::tcltest::temporaryDirectory
the output directory - defaults to ::tcltest::workingDirectory and can be specified using -tmpdir on the command line.

::tcltest::testsDirectory
where the tests reside - defaults to ::tcltest::workingDirectory if the script cannot determine where the tests directory is located. It is possible to change the default by specifying -testdir on the commandline. This variable should be explicitly set if tests are being run from an all.tcl file.

::tcltest::tcltest
the name of the executable used to invoke the test suite.

::tcltest::loadScript
The script executed loadTestedCommands. Specified either by -load or -loadfile.

TEST CONSTRAINTS

Constraints are used to determine whether a test should be skipped. Each constraint is stored as an index in the array ::tcltest::testConstraints. For example, the unixOnly constraint is defined as the following:
set ::tcltest::testConstraints(unixOnly) \
    [string equal $tcl_platform(platform) "unix"]
If a test is constrained by "unixOnly", then it will only be run if the value of ::tcltest::testConstraints(unixOnly) is true. Several constraints are defined in the tcltest package. To add file- or test-specific constraints, you can set the desired index of the ::tcltest::testsConstraints array in your own test file.

The following is a list of constraints defined in the tcltest package:

unix
test can only be run on any UNIX platform

pc
test can only be run on any Windows platform

nt
test can only be run on any Windows NT platform

95
test can only be run on any Windows 95 platform

98
test can only be run on any Windows 98 platform

mac
test can only be run on any Mac platform

unixOrPc
test can only be run on a UNIX or PC platform

macOrPc
test can only be run on a Mac or PC platform

macOrUnix
test can only be run on a Mac or UNIX platform

tempNotPc
test can not be run on Windows. This flag is used to temporarily disable a test.

tempNotMac
test can not be run on a Mac. This flag is used to temporarily disable a test.

unixCrash
test crashes if it's run on UNIX. This flag is used to temporarily disable a test.

pcCrash
test crashes if it's run on Windows. This flag is used to temporarily disable a test.

macCrash
test crashes if it's run on a Mac. This flag is used to temporarily disable a test.

emptyTest
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 always causes tests to be skipped.

knownBug
test is known to fail and the bug is not yet fixed. This constraint always causes tests to be skipped unless the user specifies otherwise. See the "Introduction" section for more details.

nonPortable
test can only be run in the master Tcl/Tk development environment. Some tests are inherently non-portable because they depend on things like word length, file system configuration, window manager, etc. These tests are only run in the main Tcl development directory where the configuration is well known. This constraint always causes tests to be skipped unless the user specifies otherwise.

userInteraction
test requires interaction from the user. This constraint always causes tests to be skipped unless the user specifies otherwise.

interactive
test can only be run in if the interpreter is in interactive mode, that is the global tcl_interactive variable is set to 1.

nonBlockFiles
test can only be run if platform supports setting files into nonblocking mode

asyncPipeClose
test can only be run if platform supports async flush and async close on a pipe

unixExecs
test can only be run if this machine has commands such as 'cat', 'echo', etc. available.

hasIsoLocale
test can only be run if can switch to an ISO locale

root
test can only run if Unix user is root

notRoot
test can only run if Unix user is not root

eformat
test can only run if app has a working version of sprintf with respect to the "e" format of floating-point numbers.

stdio
test can only be run if the current app can be spawned via a pipe

RUNNING TEST FILES

Use the following command to run a test file that uses package tcltest:
<shell> <testFile> ?<option> ?<value>?? ...
Command line options include (tcltest namespace variables that correspond to each flag are listed at the end of each flag description in parenthesis):

-help
display usage information.

-verbose <level>
set the level of verbosity to a substring of "bps". See the "Test output" section for an explanation of this option. (::tcltest::verbose)

-match <matchList>
only run tests that match one or more of the glob patterns in <matchList>. (::tcltest::match)

-skip <skipList>
do not run tests that match one or more of the glob patterns in <skipList>. (::tcltest::skip)

-file <globPatternList>
only source test files that match any of the items in <globPatternList> relative to ::tcltest::testsDirectory. This option only makes sense if you are running tests using "all.tcl" as the <testFile> instead of running single test files directly. (::tcltest::matchFiles)

-notfile <globPatternList>
source files except for those that match any of the items in <globPatternList> relative to ::tcltest::testsDirectory. This option only makes sense if you are running tests using "all.tcl" as the <testFile> instead of running single test files directly. (::tcltest::skipFiles)

-constraints <list>
tests with any constraints in <list> will not be skipped. Note that elements of <list> must exactly match the existing constraints. This is useful if you want to make sure that tests with a particular constraint are run (for example, if the tester wants to run all tests with the knownBug constraint). (::tcltest::testConstraints(constraintName))

-limitconstraints <bool>
If the argument to this flag is 1, the test harness limits test runs to those tests that match the constraints listed by the -constraints flag. Use of this flag requires use of the -constraints flag. The default value for this flag is 0 (false). This is useful if you want to run only those tests that match the constraints listed using the -constraints option. A tester might want to do this if he were interested in running only those tests that are constrained to be unixOnly and no other tests. (::tcltest::limitConstraints)

-load <script>
will use the specified script to load the commands under test (::tcltest::loadTestedCommands). The default is the empty script. See -loadfile below too. (::tcltest::loadScript)

-loadfile <scriptfile>
will use the contents of the named file to load the commands under test (::tcltest::loadTestedCommands). See -load above too. The default is the empty script. (::tcltest::loadScript)

-tmpdir <directoryName>
put any temporary files (created with ::tcltest::makeFile and ::tcltest::makeDirectory) into the named directory. The default location is ::tcltest::workingDirectory. (::tcltest::temporaryDirectory)

-testdir <directoryName>
search the test suite to execute in the named directory. The default location is ::tcltest::workingDirectory. (::tcltest::testsDirectory)

-preservecore <level>
check for core files. This flag is used to determine how much checking should be done for core files. The default value for level is 0. Levels are defined as:

0
No checking - do not check for core files at the end of each test command, but do check for them whenever ::tcltest::cleanupTests is called from an all.tcl file.

1
Check for core files at the end of each test command and whenever ::tcltest::cleanupTests is called from all.tcl.

2
Check for core files at the end of all test commands and whenever ::tcltest::cleanupTests is called from all.tcl. Save any core files produced in ::tcltest::temporaryDirectory.

(::tcltest::preserveCore)

-debug <debugLevel>
print debug information to stdout. This is used to debug code in the test harness. The default debug level is 0. Levels are defined as:

0
Do not display any debug information.

1
Display information regarding whether a test is skipped because it doesn't match any of the tests that were specified using -match or ::tcltest::match (userSpecifiedNonMatch) or matches any of the tests specified by -skip or ::tcltest::skip (userSpecifiedSkip).

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.

3
Display information regarding what individual procs in the test harness are doing.

(::tcltest::debug)

-outfile <filename>
print output generated by the tcltest package to the named file. This defaults to stdout. Note that debug output always goes to stdout, regardless of this flag's setting. (::tcltest::outputChannel)

-errfile <filename>
print errors generated by the tcltest package to the named file. This defaults to stderr. (::tcltest::errorChannel)

A second way to run tets is to start up a shell, load the tcltest package, and then source an appropriate test file or use the test command. To use the options in interactive mode, set their corresponding tcltest namespace variables after loading the package.

See "Test Constraints" for all built-in constraint names that can be used in the ::tcltest::testConstraints array. See "Tcltest namespace variables" for details on other variables defined in the tcltest namespace.

A final way to run tests would be to specify which test files to run within an all.tcl (or otherwise named) file. This is the approach used by the Tcl test suite. This file loads the tcltest package, sets the location of the test directory (::tcltest::testsDirectory), determines which test files to run, sources each of these files, calls ::tcltest::cleanupTests and then exits.

A more elaborate all.tcl file might do some pre- and post-processing before sourcing each .test file, use separate interpreters for each file, or handle complex directory structures. For an example of an all.tcl file, please see the "Examples" section of this document.

TEST OUTPUT

After all specified test files are run, the number of tests passed, skipped, and failed is printed to ::tcltest::outputChannel. Aside from this statistical information, output can be controlled on a per-test basis by the ::tcltest::verbose variable.

::tcltest::verbose can be set to any substring or permutation of "bps". In the string "bps", the 'b' stands for a test's "body", the 'p' stands for "passed" tests, and the 's' stands for "skipped" tests. The default value of ::tcltest::verbose is "b". If 'b' is present, then the entire body of the test is printed for each failed test, otherwise only the test's name, desired output, and actual output, are printed for each failed test. If 'p' is present, then a line is printed for each passed test, otherwise no line is printed for passed tests. If 's' is present, then a line (containing the consraints that cause the test to be skipped) is printed for each skipped test, otherwise no line is printed for skipped tests.

You can set ::tcltest::verbose either interactively (after the tcltest package has been loaded) or by using the command line argument -verbose, for example:

tclsh socket.test -verbose bps

CONTENTS OF A TEST FILE

Test files should begin by loading the tcltest package:
if {[lsearch [namespace children] ::tcltest] == -1} {
    package require tcltest
    namespace import ::tcltest::*
}
Test files should end by cleaning up after themselves and calling ::tcltest::cleanupTests. The ::tcltest::cleanupTests procedure prints statistics about the number of tests that passed, skipped, and failed, and removes all files that were created using the ::tcltest::makeFile and ::tcltest::makeDirectory procedures.
# Remove files created by these tests
# Change to original working directory
# Unset global arrays
::tcltest::cleanupTests
return
When naming test files, file names should end with a .test extension. The names of test files that contain regression (or glass-box) tests should correspond to the Tcl or C code file that they are testing. For example, the test file for the C file "tclCmdAH.c" is "cmdAH.test". Test files that contain black-box tests should match the pattern "*_bb.test".

SELECTING TESTS FOR EXECUTION WITHIN A FILE

Normally, all the tests in a file are run whenever the file is sourced. An individual test will be skipped if one of the following conditions is met:

[1]
the name of the tests does not match (using glob style matching) one or more elements in the ::tcltest::match variable

[2]
the name of the tests matches (using glob style matching) one or more elements in the ::tcltest::skip variable

[3]
the constraints argument to the ::tcltest::test call, if given, contains one or more false elements.

You can set ::tcltest::match and/or ::tcltest::skip either interactively (after the tcltest package has been sourced), or by using the command line arguments -match and -skip, for example:

tclsh info.test -match '*-5.* *-7.*' -skip '*-7.1*'

Be sure to use the proper quoting convention so that your shell does not perform the glob substitution on the match or skip patterns you specify.

Predefined constraints (e.g. knownBug and nonPortable) can be overridden either interactively (after the tcltest package has been sourced) by setting the proper ::tcltest::testConstraints(constraint) variable or by using the -constraints command line option with the name of the constraint in the argument. The following example shows how to run tests that are constrained by the knownBug and nonPortable restrictions:

tclsh all.tcl -constraints "knownBug nonPortable"

See the "Constraints" package for information about using built-in constraints and adding new ones.

HOW TO CUSTOMIZE THE TEST HARNESS

To create your own custom test harness, create a .tcl file that contains your namespace. Within this file, require package tcltest. Commands that can be redefined to customize the test harness include:

::tcltest::PrintUsageInfoHook
print additional usage information specific to your situation.

::tcltest::processCmdLineArgsFlagHook
tell the test harness about additional flags that you want it to understand.

::tcltest::processCmdLineArgsHook flags
process the additional flags that you told the harness about in ::tcltest::processCmdLineArgsFlagHook.

::tcltest::initConstraintsHook
used to add additional built-in constraints to those already defined by tcltest.

::tcltest::cleanupTestsHook
do additional cleanup

To add new flags to your customized test harness, redefine ::tcltest::processCmdLineArgsAddFlagHook to define additional flags to be parsed and ::tcltest::processCmdLineArgsHook to actually process them. For example:

proc ::tcltest::processCmdLineArgsAddFlagHook {} {
    return [list -flag1 -flag2]
}

proc ::tcltest::processCmdLineArgsHook {flagArray} {
    array set flag $flagArray

    if {[info exists flag(-flag1)]} {
        # Handle flag1
    }

    if {[info exists flag(-flag2)]} {
        # Handle flag2
    }

    return
}
You may also want to add usage information for these flags. This information would be displayed whenever the user specifies -help. To define additional usage information, define your own ::tcltest::PrintUsageInfoHook proc. Within this proc, you should print out additional usage information for any flags that you've implemented.

To add new built-in constraints to the test harness, define your own version of ::tcltest::initConstraintsHook. Within your proc, you can add to the ::tcltest::testConstraints array. For example:

proc ::tcltest::initConstraintsHook {} {
    set ::tcltest::testConstraints(win95Or98) \
            [expr {$::tcltest::testConstraints(95) || \
            $::tcltest::testConstraints(98)}]
}

Finally, if you want to add additional cleanup code to your harness you can define your own ::tcltest::cleanupTestsHook. For example:

proc ::tcltest::cleanupTestsHook {} {
    # Add your cleanup code here
}

EXAMPLES

[1]
A simple test file (foo.test)
if {[lsearch [namespace children] ::tcltest] == -1} {
    package require tcltest
    namespace import ::tcltest::*
}

test foo-1.1 {save 1 in variable name foo} {} {
    set foo 1
} {1}

::tcltest::cleanupTests
return

[2]
A simple all.tcl
if {[lsearch [namespace children] ::tcltest] == -1} {
    package require tcltest
    namespace import ::tcltest::*
}

set ::tcltest::testSingleFile false
set ::tcltest::testsDirectory [file dir [info script]]

foreach file [::tcltest::getMatchingTestFiles] {
    if {[catch {source $file} msg]} {
        puts stdout $msg
    }
}

::tclttest::cleanupTests 1
return

[3]
Running a single test
tclsh foo.test

[4]
Running multiple tests
tclsh all.tcl -file 'foo*.test' -notfile 'foo2.test'

KEYWORDS

test, test harness, test suite
Copyright © 1990-1994 The Regents of the University of California
Copyright © 1994-1997 Sun Microsystems, Inc.
Copyright © 1998-1999 Scriptics Corporation


Tcl Built-In Commands - tclvars manual page

NAME
tclvars - Variables used by Tcl
DESCRIPTION
env
LOGIN
USER
SYS_FOLDER
APPLE_M_FOLDER
CP_FOLDER
DESK_FOLDER
EXT_FOLDER
PREF_FOLDER
PRINT_MON_FOLDER
SHARED_TRASH_FOLDER
TRASH_FOLDER
START_UP_FOLDER
HOME
errorCode
ARITH code msg
CHILDKILLED pid sigName msg
CHILDSTATUS pid code
CHILDSUSP pid sigName msg
NONE
POSIX errName msg
errorInfo
tcl_library
tcl_patchLevel
tcl_pkgPath
tcl_platform
byteOrder
debug
machine
os
osVersion
platform
threaded
user
tcl_precision
tcl_rcFileName
tcl_rcRsrcName
tcl_traceCompile
tcl_traceExec
tcl_wordchars
tcl_nonwordchars
tcl_version
SEE ALSO
KEYWORDS

NAME

tclvars - Variables used by Tcl

DESCRIPTION

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.

env
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 environment variable. Setting an element of the array will modify the corresponding environment variable or create a new one if it doesn't already exist. Unsetting an element of env will remove the corresponding environment variable. Changes to the env array will affect the environment passed to children by commands like exec. If the entire env array is unset then Tcl will stop monitoring env accesses and will not update environment variables.

Under Windows, the environment variables PATH and COMSPEC in any capitalization are converted automatically to upper case. For instance, the PATH variable could be exported by the operating system as ``path'', ``Path'', ``PaTh'', etc., causing otherwise simple Tcl code to have to support many special cases. All other environment variables inherited by Tcl are left unmodified.

On the Macintosh, the environment variable is constructed by Tcl as no global environment variable exists. The environment variables that are created for Tcl include:

LOGIN
This holds the Chooser name of the Macintosh.

USER
This also holds the Chooser name of the Macintosh.

SYS_FOLDER
The path to the system directory.

APPLE_M_FOLDER
The path to the Apple Menu directory.

CP_FOLDER
The path to the control panels directory.

DESK_FOLDER
The path to the desk top directory.

EXT_FOLDER
The path to the system extensions directory.

PREF_FOLDER
The path to the preferences directory.

PRINT_MON_FOLDER
The path to the print monitor directory.

SHARED_TRASH_FOLDER
The path to the network trash directory.

TRASH_FOLDER
The path to the trash directory.

START_UP_FOLDER
The path to the start up directory.

HOME
The path to the application's default directory.

You can also create your own environment variables for the Macintosh. A file named Tcl Environment Variables may be placed in the preferences folder in the Mac system folder. Each line of this file should be of the form VAR_NAME=var_data.

The last alternative is to place environment variables in a 'STR#' resource named Tcl Environment Variables of the application. This is considered a little more ``Mac like'' than a Unix style Environment Variable file. Each entry in the 'STR#' resource has the same format as above. The source code file tclMacEnv.c contains the implementation of the env mechanisms. This file contains many #define's that allow customization of the env mechanisms to fit your applications needs.

errorCode
After an error has occurred, this variable will be set to hold additional information about the error in a form that is easy to process with programs. errorCode consists of a Tcl list with one or more elements. The first element of the list identifies a general class of errors, and determines the format of the rest of the list. The following formats for errorCode are used by the Tcl core; individual applications may define additional formats.

ARITH code msg
This format is used when an arithmetic error occurs (e.g. an attempt to divide by zero in the expr command). Code identifies the precise error and msg provides a human-readable description of the error. Code will be either DIVZERO (for an attempt to divide by zero), DOMAIN (if an argument is outside the domain of a function, such as acos(-3)), IOVERFLOW (for integer overflow), OVERFLOW (for a floating-point overflow), or UNKNOWN (if the cause of the error cannot be determined).

CHILDKILLED pid sigName msg
This format is used when a child process has been killed because of a signal. The second element of errorCode will be the process's identifier (in decimal). The third element will be the symbolic name of the signal that caused the process to terminate; it will be one of the names from the include file signal.h, such as SIGPIPE. The fourth element will be a short human-readable message describing the signal, such as ``write on pipe with no readers'' for SIGPIPE.

CHILDSTATUS pid code
This format is used when a child process has exited with a non-zero exit status. The second element of errorCode will be the process's identifier (in decimal) and the third element will be the exit code returned by the process (also in decimal).

CHILDSUSP pid sigName msg
This format is used when a child process has been suspended because of a signal. The second element of errorCode will be the process's identifier, in decimal. The third element will be the symbolic name of the signal that caused the process to suspend; this will be one of the names from the include file signal.h, such as SIGTTIN. The fourth element will be a short human-readable message describing the signal, such as ``background tty read'' for SIGTTIN.

NONE
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 errorCode will consist of a list containing a single element whose contents are NONE.

POSIX errName msg
If the first element of errorCode is POSIX, then the error occurred during a POSIX kernel call. The second element of the list will contain the symbolic name of the error that occurred, such as ENOENT; this will be one of the values defined in the include file errno.h. The third element of the list will be a human-readable message corresponding to errName, such as ``no such file or directory'' for the ENOENT case.

To set errorCode, applications should use library procedures such as Tcl_SetErrorCode and Tcl_PosixError, or they may invoke the error command. If one of these methods hasn't been used, then the Tcl interpreter will reset the variable to NONE after the next error.

errorInfo
After an error has occurred, this string will contain one or more lines identifying the Tcl commands and procedures that were being executed when the most recent error occurred. 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.

tcl_library
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 info library command. See the library manual entry for details of the facilities provided by the Tcl script library. Normally each application or package will have its own application-specific script library in addition to the Tcl script library; each application should set a global variable with a name like $app_library (where app is the application's name) to hold the network file name for that application's library directory. The initial value of tcl_library is set when an interpreter is created by searching several different directories until one is found that contains an appropriate Tcl startup script. If the TCL_LIBRARY environment variable exists, then the directory it names is checked first. If TCL_LIBRARY isn't set or doesn't refer to an appropriate directory, then Tcl checks several other directories based on a compiled-in default location, the location of the binary containing the application, and the current working directory.

tcl_patchLevel
When an interpreter is created Tcl initializes this variable to hold a string giving the current patch level for Tcl, such as 7.3p2 for Tcl 7.3 with the first two official patches, or 7.4b4 for the fourth beta release of Tcl 7.4. The value of this variable is returned by the info patchlevel command.

tcl_pkgPath
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 $tcl_pkgPath. The directories in $tcl_pkgPath are included by default in the auto_path variable, so they and their immediate subdirectories are automatically searched for packages during package require commands. Note: tcl_pkgPath it not intended to be modified by the application. Its value is added to auto_path at startup; changes to tcl_pkgPath are not reflected in auto_path. If you want Tcl to search additional directories for packages you should add the names of those directories to auto_path, not tcl_pkgPath.

tcl_platform
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 instruction set. The elements listed below will always be defined, but they may have empty strings as values if Tcl couldn't retrieve any relevant information. In addition, extensions and applications may add additional values to the array. The predefined elements are:

byteOrder
The native byte order of this machine: either littleEndian or bigEndian.

debug
If this variable exists, then the interpreter was compiled with debugging symbols enabled. This varible will only exist on Windows so extension writers can specify which package to load depending on the C run-time library that is loaded.

machine
The instruction set executed by this machine, such as intel, PPC, 68k, or sun4m. On UNIX machines, this is the value returned by uname -m.

os
The name of the operating system running on this machine, such as Windows 95, Windows NT, MacOS, or SunOS. On UNIX machines, this is the value returned by uname -s. On Windows 95 and Windows 98, the value returned will be Windows 95 to provide better backwards compatibility to Windows 95; to distinguish between the two, check the osVersion.

osVersion
The version number for the operating system running on this machine. On UNIX machines, this is the value returned by uname -r. On Windows 95, the version will be 4.0; on Windows 98, the version will be 4.10.

platform
Either windows, macintosh, or unix. This identifies the general operating environment of the machine.

threaded
If this variable exists, then the interpreter was compiled with threads enabled.

user
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 and Macintosh.

tcl_precision
This variable controls the number of digits to generate when converting floating-point values to strings. It defaults to 12. 17 digits is ``perfect'' for IEEE floating-point in that it allows double-precision values to be converted to strings and back to binary with no loss of information. However, using 17 digits prevents any rounding, which produces longer, less intuitive results. For example, expr 1.4 returns 1.3999999999999999 with tcl_precision set to 17, vs. 1.4 if tcl_precision is 12.

All interpreters in a process share a single tcl_precision value: changing it in one interpreter will affect all other interpreters as well. However, safe interpreters are not allowed to modify the variable.

tcl_rcFileName
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 of this file and source it if it exists. For example, for wish the variable is set to ~/.wishrc for Unix and ~/wishrc.tcl for Windows.

tcl_rcRsrcName
This variable is only used on Macintosh systems. The variable is used during initialization to indicate the name of a user-specific TEXT resource located in the application or extension resource forks. If it is set by application-specific initialization, then the Tcl startup code will check for the existence of this resource and source it if it exists. For example, the Macintosh wish application has the variable is set to tclshrc.

tcl_traceCompile
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 whenever a procedure or top level command is compiled. Setting it to 2 generates a detailed listing in stdout of the bytecode instructions emitted during every compilation. This variable is useful in tracking down suspected problems with the Tcl compiler. It is also occasionally useful when converting existing code to use Tcl8.0.

tcl_traceExec
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 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, commands such as set and incr that have been entirely replaced by a sequence of bytecode instructions are not shown. Setting this variable is useful in tracking down suspected problems with the bytecode compiler and interpreter. It is also occasionally useful when converting code to use Tcl8.0.

tcl_wordchars
The value of this variable is a regular expression that can be set to control what are considered ``word'' characters, for instances like selecting a word by double-clicking in text in Tk. It is platform dependent. On Windows, it defaults to \S, meaning anything but a Unicode space character. Otherwise it defaults to \w, which is any Unicode word character (number, letter, or underscore).

tcl_nonwordchars
The value of this variable is a regular expression that can be set to control what are considered ``non-word'' characters, for instances like selecting a word by double-clicking in text in Tk. It is platform dependent. On Windows, it defaults to \s, meaning any Unicode space character. Otherwise it defaults to \W, which is anything but a Unicode word character (number, letter, or underscore).

tcl_version
When an interpreter is created Tcl initializes this variable to hold the version number for this version of Tcl in the form x.y. Changes to x represent major changes with probable incompatibilities and changes to y represent small enhancements and bug fixes that retain backward compatibility. The value of this variable is returned by the info tclversion command.

SEE ALSO

eval

KEYWORDS

arithmetic, bytecode, compiler, error, environment, POSIX, precision, subprocess, variables
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Built-In Commands - tell manual page

NAME

tell - Return current access position for an open channel

SYNOPSIS

tell channelId

DESCRIPTION

Returns an integer string giving the current access position in channelId. This value returned is a byte offset that can be passed to seek in order to set the channel to a particular position. Note that this value is in terms of bytes, not characters like read. The value returned is -1 for channels that do not support seeking.

SEE ALSO

file, open, close, gets, seek

KEYWORDS

access position, channel, seeking
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - time manual page

NAME

time - Time the execution of a script

SYNOPSIS

time script ?count?

DESCRIPTION

This command will call the Tcl interpreter count times to evaluate script (or once if count isn't specified). It will then return a string of the form
503 microseconds per iteration
which indicates the average amount of time required per iteration, in microseconds. Time is measured in elapsed time, not CPU time.

SEE ALSO

clock

KEYWORDS

script, time
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - trace manual page

NAME
trace - Monitor variable accesses
SYNOPSIS
trace option ?arg arg ...?
DESCRIPTION
trace variable name ops command
r
w
u
trace vdelete name ops command
trace vinfo name
KEYWORDS

NAME

trace - Monitor variable accesses

SYNOPSIS

trace option ?arg arg ...?

DESCRIPTION

This command causes Tcl commands to be executed whenever certain operations are invoked. At present, only variable tracing is implemented. The legal option's (which may be abbreviated) are:

trace variable name ops command
Arrange for command to be executed whenever variable name is accessed in one of the ways given by ops. Name may refer to a normal variable, an element of an array, or to an array as a whole (i.e. name may be just the name of an array, with no parenthesized index). If name refers to a whole array, then command is invoked whenever any element of the array is manipulated. If the variable does not exist, it will be created but will not be given a value, so it will be visible to namespace which queries, but not to info exists queries.

Ops indicates which operations are of interest, and consists of one or more of the following letters:

r
Invoke command whenever the variable is read.

w
Invoke command whenever the variable is written.

u
Invoke command whenever the variable is unset. Variables can be unset explicitly with the unset command, or implicitly when procedures return (all of their local variables are unset). Variables are also unset when interpreters are deleted, but traces will not be invoked because there is no interpreter in which to execute them.

When the trace triggers, three arguments are appended to command so that the actual command is as follows:

command name1 name2 op
Name1 and name2 give the name(s) for the variable being accessed: if the variable is a scalar then name1 gives the variable's name and name2 is an empty string; if the variable is an array element then name1 gives the name of the array and name2 gives the index into the array; if an entire array is being deleted and the trace was registered on the overall array, rather than a single element, then name1 gives the array name and name2 is an empty string. Name1 and name2 are not necessarily the same as the name used in the trace variable command: the upvar command allows a procedure to reference a variable under a different name. Op indicates what operation is being performed on the variable, and is one of r, w, or u as defined above.

Command executes in the same context as the code that invoked the traced operation: if the variable was accessed as part of a Tcl procedure, then command will have access to the same local variables as code in the procedure. This context may be different than the context in which the trace was created. If command invokes a procedure (which it normally does) then the procedure will have to use upvar or uplevel if it wishes to access the traced variable. Note also that name1 may not necessarily be the same as the name used to set the trace on the variable; differences can occur if the access is made through a variable defined with the upvar command.

For read and write traces, command can modify the variable to affect the result of the traced operation. If command modifies the value of a variable during a read or write trace, then the new value will be returned as the result of the traced operation. The return value from command is ignored except that if it returns an error of any sort then the traced operation also returns an error with the same error message returned by the trace command (this mechanism can be used to implement read-only variables, for example). For write traces, command is invoked after the variable's value has been changed; it can write a new value into the variable to override the original value specified in the write operation. To implement read-only variables, command will have to restore the old value of the variable.

While command is executing during a read or write trace, traces on the variable are temporarily disabled. This means that reads and writes invoked by command will occur directly, without invoking command (or any other traces) again. However, if command unsets the variable then unset traces will be invoked.

When an unset trace is invoked, the variable has already been deleted: it will appear to be undefined with no traces. If an unset occurs because of a procedure return, then the trace will be invoked in the variable context of the procedure being returned to: the stack frame of the returning procedure will no longer exist. Traces are not disabled during unset traces, so if an unset trace command creates a new trace and accesses the variable, the trace will be invoked. Any errors in unset traces are ignored.

If there are multiple traces on a variable they are invoked in order of creation, most-recent first. If one trace returns an error, then no further traces are invoked for the variable. If an array element has a trace set, and there is also a trace set on the array as a whole, the trace on the overall array is invoked before the one on the element.

Once created, the trace remains in effect either until the trace is removed with the trace vdelete command described below, until the variable is unset, or until the interpreter is deleted. Unsetting an element of array will remove any traces on that element, but will not remove traces on the overall array.

This command returns an empty string.

trace vdelete name ops command
If there is a trace set on variable name with the operations and command given by ops and command, then the trace is removed, so that command will never again be invoked. Returns an empty string.

trace vinfo name
Returns a list containing one element for each trace currently set on variable name. Each element of the list is itself a list containing two elements, which are the ops and command associated with the trace. If name doesn't exist or doesn't have any traces set, then the result of the command will be an empty string.

KEYWORDS

read, variable, write, trace, unset
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - unknown manual page

NAME

unknown - Handle attempts to use non-existent commands

SYNOPSIS

unknown cmdName ?arg arg ...?

DESCRIPTION

This command is invoked by the Tcl interpreter whenever a script tries to invoke a command that doesn't exist. The implementation of unknown isn't part of the Tcl core; instead, it is a library procedure defined by default when Tcl starts up. You can override the default unknown to change its functionality.

If the Tcl interpreter encounters a command name for which there is not a defined command, then Tcl checks for the existence of a command named unknown. If there is no such command, then the interpreter returns an error. If the unknown command exists, then it is invoked with arguments consisting of the fully-substituted name and arguments for the original non-existent command. The unknown command typically does things like searching through library directories for a command procedure with the name cmdName, or expanding abbreviated command names to full-length, or automatically executing unknown commands as sub-processes. In some cases (such as expanding abbreviations) unknown will change the original command slightly and then (re-)execute it. The result of the unknown command is used as the result for the original non-existent command.

The default implementation of unknown behaves as follows. It first calls the auto_load library procedure to load the command. If this succeeds, then it executes the original command with its original arguments. If the auto-load fails then unknown calls auto_execok to see if there is an executable file by the name cmd. If so, it invokes the Tcl exec command with cmd and all the args as arguments. If cmd can't be auto-executed, unknown checks to see if the command was invoked at top-level and outside of any script. If so, then unknown takes two additional steps. First, it sees if cmd has one of the following three forms: !!, !event, or ^old^new?^?. If so, then unknown carries out history substitution in the same way that csh would for these constructs. Finally, unknown checks to see if cmd is a unique abbreviation for an existing Tcl command. If so, it expands the command name and executes the command with the original arguments. If none of the above efforts has been able to execute the command, unknown generates an error return. If the global variable auto_noload is defined, then the auto-load step is skipped. If the global variable auto_noexec is defined then the auto-exec step is skipped. Under normal circumstances the return value from unknown is the return value from the command that was eventually executed.

SEE ALSO

info, proc

KEYWORDS

error, non-existent command
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - unset manual page

NAME

unset - Delete variables

SYNOPSIS

unset name ?name name ...?

DESCRIPTION

This command removes one or more variables. Each name is a variable name, specified in any of the ways acceptable to the set command. If a name refers to an element of an array then that element is removed without affecting the rest of the array. If a name consists of an array name with no parenthesized index, then the entire array is deleted. The unset command returns an empty string as result. An error occurs if any of the variables doesn't exist, and any variables after the non-existent one are not deleted.

KEYWORDS

remove, variable
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Built-In Commands - update manual page

NAME

update - Process pending events and idle callbacks

SYNOPSIS

update ?idletasks?

DESCRIPTION

This command is used to bring the application ``up to date'' by entering the event loop repeatedly until all pending events (including idle callbacks) have been processed.

If the idletasks keyword is specified as an argument to the command, then no new events or errors are processed; only idle callbacks are invoked. This causes operations that are normally deferred, such as display updates and window layout calculations, to be performed immediately.

The update idletasks command is useful in scripts where changes have been made to the application's state and you want those changes to appear on the display immediately, rather than waiting for the script to complete. Most display updates are performed as idle callbacks, so update idletasks will cause them to run. However, there are some kinds of updates that only happen in response to events, such as those triggered by window size changes; these updates will not occur in update idletasks.

The update command with no options is useful in scripts where you are performing a long-running computation but you still want the application to respond to events such as user interactions; if you occasionally call update then user input will be processed during the next call to update.

SEE ALSO

after, bgerror

KEYWORDS

event, flush, handler, idle, update
Copyright © 1990-1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - uplevel manual page

NAME

uplevel - Execute a script in a different stack frame

SYNOPSIS

uplevel ?level? arg ?arg ...?

DESCRIPTION

All of the arg arguments are concatenated as if they had been passed to concat; the result is then evaluated in the variable context indicated by level. Uplevel returns the result of that evaluation.

If level is an integer then it gives a distance (up the procedure calling stack) to move before executing the command. If level consists of # followed by a number then the number gives an absolute level number. If level is omitted then it defaults to 1. Level cannot be defaulted if the first command argument starts with a digit or #.

For example, suppose that procedure a was invoked from top-level, and that it called b, and that b called c. Suppose that c invokes the uplevel command. If level is 1 or #2 or omitted, then the command will be executed in the variable context of b. If level is 2 or #1 then the command will be executed in the variable context of a. If level is 3 or #0 then the command will be executed at top-level (only global variables will be visible).

The uplevel command causes the invoking procedure to disappear from the procedure calling stack while the command is being executed. In the above example, suppose c invokes the command

uplevel 1 {set x 43; d}
where d is another Tcl procedure. The set command will modify the variable x in b's context, and d will execute at level 3, as if called from b. If it in turn executes the command
uplevel {set x 42}
then the set command will modify the same variable x in b's context: the procedure c does not appear to be on the call stack when d is executing. The command ``info level'' may be used to obtain the level of the current procedure.

Uplevel makes it possible to implement new control constructs as Tcl procedures (for example, uplevel could be used to implement the while construct as a Tcl procedure).

namespace eval is another way (besides procedure calls) that the Tcl naming context can change. It adds a call frame to the stack to represent the namespace context. This means each namespace eval command counts as another call level for uplevel and upvar commands. For example, info level 1 will return a list describing a command that is either the outermost procedure call or the outermost namespace eval command. Also, uplevel #0 evaluates a script at top-level in the outermost namespace (the global namespace).

SEE ALSO

namespace, upvar

KEYWORDS

context, level, namespace, stack frame, variables
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Built-In Commands - upvar manual page

NAME

upvar - Create link to variable in a different stack frame

SYNOPSIS

upvar ?level? otherVar myVar ?otherVar myVar ...?

DESCRIPTION

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. Level may have any of the forms permitted for the uplevel command, and may be omitted if the first letter of the first otherVar isn't # or a digit (it defaults to 1). For each otherVar argument, upvar makes the variable by that name in the procedure frame given by level (or at global level, if level is #0) accessible in the current procedure by the name given in the corresponding myVar argument. The variable named by otherVar need not exist at the time of the call; it will be created the first time myVar is referenced, just like an ordinary variable. There must not exist a variable by the name myVar at the time upvar is invoked. MyVar is always treated as the name of a variable, not an array element. Even if the name looks like an array element, such as a(b), a regular variable is created. OtherVar may refer to a scalar variable, an array, or an array element. Upvar returns an empty string.

The upvar 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:

proc add2 name {
    upvar $name x
    set x [expr $x+2]
}
Add2 is invoked with an argument giving the name of a variable, and it adds two to the value of that variable. Although add2 could have been implemented using uplevel instead of upvar, upvar makes it simpler for add2 to access the variable in the caller's procedure frame.

namespace eval is another way (besides procedure calls) that the Tcl naming context can change. It adds a call frame to the stack to represent the namespace context. This means each namespace eval command counts as another call level for uplevel and upvar commands. For example, info level 1 will return a list describing a command that is either the outermost procedure call or the outermost namespace eval command. Also, uplevel #0 evaluates a script at top-level in the outermost namespace (the global namespace).

If an upvar variable is unset (e.g. x in add2 above), the unset operation affects the variable it is linked to, not the upvar variable. There is no way to unset an upvar variable except by exiting the procedure in which it is defined. However, it is possible to retarget an upvar variable by executing another upvar command.

Traces and upvar

Upvar interacts with traces in a straightforward but possibly unexpected manner. If a variable trace is defined on otherVar, that trace will be triggered by actions involving myVar. However, the trace procedure will be passed the name of myVar, rather than the name of otherVar. Thus, the output of the following code will be localVar rather than originalVar:
proc traceproc { name index op } {
    puts $name
}
proc setByUpvar { name value } {
    upvar $name localVar
    set localVar $value
}
set originalVar 1
trace variable originalVar w traceproc
setByUpvar originalVar 2
}
If otherVar refers to an element of an array, then variable traces set for the entire array will not be invoked when myVar is accessed (but traces on the particular element will still be invoked). In particular, if the array is env, then changes made to myVar will not be passed to subprocesses correctly.

SEE ALSO

global, namespace, uplevel, variable

KEYWORDS

context, frame, global, level, namespace, procedure, variable
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Built-In Commands - variable manual page

NAME

variable - create and initialize a namespace variable

SYNOPSIS

variable ?name value...? name ?value?

DESCRIPTION

This command is normally used within a namespace eval command to create one or more variables within a namespace. Each variable name is initialized with value. The value for the last variable is optional.

If a variable name does not exist, it is created. In this case, if value is specified, it is assigned to the newly created variable. If no value is specified, the new variable is left undefined. If the variable already exists, it is set to value if value is specified or left unchanged if no value is given. Normally, name is unqualified (does not include the names of any containing namespaces), and the variable is created in the current namespace. If name includes any namespace qualifiers, the variable is created in the specified namespace. If the variable is not defined, it will be visible to the namespace which command, but not to the info exists command.

If the variable command is executed inside a Tcl procedure, it creates local variables linked to the corresponding namespace variables (and therefore these variables are listed by info locals.) In this way the variable command resembles the global command, although the global command only links to variables in the global namespace. If any values are given, they are used to modify the values of the associated namespace variables. If a namespace variable does not exist, it is created and optionally initialized.

A name argument cannot reference an element within an array. Instead, name should reference the entire array, and the initialization value should be left off. After the variable has been declared, elements within the array can be set using ordinary set or array commands.

SEE ALSO

global, namespace, upvar

KEYWORDS

global, namespace, procedure, variable
Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
Copyright © 1997 Sun Microsystems, Inc.


Tcl Built-In Commands - vwait manual page

NAME

vwait - Process events until a variable is written

SYNOPSIS

vwait varName

DESCRIPTION

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 varName. Once varName has been set, the vwait command will return as soon as the event handler that modified varName completes. varName must globally scoped (either with a call to global for the varName, or with the full namespace path specification).

In some cases the vwait command may not return immediately after varName is set. This can happen if the event handler that sets varName does not complete immediately. For example, if an event handler sets varName and then itself calls vwait to wait for a different variable, then it may not return for a long time. During this time the top-level vwait is blocked waiting for the event handler to complete, so it cannot return either.

SEE ALSO

global

KEYWORDS

event, variable, wait
Copyright © 1995-1996 Sun Microsystems, Inc.


Built-In Commands - while manual page

NAME

while - Execute script repeatedly as long as a condition is met

SYNOPSIS

while test body

DESCRIPTION

The while command evaluates test as an expression (in the same way that expr evaluates its argument). The value of the expression must a proper boolean value; if it is a true value then body is executed by passing it to the Tcl interpreter. Once body has been executed then test is evaluated again, and the process repeats until eventually test evaluates to a false boolean value. Continue commands may be executed inside body to terminate the current iteration of the loop, and break commands may be executed inside body to cause immediate termination of the while command. The while command always returns an empty string.

Note: test should almost always be enclosed in braces. If not, variable substitutions will be made before the while command starts executing, which means that variable changes made by the loop body will not be considered in the expression. This is likely to result in an infinite loop. If test is enclosed in braces, variable substitutions are delayed until the 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 $x<10:

set x 0
while {$x<10} {
    puts "x is $x"
    incr x
}

SEE ALSO

break, continue, for, foreach

KEYWORDS

boolean value, loop, test, while
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Access manual page

NAME

Tcl_Access, Tcl_Stat - check file permissions and other attributes

SYNOPSIS

#include <tcl.h>
int
Tcl_Access(path, mode)
int
Tcl_Stat(path, statPtr)

ARGUMENTS

char *path (in)
Native name of the file to check the attributes of.

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.

stat *statPtr (out)
The structure that contains the result.

DESCRIPTION

There are two reasons for calling Tcl_Access and Tcl_Stat rather than calling system level functions access and stat directly. First, the Windows implementation of both functions fixes some bugs in the system level calls. Second, both Tcl_Access and Tcl_Stat (as well as Tcl_OpenFileChannelProc) hook into a linked list of functions. This allows the possibity to reroute file access to alternative media or access methods.

Tcl_Access 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.

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.

Tcl_Stat fills the stat structure statPtr 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), priviledge 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.

If path exists, Tcl_Stat returns 0 and the stat structure is filled with data. Otherwise, -1 is returned, and no stat info is given.

KEYWORDS

stat access
Copyright © 1998-1999 Scriptics Corportation


Tcl Library Procedures - Tcl_AddErrorInfo manual page

NAME

Tcl_AddObjErrorInfo, Tcl_AddErrorInfo, Tcl_SetObjErrorCode, Tcl_SetErrorCode, Tcl_SetErrorCodeVA, Tcl_PosixError, Tcl_LogCommandInfo - record information about errors

SYNOPSIS

#include <tcl.h>
Tcl_AddObjErrorInfo(interp, message, length)
Tcl_AddErrorInfo(interp, message)
Tcl_SetObjErrorCode(interp, errorObjPtr)
Tcl_SetErrorCode(interp, element, element, ... (char *) NULL)
Tcl_SetErrorCodeVA(interp, argList)
char *
Tcl_PosixError(interp)
void
Tcl_LogCommandInfo(interp, script, command, commandLength)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which to record information.

char *message (in)
For Tcl_AddObjErrorInfo, this points to the first byte of an array of bytes containing a string to record in the errorInfo variable. This byte array may contain embedded null bytes unless length is negative. For Tcl_AddErrorInfo, this is a conventional C string to record in the errorInfo variable.

int length (in)
The number of bytes to copy from message when setting the errorInfo variable. If negative, all bytes up to the first null byte are used.

Tcl_Obj *errorObjPtr (in)
This variable errorCode will be set to this value.

char *element (in)
String to record as one element of errorCode variable. Last element argument must be NULL.

va_list argList (in)
An argument list which must have been initialised using TCL_VARARGS_START, and cleared using va_end.

char *script (in)
Pointer to first character in script containing command (must be <= command)

char *command (in)
Pointer to first character in command that generated the error

int commandLength (in)
Number of bytes in command; -1 means use all bytes up to first NULL byte

DESCRIPTION

These procedures are used to manipulate two Tcl global variables that hold information about errors. The variable errorInfo holds a stack trace of the operations that were in progress when an error occurred, and is intended to be human-readable. The variable errorCode holds a list of items that are intended to be machine-readable. The first item in errorCode identifies the class of error that occurred (e.g. POSIX means an error occurred in a POSIX system call) and additional elements in errorCode hold additional pieces of information that depend on the class. See the Tcl overview manual entry for details on the various formats for errorCode.

The errorInfo variable is gradually built up as an error unwinds through the nested operations. Each time an error code is returned to Tcl_EvalObjEx (or Tcl_Eval, which calls Tcl_EvalObjEx) it calls the procedure Tcl_AddObjErrorInfo to add additional text to errorInfo describing the command that was being executed when the error occurred. By the time the error has been passed all the way back to the application, it will contain a complete trace of the activity in progress when the error occurred.

It is sometimes useful to add additional information to errorInfo beyond what can be supplied automatically by Tcl_EvalObjEx. Tcl_AddObjErrorInfo may be used for this purpose: its message and length arguments describe an additional string to be appended to errorInfo. For example, the source command calls Tcl_AddObjErrorInfo to record the name of the file being processed and the line number on which the error occurred; for Tcl procedures, the procedure name and line number within the procedure are recorded, and so on. The best time to call Tcl_AddObjErrorInfo is just after Tcl_EvalObjEx has returned TCL_ERROR. In calling Tcl_AddObjErrorInfo, you may find it useful to use the errorLine field of the interpreter (see the Tcl_Interp manual entry for details).

Tcl_AddErrorInfo resembles Tcl_AddObjErrorInfo but differs in initializing errorInfo from the string value of the interpreter's result if the error is just starting to be logged. It does not use the result as a Tcl object so any embedded null characters in the result will cause information to be lost. It also takes a conventional C string in message instead of Tcl_AddObjErrorInfo's counted string.

The procedure Tcl_SetObjErrorCode is used to set the errorCode variable. errorObjPtr contains a list object built up by the caller. errorCode is set to this value. Tcl_SetObjErrorCode is typically invoked just before returning an error in an object command. If an error is returned without calling Tcl_SetObjErrorCode or Tcl_SetErrorCode the Tcl interpreter automatically sets errorCode to NONE.

The procedure Tcl_SetErrorCode is also used to set the errorCode variable. However, it takes one or more strings to record instead of an object. Otherwise, it is similar to Tcl_SetObjErrorCode in behavior.

Tcl_SetErrorCodeVA is the same as Tcl_SetErrorCode except that instead of taking a variable number of arguments it takes an argument list.

Tcl_PosixError sets the errorCode variable after an error in a POSIX kernel call. It reads the value of the errno C variable and calls Tcl_SetErrorCode to set errorCode in the POSIX format. The caller must previously have called Tcl_SetErrno to set errno; this is necessary on some platforms (e.g. Windows) where Tcl is linked into an application as a shared library, or when the error occurs in a dynamically loaded extension. See the manual entry for Tcl_SetErrno for more information.

Tcl_PosixError returns a human-readable diagnostic message for the error (this is the same value that will appear as the third element in errorCode). It may be convenient to include this string as part of the error message returned to the application in the interpreter's result.

Tcl_LogCommandInfo is invoked after an error occurs in an interpreter. It adds information about the command that was being executed when the error occured to the errorInfo variable, and the line number stored internally in the interpreter is set. On the first call to Tcl_LogCommandInfo or Tcl_AddObjErrorInfo since an error occurred, the old information in errorInfo is deleted.

It is important to call the procedures described here rather than setting errorInfo or errorCode directly with Tcl_ObjSetVar2. The reason for this is that the Tcl interpreter keeps information about whether these procedures have been called. For example, the first time Tcl_AddObjErrorInfo is called for an error, it clears the existing value of errorInfo and adds the error message in the interpreter's result to the variable before appending message; in subsequent calls, it just appends the new message. When Tcl_SetErrorCode is called, it sets a flag indicating that errorCode has been set; this allows the Tcl interpreter to set errorCode to NONE if it receives an error return when Tcl_SetErrorCode hasn't been called.

If the procedure Tcl_ResetResult is called, it clears all of the state associated with errorInfo and errorCode (but it doesn't actually modify the variables). If an error had occurred, this will clear the error state to make it appear as if no error had occurred after all.

SEE ALSO

Tcl_DecrRefCount, Tcl_IncrRefCount, Tcl_Interp, Tcl_ResetResult, Tcl_SetErrno

KEYWORDS

error, object, object result, stack, trace, variable
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Alloc manual page

NAME

Tcl_Alloc, Tcl_Free, Tcl_Realloc - allocate or free heap memory

SYNOPSIS

#include <tcl.h>
char *
Tcl_Alloc(size)
Tcl_Free(ptr)
char *
Tcl_Realloc(ptr, size)

ARGUMENTS

int size (in)
Size in bytes of the memory block to allocate.

char *ptr (in)
Pointer to memory block to free or realloc.

DESCRIPTION

These procedures provide a platform and compiler independent interface for memory allocation. Programs that need to transfer ownership of memory blocks between Tcl and other modules should use these routines rather than the native malloc() and free() routines provided by the C run-time library.

Tcl_Alloc returns a pointer to a block of at least size bytes suitably aligned for any use.

Tcl_Free makes the space referred to by ptr available for further allocation.

Tcl_Realloc changes the size of the block pointed to by ptr to size bytes and returns a pointer to the new block. The contents will be unchanged up to the lesser of the new and old sizes. The returned location may be different from ptr.

KEYWORDS

alloc, allocation, free, malloc, memory, realloc
Copyright © 1995-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_AllowExceptions manual page

NAME

Tcl_AllowExceptions - allow all exceptions in next script evaluation

SYNOPSIS

#include <tcl.h>
Tcl_AllowExceptions(interp)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which script will be evaluated.

DESCRIPTION

If a script is evaluated at top-level (i.e. no other scripts are pending evaluation when the script is invoked), and if the script terminates with a completion code other than TCL_OK, TCL_CONTINUE or TCL_RETURN, then Tcl normally converts this into a TCL_ERROR return with an appropriate message.

However, if Tcl_AllowExceptions is invoked immediately before calling a procedure such as Tcl_Eval, then arbitrary completion codes are permitted from the script, and they are returned without modification. This is useful in cases where the caller can deal with exceptions such as TCL_BREAK or TCL_CONTINUE in a meaningful way.

KEYWORDS

continue, break, exception, interpreter
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_AppInit manual page

NAME

Tcl_AppInit - perform application-specific initialization

SYNOPSIS

#include <tcl.h>
int
Tcl_AppInit(interp)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter for the application.

DESCRIPTION

Tcl_AppInit is a ``hook'' procedure that is invoked by the main programs for Tcl applications such as tclsh and wish. Its purpose is to allow new Tcl applications to be created without modifying the main programs provided as part of Tcl and Tk. To create a new application you write a new version of Tcl_AppInit to replace the default version provided by Tcl, then link your new Tcl_AppInit with the Tcl library.

Tcl_AppInit is invoked after by Tcl_Main and Tk_Main after their own initialization and before entering the main loop to process commands. Here are some examples of things that Tcl_AppInit might do:

[1]
Call initialization procedures for various packages used by the application. Each initialization procedure adds new commands to interp for its package and performs other package-specific initialization.

[2]
Process command-line arguments, which can be accessed from the Tcl variables argv and argv0 in interp.

[3]
Invoke a startup script to initialize the application.

Tcl_AppInit returns TCL_OK or TCL_ERROR. If it returns TCL_ERROR then it must leave an error message in for the interpreter's result; otherwise the result is ignored.

In addition to Tcl_AppInit, your application should also contain a procedure main that calls Tcl_Main as follows:

Tcl_Main(argc, argv, Tcl_AppInit);
The third argument to Tcl_Main gives the address of the application-specific initialization procedure to invoke. This means that you don't have to use the name Tcl_AppInit for the procedure, but in practice the name is nearly always Tcl_AppInit (in versions before Tcl 7.4 the name Tcl_AppInit was implicit; there was no way to specify the procedure explicitly). The best way to get started is to make a copy of the file tclAppInit.c from the Tcl library or source directory. It already contains a main procedure and a template for Tcl_AppInit that you can modify for your application.

KEYWORDS

application, argument, command, initialization, interpreter
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_SetAssocData manual page

NAME

Tcl_GetAssocData, Tcl_SetAssocData, Tcl_DeleteAssocData - manage associations of string keys and user specified data with Tcl interpreters.

SYNOPSIS

#include <tcl.h>
ClientData
Tcl_GetAssocData(interp, key, delProcPtr)
Tcl_SetAssocData(interp, key, delProc, clientData)
Tcl_DeleteAssocData(interp, key)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which to execute the specified command.

char *key (in)
Key for association with which to store data or from which to delete or retrieve data. Typically the module prefix for a package.

Tcl_InterpDeleteProc *delProc (in)
Procedure to call when interp is deleted.

Tcl_InterpDeleteProc **delProcPtr (in)
Pointer to location in which to store address of current deletion procedure for association. Ignored if NULL.

ClientData clientData (in)
Arbitrary one-word value associated with the given key in this interpreter. This data is owned by the caller.

DESCRIPTION

These procedures allow extensions to associate their own data with a Tcl interpreter. An association consists of a string key, typically the name of the extension, and a one-word value, which is typically a pointer to a data structure holding data specific to the extension. Tcl makes no interpretation of either the key or the value for an association.

Storage management is facilitated by storing with each association a procedure to call when the interpreter is deleted. This procedure can dispose of the storage occupied by the client's data in any way it sees fit.

Tcl_SetAssocData creates an association between a string key and a user specified datum in the given interpreter. If there is already an association with the given key, Tcl_SetAssocData overwrites it with the new information. It is up to callers to organize their use of names to avoid conflicts, for example, by using package names as the keys. If the deleteProc argument is non-NULL it specifies the address of a procedure to invoke if the interpreter is deleted before the association is deleted. DeleteProc should have arguments and result that match the type Tcl_InterpDeleteProc:

typedef void Tcl_InterpDeleteProc(
    ClientData clientData,
    Tcl_Interp *interp);
When deleteProc is invoked the clientData and interp arguments will be the same as the corresponding arguments passed to Tcl_SetAssocData. The deletion procedure will not be invoked if the association is deleted before the interpreter is deleted.

Tcl_GetAssocData returns the datum stored in the association with the specified key in the given interpreter, and if the delProcPtr field is non-NULL, the address indicated by it gets the address of the delete procedure stored with this association. If no association with the specified key exists in the given interpreter Tcl_GetAssocData returns NULL.

Tcl_DeleteAssocData deletes an association with a specified key in the given interpreter. Then it calls the deletion procedure.

KEYWORDS

association, data, deletion procedure, interpreter, key
Copyright © 1995-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_AsyncCreate manual page

NAME

Tcl_AsyncCreate, Tcl_AsyncMark, Tcl_AsyncInvoke, Tcl_AsyncDelete, Tcl_AsyncReady - handle asynchronous events

SYNOPSIS

#include <tcl.h>
Tcl_AsyncHandler
Tcl_AsyncCreate(proc, clientData)
Tcl_AsyncMark(async)
int
Tcl_AsyncInvoke(interp, code)
Tcl_AsyncDelete(async)
int
Tcl_AsyncReady()

ARGUMENTS

Tcl_AsyncProc *proc (in)
Procedure to invoke to handle an asynchronous event.

ClientData clientData (in)
One-word value to pass to proc.

Tcl_AsyncHandler async (in)
Token for asynchronous event handler.

Tcl_Interp *interp (in)
Tcl interpreter in which command was being evaluated when handler was invoked, or NULL if handler was invoked when there was no interpreter active.

int code (in)
Completion code from command that just completed in interp, or 0 if interp is NULL.

DESCRIPTION

These procedures provide a safe mechanism for dealing with asynchronous events such as signals. If an event such as a signal occurs while a Tcl script is being evaluated then it isn't safe to take any substantive action to process the event. For example, it isn't safe to evaluate a Tcl script since the interpreter may already be in the middle of evaluating a script; it may not even be safe to allocate memory, since a memory allocation could have been in progress when the event occurred. The only safe approach is to set a flag indicating that the event occurred, then handle the event later when the world has returned to a clean state, such as after the current Tcl command completes.

Tcl_AsyncCreate, Tcl_AsyncDelete, and Tcl_AsyncReady are thread sensitive. They access and/or set a thread-specific data structure in the event of an --enable-thread built core. The token created by Tcl_AsyncCreate contains the needed thread information it was called from so that calling Tcl_AsyncMark(token) will only yield the origin thread into the AsyncProc.

Tcl_AsyncCreate creates an asynchronous handler and returns a token for it. The asynchronous handler must be created before any occurrences of the asynchronous event that it is intended to handle (it is not safe to create a handler at the time of an event). When an asynchronous event occurs the code that detects the event (such as a signal handler) should call Tcl_AsyncMark with the token for the handler. Tcl_AsyncMark will mark the handler as ready to execute, but it will not invoke the handler immediately. Tcl will call the proc associated with the handler later, when the world is in a safe state, and proc can then carry out the actions associated with the asynchronous event. Proc should have arguments and result that match the type Tcl_AsyncProc:

typedef int Tcl_AsyncProc(
    ClientData clientData,
    Tcl_Interp *interp,
    int code);
The clientData will be the same as the clientData argument passed to Tcl_AsyncCreate when the handler was created. If proc is invoked just after a command has completed execution in an interpreter, then interp will identify the interpreter in which the command was evaluated and code will be the completion code returned by that command. The command's result will be present in the interpreter's result. When proc returns, whatever it leaves in the interpreter's result will be returned as the result of the command and the integer value returned by proc will be used as the new completion code for the command.

It is also possible for proc to be invoked when no interpreter is active. This can happen, for example, if an asynchronous event occurs while the application is waiting for interactive input or an X event. In this case interp will be NULL and code will be 0, and the return value from proc will be ignored.

The procedure Tcl_AsyncInvoke is called to invoke all of the handlers that are ready. The procedure Tcl_AsyncReady will return non-zero whenever any asynchronous handlers are ready; it can be checked to avoid calls to Tcl_AsyncInvoke when there are no ready handlers. Tcl calls Tcl_AsyncReady after each command is evaluated and calls Tcl_AsyncInvoke if needed. Applications may also call Tcl_AsyncInvoke at interesting times for that application. For example, Tcl's event handler calls Tcl_AsyncReady after each event and calls Tcl_AsyncInvoke if needed. The interp and code arguments to Tcl_AsyncInvoke have the same meaning as for proc: they identify the active interpreter, if any, and the completion code from the command that just completed.

Tcl_AsyncDelete removes an asynchronous handler so that its proc will never be invoked again. A handler can be deleted even when ready, and it will still not be invoked.

If multiple handlers become active at the same time, the handlers are invoked in the order they were created (oldest handler first). The code and the interpreter's result for later handlers reflect the values returned by earlier handlers, so that the most recently created handler has last say about the interpreter's result and completion code. If new handlers become ready while handlers are executing, Tcl_AsyncInvoke will invoke them all; at each point it invokes the highest-priority (oldest) ready handler, repeating this over and over until there are no longer any ready handlers.

WARNING

It is almost always a bad idea for an asynchronous event handler to modify the interpreter's result or return a code different from its code argument. This sort of behavior can disrupt the execution of scripts in subtle ways and result in bugs that are extremely difficult to track down. If an asynchronous event handler needs to evaluate Tcl scripts then it should first save the interpreter's result plus the values of the variables errorInfo and errorCode (this can be done, for example, by storing them in dynamic strings). When the asynchronous handler is finished it should restore the interpreter's result, errorInfo, and errorCode, and return the code argument.

KEYWORDS

asynchronous event, handler, signal
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_BackgroundError manual page

NAME

Tcl_BackgroundError - report Tcl error that occurred in background processing

SYNOPSIS

#include <tcl.h>
Tcl_BackgroundError(interp)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which the error occurred.

DESCRIPTION

This procedure is typically invoked when a Tcl error occurs during ``background processing'' such as executing an event handler. When such an error occurs, the error 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 Tcl_BackgroundError with an interp argument identifying the interpreter in which the error occurred. At the time Tcl_BackgroundError is invoked, the interpreter's result is expected to contain an error message. Tcl_BackgroundError will invoke the bgerror Tcl command to report the error in an application-specific fashion. If no bgerror command exists, or if it returns with an error condition, then Tcl_BackgroundError reports the error itself by printing a message on the standard error file.

Tcl_BackgroundError does not invoke bgerror immediately because this could potentially interfere with scripts that are in process at the time the error occurred. Instead, it invokes bgerror later as an idle callback. Tcl_BackgroundError saves the values of the errorInfo and errorCode variables and restores these values just before invoking bgerror.

It is possible for many background errors to accumulate before bgerror is invoked. When this happens, each of the errors is processed in order. However, if bgerror returns a break exception, then all remaining error reports for the interpreter are skipped.

KEYWORDS

background, bgerror, error
Copyright © 1992-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Backslash manual page

NAME

Tcl_Backslash - parse a backslash sequence

SYNOPSIS

#include <tcl.h>
char
Tcl_Backslash(src, countPtr)

ARGUMENTS

char *src (in)
Pointer to a string starting with a backslash.

int *countPtr (out)
If countPtr isn't NULL, *countPtr gets filled in with number of characters in the backslash sequence, including the backslash character.

DESCRIPTION

The use of Tcl_Backslash is deprecated in favor of Tcl_UtfBackslash.

This is a utility procedure provided for backwards compatibilty with non-internationalized Tcl extensions. It parses a backslash sequence and returns the low byte of the Unicode character corresponding to the sequence. Tcl_Backslash modifies *countPtr to contain the number of characters in the backslash sequence.

See the Tcl manual entry for information on the valid backslash sequences. All of the sequences described in the Tcl manual entry are supported by Tcl_Backslash.

SEE ALSO

Tcl, Tcl_UtfBackslash

KEYWORDS

backslash, parse
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_BooleanObj manual page

NAME

Tcl_NewBooleanObj, Tcl_SetBooleanObj, Tcl_GetBooleanFromObj - manipulate Tcl objects as boolean values

SYNOPSIS

#include <tcl.h>
Tcl_Obj *
Tcl_NewBooleanObj(boolValue)
Tcl_SetBooleanObj(objPtr, boolValue)
int
Tcl_GetBooleanFromObj(interp, objPtr, boolPtr)

ARGUMENTS

int boolValue (in)
Integer value used to initialize or set a boolean object. If the integer is nonzero, the boolean object is set to 1; otherwise the boolean object is set to 0.

Tcl_Obj *objPtr (in/out)
For Tcl_SetBooleanObj, this points to the object to be converted to boolean type. For Tcl_GetBooleanFromObj, this refers to the object from which to get a boolean value; if objPtr does not already point to a boolean object, an attempt will be made to convert it to one.

Tcl_Interp *interp (in/out)
If an error occurs during conversion, an error message is left in the interpreter's result object unless interp is NULL.

int *boolPtr (out)
Points to place where Tcl_GetBooleanFromObj stores the boolean value (0 or 1) obtained from objPtr.

DESCRIPTION

These procedures are used to create, modify, and read boolean Tcl objects from C code. Tcl_NewBooleanObj and Tcl_SetBooleanObj will create a new object of boolean type or modify an existing object to have boolean type. Both of these procedures set the object to have the boolean value (0 or 1) specified by boolValue; if boolValue is nonzero, the object is set to 1, otherwise to 0. Tcl_NewBooleanObj returns a pointer to a newly created object with reference count zero. Both procedures set the object's type to be boolean and assign the boolean value to the object's internal representation longValue member. Tcl_SetBooleanObj invalidates any old string representation and, if the object is not already a boolean object, frees any old internal representation.

Tcl_GetBooleanFromObj attempts to return a boolean value from the Tcl object objPtr. If the object is not already a boolean object, it will attempt to convert it to one. If an error occurs during conversion, it returns TCL_ERROR and leaves an error message in the interpreter's result object unless interp is NULL. Otherwise, Tcl_GetBooleanFromObj returns TCL_OK and stores the boolean value in the address given by boolPtr. If the object is not already a boolean object, the conversion will free any old internal representation.

SEE ALSO

Tcl_NewObj, Tcl_DecrRefCount, Tcl_IncrRefCount, Tcl_GetObjResult

KEYWORDS

boolean, boolean object, boolean type, internal representation, object, object type, string representation
Copyright © 1996-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_ByteArrayObj manual page

NAME

Tcl_NewByteArrayObj, Tcl_SetByteArrayObj, Tcl_GetByteArrayFromObj, Tcl_SetByteArrayLength - manipulate Tcl objects as a arrays of bytes

SYNOPSIS

#include <tcl.h>
Tcl_Obj *
Tcl_NewByteArrayObj(bytes, length)
void
Tcl_SetByteArrayObj(objPtr, bytes, length)
unsigned char *
Tcl_GetByteArrayFromObj(objPtr, lengthPtr)
unsigned char *
Tcl_SetByteArrayLength(objPtr, length)

ARGUMENTS

unsigned char *bytes (in)
The array of bytes used to initialize or set a byte-array object.

int length (in)
The length of the array of bytes. It must be >= 0.

Tcl_Obj *objPtr (in/out)
For Tcl_SetByteArrayObj, this points to the object to be converted to byte-array type. For Tcl_GetByteArrayFromObj and Tcl_SetByteArrayLength, this points to the object from which to get the byte-array value; if objPtr does not already point to a byte-array object, it will be converted to one.

int *lengthPtr (out)
If non-NULL, filled with the length of the array of bytes in the object.

DESCRIPTION

These procedures are used to create, modify, and read Tcl byte-array objects from C code. Byte-array objects are typically used to hold the results of binary IO operations or data structures created with the binary command. In Tcl, an array of bytes is not equivalent to a string. Conceptually, a string is an array of Unicode characters, while a byte-array is an array of 8-bit quantities with no implicit meaning. Accesser functions are provided to get the string representation of a byte-array or to convert an arbitrary object to a byte-array. Obtaining the string representation of a byte-array object (by calling Tcl_GetStringFromObj) 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.

Tcl_NewByteArrayObj and Tcl_SetByteArrayObj will create a new object of byte-array type or modify an existing object to have a byte-array type. Both of these procedures set the object's type to be byte-array and set the object's internal representation to a copy of the array of bytes given by bytes. Tcl_NewByteArrayObj returns a pointer to a newly allocated object with a reference count of zero. Tcl_SetByteArrayObj invalidates any old string representation and, if the object is not already a byte-array object, frees any old internal representation.

Tcl_GetByteArrayFromObj converts a Tcl object to byte-array type and returns a pointer to the object's new internal representation as an array of bytes. The length of this array is stored in lengthPtr if lengthPtr 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.

Tcl_SetByteArrayLength converts the Tcl object to byte-array type and changes the length of the object's internal representation as an array of bytes. If length is greater than the space currently allocated for the array, the array is reallocated to the new length; the newly allocated bytes at the end of the array have arbitrary values. If length is less than the space currently allocated for the array, the length of array is reduced to the new length. The return value is a pointer to the object's new array of bytes.

SEE ALSO

Tcl_GetStringFromObj, Tcl_NewObj, Tcl_IncrRefCount, Tcl_DecrRefCount

KEYWORDS

object, byte array, utf, unicode, internationalization
Copyright © 1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_CallWhenDeleted manual page

NAME

Tcl_CallWhenDeleted, Tcl_DontCallWhenDeleted - Arrange for callback when interpreter is deleted

SYNOPSIS

#include <tcl.h>
Tcl_CallWhenDeleted(interp, proc, clientData)
Tcl_DontCallWhenDeleted(interp, proc, clientData)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter with which to associated callback.

Tcl_InterpDeleteProc *proc (in)
Procedure to call when interp is deleted.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

Tcl_CallWhenDeleted arranges for proc to be called by Tcl_DeleteInterp if/when interp is deleted at some future time. Proc will be invoked just before the interpreter is deleted, but the interpreter will still be valid at the time of the call. Proc should have arguments and result that match the type Tcl_InterpDeleteProc:
typedef void Tcl_InterpDeleteProc(
    ClientData clientData,
    Tcl_Interp *interp);
The clientData and interp parameters are copies of the clientData and interp arguments given to Tcl_CallWhenDeleted. Typically, clientData points to an application-specific data structure that proc uses to perform cleanup when an interpreter is about to go away. Proc does not return a value.

Tcl_DontCallWhenDeleted cancels a previous call to Tcl_CallWhenDeleted with the same arguments, so that proc won't be called after all when interp is deleted. If there is no deletion callback that matches interp, proc, and clientData then the call to Tcl_DontCallWhenDeleted has no effect.

KEYWORDS

callback, delete, interpreter
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_StackChannel manual page

NAME

Tcl_StackChannel, Tcl_UnstackChannel, Tcl_GetStackedChannel - stack an I/O channel on top of another, and undo it

SYNOPSIS

#include <tcl.h>
Tcl_Channel
Tcl_StackChannel(interp, typePtr, clientData, mask, channel)
int
Tcl_UnstackChannel(interp, channel)
Tcl_Channel
Tcl_GetStackedChannel(channel)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter for error reporting - can be NULL.

Tcl_ChannelType *typePtr (in)
The new channel I/O procedures to use for channel.

ClientData clientData (in)
Arbitrary one-word value to pass to channel I/O procedures.

int mask (in)
Conditions under which channel will be used: OR-ed combination of TCL_READABLE, TCL_WRITABLE and TCL_EXCEPTION. This can be a subset of the operations currently allowed on channel.

Tcl_Channel channel (in)
An existing Tcl channel such as returned by Tcl_CreateChannel.

DESCRIPTION

These functions are for use by extensions that add processing layers to Tcl I/O channels. Examples include compression and encryption modules. These functions transparently stack and unstack a new channel on top of an existing one. Any number of channels can be stacked together.

The implementation of the Tcl channel code was rewritten in 8.3.2 to correct some problems with the previous implementation with regard to stacked channels. Anyone using stacked channels or creating stacked channel drivers should update to the new TCL_CHANNEL_VERSION_2 Tcl_ChannelType structure. See Tcl_CreateChannel for details.

Tcl_StackChannel stacks a new channel on an existing channel with the same name that was registered for channel by Tcl_RegisterChannel.

Tcl_StackChannel works by creating a new channel structure and placing itself on top of the channel stack. EOL translation, encoding and buffering options are shared between all channels in the stack. The hidden channel does no buffering, newline translations, or character set encoding. Instead, the buffering, newline translations, and encoding functions all remain at the top of the channel stack. A pointer to the new top channel structure is returned. If an error occurs when stacking the channel, NULL is returned instead.

The mask parameter specifies the operations that are allowed on the new channel. These can be a subset of the operations allowed on the original channel. For example, a read-write channel may become read-only after the Tcl_StackChannel call.

Closing a channel closes the channels stacked below it. The close of stacked channels is executed in a way that allows buffered data to be properly flushed.

Tcl_UnstackChannel reverses the process. The old channel is associated with the channel name, and the processing module added by Tcl_StackChannel is destroyed. If there is no old channel, then Tcl_UnstackChannel is equivalent to Tcl_Close. If an error occurs unstacking the channel, TCL_ERROR is returned, otherwise TCL_OK is returned.

SEE ALSO

Notifier, Tcl_CreateChannel, Tcl_OpenFileChannel, vwait(n).

KEYWORDS

channel, compression
Copyright © 1999-2000 Ajuba Solutions.


Library Procedures - Tcl_CommandComplete manual page

NAME

Tcl_CommandComplete - Check for unmatched braces in a Tcl command

SYNOPSIS

#include <tcl.h>
int
Tcl_CommandComplete(cmd)

ARGUMENTS

char *cmd (in)
Command string to test for completeness.

DESCRIPTION

Tcl_CommandComplete takes a Tcl command string as argument and determines whether it contains one or more complete commands (i.e. there are no unclosed quotes, braces, brackets, or variable references). If the command string is complete then it returns 1; otherwise it returns 0.

KEYWORDS

complete command, partial command
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Concat manual page

NAME

Tcl_Concat - concatenate a collection of strings

SYNOPSIS

#include <tcl.h>
char *
Tcl_Concat(argc, argv)

ARGUMENTS

int argc (in)
Number of strings.

char *argv[] (in)
Array of strings to concatenate. Must have argc entries.

DESCRIPTION

Tcl_Concat is a utility procedure used by several of the Tcl commands. Given a collection of strings, it concatenates them together into a single string, with the original strings separated by spaces. This procedure behaves differently than Tcl_Merge, in that the arguments are simply concatenated: no effort is made to ensure proper list structure. However, in most common usage the arguments will all be proper lists themselves; if this is true, then the result will also have proper list structure.

Tcl_Concat eliminates leading and trailing white space as it copies strings from argv to the result. If an element of argv consists of nothing but white space, then that string is ignored entirely. This white-space removal was added to make the output of the concat command cleaner-looking.

The result string is dynamically allocated using Tcl_Alloc; the caller must eventually release the space by calling Tcl_Free.

SEE ALSO

Tcl_ConcatObj

KEYWORDS

concatenate, strings
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_CreateChannel manual page

NAME
Tcl_CreateChannel, Tcl_GetChannelInstanceData, Tcl_GetChannelType, Tcl_GetChannelName, Tcl_GetChannelHandle, Tcl_GetChannelMode, Tcl_GetChannelBufferSize, Tcl_SetChannelBufferSize, Tcl_NotifyChannel, Tcl_BadChannelOption, Tcl_ChannelName, Tcl_ChannelVersion, Tcl_ChannelBlockModeProc, Tcl_ChannelCloseProc, Tcl_ChannelClose2Proc, Tcl_ChannelInputProc, Tcl_ChannelOutputProc, Tcl_ChannelSeekProc, Tcl_ChannelSetOptionProc, Tcl_ChannelGetOptionProc, Tcl_ChannelWatchProc, Tcl_ChannelGetHandleProc, Tcl_ChannelFlushProc, Tcl_ChannelHandlerProc, - procedures for creating and manipulating channels
SYNOPSIS
ARGUMENTS
DESCRIPTION
TCL_CHANNELTYPE
TYPENAME
VERSION
BLOCKMODEPROC
CLOSEPROC AND CLOSE2PROC
INPUTPROC
OUTPUTPROC
SEEKPROC
SETOPTIONPROC
GETOPTIONPROC
WATCHPROC
GETHANDLEPROC
FLUSHPROC
HANDLERPROC
TCL_BADCHANNELOPTION
OLD_CHANNEL
SEE ALSO
KEYWORDS

NAME

Tcl_CreateChannel, Tcl_GetChannelInstanceData, Tcl_GetChannelType, Tcl_GetChannelName, Tcl_GetChannelHandle, Tcl_GetChannelMode, Tcl_GetChannelBufferSize, Tcl_SetChannelBufferSize, Tcl_NotifyChannel, Tcl_BadChannelOption, Tcl_ChannelName, Tcl_ChannelVersion, Tcl_ChannelBlockModeProc, Tcl_ChannelCloseProc, Tcl_ChannelClose2Proc, Tcl_ChannelInputProc, Tcl_ChannelOutputProc, Tcl_ChannelSeekProc, Tcl_ChannelSetOptionProc, Tcl_ChannelGetOptionProc, Tcl_ChannelWatchProc, Tcl_ChannelGetHandleProc, Tcl_ChannelFlushProc, Tcl_ChannelHandlerProc, - procedures for creating and manipulating channels

SYNOPSIS

#include <tcl.h>
Tcl_Channel
Tcl_CreateChannel(typePtr, channelName, instanceData, mask)
ClientData
Tcl_GetChannelInstanceData(channel)
Tcl_ChannelType *
Tcl_GetChannelType(channel)
char *
Tcl_GetChannelName(channel)
int
Tcl_GetChannelHandle(channel, direction, handlePtr)
int
Tcl_GetChannelBufferSize(channel)
Tcl_SetChannelBufferSize(channel, size)
Tcl_NotifyChannel(channel, mask)
int
Tcl_BadChannelOption(interp, optionName, optionList)
char *
Tcl_ChannelName(typePtr)
Tcl_ChannelTypeVersion
Tcl_ChannelVersion(typePtr)
Tcl_DriverBlockModeProc *
Tcl_ChannelBlockModeProc(typePtr)
Tcl_DriverCloseProc *
Tcl_ChannelCloseProc(typePtr)
Tcl_DriverClose2Proc *
Tcl_ChannelClose2Proc(typePtr)
Tcl_DriverInputProc *
Tcl_ChannelInputProc(typePtr)
Tcl_DriverOutputProc *
Tcl_ChannelOutputProc(typePtr)
Tcl_DriverSeekProc *
Tcl_ChannelSeekProc(typePtr)
Tcl_DriverSetOptionProc *
Tcl_ChannelSetOptionProc(typePtr)
Tcl_DriverGetOptionProc *
Tcl_ChannelGetOptionProc(typePtr)
Tcl_DriverWatchProc *
Tcl_ChannelWatchProc(typePtr)
Tcl_DriverGetHandleProc *
Tcl_ChannelGetHandleProc(typePtr)
Tcl_DriverFlushProc *
Tcl_ChannelFlushProc(typePtr)
Tcl_DriverHandlerProc *
Tcl_ChannelHandlerProc(typePtr)

ARGUMENTS

Tcl_ChannelType *typePtr (in)
Points to a structure containing the addresses of procedures that can be called to perform I/O and other functions on the channel.

char *channelName (in)
The name of this channel, such as file3; must not be in use by any other channel. Can be NULL, in which case the channel is created without a name.

ClientData instanceData (in)
Arbitrary one-word value to be associated with this channel. This value is passed to procedures in typePtr when they are invoked.

int mask (in)
OR-ed combination of TCL_READABLE and TCL_WRITABLE to indicate whether a channel is readable and writable.

Tcl_Channel channel (in)
The channel to operate on.

int direction (in)
TCL_READABLE means the input handle is wanted; TCL_WRITABLE means the output handle is wanted.

ClientData *handlePtr (out)
Points to the location where the desired OS-specific handle should be stored.

Tcl_EolTranslation transMode (in)
The translation mode; one of the constants TCL_TRANSLATE_AUTO, TCL_TRANSLATE_CR, TCL_TRANSLATE_LF and TCL_TRANSLATE_CRLF.

int size (in)
The size, in bytes, of buffers to allocate in this channel.

int mask (in)
An OR-ed combination of TCL_READABLE, TCL_WRITABLE and TCL_EXCEPTION that indicates events that have occurred on this channel.

Tcl_Interp *interp (in)
Current interpreter. (can be NULL)

char *optionName (in)
Name of the invalid option.

char *optionList (in)
Specific options list (space separated words, without "-") to append to the standard generic options list. Can be NULL for generic options error message only.

DESCRIPTION

Tcl uses a two-layered channel architecture. It provides a generic upper layer to enable C and Tcl programs to perform input and output using the same APIs for a variety of files, devices, sockets etc. The generic C APIs are described in the manual entry for Tcl_OpenFileChannel.

The lower layer provides type-specific channel drivers for each type of device supported on each platform. This manual entry describes the C APIs used to communicate between the generic layer and the type-specific channel drivers. It also explains how new types of channels can be added by providing new channel drivers.

Channel drivers consist of a number of components: First, each channel driver provides a Tcl_ChannelType structure containing pointers to functions implementing the various operations used by the generic layer to communicate with the channel driver. The Tcl_ChannelType structure and the functions referenced by it are described in the section TCL_CHANNELTYPE, below.

Second, channel drivers usually provide a Tcl command to create instances of that type of channel. For example, the Tcl open command creates channels that use the file and command channel drivers, and the Tcl socket command creates channels that use TCP sockets for network communication.

Third, a channel driver optionally provides a C function to open channel instances of that type. For example, Tcl_OpenFileChannel opens a channel that uses the file channel driver, and Tcl_OpenTcpClient opens a channel that uses the TCP network protocol. These creation functions typically use Tcl_CreateChannel internally to open the channel.

To add a new type of channel you must implement a C API or a Tcl command that opens a channel by invoking Tcl_CreateChannel. When your driver calls Tcl_CreateChannel it passes in a Tcl_ChannelType structure describing the driver's I/O procedures. The generic layer will then invoke the functions referenced in that structure to perform operations on the channel.

Tcl_CreateChannel opens a new channel and associates the supplied typePtr and instanceData with it. The channel is opened in the mode indicated by mask. For a discussion of channel drivers, their operations and the Tcl_ChannelType structure, see the section TCL_CHANNELTYPE, below.

Tcl_GetChannelInstanceData returns the instance data associated with the channel in channel. This is the same as the instanceData argument in the call to Tcl_CreateChannel that created this channel.

Tcl_GetChannelType returns a pointer to the Tcl_ChannelType structure used by the channel in the channel argument. This is the same as the typePtr argument in the call to Tcl_CreateChannel that created this channel.

Tcl_GetChannelName returns a string containing the name associated with the channel, or NULL if the channelName argument to Tcl_CreateChannel was NULL.

Tcl_GetChannelHandle places the OS-specific device handle associated with channel for the given direction in the location specified by handlePtr and returns TCL_OK. If the channel does not have a device handle for the specified direction, then TCL_ERROR is returned instead. Different channel drivers will return different types of handle. Refer to the manual entries for each driver to determine what type of handle is returned.

Tcl_GetChannelMode returns an OR-ed combination of TCL_READABLE and TCL_WRITABLE, indicating whether the channel is open for input and output.

Tcl_GetChannelBufferSize returns the size, in bytes, of buffers allocated to store input or output in chan. If the value was not set by a previous call to Tcl_SetChannelBufferSize, described below, then the default value of 4096 is returned.

Tcl_SetChannelBufferSize sets the size, in bytes, of buffers that will be allocated in subsequent operations on the channel to store input or output. The size argument should be between ten and one million, allowing buffers of ten bytes to one million bytes. If size is outside this range, Tcl_SetChannelBufferSize sets the buffer size to 4096.

Tcl_NotifyChannel is called by a channel driver to indicate to the generic layer that the events specified by mask have occurred on the channel. Channel drivers are responsible for invoking this function whenever the channel handlers need to be called for the channel. See WATCHPROC below for more details.

Tcl_BadChannelOption is called from driver specific set or get option procs to generate a complete error message.

TCL_CHANNELTYPE

A channel driver provides a Tcl_ChannelType structure that contains pointers to functions that implement the various operations on a channel; these operations are invoked as needed by the generic layer. The structure was versioned starting in Tcl 8.3.2/8.4 to correct a problem with stacked channel drivers. See the OLD_CHANNEL section below for details about the old structure.

The Tcl_ChannelType structure contains the following fields:

typedef struct Tcl_ChannelType {
    char *typeName;
    Tcl_ChannelTypeVersion version;
    Tcl_DriverCloseProc *closeProc;
    Tcl_DriverInputProc *inputProc;
    Tcl_DriverOutputProc *outputProc;
    Tcl_DriverSeekProc *seekProc;
    Tcl_DriverSetOptionProc *setOptionProc;
    Tcl_DriverGetOptionProc *getOptionProc;
    Tcl_DriverWatchProc *watchProc;
    Tcl_DriverGetHandleProc *getHandleProc;
    Tcl_DriverClose2Proc *close2Proc;
    Tcl_DriverBlockModeProc *blockModeProc;
    Tcl_DriverFlushProc *flushProc;
    Tcl_DriverHandlerProc *handlerProc;
} Tcl_ChannelType;

The driver must provide implementations for all functions except blockModeProc, seekProc, setOptionProc, getOptionProc, and close2Proc, which may be specified as NULL. Other functions that can not be implemented for this type of device should return EINVAL when invoked to indicate that they are not implemented, except in the case of flushProc and handlerProc, which should specified as NULL if not otherwise defined.

The user should only use the above structure for Tcl_ChannelType instantiation. When referencing fields in a Tcl_ChannelType structure, the following functions should be used to obtain the values: Tcl_ChannelName, Tcl_ChannelVersion, Tcl_ChannelBlockModeProc, Tcl_ChannelCloseProc, Tcl_ChannelClose2Proc, Tcl_ChannelInputProc, Tcl_ChannelOutputProc, Tcl_ChannelSeekProc, Tcl_ChannelSetOptionProc, Tcl_ChannelGetOptionProc, Tcl_ChannelWatchProc, Tcl_ChannelGetHandleProc, Tcl_ChannelFlushProc, or Tcl_ChannelHandlerProc.

The change to the structures was made in such a way that standard channel types are binary compatible. However, channel types that use stacked channels (ie: TLS, Trf) have new versions to correspond to the above change since the previous code for stacked channels had problems.

TYPENAME

The typeName field contains a null-terminated string that identifies the type of the device implemented by this driver, e.g. file or socket.

This value can be retrieved with Tcl_ChannelName, which returns a pointer to the string.

VERSION

The version field should be set to TCL_CHANNEL_VERSION_2. If it is not set to this value TCL_CHANNEL_VERSION_2, then this Tcl_ChannelType is assumed to have the older structure. See OLD_CHANNEL for more details. While Tcl will recognize and function with either structure, stacked channels must be of the newer style to function correctly.

This value can be retrieved with Tcl_ChannelVersion, which returns either TCL_CHANNEL_VERSION_2 or TCL_CHANNEL_VERSION_1.

BLOCKMODEPROC

The blockModeProc field contains the address of a function called by the generic layer to set blocking and nonblocking mode on the device. BlockModeProc should match the following prototype:

typedef int Tcl_DriverBlockModeProc(
    ClientData instanceData,
    int mode);

The instanceData is the same as the value passed to Tcl_CreateChannel when this channel was created. The mode argument is either TCL_MODE_BLOCKING or TCL_MODE_NONBLOCKING to set the device into blocking or nonblocking mode. The function should return zero if the operation was successful, or a nonzero POSIX error code if the operation failed.

If the operation is successful, the function can modify the supplied instanceData to record that the channel entered blocking or nonblocking mode and to implement the blocking or nonblocking behavior. For some device types, the blocking and nonblocking behavior can be implemented by the underlying operating system; for other device types, the behavior must be emulated in the channel driver.

This value can be retrieved with Tcl_ChannelBlockModeProc, which returns a pointer to the function.

CLOSEPROC AND CLOSE2PROC

The closeProc field contains the address of a function called by the generic layer to clean up driver-related information when the channel is closed. CloseProc must match the following prototype:

typedef int Tcl_DriverCloseProc(
    ClientData instanceData,
    Tcl_Interp *interp);

The instanceData argument is the same as the value provided to Tcl_CreateChannel when the channel was created. The function should release any storage maintained by the channel driver for this channel, and close the input and output devices encapsulated by this channel. All queued output will have been flushed to the device before this function is called, and no further driver operations will be invoked on this instance after calling the closeProc. If the close operation is successful, the procedure should return zero; otherwise it should return a nonzero POSIX error code. In addition, if an error occurs and interp is not NULL, the procedure should store an error message in the interpreter's result.

Alternatively, channels that support closing the read and write sides independently may set closeProc to TCL_CLOSE2PROC and set close2Proc to the address of a function that matches the following prototype:

typedef int Tcl_DriverClose2Proc(
    ClientData instanceData,
    Tcl_Interp *interp,
    int flags);

The close2Proc will be called with flags set to an OR'ed combination of TCL_CLOSE_READ or TCL_CLOSE_WRITE to indicate that the driver should close the read and/or write side of the channel. The channel driver may be invoked to perform additional operations on the channel after close2Proc is called to close one or both sides of the channel. If flags is 0 (zero), the driver should close the channel in the manner described above for closeProc. No further operations will be invoked on this instance after close2Proc is called with all flags cleared. In all cases, the close2Proc function should return zero if the close operation was successful; otherwise it should return a nonzero POSIX error code. In addition, if an error occurs and interp is not NULL, the procedure should store an error message in the interpreter's result.

These value can be retrieved with Tcl_ChannelCloseProc or Tcl_ChannelClose2Proc, which returns a pointer to the respective function.

INPUTPROC

The inputProc field contains the address of a function called by the generic layer to read data from the file or device and store it in an internal buffer. InputProc must match the following prototype:

typedef int Tcl_DriverInputProc(
    ClientData instanceData,
    char *buf,
    int bufSize,
    int *errorCodePtr);

InstanceData is the same as the value passed to Tcl_CreateChannel when the channel was created. The buf argument points to an array of bytes in which to store input from the device, and the bufSize argument indicates how many bytes are available at buf.

The errorCodePtr argument points to an integer variable provided by the generic layer. If an error occurs, the function should set the variable to a POSIX error code that identifies the error that occurred.

The function should read data from the input device encapsulated by the channel and store it at buf. On success, the function should return a nonnegative integer indicating how many bytes were read from the input device and stored at buf. On error, the function should return -1. If an error occurs after some data has been read from the device, that data is lost.

If inputProc can determine that the input device has some data available but less than requested by the bufSize argument, the function should only attempt to read as much data as is available and return without blocking. If the input device has no data available whatsoever and the channel is in nonblocking mode, the function should return an EAGAIN error. If the input device has no data available whatsoever and the channel is in blocking mode, the function should block for the shortest possible time until at least one byte of data can be read from the device; then, it should return as much data as it can read without blocking.

This value can be retrieved with Tcl_ChannelInputProc, which returns a pointer to the function.

OUTPUTPROC

The outputProc field contains the address of a function called by the generic layer to transfer data from an internal buffer to the output device. OutputProc must match the following prototype:

typedef int Tcl_DriverOutputProc(
    ClientData instanceData,
    char *buf,
    int toWrite,
    int *errorCodePtr);

InstanceData is the same as the value passed to Tcl_CreateChannel when the channel was created. The buf argument contains an array of bytes to be written to the device, and the toWrite argument indicates how many bytes are to be written from the buf argument.

The errorCodePtr argument points to an integer variable provided by the generic layer. If an error occurs, the function should set this variable to a POSIX error code that identifies the error.

The function should write the data at buf to the output device encapsulated by the channel. On success, the function should return a nonnegative integer indicating how many bytes were written to the output device. The return value is normally the same as toWrite, but may be less in some cases such as if the output operation is interrupted by a signal. If an error occurs the function should return -1. In case of error, some data may have been written to the device.

If the channel is nonblocking and the output device is unable to absorb any data whatsoever, the function should return -1 with an EAGAIN error without writing any data.

This value can be retrieved with Tcl_ChannelOutputProc, which returns a pointer to the function.

SEEKPROC

The seekProc field contains the address of a function called by the generic layer to move the access point at which subsequent input or output operations will be applied. SeekProc must match the following prototype:

typedef int Tcl_DriverSeekProc(
    ClientData instanceData,
    long offset,
    int seekMode,
    int *errorCodePtr);

The instanceData argument is the same as the value given to Tcl_CreateChannel when this channel was created. Offset and seekMode have the same meaning as for the Tcl_Seek procedure (described in the manual entry for Tcl_OpenFileChannel).

The errorCodePtr argument points to an integer variable provided by the generic layer for returning errno values from the function. The function should set this variable to a POSIX error code if an error occurs. The function should store an EINVAL error code if the channel type does not implement seeking.

The return value is the new access point or -1 in case of error. If an error occurred, the function should not move the access point.

This value can be retrieved with Tcl_ChannelSeekProc, which returns a pointer to the function.

SETOPTIONPROC

The setOptionProc field contains the address of a function called by the generic layer to set a channel type specific option on a channel. setOptionProc must match the following prototype:

typedef int Tcl_DriverSetOptionProc(
    ClientData instanceData,
    Tcl_Interp *interp,
    char *optionName,
    char *optionValue);

optionName is the name of an option to set, and optionValue is the new value for that option, as a string. The instanceData is the same as the value given to Tcl_CreateChannel when this channel was created. The function should do whatever channel type specific action is required to implement the new value of the option.

Some options are handled by the generic code and this function is never called to set them, e.g. -blockmode. Other options are specific to each channel type and the setOptionProc procedure of the channel driver will get called to implement them. The setOptionProc field can be NULL, which indicates that this channel type supports no type specific options.

If the option value is successfully modified to the new value, the function returns TCL_OK. It should call Tcl_BadChannelOption which itself returns TCL_ERROR if the optionName is unrecognized. If optionValue specifies a value for the option that is not supported or if a system call error occurs, the function should leave an error message in the result field of interp if interp is not NULL. The function should also call Tcl_SetErrno to store an appropriate POSIX error code.

This value can be retrieved with Tcl_ChannelSetOptionProc, which returns a pointer to the function.

GETOPTIONPROC

The getOptionProc field contains the address of a function called by the generic layer to get the value of a channel type specific option on a channel. getOptionProc must match the following prototype:

typedef int Tcl_DriverGetOptionProc(
    ClientData instanceData,
    Tcl_Interp *interp,
    char *optionName,
    Tcl_DString *dsPtr);

OptionName is the name of an option supported by this type of channel. If the option name is not NULL, the function stores its current value, as a string, in the Tcl dynamic string dsPtr. If optionName is NULL, the function stores in dsPtr an alternating list of all supported options and their current values. On success, the function returns TCL_OK. It should call Tcl_BadChannelOption which itself returns TCL_ERROR if the optionName is unrecognized. If a system call error occurs, the function should leave an error message in the result field of interp if interp is not NULL. The function should also call Tcl_SetErrno to store an appropriate POSIX error code.

Some options are handled by the generic code and this function is never called to retrieve their value, e.g. -blockmode. Other options are specific to each channel type and the getOptionProc procedure of the channel driver will get called to implement them. The getOptionProc field can be NULL, which indicates that this channel type supports no type specific options.

This value can be retrieved with Tcl_ChannelGetOptionProc, which returns a pointer to the function.

WATCHPROC

The watchProc field contains the address of a function called by the generic layer to initialize the event notification mechanism to notice events of interest on this channel. WatchProc should match the following prototype:

typedef void Tcl_DriverWatchProc(
    ClientData instanceData,
    int mask);

The instanceData is the same as the value passed to Tcl_CreateChannel when this channel was created. The mask argument is an OR-ed combination of TCL_READABLE, TCL_WRITABLE and TCL_EXCEPTION; it indicates events the caller is interested in noticing on this channel.

The function should initialize device type specific mechanisms to notice when an event of interest is present on the channel. When one or more of the designated events occurs on the channel, the channel driver is responsible for calling Tcl_NotifyChannel to inform the generic channel module. The driver should take care not to starve other channel drivers or sources of callbacks by invoking Tcl_NotifyChannel too frequently. Fairness can be insured by using the Tcl event queue to allow the channel event to be scheduled in sequence with other events. See the description of Tcl_QueueEvent for details on how to queue an event.

This value can be retrieved with Tcl_ChannelWatchProc, which returns a pointer to the function.

GETHANDLEPROC

The getHandleProc field contains the address of a function called by the generic layer to retrieve a device-specific handle from the channel. GetHandleProc should match the following prototype:

typedef int Tcl_DriverGetHandleProc(
    ClientData instanceData,
    int direction,
    ClientData *handlePtr);

InstanceData is the same as the value passed to Tcl_CreateChannel when this channel was created. The direction argument is either TCL_READABLE to retrieve the handle used for input, or TCL_WRITABLE to retrieve the handle used for output.

If the channel implementation has device-specific handles, the function should retrieve the appropriate handle associated with the channel, according the direction argument. The handle should be stored in the location referred to by handlePtr, and TCL_OK should be returned. If the channel is not open for the specified direction, or if the channel implementation does not use device handles, the function should return TCL_ERROR.

This value can be retrieved with Tcl_ChannelGetHandleProc, which returns a pointer to the function.

FLUSHPROC

The flushProc field is currently reserved for future use. It should be set to NULL. FlushProc should match the following prototype:

typedef int Tcl_DriverFlushProc(
    ClientData instanceData);

This value can be retrieved with Tcl_ChannelFlushProc, which returns a pointer to the function.

HANDLERPROC

The handlerProc field contains the address of a function called by the generic layer to notify the channel that an event occured. It should be defined for stacked channel drivers that wish to be notified of events that occur on the underlying (stacked) channel. HandlerProc should match the following prototype:

typedef int Tcl_DriverHandlerProc(
    ClientData instanceData,
    int interestMask);

InstanceData is the same as the value passed to Tcl_CreateChannel when this channel was created. The interestMask is an OR-ed combination of TCL_READABLE or TCL_WRITABLE; it indicates what type of event occured on this channel.

This value can be retrieved with Tcl_ChannelHandlerProc, which returns a pointer to the function.

TCL_BADCHANNELOPTION

This procedure generates a "bad option" error message in an (optional) interpreter. It is used by channel drivers when a invalid Set/Get option is requested. Its purpose is to concatenate the generic options list to the specific ones and factorize the generic options error message string.

It always return TCL_ERROR

An error message is generated in interp's result object to indicate that a command was invoked with the a bad option The message has the form

bad option "blah": should be one of
    <...generic options...>+<...specific options...>
so you get for instance:
    bad option "-blah": should be one of -blocking,
    -buffering, -buffersize, -eofchar, -translation,
    -peername, or -sockname
when called with optionList="peername sockname"
``blah'' is the optionName argument and ``<specific options>'' is a space separated list of specific option words. The function takes good care of inserting minus signs before each option, commas after, and an ``or'' before the last option.

OLD_CHANNEL

The original (8.3.1 and below) Tcl_ChannelType structure contains the following fields:

typedef struct Tcl_ChannelType {
    char *typeName;
    Tcl_DriverBlockModeProc *blockModeProc;
    Tcl_DriverCloseProc *closeProc;
    Tcl_DriverInputProc *inputProc;
    Tcl_DriverOutputProc *outputProc;
    Tcl_DriverSeekProc *seekProc;
    Tcl_DriverSetOptionProc *setOptionProc;
    Tcl_DriverGetOptionProc *getOptionProc;
    Tcl_DriverWatchProc *watchProc;
    Tcl_DriverGetHandleProc *getHandleProc;
    Tcl_DriverClose2Proc *close2Proc;
} Tcl_ChannelType;

It is still possible to create channel with the above structure. The internal channel code will determine the version. It is imperative to use the new Tcl_ChannelType structure if you are creating a stacked channel driver, due to problems with the earlier stacked channel implementation (in 8.2.0 to 8.3.1).

SEE ALSO

Tcl_Close, Tcl_OpenFileChannel, Tcl_SetErrno, Tcl_QueueEvent, Tcl_StackChannel

KEYWORDS

blocking, channel driver, channel registration, channel type, nonblocking
Copyright © 1996-1997 Sun Microsystems, Inc.
Copyright © 1997-2000 Ajuba Solutions.


Tcl Library Procedures - Tcl_CreateChannelHandler manual page

NAME

Tcl_CreateChannelHandler, Tcl_DeleteChannelHandler - call a procedure when a channel becomes readable or writable

SYNOPSIS

#include <tcl.h>
void
Tcl_CreateChannelHandler(channel, mask, proc, clientData)
void
Tcl_DeleteChannelHandler(channel, proc, clientData)

ARGUMENTS

Tcl_Channel channel (in)
Tcl channel such as returned by Tcl_CreateChannel.

int mask (in)
Conditions under which proc should be called: OR-ed combination of TCL_READABLE, TCL_WRITABLE and TCL_EXCEPTION. Specify a zero value to temporarily disable an existing handler.

Tcl_FileProc *proc (in)
Procedure to invoke whenever the channel indicated by channel meets the conditions specified by mask.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

Tcl_CreateChannelHandler arranges for proc to be called in the future whenever input or output becomes possible on the channel identified by channel, or whenever an exceptional condition exists for channel. The conditions of interest under which proc will be invoked are specified by the mask argument. See the manual entry for fileevent for a precise description of what it means for a channel to be readable or writable. Proc must conform to the following prototype:
typedef void Tcl_ChannelProc(
    ClientData clientData,
    int mask);

The clientData argument is the same as the value passed to Tcl_CreateChannelHandler when the handler was created. Typically, clientData points to a data structure containing application-specific information about the channel. Mask is an integer mask indicating which of the requested conditions actually exists for the channel; it will contain a subset of the bits from the mask argument to Tcl_CreateChannelHandler when the handler was created.

Each channel handler is identified by a unique combination of channel, proc and clientData. There may be many handlers for a given channel as long as they don't have the same channel, proc, and clientData. If Tcl_CreateChannelHandler is invoked when there is already a handler for channel, proc, and clientData, then no new handler is created; instead, the mask is changed for the existing handler.

Tcl_DeleteChannelHandler deletes a channel handler identified by channel, proc and clientData; if no such handler exists, the call has no effect.

Channel handlers are invoked via the Tcl event mechanism, so they are only useful in applications that are event-driven. Note also that the conditions specified in the mask argument to proc may no longer exist when proc is invoked: for example, if there are two handlers for TCL_READABLE on the same channel, the first handler could consume all of the available input 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.

SEE ALSO

Notifier, Tcl_CreateChannel, Tcl_OpenFileChannel, vwait(n).

KEYWORDS

blocking, callback, channel, events, handler, nonblocking.
Copyright © 1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_CreateCloseHandler manual page

NAME

Tcl_CreateCloseHandler, Tcl_DeleteCloseHandler - arrange for callbacks when channels are closed

SYNOPSIS

#include <tcl.h>
void
Tcl_CreateCloseHandler(channel, proc, clientData)
void
Tcl_DeleteCloseHandler(channel, proc, clientData)

ARGUMENTS

Tcl_Channel channel (in)
The channel for which to create or delete a close callback.

Tcl_CloseProc *proc (in)
The procedure to call as the callback.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

Tcl_CreateCloseHandler arranges for proc to be called when channel is closed with Tcl_Close or Tcl_UnregisterChannel, or using the Tcl close command. Proc should match the following prototype:

typedef void Tcl_CloseProc(
    ClientData clientData);

The clientData is the same as the value provided in the call to Tcl_CreateCloseHandler.

Tcl_DeleteCloseHandler removes a close callback for channel. The proc and clientData identify which close callback to remove; Tcl_DeleteCloseHandler does nothing if its proc and clientData arguments do not match the proc and clientData for a close handler for channel.

SEE ALSO

close, Tcl_Close, Tcl_UnregisterChannel

KEYWORDS

callback, channel closing
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tcl_CreateCommand manual page

NAME

Tcl_CreateCommand - implement new commands in C

SYNOPSIS

#include <tcl.h>
Tcl_Command
Tcl_CreateCommand(interp, cmdName, proc, clientData, deleteProc)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which to create new command.

char *cmdName (in)
Name of command.

Tcl_CmdProc *proc (in)
Implementation of new command: proc will be called whenever cmdName is invoked as a command.

ClientData clientData (in)
Arbitrary one-word value to pass to proc and deleteProc.

Tcl_CmdDeleteProc *deleteProc (in)
Procedure to call before cmdName is deleted from the interpreter; allows for command-specific cleanup. If NULL, then no procedure is called before the command is deleted.

DESCRIPTION

Tcl_CreateCommand defines a new command in interp and associates it with procedure proc such that whenever cmdName is invoked as a Tcl command (via a call to Tcl_Eval) the Tcl interpreter will call proc to process the command. It differs from Tcl_CreateObjCommand in that a new string-based command is defined; that is, a command procedure is defined that takes an array of argument strings instead of objects. The object-based command procedures registered by Tcl_CreateObjCommand can execute significantly faster than the string-based command procedures defined by Tcl_CreateCommand. This is because they take Tcl objects as arguments and those objects can retain an internal representation that can be manipulated more efficiently. Also, Tcl's interpreter now uses objects internally. In order to invoke a string-based command procedure registered by Tcl_CreateCommand, 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. New commands should be defined using Tcl_CreateObjCommand. We support Tcl_CreateCommand for backwards compatibility.

The procedures Tcl_DeleteCommand, Tcl_GetCommandInfo, and Tcl_SetCommandInfo are used in conjunction with Tcl_CreateCommand.

Tcl_CreateCommand will delete an existing command cmdName, if one is already associated with the interpreter. It returns a token that may be used to refer to the command in subsequent calls to Tcl_GetCommandName. If cmdName contains any :: namespace qualifiers, then the command is added to the specified namespace; otherwise the command is added to the global namespace. If Tcl_CreateCommand is called for an interpreter that is in the process of being deleted, then it does not create a new command and it returns NULL. Proc should have arguments and result that match the type Tcl_CmdProc:

typedef int Tcl_CmdProc(
    ClientData clientData,
    Tcl_Interp *interp,
    int argc,
    char *argv[]);
When proc is invoked the clientData and interp parameters will be copies of the clientData and interp arguments given to Tcl_CreateCommand. Typically, clientData points to an application-specific data structure that describes what to do when the command procedure is invoked. Argc and argv describe the arguments to the command, argc giving the number of arguments (including the command name) and argv giving the values of the arguments as strings. The argv array will contain argc+1 values; the first argc values point to the argument strings, and the last value is NULL. Note that the argument strings should not be modified as they may point to constant strings or may be shared with other parts of the interpreter.

Proc must return an integer code that is either TCL_OK, TCL_ERROR, TCL_RETURN, TCL_BREAK, or TCL_CONTINUE. See the Tcl overview man page for details on what these codes mean. Most normal commands will only return TCL_OK or TCL_ERROR. In addition, proc must set the interpreter result to point to a string value; in the case of a TCL_OK return code this gives the result of the command, and in the case of TCL_ERROR it gives an error message. The Tcl_SetResult procedure provides an easy interface for setting the return value; for complete details on how the the interpreter result field is managed, see the Tcl_Interp man page. Before invoking a command procedure, Tcl_Eval sets the interpreter result to point to an empty string, so simple commands can return an empty result by doing nothing at all.

The contents of the argv array belong to Tcl and are not guaranteed to persist once proc returns: proc should not modify them, nor should it set the interpreter result to point anywhere within the argv values. Call Tcl_SetResult with status TCL_VOLATILE if you want to return something from the argv array.

DeleteProc will be invoked when (if) cmdName is deleted. This can occur through a call to Tcl_DeleteCommand or Tcl_DeleteInterp, or by replacing cmdName in another call to Tcl_CreateCommand. DeleteProc is invoked before the command is deleted, and gives the application an opportunity to release any structures associated with the command. DeleteProc should have arguments and result that match the type Tcl_CmdDeleteProc:

typedef void Tcl_CmdDeleteProc(ClientData clientData);
The clientData argument will be the same as the clientData argument passed to Tcl_CreateCommand.

SEE ALSO

Tcl_CreateObjCommand, Tcl_DeleteCommand, Tcl_GetCommandInfo, Tcl_SetCommandInfo, Tcl_GetCommandName, Tcl_SetObjResult

KEYWORDS

bind, command, create, delete, interpreter, namespace
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_CreateFileHandler manual page

NAME

Tcl_CreateFileHandler, Tcl_DeleteFileHandler - associate procedure callbacks with files or devices (Unix only)

SYNOPSIS

#include <tcl.h>
Tcl_CreateFileHandler(fd, mask, proc, clientData)
Tcl_DeleteFileHandler(fd)

ARGUMENTS

int fd (in)
Unix file descriptor for an open file or device.

int mask (in)
Conditions under which proc should be called: OR-ed combination of TCL_READABLE, TCL_WRITABLE, and TCL_EXCEPTION. May be set to 0 to temporarily disable a handler.

Tcl_FileProc *proc (in)
Procedure to invoke whenever the file or device indicated by file meets the conditions specified by mask.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

Tcl_CreateFileHandler arranges for proc to be invoked in the future whenever I/O becomes possible on a file or an exceptional condition exists for the file. The file is indicated by fd, and the conditions of interest are indicated by mask. For example, if mask is TCL_READABLE, proc will be called when the file is readable. The callback to proc is made by Tcl_DoOneEvent, so Tcl_CreateFileHandler is only useful in programs that dispatch events through Tcl_DoOneEvent or through Tcl commands such as vwait.

Proc should have arguments and result that match the type Tcl_FileProc:

typedef void Tcl_FileProc(
    ClientData clientData,
    int mask);
The clientData parameter to proc is a copy of the clientData argument given to Tcl_CreateFileHandler when the callback was created. Typically, clientData points to a data structure containing application-specific information about the file. Mask is an integer mask indicating which of the requested conditions actually exists for the file; it will contain a subset of the bits in the mask argument to Tcl_CreateFileHandler.

There may exist only one handler for a given file at a given time. If Tcl_CreateFileHandler is called when a handler already exists for fd, then the new callback replaces the information that was previously recorded.

Tcl_DeleteFileHandler may be called to delete the file handler for fd; if no handler exists for the file given by fd then the procedure has no effect.

The purpose of file handlers is to enable an application to respond to events while waiting for files to become ready for I/O. For this to work correctly, the application may need to use non-blocking I/O operations on the files for which handlers are declared. Otherwise the application may block if it reads or writes too much data; while waiting for the I/O to complete the application won't be able to service other events. Use Tcl_SetChannelOption with -blocking to set the channel into blocking or nonblocking mode as required.

Note that these interfaces are only supported by the Unix implementation of the Tcl notifier.

KEYWORDS

callback, file, handler
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_CreateInterp manual page

NAME
Tcl_CreateInterp, Tcl_DeleteInterp, Tcl_InterpDeleted - create and delete Tcl command interpreters
SYNOPSIS
ARGUMENTS
DESCRIPTION
INTERPRETERS AND MEMORY MANAGEMENT
Interpreters Passed As Arguments
Interpreter Creation And Deletion
Retrieving An Interpreter From A Data Structure
SEE ALSO
KEYWORDS

NAME

Tcl_CreateInterp, Tcl_DeleteInterp, Tcl_InterpDeleted - create and delete Tcl command interpreters

SYNOPSIS

#include <tcl.h>
Tcl_Interp *
Tcl_CreateInterp()
Tcl_DeleteInterp(interp)
int
Tcl_InterpDeleted(interp)

ARGUMENTS

Tcl_Interp *interp (in)
Token for interpreter to be destroyed.

DESCRIPTION

Tcl_CreateInterp creates a new interpreter structure and returns a token for it. The token is required in calls to most other Tcl procedures, such as Tcl_CreateCommand, Tcl_Eval, and Tcl_DeleteInterp. Clients are only allowed to access a few of the fields of Tcl_Interp structures; see the Tcl_Interp and Tcl_CreateCommand man pages for details. The new interpreter is initialized with no defined variables and only the built-in Tcl commands. To bind in additional commands, call Tcl_CreateCommand.

Tcl_DeleteInterp marks an interpreter as deleted; the interpreter will eventually be deleted when all calls to Tcl_Preserve for it have been matched by calls to Tcl_Release. At that time, all of the resources associated with it, including variables, procedures, and application-specific command bindings, will be deleted. After Tcl_DeleteInterp returns any attempt to use Tcl_Eval on the interpreter will fail and return TCL_ERROR. After the call to Tcl_DeleteInterp it is safe to examine the interpreter's result, query or set the values of variables, define, undefine or retrieve procedures, and examine the runtime evaluation stack. See below, in the section INTERPRETERS AND MEMORY MANAGEMENT for details.

Tcl_InterpDeleted returns nonzero if Tcl_DeleteInterp was called with interp as its argument; this indicates that the interpreter will eventually be deleted, when the last call to Tcl_Preserve for it is matched by a call to Tcl_Release. If nonzero is returned, further calls to Tcl_Eval in this interpreter will return TCL_ERROR.

Tcl_InterpDeleted is useful in deletion callbacks to distinguish 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.

INTERPRETERS AND MEMORY MANAGEMENT

Tcl_DeleteInterp can be called at any time on an interpreter that may be used by nested evaluations and C code in various extensions. Tcl implements a simple mechanism that allows callers to use interpreters without worrying about the interpreter being deleted in a nested call, and without requiring special code to protect the interpreter, in most cases. This mechanism ensures that nested uses of an interpreter can safely continue using it even after Tcl_DeleteInterp is called.

The mechanism relies on matching up calls to Tcl_Preserve with calls to Tcl_Release. If Tcl_DeleteInterp has been called, only when the last call to Tcl_Preserve is matched by a call to Tcl_Release, will the interpreter be freed. See the manual entry for Tcl_Preserve for a description of these functions.

The rules for when the user of an interpreter must call Tcl_Preserve and Tcl_Release are simple:

Interpreters Passed As Arguments
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.

Interpreter Creation And Deletion
When a new interpreter is created and used in a call to Tcl_Eval, Tcl_VarEval, Tcl_GlobalEval, Tcl_SetVar, or Tcl_GetVar, a pair of calls to Tcl_Preserve and Tcl_Release should be wrapped around all uses of the interpreter. Remember that it is unsafe to use the interpreter once Tcl_Release has been called. To ensure that the interpreter is properly deleted when it is no longer needed, call Tcl_InterpDeleted to test if some other code already called Tcl_DeleteInterp; if not, call Tcl_DeleteInterp before calling Tcl_Release in your own code. Do not call Tcl_DeleteInterp on an interpreter for which Tcl_InterpDeleted returns nonzero.

Retrieving An Interpreter From A Data Structure
When an interpreter is retrieved from a data structure (e.g. the client data of a callback) for use in Tcl_Eval, Tcl_VarEval, Tcl_GlobalEval, Tcl_SetVar, or Tcl_GetVar, a pair of calls to Tcl_Preserve and Tcl_Release should be wrapped around all uses of the interpreter; it is unsafe to reuse the interpreter once Tcl_Release 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 to NULL) when the interpreter is deleted. Otherwise, you may be using an interpreter that has been freed and whose memory may already have been 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.

SEE ALSO

Tcl_Preserve, Tcl_Release

KEYWORDS

command, create, delete, interpreter
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_CreateMathFunc manual page

NAME

Tcl_CreateMathFunc - Define a new math function for expressions

SYNOPSIS

#include <tcl.h>
Tcl_CreateMathFunc(interp, name, numArgs, argTypes, proc, clientData)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which new function will be defined.

char *name (in)
Name for new function.

int numArgs (in)
Number of arguments to new function; also gives size of argTypes array.

Tcl_ValueType *argTypes (in)
Points to an array giving the permissible types for each argument to function.

Tcl_MathProc *proc (in)
Procedure that implements the function.

ClientData clientData (in)
Arbitrary one-word value to pass to proc when it is invoked.

DESCRIPTION

Tcl allows a number of mathematical functions to be used in expressions, such as sin, cos, and hypot. Tcl_CreateMathFunc allows applications to add additional functions to those already provided by Tcl or to replace existing functions. Name is the name of the function as it will appear in expressions. If name doesn't already exist as a function then a new function is created. If it does exist, then the existing function is replaced. NumArgs and argTypes describe the arguments to the function. Each entry in the argTypes array must be either TCL_INT, TCL_DOUBLE, or TCL_EITHER to indicate whether the corresponding argument must be an integer, a double-precision floating value, or either, respectively.

Whenever the function is invoked in an expression Tcl will invoke proc. Proc should have arguments and result that match the type Tcl_MathProc:

typedef int Tcl_MathProc(
    ClientData clientData,
    Tcl_Interp *interp,
    Tcl_Value *args,
    Tcl_Value *resultPtr);

When proc is invoked the clientData and interp arguments will be the same as those passed to Tcl_CreateMathFunc. Args will point to an array of numArgs Tcl_Value structures, which describe the actual arguments to the function:

typedef struct Tcl_Value {
    Tcl_ValueType type;
    long intValue;
    double doubleValue;
} Tcl_Value;

The type field indicates the type of the argument and is either TCL_INT or TCL_DOUBLE. It will match the argTypes value specified for the function unless the argTypes value was TCL_EITHER. Tcl converts the argument supplied in the expression to the type requested in argTypes, if that is necessary. Depending on the value of the type field, the intValue or doubleValue field will contain the actual value of the argument.

Proc should compute its result and store it either as an integer in resultPtr->intValue or as a floating value in resultPtr->doubleValue. It should set also resultPtr->type to either TCL_INT or TCL_DOUBLE to indicate which value was set. Under normal circumstances proc should return TCL_OK. If an error occurs while executing the function, proc should return TCL_ERROR and leave an error message in the interpreter's result.

KEYWORDS

expression, mathematical function
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_CreateObjCommand manual page

NAME

Tcl_CreateObjCommand, Tcl_DeleteCommand, Tcl_DeleteCommandFromToken, Tcl_GetCommandInfo, Tcl_SetCommandInfo, Tcl_GetCommandName - implement new commands in C

SYNOPSIS

#include <tcl.h>
Tcl_Command
Tcl_CreateObjCommand(interp, cmdName, proc, clientData, deleteProc)
int
Tcl_DeleteCommand(interp, cmdName)
int
Tcl_DeleteCommandFromToken(interp, token)
int
Tcl_GetCommandInfo(interp, cmdName, infoPtr)
int
Tcl_SetCommandInfo(interp, cmdName, infoPtr)
char *
Tcl_GetCommandName(interp, token)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which to create a new command or that contains a command.

char *cmdName (in)
Name of command.

Tcl_ObjCmdProc *proc (in)
Implementation of the new command: proc will be called whenever cmdName is invoked as a command.

ClientData clientData (in)
Arbitrary one-word value to pass to proc and deleteProc.

Tcl_CmdDeleteProc *deleteProc (in)
Procedure to call before cmdName is deleted from the interpreter; allows for command-specific cleanup. If NULL, then no procedure is called before the command is deleted.

Tcl_Command token (in)
Token for command, returned by previous call to Tcl_CreateObjCommand. The command must not have been deleted.

Tcl_CmdInfo *infoPtr (in/out)
Pointer to structure containing various information about a Tcl command.

DESCRIPTION

Tcl_CreateObjCommand defines a new command in interp and associates it with procedure proc such that whenever name is invoked as a Tcl command (e.g., via a call to Tcl_EvalObjEx) the Tcl interpreter will call proc to process the command.

Tcl_CreateObjCommand deletes any existing command name 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 Tcl_GetCommandName. If name contains any :: namespace qualifiers, then the command is added to the specified namespace; otherwise the command is added to the global namespace. If Tcl_CreateObjCommand is called for an interpreter that is in the process of being deleted, then it does not create a new command and it returns NULL. proc should have arguments and result that match the type Tcl_ObjCmdProc:

typedef int Tcl_ObjCmdProc(
    ClientData clientData,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *CONST objv[]);
When proc is invoked, the clientData and interp parameters will be copies of the clientData and interp arguments given to Tcl_CreateObjCommand. Typically, clientData points to an application-specific data structure that describes what to do when the command procedure is invoked. Objc and objv describe the arguments to the command, objc giving the number of argument objects (including the command name) and objv giving the values of the arguments. The objv array will contain objc values, pointing to the argument objects. Unlike argv[argv] used in a string-based command procedure, objv[objc] will not contain NULL.

Additionally, when proc is invoked, it must not modify the contents of the objv array by assigning new pointer values to any element of the array (for example, objv[2] = NULL) because this will cause memory to be lost and the runtime stack to be corrupted. The CONST in the declaration of objv will cause ANSI-compliant compilers to report any such attempted assignment as an error. However, it is acceptable to modify the internal representation of any individual object argument. For instance, the user may call Tcl_GetIntFromObj on objv[2] to obtain the integer representation of that object; that call may change the type of the object that objv[2] points at, but will not change where objv[2] points.

proc must return an integer code that is either TCL_OK, TCL_ERROR, TCL_RETURN, TCL_BREAK, or TCL_CONTINUE. See the Tcl overview man page for details on what these codes mean. Most normal commands will only return TCL_OK or TCL_ERROR. In addition, if proc needs to return a non-empty result, it can call Tcl_SetObjResult to set the interpreter's result. In the case of a TCL_OK return code this gives the result of the command, and in the case of TCL_ERROR this gives an error message. Before invoking a command procedure, Tcl_EvalObjEx sets interpreter's result to point to an object representing an empty string, so simple commands can return an empty result by doing nothing at all.

The contents of the objv array belong to Tcl and are not guaranteed to persist once proc returns: proc should not modify them. Call Tcl_SetObjResult if you want to return something from the objv array.

Ordinarily, Tcl_CreateObjCommand deletes any existing command name already associated with the interpreter. However, if the existing command was created by a previous call to Tcl_CreateCommand, Tcl_CreateObjCommand does not delete the command but instead arranges for the Tcl interpreter to call the Tcl_ObjCmdProc proc in the future. The old string-based Tcl_CmdProc associated with the command is retained and its address can be obtained by subsequent Tcl_GetCommandInfo calls. This is done for backwards compatibility.

DeleteProc will be invoked when (if) name is deleted. This can occur through a call to Tcl_DeleteCommand, Tcl_DeleteCommandFromToken, or Tcl_DeleteInterp, or by replacing name in another call to Tcl_CreateObjCommand. DeleteProc is invoked before the command is deleted, and gives the application an opportunity to release any structures associated with the command. DeleteProc should have arguments and result that match the type Tcl_CmdDeleteProc:

typedef void Tcl_CmdDeleteProc(ClientData clientData);
The clientData argument will be the same as the clientData argument passed to Tcl_CreateObjCommand.

Tcl_DeleteCommand deletes a command from a command interpreter. Once the call completes, attempts to invoke cmdName in interp will result in errors. If cmdName isn't bound as a command in interp then Tcl_DeleteCommand does nothing and returns -1; otherwise it returns 0. There are no restrictions on cmdName: it may refer to a built-in command, an application-specific command, or a Tcl procedure. If name contains any :: namespace qualifiers, the command is deleted from the specified namespace.

Given a token returned by Tcl_CreateObjCommand, Tcl_DeleteCommandFromToken deletes the command from a command interpreter. It will delete a command even if that command has been renamed. Once the call completes, attempts to invoke the command in interp will result in errors. If the command corresponding to token has already been deleted from interp then Tcl_DeleteCommand does nothing and returns -1; otherwise it returns 0.

Tcl_GetCommandInfo checks to see whether its cmdName argument exists as a command in interp. cmdName may include :: namespace qualifiers to identify a command in a particular namespace. If the command is not found, then it returns 0. Otherwise it places information about the command in the Tcl_CmdInfo structure pointed to by infoPtr and returns 1. A Tcl_CmdInfo structure has the following fields:

typedef struct Tcl_CmdInfo {
    int isNativeObjectProc;
    Tcl_ObjCmdProc *objProc;
    ClientData objClientData;
    Tcl_CmdProc *proc;
    ClientData clientData;
    Tcl_CmdDeleteProc *deleteProc;
    ClientData deleteData;
    Tcl_Namespace *namespacePtr;
} Tcl_CmdInfo;
The isNativeObjectProc field has the value 1 if Tcl_CreateObjCommand was called to register the command; it is 0 if only Tcl_CreateCommand was called. It allows a program to determine whether it is faster to call objProc or proc: objProc is normally faster if isNativeObjectProc has the value 1. The fields objProc and objClientData have the same meaning as the proc and clientData arguments to Tcl_CreateObjCommand; they hold information about the object-based command procedure that the Tcl interpreter calls to implement the command. The fields proc and clientData hold information about the string-based command procedure that implements the command. If Tcl_CreateCommand was called for this command, this is the procedure passed to it; otherwise, this is a compatibility procedure registered by Tcl_CreateObjCommand that simply calls the command's object-based procedure after converting its string arguments to Tcl objects. The field deleteData is the ClientData value to pass to deleteProc; it is normally the same as clientData but may be set independently using the Tcl_SetCommandInfo procedure. The field namespacePtr holds a pointer to the Tcl_Namespace that contains the command.

Tcl_SetCommandInfo is used to modify the procedures and ClientData values associated with a command. Its cmdName argument is the name of a command in interp. cmdName may include :: namespace qualifiers to identify a command in a particular namespace. If this command does not exist then Tcl_SetCommandInfo returns 0. Otherwise, it copies the information from *infoPtr to Tcl's internal structure for the command and returns 1. Note that this procedure allows the ClientData for a command's deletion procedure to be given a different value than the ClientData for its command procedure. Note that Tcl_SetCmdInfo will not change a command's namespace; you must use Tcl_RenameCommand to do that.

Tcl_GetCommandName provides a mechanism for tracking commands that have been renamed. Given a token returned by Tcl_CreateObjCommand when the command was created, Tcl_GetCommandName returns the string name of the command. If the command has been renamed since it was created, then Tcl_GetCommandName returns the current name. This name does not include any :: namespace qualifiers. The command corresponding to token must not have been deleted. The string returned by Tcl_GetCommandName is in dynamic memory owned by Tcl and is only guaranteed to retain its value as long as the command isn't deleted or renamed; callers should copy the string if they need to keep it for a long time.

SEE ALSO

Tcl_CreateCommand, Tcl_ResetResult, Tcl_SetObjResult

KEYWORDS

bind, command, create, delete, namespace, object
Copyright © 1996-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_CreateSlave manual page

NAME

Tcl_IsSafe, Tcl_MakeSafe, Tcl_CreateSlave, Tcl_GetSlave, Tcl_GetMaster, Tcl_GetInterpPath, Tcl_CreateAlias, Tcl_CreateAliasObj, Tcl_GetAlias, Tcl_GetAliasObj, Tcl_ExposeCommand, Tcl_HideCommand - manage multiple Tcl interpreters, aliases and hidden commands.

SYNOPSIS

#include <tcl.h>
int
Tcl_IsSafe(interp)
int
Tcl_MakeSafe(interp)
Tcl_Interp *
Tcl_CreateSlave(interp, slaveName, isSafe)
Tcl_Interp *
Tcl_GetSlave(interp, slaveName)
Tcl_Interp *
Tcl_GetMaster(interp)
int
Tcl_GetInterpPath(askingInterp, slaveInterp)
int
Tcl_CreateAlias(slaveInterp, srcCmd, targetInterp, targetCmd, argc, argv)
int
Tcl_CreateAliasObj(slaveInterp, srcCmd, targetInterp, targetCmd, objc, objv)
int
Tcl_GetAlias(interp, srcCmd, targetInterpPtr, targetCmdPtr, argcPtr, argvPtr)
int
Tcl_GetAliasObj(interp, srcCmd, targetInterpPtr, targetCmdPtr, objcPtr, objvPtr)
int
Tcl_ExposeCommand(interp, hiddenCmdName, cmdName)
int
Tcl_HideCommand(interp, cmdName, hiddenCmdName)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which to execute the specified command.

char *slaveName (in)
Name of slave interpreter to create or manipulate.

int isSafe (in)
If non-zero, a ``safe'' slave that is suitable for running untrusted code is created, otherwise a trusted slave is created.

Tcl_Interp *slaveInterp (in)
Interpreter to use for creating the source command for an alias (see below).

char *srcCmd (in)
Name of source command for alias.

Tcl_Interp *targetInterp (in)
Interpreter that contains the target command for an alias.

char *targetCmd (in)
Name of target command for alias in targetInterp.

int argc (in)
Count of additional arguments to pass to the alias command.

char **argv (in)
Vector of strings, the additional arguments to pass to the alias command. This storage is owned by the caller.

int objc (in)
Count of additional object arguments to pass to the alias object command.

Tcl_Object **objv (in)
Vector of Tcl_Obj structures, the additional object argumenst to pass to the alias object command. This storage is owned by the caller.

Tcl_Interp **targetInterpPtr (in)
Pointer to location to store the address of the interpreter where a target command is defined for an alias.

char **targetCmdPtr (out)
Pointer to location to store the address of the name of the target command for an alias.

int *argcPtr (out)
Pointer to location to store count of additional arguments to be passed to the alias. The location is in storage owned by the caller.

char ***argvPtr (out)
Pointer to location to store a vector of strings, the additional arguments to pass to an alias. The location is in storage owned by the caller, the vector of strings is owned by the called function.

int *objcPtr (out)
Pointer to location to store count of additional object arguments to be passed to the alias. The location is in storage owned by the caller.

Tcl_Obj ***objvPtr (out)
Pointer to location to store a vector of Tcl_Obj structures, the additional arguments to pass to an object alias command. The location is in storage owned by the caller, the vector of Tcl_Obj structures is owned by the called function.

char *cmdName (in)
Name of an exposed command to hide or create.

char *hiddenCmdName (in)
Name under which a hidden command is stored and with which it can be exposed or invoked.

DESCRIPTION

These procedures are intended for access to the multiple interpreter facility from inside C programs. They enable managing multiple interpreters in a hierarchical relationship, and the management of aliases, commands that when invoked in one interpreter execute a command in another interpreter. The return value for those procedures that return an int is either TCL_OK or TCL_ERROR. If TCL_ERROR is returned then the result field of the interpreter contains an error message.

Tcl_CreateSlave creates a new interpreter as a slave of interp. It also creates a slave command named slaveName in interp which allows interp to manipulate the new slave. If isSafe is zero, the command creates a trusted slave in which Tcl code has access to all the Tcl commands. If it is 1, the command creates a ``safe'' slave in which Tcl code has access only to set of Tcl commands defined as ``Safe Tcl''; see the manual entry for the Tcl interp command for details. If the creation of the new slave interpreter failed, NULL is returned.

Tcl_IsSafe returns 1 if interp is ``safe'' (was created with the TCL_SAFE_INTERPRETER flag specified), 0 otherwise.

Tcl_MakeSafe makes interp ``safe'' by removing all non-core and core unsafe functionality. Note that if you call this after adding some extension to an interpreter, all traces of that extension will be removed from the interpreter.

Tcl_GetSlave returns a pointer to a slave interpreter of interp. The slave interpreter is identified by slaveName. If no such slave interpreter exists, NULL is returned.

Tcl_GetMaster returns a pointer to the master interpreter of interp. If interp has no master (it is a top-level interpreter) then NULL is returned.

Tcl_GetInterpPath sets the result field in askingInterp to the relative path between askingInterp and slaveInterp; slaveInterp must be a slave of askingInterp. If the computation of the relative path succeeds, TCL_OK is returned, else TCL_ERROR is returned and the result field in askingInterp contains the error message.

Tcl_CreateAlias creates an object command named srcCmd in slaveInterp that when invoked, will cause the command targetCmd to be invoked in targetInterp. The arguments specified by the strings contained in argv are always prepended to any arguments supplied in the invocation of srcCmd and passed to targetCmd. This operation returns TCL_OK if it succeeds, or TCL_ERROR if it fails; in that case, an error message is left in the object result of slaveInterp. Note that there are no restrictions on the ancestry relationship (as created by Tcl_CreateSlave) between slaveInterp and targetInterp. Any two interpreters can be used, without any restrictions on how they are related.

Tcl_CreateAliasObj is similar to Tcl_CreateAlias except that it takes a vector of objects to pass as additional arguments instead of a vector of strings.

Tcl_GetAlias returns information about an alias aliasName in interp. Any of the result fields can be NULL, in which case the corresponding datum is not returned. If a result field is non-NULL, the address indicated is set to the corresponding datum. For example, if targetNamePtr is non-NULL it is set to a pointer to the string containing the name of the target command.

Tcl_GetAliasObj is similar to Tcl_GetAlias except that it returns a pointer to a vector of Tcl_Obj structures instead of a vector of strings.

Tcl_ExposeCommand moves the command named hiddenCmdName from the set of hidden commands to the set of exposed commands, putting it under the name cmdName. HiddenCmdName must be the name of an existing hidden command, or the operation will return TCL_ERROR and leave an error message in the result field in interp. If an exposed command named cmdName already exists, the operation returns TCL_ERROR and leaves an error message in the object result of interp. If the operation succeeds, it returns TCL_OK. After executing this command, attempts to use cmdName in a call to Tcl_Eval or with the Tcl eval command will again succeed.

Tcl_HideCommand moves the command named cmdName from the set of exposed commands to the set of hidden commands, under the name hiddenCmdName. CmdName must be the name of an existing exposed command, or the operation will return TCL_ERROR and leave an error message in the object result of interp. Currently both cmdName and hiddenCmdName must not contain namespace qualifiers, or the operation will return TCL_ERROR and leave an error message in the object result of interp. The CmdName will be looked up in the global namespace, and not relative to the current namespace, even if the current namespace is not the global one. If a hidden command whose name is hiddenCmdName already exists, the operation also returns TCL_ERROR and the result field in interp contains an error message. If the operation succeeds, it returns TCL_OK. After executing this command, attempts to use cmdName in a call to Tcl_Eval or with the Tcl eval command will fail.

For a description of the Tcl interface to multiple interpreters, see interp(n).

SEE ALSO

interp

KEYWORDS

alias, command, exposed commands, hidden commands, interpreter, invoke, master, slave,
Copyright © 1995-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_CreateTimerHandler manual page

NAME

Tcl_CreateTimerHandler, Tcl_DeleteTimerHandler - call a procedure at a given time

SYNOPSIS

#include <tcl.h>
Tcl_TimerToken
Tcl_CreateTimerHandler(milliseconds, proc, clientData)
Tcl_DeleteTimerHandler(token)

ARGUMENTS

int milliseconds (in)
How many milliseconds to wait before invoking proc.

Tcl_TimerProc *proc (in)
Procedure to invoke after milliseconds have elapsed.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

Tcl_TimerToken token (in)
Token for previously-created timer handler (the return value from some previous call to Tcl_CreateTimerHandler).

DESCRIPTION

Tcl_CreateTimerHandler arranges for proc to be invoked at a time milliseconds milliseconds in the future. The callback to proc will be made by Tcl_DoOneEvent, so Tcl_CreateTimerHandler is only useful in programs that dispatch events through Tcl_DoOneEvent or through Tcl commands such as vwait. The call to proc may not be made at the exact time given by milliseconds: it will be made at the next opportunity after that time. For example, if Tcl_DoOneEvent isn't called until long after the time has elapsed, or if there are other pending events to process before the call to proc, then the call to proc will be delayed.

Proc should have arguments and return value that match the type Tcl_TimerProc:

typedef void Tcl_TimerProc(ClientData clientData);
The clientData parameter to proc is a copy of the clientData argument given to Tcl_CreateTimerHandler when the callback was created. Typically, clientData points to a data structure containing application-specific information about what to do in proc.

Tcl_DeleteTimerHandler may be called to delete a previously-created timer handler. It deletes the handler indicated by token so that no call to proc will be made; if that handler no longer exists (e.g. because the time period has already elapsed and proc has been invoked then Tcl_DeleteTimerHandler does nothing. The tokens returned by Tcl_CreateTimerHandler never have a value of NULL, so if NULL is passed to Tcl_DeleteTimerHandler then the procedure does nothing.

KEYWORDS

callback, clock, handler, timer
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tcl_CreateTrace manual page

NAME

Tcl_CreateTrace, Tcl_DeleteTrace - arrange for command execution to be traced

SYNOPSIS

#include <tcl.h>
Tcl_Trace
Tcl_CreateTrace(interp, level, proc, clientData)
Tcl_DeleteTrace(interp, trace)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter containing command to be traced or untraced.

int level (in)
Only commands at or below this nesting level will be traced. 1 means top-level commands only, 2 means top-level commands or those that are invoked as immediate consequences of executing top-level commands (procedure bodies, bracketed commands, etc.) and so on.

Tcl_CmdTraceProc *proc (in)
Procedure to call for each command that's executed. See below for details on the calling sequence.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

Tcl_Trace trace (in)
Token for trace to be removed (return value from previous call to Tcl_CreateTrace).

DESCRIPTION

Tcl_CreateTrace arranges for command tracing. From now on, proc will be invoked before Tcl calls command procedures to process commands in interp. The return value from Tcl_CreateTrace is a token for the trace, which may be passed to Tcl_DeleteTrace to remove the trace. There may be many traces in effect simultaneously for the same command interpreter.

Proc should have arguments and result that match the type Tcl_CmdTraceProc:

typedef void Tcl_CmdTraceProc(
    ClientData clientData,
    Tcl_Interp *interp,
    int level,
    char *command,
    Tcl_CmdProc *cmdProc,
    ClientData cmdClientData,
    int argc,
    char *argv[]);
The clientData and interp parameters are copies of the corresponding arguments given to Tcl_CreateTrace. ClientData typically points to an application-specific data structure that describes what to do when proc is invoked. Level gives the nesting level of the command (1 for top-level commands passed to Tcl_Eval by the application, 2 for the next-level commands passed to Tcl_Eval as part of parsing or interpreting level-1 commands, and so on). Command points to a string containing the text of the command, before any argument substitution. CmdProc contains the address of the command procedure that will be called to process the command (i.e. the proc argument of some previous call to Tcl_CreateCommand) and cmdClientData contains the associated client data for cmdProc (the clientData value passed to Tcl_CreateCommand). Argc and argv give the final argument information that will be passed to cmdProc, after command, variable, and backslash substitution. Proc must not modify the command or argv strings.

Tracing will only occur for commands at nesting level less than or equal to the level parameter (i.e. the level parameter to proc will always be less than or equal to the level parameter to Tcl_CreateTrace).

Calls to proc will be made by the Tcl parser immediately before it calls the command procedure for the command (cmdProc). This occurs after argument parsing and substitution, so tracing for substituted commands occurs before tracing of the commands containing the substitutions. If there is a syntax error in a command, or if there is no command procedure associated with a command name, then no tracing will occur for that command. If a string passed to Tcl_Eval contains multiple commands (bracketed, or on different lines) then multiple calls to proc will occur, one for each command. The command string for each of these trace calls will reflect only a single command, not the entire string passed to Tcl_Eval.

Tcl_DeleteTrace removes a trace, so that no future calls will be made to the procedure associated with the trace. After Tcl_DeleteTrace returns, the caller should never again use the trace token.

KEYWORDS

command, create, delete, interpreter, trace
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tcl_DetachPids manual page

NAME

Tcl_DetachPids, Tcl_ReapDetachedProcs, Tcl_WaitPid - manage child processes in background

SYNOPSIS

#include <tcl.h>
Tcl_DetachPids(numPids, pidPtr)
Tcl_ReapDetachedProcs()
Tcl_Pid
Tcl_WaitPid(pid, statPtr, options)

ARGUMENTS

int numPids (in)
Number of process ids contained in the array pointed to by pidPtr.

int *pidPtr (in)
Address of array containing numPids process ids.

Tcl_Pid pid (in)
The id of the process (pipe) to wait for.

int* statPtr (out)
The result of waiting on a process (pipe). Either 0 or ECHILD.

int options ()
The options controlling the wait. WNOHANG specifies not to wait when checking the process.

DESCRIPTION

Tcl_DetachPids and Tcl_ReapDetachedProcs provide a mechanism for managing subprocesses that are running in background. These procedures are needed because the parent of a process must eventually invoke the waitpid kernel call (or one of a few other similar kernel calls) to wait for the child to exit. Until the parent waits for the child, the child's state cannot be completely reclaimed by the system. If a parent continually creates children and doesn't wait on them, the system's process table will eventually overflow, even if all the children have exited.

Tcl_DetachPids may be called to ask Tcl to take responsibility for one or more processes whose process ids are contained in the pidPtr array passed as argument. The caller presumably has started these processes running in background and doesn't want to have to deal with them again.

Tcl_ReapDetachedProcs invokes the waitpid kernel call on each of the background processes so that its state can be cleaned up if it has exited. If the process hasn't exited yet, Tcl_ReapDetachedProcs doesn't wait for it to exit; it will check again the next time it is invoked. Tcl automatically calls Tcl_ReapDetachedProcs each time the exec command is executed, so in most cases it isn't necessary for any code outside of Tcl to invoke Tcl_ReapDetachedProcs. However, if you call Tcl_DetachPids in situations where the exec command may never get executed, you may wish to call Tcl_ReapDetachedProcs from time to time so that background processes can be cleaned up.

Tcl_WaitPid is a thin wrapper around the facilities provided by the operating system to wait on the end of a spawned process and to check a whether spawned process is still running. It is used by Tcl_ReapDetachedProcs and the channel system to portably access the operating system.

KEYWORDS

background, child, detach, process, wait
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_DoOneEvent manual page

NAME
Tcl_DoOneEvent - wait for events and invoke event handlers
SYNOPSIS
ARGUMENTS
DESCRIPTION
TCL_WINDOW_EVENTS -
TCL_FILE_EVENTS -
TCL_TIMER_EVENTS -
TCL_IDLE_EVENTS -
TCL_ALL_EVENTS -
TCL_DONT_WAIT -
KEYWORDS

NAME

Tcl_DoOneEvent - wait for events and invoke event handlers

SYNOPSIS

#include <tcl.h>
int
Tcl_DoOneEvent(flags)

ARGUMENTS

int flags (in)
This parameter is normally zero. It may be an OR-ed combination of any of the following flag bits: TCL_WINDOW_EVENTS, TCL_FILE_EVENTS, TCL_TIMER_EVENTS, TCL_IDLE_EVENTS, TCL_ALL_EVENTS, or TCL_DONT_WAIT.

DESCRIPTION

This procedure is the entry point to Tcl's event loop; it is responsible for waiting for events and dispatching event handlers created with procedures such as Tk_CreateEventHandler, Tcl_CreateFileHandler, Tcl_CreateTimerHandler, and Tcl_DoWhenIdle. Tcl_DoOneEvent checks to see if events are already present on the Tcl event queue; if so, it calls the handler(s) for the first (oldest) event, removes it from the queue, and returns. If there are no events ready to be handled, then Tcl_DoOneEvent checks for new events from all possible sources. If any are found, it puts all of them on Tcl's event queue, calls handlers for the first event on the queue, and returns. If no events are found, Tcl_DoOneEvent checks for Tcl_DoWhenIdle callbacks; if any are found, it invokes all of them and returns. Finally, if no events or idle callbacks have been found, then Tcl_DoOneEvent sleeps until an event occurs; then it adds any new events to the Tcl event queue, calls handlers for the first event, and returns. The normal return value is 1 to signify that some event was processed (see below for other alternatives).

If the flags argument to Tcl_DoOneEvent is non-zero, it restricts the kinds of events that will be processed by Tcl_DoOneEvent. Flags may be an OR-ed combination of any of the following bits:

TCL_WINDOW_EVENTS -
Process window system events.

TCL_FILE_EVENTS -
Process file events.

TCL_TIMER_EVENTS -
Process timer events.

TCL_IDLE_EVENTS -
Process idle callbacks.

TCL_ALL_EVENTS -
Process all kinds of events: equivalent to OR-ing together all of the above flags or specifying none of them.

TCL_DONT_WAIT -
Don't sleep: process only events that are ready at the time of the call.

If any of the flags TCL_WINDOW_EVENTS, TCL_FILE_EVENTS, TCL_TIMER_EVENTS, or TCL_IDLE_EVENTS is set, then the only events that will be considered are those for which flags are set. Setting none of these flags is equivalent to the value TCL_ALL_EVENTS, which causes all event types to be processed. If an application has defined additional event sources with Tcl_CreateEventSource, then additional flag values may also be valid, depending on those event sources.

The TCL_DONT_WAIT flag causes Tcl_DoOneEvent not to put the process to sleep: it will check for events but if none are found then it returns immediately with a return value of 0 to indicate that no work was done. Tcl_DoOneEvent will also return 0 without doing anything if the only alternative is to block forever (this can happen, for example, if flags is TCL_IDLE_EVENTS and there are no Tcl_DoWhenIdle callbacks pending, or if no event handlers or timer handlers exist).

Tcl_DoOneEvent may be invoked recursively. For example, it is possible to invoke Tcl_DoOneEvent recursively from a handler called by Tcl_DoOneEvent. This sort of operation is useful in some modal situations, such as when a notification dialog has been popped up and an application wishes to wait for the user to click a button in the dialog before doing anything else.

KEYWORDS

callback, event, handler, idle, timer
Copyright © 1990-1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_DoubleObj manual page

NAME

Tcl_NewDoubleObj, Tcl_SetDoubleObj, Tcl_GetDoubleFromObj - manipulate Tcl objects as floating-point values

SYNOPSIS

#include <tcl.h>
Tcl_Obj *
Tcl_NewDoubleObj(doubleValue)
Tcl_SetDoubleObj(objPtr, doubleValue)
int
Tcl_GetDoubleFromObj(interp, objPtr, doublePtr)

ARGUMENTS

double doubleValue (in)
A double-precision floating point value used to initialize or set a double object.

Tcl_Obj *objPtr (in/out)
For Tcl_SetDoubleObj, this points to the object to be converted to double type. For Tcl_GetDoubleFromObj, this refers to the object from which to get a double value; if objPtr does not already point to a double object, an attempt will be made to convert it to one.

Tcl_Interp *interp (in/out)
If an error occurs during conversion, an error message is left in the interpreter's result object unless interp is NULL.

double *doublePtr (out)
Points to place to store the double value obtained from objPtr.

DESCRIPTION

These procedures are used to create, modify, and read double Tcl objects from C code. Tcl_NewDoubleObj and Tcl_SetDoubleObj will create a new object of double type or modify an existing object to have double type. Both of these procedures set the object to have the double-precision floating point value given by doubleValue; Tcl_NewDoubleObj returns a pointer to a newly created object with reference count zero. Both procedures set the object's type to be double and assign the double value to the object's internal representation doubleValue member. Tcl_SetDoubleObj invalidates any old string representation and, if the object is not already a double object, frees any old internal representation.

Tcl_GetDoubleFromObj attempts to return a double value from the Tcl object objPtr. If the object is not already a double object, it will attempt to convert it to one. If an error occurs during conversion, it returns TCL_ERROR and leaves an error message in the interpreter's result object unless interp is NULL. Otherwise, it returns TCL_OK and stores the double value in the address given by doublePtr. If the object is not already a double object, the conversion will free any old internal representation.

SEE ALSO

Tcl_NewObj, Tcl_DecrRefCount, Tcl_IncrRefCount, Tcl_GetObjResult

KEYWORDS

double, double object, double type, internal representation, object, object type, string representation
Copyright © 1996-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_DoWhenIdle manual page

NAME

Tcl_DoWhenIdle, Tcl_CancelIdleCall - invoke a procedure when there are no pending events

SYNOPSIS

#include <tcl.h>
Tcl_DoWhenIdle(proc, clientData)
Tcl_CancelIdleCall(proc, clientData)

ARGUMENTS

Tcl_IdleProc *proc (in)
Procedure to invoke.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

Tcl_DoWhenIdle arranges for proc to be invoked when the application becomes idle. The application is considered to be idle when Tcl_DoOneEvent has been called, couldn't find any events to handle, and is about to go to sleep waiting for an event to occur. At this point all pending Tcl_DoWhenIdle handlers are invoked. For each call to Tcl_DoWhenIdle there will be a single call to proc; after proc is invoked the handler is automatically removed. Tcl_DoWhenIdle is only usable in programs that use Tcl_DoOneEvent to dispatch events.

Proc should have arguments and result that match the type Tcl_IdleProc:

typedef void Tcl_IdleProc(ClientData clientData);
The clientData parameter to proc is a copy of the clientData argument given to Tcl_DoWhenIdle. Typically, clientData points to a data structure containing application-specific information about what proc should do.

Tcl_CancelIdleCall may be used to cancel one or more previous calls to Tcl_DoWhenIdle: if there is a Tcl_DoWhenIdle handler registered for proc and clientData, then it is removed without invoking it. If there is more than one handler on the idle list that refers to proc and clientData, all of the handlers are removed. If no existing handlers match proc and clientData then nothing happens.

Tcl_DoWhenIdle is most useful in situations where (a) a piece of work will have to be done but (b) it's possible that something will happen in the near future that will change what has to be done or require something different to be done. Tcl_DoWhenIdle allows the actual work to be deferred until all pending events have been processed. At this point the exact work to be done will presumably be known and it can be done exactly once.

For example, Tcl_DoWhenIdle might be used by an editor to defer display updates until all pending commands have been processed. Without this feature, redundant redisplays might occur in some situations, such as the processing of a command file.

BUGS

At present it is not safe for an idle callback to reschedule itself 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.

KEYWORDS

callback, defer, idle callback
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_DString manual page

NAME

Tcl_DStringInit, Tcl_DStringAppend, Tcl_DStringAppendElement, Tcl_DStringStartSublist, Tcl_DStringEndSublist, Tcl_DStringLength, Tcl_DStringValue, Tcl_DStringSetLength, Tcl_DStringFree, Tcl_DStringResult, Tcl_DStringGetResult - manipulate dynamic strings

SYNOPSIS

#include <tcl.h>
Tcl_DStringInit(dsPtr)
char *
Tcl_DStringAppend(dsPtr, string, length)
char *
Tcl_DStringAppendElement(dsPtr, string)
Tcl_DStringStartSublist(dsPtr)
Tcl_DStringEndSublist(dsPtr)
int
Tcl_DStringLength(dsPtr)
char *
Tcl_DStringValue(dsPtr)
Tcl_DStringSetLength(dsPtr, newLength)
Tcl_DStringTrunc(dsPtr, newLength)
Tcl_DStringFree(dsPtr)
Tcl_DStringResult(interp, dsPtr)
Tcl_DStringGetResult(interp, dsPtr)

ARGUMENTS

Tcl_DString *dsPtr (in/out)
Pointer to structure that is used to manage a dynamic string.

char *string (in)
Pointer to characters to add to dynamic string.

int length (in)
Number of characters from string to add to dynamic string. If -1, add all characters up to null terminating character.

int newLength (in)
New length for dynamic string, not including null terminating character.

Tcl_Interp *interp (in/out)
Interpreter whose result is to be set from or moved to the dynamic string.

DESCRIPTION

Dynamic strings provide a mechanism for building up arbitrarily long strings by gradually appending information. If the dynamic string is short then there will be no memory allocation overhead; as the string gets larger, additional space will be allocated as needed.

Tcl_DStringInit initializes a dynamic string to zero length. The Tcl_DString structure must have been allocated by the caller. No assumptions are made about the current state of the structure; anything already in it is discarded. If the structure has been used previously, Tcl_DStringFree should be called first to free up any memory allocated for the old string.

Tcl_DStringAppend adds new information to a dynamic string, allocating more memory for the string if needed. If length is less than zero then everything in string is appended to the dynamic string; otherwise length specifies the number of bytes to append. Tcl_DStringAppend returns a pointer to the characters of the new string. The string can also be retrieved from the string field of the Tcl_DString structure.

Tcl_DStringAppendElement is similar to Tcl_DStringAppend except that it doesn't take a length argument (it appends all of string) and it converts the string to a proper list element before appending. Tcl_DStringAppendElement adds a separator space before the new list element unless the new list element is the first in a list or sub-list (i.e. either the current string is empty, or it contains the single character ``{'', or the last two characters of the current string are `` {''). Tcl_DStringAppendElement returns a pointer to the characters of the new string.

Tcl_DStringStartSublist and Tcl_DStringEndSublist can be used to create nested lists. To append a list element that is itself a sublist, first call Tcl_DStringStartSublist, then call Tcl_DStringAppendElement for each of the elements in the sublist, then call Tcl_DStringEndSublist to end the sublist. Tcl_DStringStartSublist appends a space character if needed, followed by an open brace; Tcl_DStringEndSublist appends a close brace. Lists can be nested to any depth.

Tcl_DStringLength is a macro that returns the current length of a dynamic string (not including the terminating null character). Tcl_DStringValue is a macro that returns a pointer to the current contents of a dynamic string.

Tcl_DStringSetLength changes the length of a dynamic string. If newLength is less than the string's current length, then the string is truncated. If newLength is greater than the string's current length, then the string will become longer and new space will be allocated for the string if needed. However, Tcl_DStringSetLength will not initialize the new space except to provide a terminating null character; it is up to the caller to fill in the new space. Tcl_DStringSetLength does not free up the string's storage space even if the string is truncated to zero length, so Tcl_DStringFree will still need to be called.

Tcl_DStringTrunc changes the length of a dynamic string. This procedure is now deprecated. Tcl_DStringSetLength should be used instead.

Tcl_DStringFree should be called when you're finished using the string. It frees up any memory that was allocated for the string and reinitializes the string's value to an empty string.

Tcl_DStringResult sets the result of interp to the value of the dynamic string given by dsPtr. It does this by moving a pointer from dsPtr to the interpreter's result. This saves the cost of allocating new memory and copying the string. Tcl_DStringResult also reinitializes the dynamic string to an empty string.

Tcl_DStringGetResult does the opposite of Tcl_DStringResult. It sets the value of dsPtr to the result of interp and it clears interp's result. If possible it does this by moving a pointer rather than by copying the string.

KEYWORDS

append, dynamic string, free, result
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_DumpActiveMemory manual page

NAME

Tcl_DumpActiveMemory, Tcl_InitMemory, Tcl_ValidateAllMemory - Validated memory allocation interface.

SYNOPSIS

#include <tcl.h>
int
Tcl_DumpActiveMemory(fileName)
void
Tcl_InitMemory(interp)
void
Tcl_ValidateAllMemory(fileName, line)

ARGUMENTS

Tcl_Interp *interp (in)
Tcl interpreter in which to add commands.

char *fileName (in)
For Tcl_DumpActiveMemory, name of the file to which memory information will be written. For Tcl_ValidateAllMemory, name of the file from which the call is being made (normally __FILE__).

int line (in)
Line number at which the call to Tcl_ValidateAllMemory is made (normally __LINE__).

DESCRIPTION

These functions provide access to Tcl memory debugging information. They are only available when Tcl has been compiled with TCL_MEM_DEBUG defined at compile-time.

Tcl_DumpActiveMemory will output a list of all currently allocated memory to the specified file. The information output for each allocated block of memory is: starting and ending addresses (excluding guard zone), size, source file where ckalloc was called to allocate the block and line number in that file. It is especially useful to call Tcl_DumpActiveMemory after the Tcl interpreter has been deleted.

Tcl_InitMemory adds the Tcl memory command to the interpreter given by interp. It is called by Tcl_Main when Tcl has been compiled with TCL_MEM_DEBUG defined.

Tcl_ValidateAllMemory forces a validation of the guard zones of all currently allocated blocks of memory. Normally validation of a block occurs when its freed, unless full validation is enabled, in which case validation of all blocks occurs when ckalloc and ckfree are called. This function forces the validation to occur at any point.

SEE ALSO

TCL_MEM_DEBUG, memory

KEYWORDS

memory, debug
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 2000 by Scriptics Corporation.


Tcl Library Procedures - Tcl_GetEncoding manual page

NAME
Tcl_GetEncoding, Tcl_FreeEncoding, Tcl_ExternalToUtfDString, Tcl_ExternalToUtf, Tcl_UtfToExternalDString, Tcl_UtfToExternal, Tcl_WinTCharToUtf, Tcl_WinUtfToTChar, Tcl_GetEncodingName, Tcl_SetSystemEncoding, Tcl_GetEncodingNames, Tcl_CreateEncoding, Tcl_GetDefaultEncodingDir, Tcl_SetDefaultEncodingDir - procedures for creating and using encodings.
SYNOPSIS
ARGUMENTS
INTRODUCTION
DESCRIPTION
TCL_OK
TCL_CONVERT_NOSPACE
TCL_CONVERT_MULTIBYTE
TCL_CONVERT_SYNTAX
TCL_CONVERT_UNKNOWN
ENCODING FILES
[1] S
[2] D
[3] M
[4] E
KEYWORDS

NAME

Tcl_GetEncoding, Tcl_FreeEncoding, Tcl_ExternalToUtfDString, Tcl_ExternalToUtf, Tcl_UtfToExternalDString, Tcl_UtfToExternal, Tcl_WinTCharToUtf, Tcl_WinUtfToTChar, Tcl_GetEncodingName, Tcl_SetSystemEncoding, Tcl_GetEncodingNames, Tcl_CreateEncoding, Tcl_GetDefaultEncodingDir, Tcl_SetDefaultEncodingDir - procedures for creating and using encodings.

SYNOPSIS

#include <tcl.h>
#include <tclPlatDecls.h> /* Tcl_Win* functions only */
Tcl_Encoding
Tcl_GetEncoding(interp, name)
void
Tcl_FreeEncoding(encoding)
char *
Tcl_ExternalToUtfDString(encoding, src, srcLen, dstPtr)
int
Tcl_ExternalToUtf(interp, encoding, src, srcLen, flags, statePtr, dst, dstLen, srcReadPtr, dstWrotePtr,
dstCharsPtr)
char *
Tcl_UtfToExternalDString(encoding, src, srcLen, dstPtr)
int
Tcl_UtfToExternal(interp, encoding, src, srcLen, flags, statePtr, dst, dstLen, srcReadPtr, dstWrotePtr,
dstCharsPtr)
char *
Tcl_WinTCharToUtf(tsrc, srcLen, dstPtr)
TCHAR *
Tcl_WinUtfToTChar(src, srcLen, dstPtr)
char *
Tcl_GetEncodingName(encoding)
int
Tcl_SetSystemEncoding(interp, name)
void
Tcl_GetEncodingNames(interp)
Tcl_Encoding
Tcl_CreateEncoding(typePtr)
char *
Tcl_GetDefaultEncodingDir(void)
void
Tcl_SetDefaultEncodingDir(path)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting, or NULL if no error reporting is desired.

CONST char *name (in)
Name of encoding to load.

Tcl_Encoding encoding (in)
The encoding to query, free, or use for converting text. If encoding is NULL, the current system encoding is used.

CONST char *src (in)
For the Tcl_ExternalToUtf functions, an array of bytes in the specified encoding that are to be converted to UTF-8. For the Tcl_UtfToExternal and Tcl_WinUtfToTChar functions, an array of UTF-8 characters to be converted to the specified encoding.

CONST TCHAR *tsrc (in)
An array of Windows TCHAR characters to convert to UTF-8.

int srcLen (in)
Length of src or tsrc in bytes. If the length is negative, the encoding-specific length of the string is used.

Tcl_DString *dstPtr (out)
Pointer to an uninitialized or free Tcl_DString in which the converted result will be stored.

int flags (in)
Various flag bits OR-ed together. TCL_ENCODING_START signifies that the source buffer is the first block in a (potentially multi-block) input stream, telling the conversion routine to reset to an initial state and perform any initialization that needs to occur before the first byte is converted. TCL_ENCODING_END signifies that the source buffer is the last block in a (potentially multi-block) input stream, telling the conversion routine to perform any finalization that needs to occur after the last byte is converted and then to reset to an initial state. TCL_ENCODING_STOPONERROR signifies that the conversion routine should return immediately upon reading a source character that doesn't exist in the target encoding; otherwise a default fallback character will automatically be substituted.

Tcl_EncodingState *statePtr (in/out)
Used when converting a (generally long or indefinite length) byte stream in a piece by piece fashion. The conversion routine stores its current state in *statePtr after src (the buffer containing the current piece) has been converted; that state information must be passed back when converting the next piece of the stream so the conversion routine knows what state it was in when it left off at the end of the last piece. May be NULL, in which case the value specified for flags is ignored and the source buffer is assumed to contain the complete string to convert.

char *dst (out)
Buffer in which the converted result will be stored. No more than dstLen bytes will be stored in dst.

int dstLen (in)
The maximum length of the output buffer dst in bytes.

int *srcReadPtr (out)
Filled with the number of bytes from src that were actually converted. This may be less than the original source length if there was a problem converting some source characters. May be NULL.

int *dstWrotePtr (out)
Filled with the number of bytes that were actually stored in the output buffer as a result of the conversion. May be NULL.

int *dstCharsPtr (out)
Filled with the number of characters that correspond to the number of bytes stored in the output buffer. May be NULL.

Tcl_EncodingType *typePtr (in)
Structure that defines a new type of encoding.

char *path (in)
A path to the location of the encoding file.

INTRODUCTION

These routines convert between Tcl's internal character representation, UTF-8, and character representations used by various operating systems or file systems, such as Unicode, ASCII, or Shift-JIS. When operating on strings, such as such as obtaining the names of files or displaying characters using international fonts, the strings must be translated into one or possibly multiple formats that the various system calls can use. For instance, on a Japanese Unix workstation, a user might obtain a filename represented in the EUC-JP file encoding and then translate the characters to the jisx0208 font encoding in order to display the filename in a Tk widget. The purpose of the encoding package is to help bridge the translation gap. UTF-8 provides an intermediate staging ground for all the various encodings. In the example above, text would be translated into UTF-8 from whatever file encoding the operating system is using. Then it would be translated from UTF-8 into whatever font encoding the display routines require.

Some basic encodings are compiled into Tcl. Others can be defined by the user or dynamically loaded from encoding files in a platform-independent manner.

DESCRIPTION

Tcl_GetEncoding finds an encoding given its name. The name may refer to a builtin Tcl encoding, a user-defined encoding registered by calling Tcl_CreateEncoding, or a dynamically-loadable encoding file. The return value is a token that represents the encoding and can be used in subsequent calls to procedures such as Tcl_GetEncodingName, Tcl_FreeEncoding, and Tcl_UtfToExternal. If the name did not refer to any known or loadable encoding, NULL is returned and an error message is returned in interp.

The encoding package maintains a database of all encodings currently in use. The first time name is seen, Tcl_GetEncoding returns an encoding with a reference count of 1. If the same name is requested further times, then the reference count for that encoding is incremented without the overhead of allocating a new encoding and all its associated data structures.

When an encoding is no longer needed, Tcl_FreeEncoding should be called to release it. When an encoding is no longer in use anywhere (i.e., it has been freed as many times as it has been gotten) Tcl_FreeEncoding will release all storage the encoding was using and delete it from the database.

Tcl_ExternalToUtfDString converts a source buffer src from the specified encoding into UTF-8. The converted bytes are stored in dstPtr, which is then NULL terminated. The caller should eventually call Tcl_DStringFree to free any information stored in dstPtr. When converting, if any of the characters in the source buffer cannot be represented in the target encoding, a default fallback character will be used. The return value is a pointer to the value stored in the DString.

Tcl_ExternalToUtf converts a source buffer src from the specified encoding into UTF-8. Up to srcLen bytes are converted from the source buffer and up to dstLen converted bytes are stored in dst. In all cases, *srcReadPtr is filled with the number of bytes that were successfully converted from src and *dstWrotePtr is filled with the corresponding number of bytes that were stored in dst. The return value is one of the following:

TCL_OK
All bytes of src were converted.

TCL_CONVERT_NOSPACE
The destination buffer was not large enough for all of the converted data; as many characters as could fit were converted though.

TCL_CONVERT_MULTIBYTE
The last fews bytes in the source buffer were the beginning of a multibyte sequence, but more bytes were needed to complete this sequence. A subsequent call to the conversion routine should pass a buffer containing the unconverted bytes that remained in src plus some further bytes from the source stream to properly convert the formerly split-up multibyte sequence.

TCL_CONVERT_SYNTAX
The source buffer contained an invalid character sequence. This may occur if the input stream has been damaged or if the input encoding method was misidentified.

TCL_CONVERT_UNKNOWN
The source buffer contained a character that could not be represented in the target encoding and TCL_ENCODING_STOPONERROR was specified.

Tcl_UtfToExternalDString converts a source buffer src from UTF-8 into the specified encoding. The converted bytes are stored in dstPtr, which is then terminated with the appropriate encoding-specific NULL. The caller should eventually call Tcl_DStringFree to free any information stored in dstPtr. When converting, if any of the characters in the source buffer cannot be represented in the target encoding, a default fallback character will be used. The return value is a pointer to the value stored in the DString.

Tcl_UtfToExternal converts a source buffer src from UTF-8 into the specified encoding. Up to srcLen bytes are converted from the source buffer and up to dstLen converted bytes are stored in dst. In all cases, *srcReadPtr is filled with the number of bytes that were successfully converted from src and *dstWrotePtr is filled with the corresponding number of bytes that were stored in dst. The return values are the same as the return values for Tcl_ExternalToUtf.

Tcl_WinUtfToTChar and Tcl_WinTCharToUtf are Windows-only convenience functions for converting between UTF-8 and Windows strings. On Windows 95 (as with the Macintosh and Unix operating systems), all strings exchanged between Tcl and the operating system are "char" based. On Windows NT, some strings exchanged between Tcl and the operating system are "char" oriented while others are in Unicode. By convention, in Windows a TCHAR is a character in the ANSI code page on Windows 95 and a Unicode character on Windows NT.

If you planned to use the same "char" based interfaces on both Windows 95 and Windows NT, you could use Tcl_UtfToExternal and Tcl_ExternalToUtf (or their Tcl_DString equivalents) with an encoding of NULL (the current system encoding). On the other hand, if you planned to use the Unicode interface when running on Windows NT and the "char" 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 psuedo-code):

if (running NT) {
    encoding <- Tcl_GetEncoding("unicode");
    nativeBuffer <- Tcl_UtfToExternal(encoding, utfBuffer);
    Tcl_FreeEncoding(encoding);
} else {
    nativeBuffer <- Tcl_UtfToExternal(NULL, utfBuffer);
Tcl_WinUtfToTChar and Tcl_WinTCharToUtf automatically handle this test and use the proper encoding based on the current operating system. Tcl_WinUtfToTChar returns a pointer to a TCHAR string, and Tcl_WinTCharToUtf expects a TCHAR string pointer as the src string. Otherwise, these functions behave identically to Tcl_UtfToExternalDString and Tcl_ExternalToUtfDString.

Tcl_GetEncodingName is roughly the inverse of Tcl_GetEncoding. Given an encoding, the return value is the name argument that was used to create the encoding. The string returned by Tcl_GetEncodingName is only guaranteed to persist until the encoding is deleted. The caller must not modify this string.

Tcl_SetSystemEncoding sets the default encoding that should be used whenever the user passes a NULL value for the encoding argument to any of the other encoding functions. If name is NULL, the system encoding is reset to the default system encoding, binary. If the name did not refer to any known or loadable encoding, TCL_ERROR is returned and an error message is left in interp. Otherwise, this procedure increments the reference count of the new system encoding, decrements the reference count of the old system encoding, and returns TCL_OK.

Tcl_GetEncodingNames sets the interp result to a list consisting of the names of all the encodings that are currently defined or can be dynamically loaded, searching the encoding path specified by Tcl_SetDefaultEncodingDir. This procedure does not ensure that the dynamically-loadable encoding files contain valid data, but merely that they exist.

Tcl_CreateEncoding defines a new encoding and registers the C procedures that are called back to convert between the encoding and UTF-8. Encodings created by Tcl_CreateEncoding are thereafter visible in the database used by Tcl_GetEncoding. Just as with the Tcl_GetEncoding procedure, the return value is a token that represents the encoding and can be used in subsequent calls to other encoding functions. Tcl_CreateEncoding returns an encoding with a reference count of 1. If an encoding with the specified name already exists, then its entry in the database is replaced with the new encoding; the token for the old encoding will remain valid and continue to behave as before, but users of the new token will now call the new encoding procedures.

The typePtr argument to Tcl_CreateEncoding contains information about the name of the encoding and the procedures that will be called to convert between this encoding and UTF-8. It is defined as follows:

typedef struct Tcl_EncodingType {
    CONST char *encodingName;
    Tcl_EncodingConvertProc *toUtfProc;
    Tcl_EncodingConvertProc *fromUtfProc;
    Tcl_EncodingFreeProc *freeProc;
    ClientData clientData;
    int nullSize;
} Tcl_EncodingType;

The encodingName provides a string name for the encoding, by which it can be referred in other procedures such as Tcl_GetEncoding. The toUtfProc refers to a callback procedure to invoke to convert text from this encoding into UTF-8. The fromUtfProc refers to a callback procedure to invoke to convert text from UTF-8 into this encoding. The freeProc refers to a callback procedure to invoke when this encoding is deleted. The freeProc field may be NULL. The clientData contains an arbitrary one-word value passed to toUtfProc, fromUtfProc, and freeProc whenever they are called. Typically, this is a pointer to a data structure containing encoding-specific information that can be used by the callback procedures. For instance, two very similar encodings such as ascii and macRoman may use the same callback procedure, but use different values of clientData to control its behavior. The nullSize specifies the number of zero bytes that signify end-of-string in this encoding. It must be 1 (for single-byte or multi-byte encodings like ASCII or Shift-JIS) or 2 (for double-byte encodings like Unicode). Constant-sized encodings with 3 or more bytes per character (such as CNS11643) are not accepted.

The callback procedures toUtfProc and fromUtfProc should match the type Tcl_EncodingConvertProc:

typedef int Tcl_EncodingConvertProc(
    ClientData clientData,
    CONST char *src,
    int srcLen,
    int flags,
    Tcl_Encoding *statePtr,
    char *dst,
    int dstLen,
    int *srcReadPtr,
    int *dstWrotePtr,
    int *dstCharsPtr);

The toUtfProc and fromUtfProc procedures are called by the Tcl_ExternalToUtf or Tcl_UtfToExternal family of functions to perform the actual conversion. The clientData parameter to these procedures is the same as the clientData field specified to Tcl_CreateEncoding when the encoding was created. The remaining arguments to the callback procedures are the same as the arguments, documented at the top, to Tcl_ExternalToUtf or Tcl_UtfToExternal, with the following exceptions. If the srcLen argument to one of those high-level functions is negative, the value passed to the callback procedure will be the appropriate encoding-specific string length of src. If any of the srcReadPtr, dstWrotePtr, or dstCharsPtr arguments to one of the high-level functions is NULL, the corresponding value passed to the callback procedure will be a non-NULL location.

The callback procedure freeProc, if non-NULL, should match the type Tcl_EncodingFreeProc:

typedef void Tcl_EncodingFreeProc(
    ClientData clientData);

This freeProc function is called when the encoding is deleted. The clientData parameter is the same as the clientData field specified to Tcl_CreateEncoding when the encoding was created.

Tcl_GetDefaultEncodingDir and Tcl_SetDefaultEncodingDir access and set the directory to use when locating the default encoding files. If this value is not NULL, the TclpInitLibraryPath routine appends the path to the head of the search path, and uses this path as the first place to look into when trying to locate the encoding file.

ENCODING FILES

Space would prohibit precompiling into Tcl every possible encoding algorithm, so many encodings are stored on disk as dynamically-loadable encoding files. This behavior also allows the user to create additional encoding files that can be loaded using the same mechanism. These encoding files contain information about the tables and/or escape sequences used to map between an external encoding and Unicode. The external encoding may consist of single-byte, multi-byte, or double-byte characters.

Each dynamically-loadable encoding is represented as a text file. The initial line of the file, beginning with a ``#'' symbol, is a comment that provides a human-readable description of the file. The next line identifies the type of encoding file. It can be one of the following letters:

[1] S
A single-byte encoding, where one character is always one byte long in the encoding. An example is iso8859-1, used by many European languages.

[2] D
A double-byte encoding, where one character is always two bytes long in the encoding. An example is big5, used for Chinese text.

[3] M
A multi-byte encoding, where one character may be either one or two bytes long. Certain bytes are a lead bytes, indicating that another byte must follow and that together the two bytes represent one character. Other bytes are not lead bytes and represent themselves. An example is shiftjis, used by many Japanese computers.

[4] E
An escape-sequence encoding, specifying that certain sequences of bytes do not represent characters, but commands that describe how following bytes should be interpreted.

The rest of the lines in the file depend on the type.

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 shiftjis encoding (this is not the complete file):

# Encoding file: shiftjis, multi-byte
M
003F 0 40
00
0000000100020003000400050006000700080009000A000B000C000D000E000F
0010001100120013001400150016001700180019001A001B001C001D001E001F
0020002100220023002400250026002700280029002A002B002C002D002E002F
0030003100320033003400350036003700380039003A003B003C003D003E003F
0040004100420043004400450046004700480049004A004B004C004D004E004F
0050005100520053005400550056005700580059005A005B005C005D005E005F
0060006100620063006400650066006700680069006A006B006C006D006E006F
0070007100720073007400750076007700780079007A007B007C007D203E007F
0080000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FF61FF62FF63FF64FF65FF66FF67FF68FF69FF6AFF6BFF6CFF6DFF6EFF6F
FF70FF71FF72FF73FF74FF75FF76FF77FF78FF79FF7AFF7BFF7CFF7DFF7EFF7F
FF80FF81FF82FF83FF84FF85FF86FF87FF88FF89FF8AFF8BFF8CFF8DFF8EFF8F
FF90FF91FF92FF93FF94FF95FF96FF97FF98FF99FF9AFF9BFF9CFF9DFF9EFF9F
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
81
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
300030013002FF0CFF0E30FBFF1AFF1BFF1FFF01309B309C00B4FF4000A8FF3E
FFE3FF3F30FD30FE309D309E30034EDD30053006300730FC20152010FF0F005C
301C2016FF5C2026202520182019201C201DFF08FF0930143015FF3BFF3DFF5B
FF5D30083009300A300B300C300D300E300F30103011FF0B221200B100D70000
00F7FF1D2260FF1CFF1E22662267221E22342642264000B0203220332103FFE5
FF0400A200A3FF05FF03FF06FF0AFF2000A72606260525CB25CF25CE25C725C6
25A125A025B325B225BD25BC203B301221922190219121933013000000000000
000000000000000000000000000000002208220B2286228722822283222A2229
000000000000000000000000000000002227222800AC21D221D4220022030000
0000000000000000000000000000000000000000222022A52312220222072261
2252226A226B221A223D221D2235222B222C0000000000000000000000000000
212B2030266F266D266A2020202100B6000000000000000025EF000000000000

The third line of the file is three numbers. The first number is the fallback character (in base 16) to use when converting from UTF-8 to this encoding. The second number is a 1 if this file represents the encoding for a symbol font, or 0 otherwise. The last number (in base 10) is how many pages of data follow.

Subsequent lines in the example above are pages that describe how to map from the encoding into 2-byte Unicode. The first line in a page identifies the page number. Following it are 256 double-byte numbers, arranged as 16 rows of 16 numbers. Given a character in the encoding, the high byte of that character is used to select which page, and the low byte of that character is used as an index to select one of the double-byte numbers in that page - the value obtained being the corresponding Unicode character. By examination of the example above, one can see that the characters 0x7E and 0x8163 in shiftjis map to 203E and 2026 in Unicode, respectively.

Following the first page will be all the other pages, each in the same format as the first: one number identifying the page followed by 256 double-byte Unicode characters. If a character in the encoding maps to the Unicode character 0000, it means that the character doesn't actually exist. 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 iso2022-jp encoding:

# Encoding file: iso2022-jp, escape-driven
E
init		{}
final		{}
iso8859-1	\x1b(B
jis0201		\x1b(J
jis0208		\x1b$@
jis0208		\x1b$B
jis0212		\x1b$(D
gb2312		\x1b$A
ksc5601		\x1b$(C

In the file, the first column represents an option and the second column is the associated value. init is a string to emit or expect before the first character is converted, while final is a string to emit or expect after the last character. All other options are names of table-based encodings; the associated value is the escape-sequence that marks that encoding. Tcl syntax is used for the values; in the above example, for instance, ``{}'' represents the empty string and ``\x1b'' represents character 27.

When Tcl_GetEncoding encounters an encoding name that has not been loaded, it attempts to load an encoding file called name.enc from the encoding subdirectory of each directory specified in the library path $tcl_libPath. If the encoding file exists, but is malformed, an error message will be left in interp.

KEYWORDS

utf, encoding, convert
Copyright © 1997-1998 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Eval manual page

NAME
Tcl_EvalObjEx, Tcl_EvalFile, Tcl_EvalObjv, Tcl_Eval, Tcl_EvalEx, Tcl_GlobalEval, Tcl_GlobalEvalObj, Tcl_VarEval, Tcl_VarEvalVA - execute Tcl scripts
SYNOPSIS
ARGUMENTS
DESCRIPTION
FLAG BITS
TCL_EVAL_DIRECT
TCL_EVAL_GLOBAL
MISCELLANEOUS DETAILS
KEYWORDS

NAME

Tcl_EvalObjEx, Tcl_EvalFile, Tcl_EvalObjv, Tcl_Eval, Tcl_EvalEx, Tcl_GlobalEval, Tcl_GlobalEvalObj, Tcl_VarEval, Tcl_VarEvalVA - execute Tcl scripts

SYNOPSIS

#include <tcl.h>
int
Tcl_EvalObjEx(interp, objPtr, flags)
int
Tcl_EvalFile(interp, fileName)
int
Tcl_EvalObjv(interp, objc, objv, flags)
int
Tcl_Eval(interp, script)
int
Tcl_EvalEx(interp, script, numBytes, flags)
int
Tcl_GlobalEval(interp, script)
int
Tcl_GlobalEvalObj(interp, objPtr, flags)
int
Tcl_VarEval(interp, string, string, ... (char *) NULL)
int
Tcl_VarEvalVA(interp, argList)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which to execute the script. The interpreter's result is modified to hold the result or error message from the script.

Tcl_Obj *objPtr (in)
A Tcl object containing the script to execute.

int flags (in)
ORed combination of flag bits that specify additional options. TCL_EVAL_GLOBAL and TCL_EVAL_DIRECT are currently supported.

char *fileName (in)
Name of a file containing a Tcl script.

int objc (in)
The number of objects in the array pointed to by objPtr; this is also the number of words in the command.

Tcl_Obj **objv (in)
Points to an array of pointers to objects; each object holds the value of a single word in the command to execute.

int numBytes (in)
The number of bytes in script, not including any null terminating character. If -1, then all characters up to the first null byte are used.

char *script (in)
Points to first byte of script to execute (NULL terminated and UTF-8). This script must be in writable memory: temporary modifications are made to it during parsing.

char *string (in)
String forming part of a Tcl script.

va_list argList (in)
An argument list which must have been initialised using TCL_VARARGS_START, and cleared using va_end.

DESCRIPTION

The procedures described here are invoked to execute Tcl scripts in various forms. Tcl_EvalObjEx is the core procedure and is used by many of the others. It executes the commands in the script stored in objPtr until either an error occurs or the end of the script is reached. If this is the first time objPtr has been executed, its commands are compiled into bytecode instructions which are then executed. The bytecodes are saved in objPtr so that the compilation step can be skipped if the object is evaluated again in the future.

The return value from Tcl_EvalObjEx (and all the other procedures described here) is a Tcl completion code with one of the values TCL_OK, TCL_ERROR, TCL_RETURN, TCL_BREAK, or TCL_CONTINUE. In addition, a result value or error message is left in interp's result; it can be retrieved using Tcl_GetObjResult.

Tcl_EvalFile reads the file given by fileName and evaluates its contents as a Tcl script. It returns the same information as Tcl_EvalObjEx. If the file couldn't be read then a Tcl error is returned to describe why the file couldn't be read.

Tcl_EvalObjv executes a single pre-parsed command instead of a script. The objc and objv arguments contain the values of the words for the Tcl command, one word in each object in objv. Tcl_EvalObjv evaluates the command and returns a completion code and result just like Tcl_EvalObjEx.

Tcl_Eval is similar to Tcl_EvalObjEx except that the script to be executed is supplied as a string instead of an object and no compilation occurs. The string should be a proper UTF-8 string as converted by Tcl_ExternalToUtfDString or Tcl_ExternalToUtf when it is known to possibly contain upper ascii characters who's possible combinations might be a UTF-8 special code. The string is parsed and executed directly (using Tcl_EvalObjv) instead of compiling it and executing the bytecodes. In situations where it is known that the script will never be executed again, Tcl_Eval may be faster than Tcl_EvalObjEx. Tcl_Eval returns a completion code and result just like Tcl_EvalObjEx. Note: for backward compatibility with versions before Tcl 8.0, Tcl_Eval copies the object result in interp to interp->result (use is deprecated) where it can be accessed directly. This makes Tcl_Eval somewhat slower than Tcl_EvalEx, which doesn't do the copy.

Tcl_EvalEx is an extended version of Tcl_Eval that takes additional arguments numBytes and flags. For the efficiency reason given above, Tcl_EvalEx is generally preferred over Tcl_Eval.

Tcl_GlobalEval and Tcl_GlobalEvalObj are older procedures that are now deprecated. They are similar to Tcl_EvalEx and Tcl_EvalObjEx except that the script is evaluated in the global namespace and its variable context consists of global variables only (it ignores any Tcl procedures that are active). These functions are equivalent to using the TCL_EVAL_GLOBAL flag (see below).

Tcl_VarEval takes any number of string arguments of any length, concatenates them into a single string, then calls Tcl_Eval to execute that string as a Tcl command. It returns the result of the command and also modifies interp->result in the same way as Tcl_Eval. The last argument to Tcl_VarEval must be NULL to indicate the end of arguments. Tcl_VarEval is now deprecated.

Tcl_VarEvalVA is the same as Tcl_VarEval except that instead of taking a variable number of arguments it takes an argument list. Like Tcl_VarEval, Tcl_VarEvalVA is deprecated.

FLAG BITS

Any ORed combination of the following values may be used for the flags argument to procedures such as Tcl_EvalObjEx:

TCL_EVAL_DIRECT
This flag is only used by Tcl_EvalObjEx; it is ignored by other procedures. If this flag bit is set, the script is not compiled to bytecodes; instead it is executed directly as is done by Tcl_EvalEx. The TCL_EVAL_DIRECT flag is useful in situations where the contents of an object are going to change immediately, so the bytecodes won't be reused in a future execution. In this case, it's faster to execute the script directly.

TCL_EVAL_GLOBAL
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).

MISCELLANEOUS DETAILS

During the processing of a Tcl command it is legal to make nested calls to evaluate other commands (this is how procedures and some control structures are implemented). If a code other than TCL_OK is returned from a nested Tcl_EvalObjEx invocation, then the caller should normally return immediately, passing that same return code back to its caller, and so on until the top-level application is reached. A few commands, like for, will check for certain return codes, like TCL_BREAK and TCL_CONTINUE, and process them specially without returning.

Tcl_EvalObjEx keeps track of how many nested Tcl_EvalObjEx invocations are in progress for interp. If a code of TCL_RETURN, TCL_BREAK, or TCL_CONTINUE is about to be returned from the topmost Tcl_EvalObjEx invocation for interp, it converts the return code to TCL_ERROR and sets interp's result to an error message indicating that the return, break, or continue command was invoked in an inappropriate place. This means that top-level applications should never see a return code from Tcl_EvalObjEx other then TCL_OK or TCL_ERROR.

KEYWORDS

execute, file, global, object, result, script
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Exit manual page

NAME

Tcl_Exit, Tcl_Finalize, Tcl_CreateExitHandler, Tcl_DeleteExitHandler, Tcl_ExitThread, Tcl_FinalizeThread, Tcl_CreateThreadExitHandler, Tcl_DeleteThreadExitHandler - end the application or thread (and invoke exit handlers)

SYNOPSIS

#include <tcl.h>
Tcl_Exit(status)
Tcl_Finalize()
Tcl_CreateExitHandler(proc, clientData)
Tcl_DeleteExitHandler(proc, clientData)
Tcl_ExitThread(status)
Tcl_FinalizeThread()
Tcl_CreateThreadExitHandler(proc, clientData)
Tcl_DeleteThreadExitHandler(proc, clientData)

ARGUMENTS

int status (in)
Provides information about why the application or thread exited. Exact meaning may be platform-specific. 0 usually means a normal exit, any nonzero value usually means that an error occurred.

Tcl_ExitProc *proc (in)
Procedure to invoke before exiting application.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

The procedures described here provide a graceful mechanism to end the execution of a Tcl application. Exit handlers are invoked to cleanup the application's state before ending the execution of Tcl code.

Invoke Tcl_Exit to end a Tcl application and to exit from this process. This procedure is invoked by the exit command, and can be invoked anyplace else to terminate the application. No-one should ever invoke the exit system procedure directly; always invoke Tcl_Exit instead, so that it can invoke exit handlers. Note that if other code invokes exit system procedure directly, or otherwise causes the application to terminate without calling Tcl_Exit, the exit handlers will not be run. Tcl_Exit internally invokes the exit system call, thus it never returns control to its caller.

Tcl_Finalize is similar to Tcl_Exit except that it does not exit from the current process. It is useful for cleaning up when a process is finished using Tcl but wishes to continue executing, and when Tcl is used in a dynamically loaded extension that is about to be unloaded. On some systems Tcl is automatically notified when it is being unloaded, and it calls Tcl_Finalize internally; on these systems it not necessary for the caller to explicitly call Tcl_Finalize. However, to ensure portability, your code should always invoke Tcl_Finalize when Tcl is being unloaded, to ensure that the code will work on all platforms. Tcl_Finalize can be safely called more than once.

Tcl_ExitThread is used to terminate the current thread and invoke per-thread exit handlers. This finalization is done by Tcl_FinalizeThread, which you can call if you just want to clean up per-thread state and invoke the thread exit handlers. Tcl_Finalize calls Tcl_FinalizeThread for the current thread automatically.

Tcl_CreateExitHandler arranges for proc to be invoked by Tcl_Finalize and Tcl_Exit. Tcl_CreateThreadExitHandler arranges for proc to be invoked by Tcl_FinalizeThread and Tcl_ExitThread. This provides a hook for cleanup operations such as flushing buffers and freeing global memory. Proc should match the type Tcl_ExitProc:

typedef void Tcl_ExitProc(ClientData clientData);
The clientData parameter to proc is a copy of the clientData argument given to Tcl_CreateExitHandler or Tcl_CreateThreadExitHandler when the callback was created. Typically, clientData points to a data structure containing application-specific information about what to do in proc.

Tcl_DeleteExitHandler and Tcl_DeleteThreadExitHandler may be called to delete a previously-created exit handler. It removes the handler indicated by proc and clientData so that no call to proc will be made. If no such handler exists then Tcl_DeleteExitHandler or Tcl_DeleteThreadExitHandler does nothing.

Tcl_Finalize and Tcl_Exit 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; if extension A loads extension B, it usually unloads B before it itself is unloaded. If extension A registers its exit handlers before loading extension B, this ensures that any exit handlers for B will be executed before the exit handlers for A.

Tcl_Finalize and Tcl_Exit call Tcl_FinalizeThread and the thread exit handlers after 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.

KEYWORDS

callback, cleanup, dynamic loading, end application, exit, unloading, thread
Copyright © 1995-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_ExprLong manual page

NAME

Tcl_ExprLong, Tcl_ExprDouble, Tcl_ExprBoolean, Tcl_ExprString - evaluate an expression

SYNOPSIS

#include <tcl.h>
int
Tcl_ExprLong(interp, string, longPtr)
int
Tcl_ExprDouble(interp, string, doublePtr)
int
Tcl_ExprBoolean(interp, string, booleanPtr)
int
Tcl_ExprString(interp, string)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in whose context to evaluate string or objPtr.

char *string (in)
Expression to be evaluated. Must be in writable memory (the expression parser makes temporary modifications to the string during parsing, which it undoes before returning).

long *longPtr (out)
Pointer to location in which to store the integer value of the expression.

int *doublePtr (out)
Pointer to location in which to store the floating-point value of the expression.

int *booleanPtr (out)
Pointer to location in which to store the 0/1 boolean value of the expression.

DESCRIPTION

These four procedures all evaluate the expression given by the string argument and return the result in one of four different forms. The expression can have any of the forms accepted by the expr command. Note that these procedures have been largely replaced by the object-based procedures Tcl_ExprLongObj, Tcl_ExprDoubleObj, Tcl_ExprBooleanObj, and Tcl_ExprStringObj. Those object-based procedures evaluate an expression held in a Tcl object instead of a string. The object argument can retain an internal representation that is more efficient to execute.

The interp argument refers to an interpreter used to evaluate the expression (e.g. for variables and nested Tcl commands) and to return error information.

For all of these procedures the return value is a standard Tcl result: TCL_OK means the expression was successfully evaluated, and TCL_ERROR means that an error occurred while evaluating the expression. If TCL_ERROR is returned then the interpreter's result will hold a message describing the error. If an error occurs while executing a Tcl command embedded in the expression then that error will be returned.

If the expression is successfully evaluated, then its value is returned in one of four forms, depending on which procedure is invoked. Tcl_ExprLong stores an integer value at *longPtr. If the expression's actual value is a floating-point number, then it is truncated to an integer. If the expression's actual value is a non-numeric string then an error is returned.

Tcl_ExprDouble stores a floating-point value at *doublePtr. If the expression's actual value is an integer, it is converted to floating-point. If the expression's actual value is a non-numeric string then an error is returned.

Tcl_ExprBoolean stores a 0/1 integer value at *booleanPtr. If the expression's actual value is an integer or floating-point number, then they store 0 at *booleanPtr if the value was zero and 1 otherwise. If the expression's actual value is a non-numeric string then it must be one of the values accepted by Tcl_GetBoolean such as ``yes'' or ``no'', or else an error occurs.

Tcl_ExprString returns the value of the expression as a string stored in the interpreter's result. If the expression's actual value is an integer then Tcl_ExprString converts it to a string using sprintf with a ``%d'' converter. If the expression's actual value is a floating-point number, then Tcl_ExprString calls Tcl_PrintDouble to convert it to a string.

SEE ALSO

Tcl_ExprLongObj, Tcl_ExprDoubleObj, Tcl_ExprBooleanObj, Tcl_ExprObj

KEYWORDS

boolean, double, evaluate, expression, integer, object, string
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_ExprLongObj manual page

NAME

Tcl_ExprLongObj, Tcl_ExprDoubleObj, Tcl_ExprBooleanObj, Tcl_ExprObj - evaluate an expression

SYNOPSIS

#include <tcl.h>
int
Tcl_ExprLongObj(interp, objPtr, longPtr)
int
Tcl_ExprDoubleObj(interp, objPtr, doublePtr)
int
Tcl_ExprBooleanObj(interp, objPtr, booleanPtr)
int
Tcl_ExprObj(interp, objPtr, resultPtrPtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in whose context to evaluate string or objPtr.

Tcl_Obj *objPtr (in)
Pointer to an object containing the expression to evaluate.

long *longPtr (out)
Pointer to location in which to store the integer value of the expression.

int *doublePtr (out)
Pointer to location in which to store the floating-point value of the expression.

int *booleanPtr (out)
Pointer to location in which to store the 0/1 boolean value of the expression.

Tcl_Obj *resultPtrPtr (out)
Pointer to location in which to store a pointer to the object that is the result of the expression.

DESCRIPTION

These four procedures all evaluate an expression, returning the result in one of four different forms. The expression is given by the objPtr argument, and it can have any of the forms accepted by the expr command.

The interp argument refers to an interpreter used to evaluate the expression (e.g. for variables and nested Tcl commands) and to return error information.

For all of these procedures the return value is a standard Tcl result: TCL_OK means the expression was successfully evaluated, and TCL_ERROR means that an error occurred while evaluating the expression. If TCL_ERROR is returned, then a message describing the error can be retrieved using Tcl_GetObjResult. If an error occurs while executing a Tcl command embedded in the expression then that error will be returned.

If the expression is successfully evaluated, then its value is returned in one of four forms, depending on which procedure is invoked. Tcl_ExprLongObj stores an integer value at *longPtr. If the expression's actual value is a floating-point number, then it is truncated to an integer. If the expression's actual value is a non-numeric string then an error is returned.

Tcl_ExprDoubleObj stores a floating-point value at *doublePtr. If the expression's actual value is an integer, it is converted to floating-point. If the expression's actual value is a non-numeric string then an error is returned.

Tcl_ExprBooleanObj stores a 0/1 integer value at *booleanPtr. If the expression's actual value is an integer or floating-point number, then they store 0 at *booleanPtr if the value was zero and 1 otherwise. If the expression's actual value is a non-numeric string then it must be one of the values accepted by Tcl_GetBoolean such as ``yes'' or ``no'', or else an error occurs.

If Tcl_ExprObj successfully evaluates the expression, it stores a pointer to the Tcl object containing the expression's value at *resultPtrPtr. In this case, the caller is responsible for calling Tcl_DecrRefCount to decrement the object's reference count when it is finished with the object.

SEE ALSO

Tcl_ExprLong, Tcl_ExprDouble, Tcl_ExprBoolean, Tcl_ExprString, Tcl_GetObjResult

KEYWORDS

boolean, double, evaluate, expression, integer, object, string
Copyright © 1996-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_FindExecutable manual page

NAME

Tcl_FindExecutable, Tcl_GetNameOfExecutable - identify or return the name of the binary file containing the application

SYNOPSIS

#include <tcl.h>
void
Tcl_FindExecutable(argv0)
CONST char *
Tcl_GetNameOfExecutable()

ARGUMENTS

char *argv0 (in)
The first command-line argument to the program, which gives the application's name.

DESCRIPTION

The Tcl_FindExecutable procedure computes the full path name of the executable file from which the application was invoked and saves it for Tcl's internal use. The executable's path name is needed for several purposes in Tcl. For example, it is needed on some platforms in the implementation of the load command. It is also returned by the info nameofexecutable command.

On UNIX platforms this procedure is typically invoked as the very first thing in the application's main program; it must be passed argv[0] as its argument. It is important not to change the working directory before the invocation. Tcl_FindExecutable uses argv0 along with the PATH environment variable to find the application's executable, if possible. If it fails to find the binary, then future calls to info nameofexecutable will return an empty string.

Tcl_GetNameOfExecutable simply returns a pointer to the internal full path name of the executable file as computed by Tcl_FindExecutable. This procedure call is the C API equivalent to the info nameofexecutable command. NULL is returned if the internal full path name has not been computed or unknown.

KEYWORDS

binary, executable file
Copyright © 1995-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_GetCwd manual page

NAME

Tcl_GetCwd, Tcl_Chdir - manipulate the current working directory

SYNOPSIS

#include <tcl.h>
char *
Tcl_GetCwd(interp, bufferPtr)
int
Tcl_Chdir(path)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which to report an error, if any.

Tcl_DString *bufferPtr (in/out)
This dynamic string is used to store the current working directory. At the time of the call it should be uninitialized or free. The caller must eventually call Tcl_DStringFree to free up anything stored here.

char *path (in)
File path in UTF-8 format.

DESCRIPTION

These procedures may be used to manipulate the current working directory for the application. They provide C-level access to the same functionality as the Tcl pwd command.

Tcl_GetCwd returns a pointer to a string specifying the current directory, or NULL if the current directory could not be determined. If NULL is returned, an error message is left in the interp's result. Storage for the result string is allocated in bufferPtr; the caller must call Tcl_DStringFree() when the result is no longer needed. The format of the path is UTF-8.

Tcl_Chdir changes the applications current working directory to the value specified in path. The format of the passed in string must be UTF-8. The function returns -1 on error or 0 on success.

KEYWORDS

pwd
Copyright © 1998-1999 Scriptics Corportation


Tcl Library Procedures - Tcl_GetHostName manual page

NAME

Tcl_GetHostName - get the name of the local host

SYNOPSIS

#include <tcl.h>
char *
Tcl_GetHostName()

DESCRIPTION

Tcl_GetHostName is a utility procedure used by some of the Tcl commands. It returns a pointer to a string containing the name for the current machine, or an empty string if the name cannot be determined. The string is statically allocated, and the caller must not modify of free it.

KEYWORDS

hostname
Copyright © 1998-2000 by Scriptics Corporation.


Tcl Library Procedures - Tcl_GetIndexFromObj manual page

NAME

Tcl_GetIndexFromObj, Tcl_GetIndexFromObjStruct - lookup string in table of keywords

SYNOPSIS

#include <tcl.h>
int
Tcl_GetIndexFromObj(interp, objPtr, tablePtr, msg, flags,
indexPtr)
int
Tcl_GetIndexFromObjStruct(interp, objPtr, tablePtr, offset,
msg, flags, indexPtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting; if NULL, then no message is provided on errors.

Tcl_Obj *objPtr (in/out)
The string value of this object is used to search through tablePtr. The internal representation is modified to hold the index of the matching table entry.

char **tablePtr (in)
An array of null-terminated strings. The end of the array is marked by a NULL string pointer.

int offset (in)
The offset to add to tablePtr to get to the next string in the list. The end of the array is marked by a NULL string pointer.

char *msg (in)
Null-terminated string describing what is being looked up, such as option. This string is included in error messages.

int flags (in)
OR-ed combination of bits providing additional information for operation. The only bit that is currently defined is TCL_EXACT.

int *indexPtr (out)
The index of the string in tablePtr that matches the value of objPtr is returned here.

DESCRIPTION

This procedure provides an efficient way for looking up keywords, switch names, option names, and similar things where the value of an object must be one of a predefined set of values. ObjPtr is compared against each of the strings in tablePtr to find a match. A match occurs if objPtr's string value is identical to one of the strings in tablePtr, or if it is a unique abbreviation for exactly one of the strings in tablePtr and the TCL_EXACT flag was not specified; in either case the index of the matching entry is stored at *indexPtr and TCL_OK is returned.

If there is no matching entry, TCL_ERROR is returned and an error message is left in interp's result if interp isn't NULL. Msg is included in the error message to indicate what was being looked up. For example, if msg is option the error message will have a form like bad option "firt": must be first, second, or third.

If Tcl_GetIndexFromObj completes successfully it modifies the internal representation of objPtr to hold the address of the table and the index of the matching entry. If Tcl_GetIndexFromObj is invoked again with the same objPtr and tablePtr arguments (e.g. during a reinvocation of a Tcl command), it returns the matching index immediately without having to redo the lookup operation. Note: Tcl_GetIndexFromObj assumes that the entries in tablePtr are static: they must not change between invocations. If the value of objPtr is the empty string, Tcl_GetIndexFromObj will treat it as a non-matching value and return TCL_ERROR.

Tcl_GetIndexFromObjStruct works just like Tcl_GetIndexFromObj, except that instead of treating tablePtr as an array of string pointers, it treats it as the first in a series of string ptrs that are spaced apart by offset bytes. This is particularly useful when processing things like Tk_ConfigurationSpec, whose string keys are in the same place in each of several array elements.

SEE ALSO

Tcl_WrongNumArgs

KEYWORDS

index, object, table lookup
Copyright © 1997 Sun Microsystems, Inc.


Library Procedures - Tcl_GetInt manual page

NAME

Tcl_GetInt, Tcl_GetDouble, Tcl_GetBoolean - convert from string to integer, double, or boolean

SYNOPSIS

#include <tcl.h>
int
Tcl_GetInt(interp, string, intPtr)
int
Tcl_GetDouble(interp, string, doublePtr)
int
Tcl_GetBoolean(interp, string, boolPtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

char *string (in)
Textual value to be converted.

int *intPtr (out)
Points to place to store integer value converted from string.

double *doublePtr (out)
Points to place to store double-precision floating-point value converted from string.

int *boolPtr (out)
Points to place to store boolean value (0 or 1) converted from string.

DESCRIPTION

These procedures convert from strings to integers or double-precision floating-point values or booleans (represented as 0- or 1-valued integers). Each of the procedures takes a string argument, converts it to an internal form of a particular type, and stores the converted value at the location indicated by the procedure's third argument. If all goes well, each of the procedures returns TCL_OK. If string doesn't have the proper syntax for the desired type then TCL_ERROR is returned, an error message is left in the interpreter's result, and nothing is stored at *intPtr or *doublePtr or *boolPtr.

Tcl_GetInt expects string to consist of a collection of integer digits, optionally signed and optionally preceded by white space. If the first two characters of string are ``0x'' then string is expected to be in hexadecimal form; otherwise, if the first character of string is ``0'' then string is expected to be in octal form; otherwise, string is expected to be in decimal form.

Tcl_GetDouble expects string to consist of a floating-point number, which is: white space; a sign; a sequence of digits; a decimal point; a sequence of digits; the letter ``e''; and a signed decimal exponent. Any of the fields may be omitted, except that the digits either before or after the decimal point must be present and if the ``e'' is present then it must be followed by the exponent number.

Tcl_GetBoolean expects string to specify a boolean value. If string is any of 0, false, no, or off, then Tcl_GetBoolean stores a zero value at *boolPtr. If string is any of 1, true, yes, or on, then 1 is stored at *boolPtr. Any of these values may be abbreviated, and upper-case spellings are also acceptable.

KEYWORDS

boolean, conversion, double, floating-point, integer
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_GetOpenFile manual page

NAME

Tcl_GetOpenFile - Get a standard IO File * handle from a channel. (Unix only)

SYNOPSIS

#include <tcl.h>
int
Tcl_GetOpenFile(interp, string, write, checkUsage, filePtr)

ARGUMENTS

Tcl_Interp *interp (in)
Tcl interpreter from which file handle is to be obtained.

char *string (in)
String identifying channel, such as stdin or file4.

int write (in)
Non-zero means the file will be used for writing, zero means it will be used for reading.

int checkUsage (in)
If non-zero, then an error will be generated if the file wasn't opened for the access indicated by write.

ClientData *filePtr (out)
Points to word in which to store pointer to FILE structure for the file given by string.

DESCRIPTION

Tcl_GetOpenFile takes as argument a file identifier of the form returned by the open command and returns at *filePtr a pointer to the FILE structure for the file. The write argument indicates whether the FILE pointer will be used for reading or writing. In some cases, such as a channel that connects to a pipeline of subprocesses, different FILE pointers will be returned for reading and writing. Tcl_GetOpenFile normally returns TCL_OK. If an error occurs in Tcl_GetOpenFile (e.g. string didn't make any sense or checkUsage was set and the file wasn't opened for the access specified by write) then TCL_ERROR is returned and the interpreter's result will contain an error message. In the current implementation checkUsage is ignored and consistency checks are always performed.

Note that this interface is only supported on the Unix platform.

KEYWORDS

channel, file handle, permissions, pipeline, read, write
Copyright © 1996-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_GetStdChannel manual page

NAME

Tcl_GetStdChannel, Tcl_SetStdChannel - procedures for retrieving and replacing the standard channels

SYNOPSIS

#include <tcl.h>
Tcl_Channel
Tcl_GetStdChannel(type)
Tcl_SetStdChannel(channel, type)

ARGUMENTS

int type (in)
The identifier for the standard channel to retrieve or modify. Must be one of TCL_STDIN, TCL_STDOUT, or TCL_STDERR.

Tcl_Channel channel (in)
The channel to use as the new value for the specified standard channel.

DESCRIPTION

Tcl defines three special channels that are used by various I/O related commands if no other channels are specified. The standard input channel has a channel name of stdin and is used by read and gets. The standard output channel is named stdout and is used by puts. The standard error channel is named stderr and is used for reporting errors. In addition, the standard channels are inherited by any child processes created using exec or open in the absence of any other redirections.

The standard channels are actually aliases for other normal channels. The current channel associated with a standard channel can be retrieved by calling Tcl_GetStdChannel with one of TCL_STDIN, TCL_STDOUT, or TCL_STDERR as the type. The return value will be a valid channel, or NULL.

A new channel can be set for the standard channel specified by type by calling Tcl_SetStdChannel with a new channel or NULL in the channel argument. If the specified channel is closed by a later call to Tcl_Close, then the corresponding standard channel will automatically be set to NULL.

If Tcl_GetStdChannel is called before Tcl_SetStdChannel, Tcl will construct a new channel to wrap the appropriate platform-specific standard file handle. If Tcl_SetStdChannel is called before Tcl_GetStdChannel, then the default channel will not be created.

If one of the standard channels is set to NULL, either by calling Tcl_SetStdChannel with a null channel argument, or by calling Tcl_Close on the channel, then the next call to Tcl_CreateChannel will automatically set the standard channel with the newly created channel. If more than one standard channel is NULL, then the standard channels will be assigned starting with standard input, followed by standard output, with standard error being last.

SEE ALSO

Tcl_Close, Tcl_CreateChannel

KEYWORDS

standard channel, standard input, standard output, standard error
Copyright © 1996 by Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_GetVersion manual page

NAME

Tcl_GetVersion - get the version of the library at runtime

SYNOPSIS

#include <tcl.h>
Tcl_GetVersion(major, minor, patchLevel, type)

ARGUMENTS

int *major (out)
Major version number of the Tcl library.

int *minor (out)
Minor version number of the Tcl library.

int *patchLevel (out)
The patch level of the Tcl library (or alpha or beta number).

Tcl_ReleaseType *type (out)
The type of release, also indicates the type of patch level. Can be one of TCL_ALPHA_RELEASE, TCL_BETA_RELEASE, or TCL_FINAL_RELEASE.

DESCRIPTION

Tcl_GetVersion should be used to query the version number of the Tcl library at runtime. This is useful when using a dynamically loaded Tcl library or when writing a stubs-aware extension. For instance, if you write an extension that is linked against the Tcl stubs library, it could be loaded into a program linked to an older version of Tcl than you expected. Use Tcl_GetVersion to verify that fact, and possibly to change the behavior of your extension.

If may pass a NULL for any of the arguments. For instance if you do not care about the patchLevel of the library, pass a NULL for the patchLevel argument.

KEYWORDS

version, patchlevel, major, minor, alpha, beta, release
Copyright © 1999 Scriptics Corporation
Copyright © 1995-1997 Roger E. Critchlow Jr.


Library Procedures - Tcl_Hash manual page

NAME
Tcl_InitHashTable, Tcl_DeleteHashTable, Tcl_CreateHashEntry, Tcl_DeleteHashEntry, Tcl_FindHashEntry, Tcl_GetHashValue, Tcl_SetHashValue, Tcl_GetHashKey, Tcl_FirstHashEntry, Tcl_NextHashEntry, Tcl_HashStats - procedures to manage hash tables
SYNOPSIS
ARGUMENTS
DESCRIPTION
TCL_STRING_KEYS
TCL_ONE_WORD_KEYS
other
KEYWORDS

NAME

Tcl_InitHashTable, Tcl_DeleteHashTable, Tcl_CreateHashEntry, Tcl_DeleteHashEntry, Tcl_FindHashEntry, Tcl_GetHashValue, Tcl_SetHashValue, Tcl_GetHashKey, Tcl_FirstHashEntry, Tcl_NextHashEntry, Tcl_HashStats - procedures to manage hash tables

SYNOPSIS

#include <tcl.h>
Tcl_InitHashTable(tablePtr, keyType)
Tcl_DeleteHashTable(tablePtr)
Tcl_HashEntry *
Tcl_CreateHashEntry(tablePtr, key, newPtr)
Tcl_DeleteHashEntry(entryPtr)
Tcl_HashEntry *
Tcl_FindHashEntry(tablePtr, key)
ClientData
Tcl_GetHashValue(entryPtr)
Tcl_SetHashValue(entryPtr, value)
char *
Tcl_GetHashKey(tablePtr, entryPtr)
Tcl_HashEntry *
Tcl_FirstHashEntry(tablePtr, searchPtr)
Tcl_HashEntry *
Tcl_NextHashEntry(searchPtr)
char *
Tcl_HashStats(tablePtr)

ARGUMENTS

Tcl_HashTable *tablePtr (in)
Address of hash table structure (for all procedures but Tcl_InitHashTable, this must have been initialized by previous call to Tcl_InitHashTable).

int keyType (in)
Kind of keys to use for new hash table. Must be either TCL_STRING_KEYS, TCL_ONE_WORD_KEYS, or an integer value greater than 1.

char *key (in)
Key to use for probe into table. Exact form depends on keyType used to create table.

int *newPtr (out)
The word at *newPtr is set to 1 if a new entry was created and 0 if there was already an entry for key.

Tcl_HashEntry *entryPtr (in)
Pointer to hash table entry.

ClientData value (in)
New value to assign to hash table entry. Need not have type ClientData, but must fit in same space as ClientData.

Tcl_HashSearch *searchPtr (in)
Pointer to record to use to keep track of progress in enumerating all the entries in a hash table.

DESCRIPTION

A hash table consists of zero or more entries, each consisting of a key and a value. Given the key for an entry, the hashing routines can 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 three forms: strings, one-word values, or integer arrays. All of the keys in a given table have the same form, which is specified when the table is initialized.

The value of a hash table entry can be anything that fits in the same space as a ``char *'' pointer. Values for hash table entries are managed entirely by clients, not by the hash module itself. Typically each entry's value is a pointer to a data structure managed by client code.

Hash tables grow gracefully as the number of entries increases, so that there are always less than three entries per hash bucket, on average. This allows for fast lookups regardless of the number of entries in a table.

Tcl_InitHashTable initializes a structure that describes a new hash table. The space for the structure is provided by the caller, not by the hash module. The value of keyType indicates what kinds of keys will be used for all entries in the table. KeyType must have one of the following values:

TCL_STRING_KEYS
Keys are null-terminated ASCII strings. They are passed to hashing routines using the address of the first character of the string.

TCL_ONE_WORD_KEYS
Keys are single-word values; they are passed to hashing routines and stored in hash table entries as ``char *'' values. The pointer value is the key; it need not (and usually doesn't) actually point to a string.

other
If keyType is not TCL_STRING_KEYS or TCL_ONE_WORD_KEYS, then it must be an integer value greater than 1. In this case the keys will be arrays of ``int'' values, where keyType gives the number of ints in each key. This allows structures to be used as keys. All keys must have the same size. Array keys are passed into hashing functions using the address of the first int in the array.

Tcl_DeleteHashTable deletes all of the entries in a hash table and frees up the memory associated with the table's bucket array and entries. It does not free the actual table structure (pointed to by tablePtr), since that memory is assumed to be managed by the client. Tcl_DeleteHashTable also does not free or otherwise manipulate the values of the hash table entries. If the entry values point to dynamically-allocated memory, then it is the client's responsibility to free these structures before deleting the table.

Tcl_CreateHashEntry locates the entry corresponding to a particular key, creating a new entry in the table if there wasn't already one with the given key. If an entry already existed with the given key then *newPtr is set to zero. If a new entry was created, then *newPtr is set to a non-zero value and the value of the new entry will be set to zero. The return value from Tcl_CreateHashEntry is a pointer to the entry, which may be used to retrieve and modify the entry's value or to delete the entry from the table.

Tcl_DeleteHashEntry will remove an existing entry from a table. The memory associated with the entry itself will be freed, but the client is responsible for any cleanup associated with the entry's value, such as freeing a structure that it points to.

Tcl_FindHashEntry is similar to Tcl_CreateHashEntry except that it doesn't create a new entry if the key doesn't exist; instead, it returns NULL as result.

Tcl_GetHashValue and Tcl_SetHashValue are used to read and write an entry's value, respectively. Values are stored and retrieved as type ``ClientData'', which is large enough to hold a pointer value. On almost all machines this is large enough to hold an integer value too.

Tcl_GetHashKey returns the key for a given hash table entry, either as a pointer to a string, a one-word (``char *'') key, or as a pointer to the first word of an array of integers, depending on the keyType used to create a hash table. In all cases Tcl_GetHashKey returns a result with type ``char *''. When the key is a string or array, the result of Tcl_GetHashKey points to information in the table entry; this information will remain valid until the entry is deleted or its table is deleted.

Tcl_FirstHashEntry and Tcl_NextHashEntry may be used to scan all of the entries in a hash table. A structure of type ``Tcl_HashSearch'', provided by the client, is used to keep track of progress through the table. Tcl_FirstHashEntry initializes the search record and returns the first entry in the table (or NULL if the table is empty). Each subsequent call to Tcl_NextHashEntry returns the next entry in the table or NULL if the end of the table has been reached. A call to Tcl_FirstHashEntry followed by calls to Tcl_NextHashEntry will return each of the entries in the table exactly once, in an arbitrary order. It is unadvisable to modify the structure of the table, e.g. by creating or deleting entries, while the search is in progress.

Tcl_HashStats returns a dynamically-allocated string with overall information about a hash table, such as the number of entries it contains, the number of buckets in its hash array, and the utilization of the buckets. It is the caller's responsibility to free the result string by passing it to ckfree.

The header file tcl.h defines the actual data structures used to implement hash tables. This is necessary so that clients can allocate Tcl_HashTable structures and so that macros can be used to read and write the values of entries. However, users of the hashing routines should never refer directly to any of the fields of any of the hash-related data structures; use the procedures and macros defined here.

KEYWORDS

hash table, key, lookup, search, value
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Init manual page

NAME

Tcl_Init - find and source initialization script

SYNOPSIS

#include <tcl.h>
int
Tcl_Init(interp)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to initialize.

DESCRIPTION

Tcl_Init is a helper procedure that finds and source's the init.tcl script, which should exist somewhere on the Tcl library path. On Macintosh systems, it additionally checks for an Init resource and sources the contents of that resource if init.tcl cannot be found.

Tcl_Init is typically called from Tcl_AppInit procedures.

SEE ALSO

Tcl_AppInit, Tcl_Main

KEYWORDS

application, initialization, interpreter
Copyright © 1998-2000 by Scriptics Corporation.


Tcl Library Procedures - Tcl_InitStubs manual page

NAME
Tcl_InitStubs - initialize the Tcl stubs mechanism
SYNOPSIS
ARGUMENTS
INTRODUCTION
1)
2)
1)
2)
3)
DESCRIPTION
SEE ALSO
KEYWORDS

NAME

Tcl_InitStubs - initialize the Tcl stubs mechanism

SYNOPSIS

#include <tcl.h>
char *
Tcl_InitStubs(interp, version, exact)

ARGUMENTS

Tcl_Interp *interp (in)
Tcl interpreter handle.

char *version (in)
A version string consisting of one or more decimal numbers separated by dots.

int exact (in)
Non-zero means that only the particular version specified by version is acceptable. Zero means that versions newer than version are also acceptable as long as they have the same major version number as version.

INTRODUCTION

The Tcl stubs mechanism defines a way to dynamically bind extensions to a particular Tcl implementation at run time. This provides two significant benefits to Tcl users:

1)
Extensions that use the stubs mechanism can be loaded into multiple versions of Tcl without being recompiled or relinked.

2)
Extensions that use the stubs mechanism can be dynamically loaded into statically-linked Tcl applications.

The stubs mechanism accomplishes this by exporting function tables that define an interface to the Tcl API. The extension then accesses the Tcl API through offsets into the function table, so there are no direct references to any of the Tcl library's symbols. This redirection is transparent to the extension, so an extension writer can continue to use all public Tcl functions as documented.

The stubs mechanism requires no changes to applications incorporating Tcl interpreters. Only developers creating C-based Tcl extensions need to take steps to use the stubs mechanism with their extensions.

Enabling the stubs mechanism for an extension requires the following steps:

1)
Call Tcl_InitStubs in the extension before calling any other Tcl functions.

2)
Define the USE_TCL_STUBS symbol. Typically, you would include the -DUSE_TCL_STUBS flag when compiling the extension.

3)
Link the extension with the Tcl stubs library instead of the standard Tcl library. On Unix platforms, the library name is libtclstub8.1.a; on Windows platforms, the library name is tclstub81.lib.

If the extension also requires the Tk API, it must also call Tk_InitStubs to initialize the Tk stubs interface and link with the Tk stubs libraries. See the Tk_InitStubs page for more information.

DESCRIPTION

Tcl_InitStubs attempts to initialize the stub table pointers and ensure that the correct version of Tcl is loaded. In addition to an interpreter handle, it accepts as arguments a version number and a Boolean flag indicating whether the extension requires an exact version match or not. If exact is 0, then the extension is indicating that newer versions of Tcl are acceptable as long as they have the same major version number as version; non-zero means that only the specified version is acceptable. Tcl_InitStubs returns a string containing the actual version of Tcl satisfying the request, or NULL if the Tcl version is not acceptable, does not support stubs, or any other error condition occurred.

SEE ALSO

Tk_InitStubs

KEYWORDS

stubs
Copyright © 1999 Scriptics Corportation
Copyright © 1995-1997 Roger E. Critchlow Jr.


Tcl Library Procedures - Tcl_Interp manual page

NAME

Tcl_Interp - client-visible fields of interpreter structures

SYNOPSIS

#include <tcl.h>
typedef struct {
char *result;
Tcl_FreeProc *freeProc;
int errorLine;
} Tcl_Interp;

typedef void Tcl_FreeProc(char *blockPtr);

DESCRIPTION

The Tcl_CreateInterp 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 many fields that are used by Tcl, but only three that may be accessed by clients: result, freeProc, and errorLine.

The result and freeProc fields are used to return results or error messages from commands. This information is returned by command procedures back to Tcl_Eval, and by Tcl_Eval back to its callers. The result field points to the string that represents the result or error message, and the freeProc field tells how to dispose of the storage for the string when it isn't needed anymore. The easiest way for command procedures to manipulate these fields is to call procedures like Tcl_SetResult or Tcl_AppendResult; they will hide all the details of managing the fields. The description below is for those procedures that manipulate the fields directly.

Whenever a command procedure returns, it must ensure that the result field of its interpreter points to the string being returned by the command. The result field must always point to a valid string. If a command wishes to return no result then interp->result should point to an empty string. Normally, results are assumed to be statically allocated, which means that the contents will not change before the next time Tcl_Eval is called or some other command procedure is invoked. In this case, the freeProc field must be zero. Alternatively, a command procedure may dynamically allocate its return value (e.g. using Tcl_Alloc) and store a pointer to it in interp->result. In this case, the command procedure must also set interp->freeProc to the address of a procedure that can free the value, or TCL_DYNAMIC if the storage was allocated directly by Tcl or by a call to Tcl_Alloc. If interp->freeProc is non-zero, then Tcl will call freeProc to free the space pointed to by interp->result before it invokes the next command. If a client procedure overwrites interp->result when interp->freeProc is non-zero, then it is responsible for calling freeProc to free the old interp->result (the Tcl_FreeResult macro should be used for this purpose).

FreeProc should have arguments and result that match the Tcl_FreeProc declaration above: it receives a single argument which is a pointer to the result value to free. In most applications TCL_DYNAMIC is the only non-zero value ever used for freeProc. However, an application may store a different procedure address in freeProc in order to use an alternate memory allocator or in order to do other cleanup when the result memory is freed.

As part of processing each command, Tcl_Eval initializes interp->result and interp->freeProc just before calling the command procedure for the command. The freeProc field will be initialized to zero, and interp->result will point to an empty string. Commands that do not return any value can simply leave the fields alone. Furthermore, the empty string pointed to by result is actually part of an array of TCL_RESULT_SIZE characters (approximately 200). If a command wishes to return a short string, it can simply copy it to the area pointed to by interp->result. Or, it can use the sprintf procedure to generate a short result string at the location pointed to by interp->result.

It is a general convention in Tcl-based applications that the result of an interpreter is normally in the initialized state described in the previous paragraph. Procedures that manipulate an interpreter's result (e.g. by returning an error) will generally assume that the result has been initialized when the procedure is called. If such a procedure is to be called after the result has been changed, then Tcl_ResetResult should be called first to reset the result to its initialized state. The direct use of interp->result is strongly deprecated (see Tcl_SetResult).

The errorLine field is valid only after Tcl_Eval returns a TCL_ERROR return code. In this situation the errorLine field identifies the line number of the command being executed when the error occurred. The line numbers are relative to the command being executed: 1 means the first line of the command passed to Tcl_Eval, 2 means the second line, and so on. The errorLine field is typically used in conjunction with Tcl_AddErrorInfo to report information about where an error occurred. ErrorLine should not normally be modified except by Tcl_Eval.

KEYWORDS

free, initialized, interpreter, malloc, result
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_IntObj manual page

NAME

Tcl_NewIntObj, Tcl_NewLongObj, Tcl_SetIntObj, Tcl_SetLongObj, Tcl_GetIntFromObj, Tcl_GetLongFromObj - manipulate Tcl objects as integers

SYNOPSIS

#include <tcl.h>
Tcl_Obj *
Tcl_NewIntObj(intValue)
Tcl_Obj *
Tcl_NewLongObj(longValue)
Tcl_SetIntObj(objPtr, intValue)
Tcl_SetLongObj(objPtr, longValue)
int
Tcl_GetIntFromObj(interp, objPtr, intPtr)
int
Tcl_GetLongFromObj(interp, objPtr, longPtr)

ARGUMENTS

int intValue (in)
Integer value used to initialize or set an integer object.

long longValue (in)
Long integer value used to initialize or set an integer object.

Tcl_Obj *objPtr (in/out)
For Tcl_SetIntObj and Tcl_SetLongObj, this points to the object to be converted to integer type. For Tcl_GetIntFromObj and Tcl_GetLongFromObj, this refers to the object from which to get an integer or long integer value; if objPtr does not already point to an integer object, an attempt will be made to convert it to one.

Tcl_Interp *interp (in/out)
If an error occurs during conversion, an error message is left in the interpreter's result object unless interp is NULL.

int *intPtr (out)
Points to place to store the integer value obtained by Tcl_GetIntFromObj from objPtr.

long *longPtr (out)
Points to place to store the long integer value obtained by Tcl_GetLongFromObj from objPtr.

DESCRIPTION

These procedures are used to create, modify, and read integer Tcl objects from C code. Tcl_NewIntObj, Tcl_NewLongObj, Tcl_SetIntObj, and Tcl_SetLongObj create a new object of integer type or modify an existing object to have integer type. Tcl_NewIntObj and Tcl_SetIntObj set the object to have the integer value given by intValue, while Tcl_NewLongObj and Tcl_SetLongObj set the object to have the long integer value given by longValue. Tcl_NewIntObj and Tcl_NewLongObj return a pointer to a newly created object with reference count zero. These procedures set the object's type to be integer and assign the integer value to the object's internal representation longValue member. Tcl_SetIntObj and Tcl_SetLongObj invalidate any old string representation and, if the object is not already an integer object, free any old internal representation.

Tcl_GetIntFromObj and Tcl_GetLongFromObj attempt to return an integer value from the Tcl object objPtr. If the object is not already an integer object, they will attempt to convert it to one. If an error occurs during conversion, they return TCL_ERROR and leave an error message in the interpreter's result object unless interp is NULL. Also, if the long integer held in the object's internal representation longValue member can not be represented in a (non-long) integer, Tcl_GetIntFromObj returns TCL_ERROR and leaves an error message in the interpreter's result object unless interp is NULL. Otherwise, both procedures return TCL_OK and store the integer or the long integer value in the address given by intPtr and longPtr respectively. If the object is not already an integer object, the conversion will free any old internal representation.

SEE ALSO

Tcl_NewObj, Tcl_DecrRefCount, Tcl_IncrRefCount, Tcl_GetObjResult

KEYWORDS

integer, integer object, integer type, internal representation, object, object type, string representation
Copyright © 1996-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_LinkVar manual page

NAME
Tcl_LinkVar, Tcl_UnlinkVar, Tcl_UpdateLinkedVar - link Tcl variable to C variable
SYNOPSIS
ARGUMENTS
DESCRIPTION
TCL_LINK_INT
TCL_LINK_DOUBLE
TCL_LINK_BOOLEAN
TCL_LINK_STRING
KEYWORDS

NAME

Tcl_LinkVar, Tcl_UnlinkVar, Tcl_UpdateLinkedVar - link Tcl variable to C variable

SYNOPSIS

#include <tcl.h>
int
Tcl_LinkVar(interp, varName, addr, type)
Tcl_UnlinkVar(interp, varName)
Tcl_UpdateLinkedVar(interp, varName)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter that contains varName. Also used by Tcl_LinkVar to return error messages.

char *varName (in)
Name of global variable. Must be in writable memory: Tcl may make temporary modifications to it while parsing the variable name.

char *addr (in)
Address of C variable that is to be linked to varName.

int type (in)
Type of C variable. Must be one of TCL_LINK_INT, TCL_LINK_DOUBLE, TCL_LINK_BOOLEAN, or TCL_LINK_STRING, optionally OR'ed with TCL_LINK_READ_ONLY to make Tcl variable read-only.

DESCRIPTION

Tcl_LinkVar uses variable traces to keep the Tcl variable named by varName in sync with the C variable at the address given by addr. Whenever the Tcl variable is read the value of the C variable will be returned, and whenever the Tcl variable is written the C variable will be updated to have the same value. Tcl_LinkVar normally returns TCL_OK; if an error occurs while setting up the link (e.g. because varName is the name of array) then TCL_ERROR is returned and the interpreter's result contains an error message.

The type argument specifies the type of the C variable, and must have one of the following values, optionally OR'ed with TCL_LINK_READ_ONLY:

TCL_LINK_INT
The C variable is of type int. Any value written into the Tcl variable must have a proper integer form acceptable to Tcl_GetInt; attempts to write non-integer values into varName will be rejected with Tcl errors.

TCL_LINK_DOUBLE
The C variable is of type double. Any value written into the Tcl variable must have a proper real form acceptable to Tcl_GetDouble; attempts to write non-real values into varName will be rejected with Tcl errors.

TCL_LINK_BOOLEAN
The C variable is of type int. If its value is zero then it will read from Tcl as ``0''; otherwise it will read from Tcl as ``1''. Whenever varName is modified, the C variable will be set to a 0 or 1 value. Any value written into the Tcl variable must have a proper boolean form acceptable to Tcl_GetBoolean; attempts to write non-boolean values into varName will be rejected with Tcl errors.

TCL_LINK_STRING
The C variable is of type char *. If its value is not null then it must be a pointer to a string allocated with Tcl_Alloc. Whenever the Tcl variable is modified the current C string will be freed and new memory will be allocated to hold a copy of the variable's new value. If the C variable contains a null pointer then the Tcl variable will read as ``NULL''.

If the TCL_LINK_READ_ONLY flag is present in type then the variable will be read-only from Tcl, so that its value can only be changed by modifying the C variable. Attempts to write the variable from Tcl will be rejected with errors.

Tcl_UnlinkVar removes the link previously set up for the variable given by varName. If there does not exist a link for varName then the procedure has no effect.

Tcl_UpdateLinkedVar may be invoked after the C variable has changed to force the Tcl variable to be updated immediately. In many cases this procedure is not needed, since any attempt to read the Tcl variable will return the latest value of the C variable. However, if a trace has been set on the Tcl variable (such as a Tk widget that wishes to display the value of the variable), the trace will not trigger when the C variable has changed. Tcl_UpdateLinkedVar ensures that any traces on the Tcl variable are invoked.

KEYWORDS

boolean, integer, link, read-only, real, string, traces, variable
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_ListObj manual page

NAME

Tcl_ListObjAppendList, Tcl_ListObjAppendElement, Tcl_NewListObj, Tcl_SetListObj, Tcl_ListObjGetElements, Tcl_ListObjLength, Tcl_ListObjIndex, Tcl_ListObjReplace - manipulate Tcl objects as lists

SYNOPSIS

#include <tcl.h>
int
Tcl_ListObjAppendList(interp, listPtr, elemListPtr)
int
Tcl_ListObjAppendElement(interp, listPtr, objPtr)
Tcl_Obj *
Tcl_NewListObj(objc, objv)
Tcl_SetListObj(objPtr, objc, objv)
int
Tcl_ListObjGetElements(interp, listPtr, objcPtr, objvPtr)
int
Tcl_ListObjLength(interp, listPtr, intPtr)
int
Tcl_ListObjIndex(interp, listPtr, index, objPtrPtr)
int
Tcl_ListObjReplace(interp, listPtr, first, count, objc, objv)

ARGUMENTS

Tcl_Interp *interp (in)
If an error occurs while converting an object to be a list object, an error message is left in the interpreter's result object unless interp is NULL.

Tcl_Obj *listPtr (in/out)
Points to the list object to be manipulated. If listPtr does not already point to a list object, an attempt will be made to convert it to one.

Tcl_Obj *elemListPtr (in/out)
For Tcl_ListObjAppendList, this points to a list object containing elements to be appended onto listPtr. Each element of *elemListPtr will become a new element of listPtr. If *elemListPtr is not NULL and does not already point to a list object, an attempt will be made to convert it to one.

Tcl_Obj *objPtr (in)
For Tcl_ListObjAppendElement, points to the Tcl object that will be appended to listPtr. For Tcl_SetListObj, this points to the Tcl object that will be converted to a list object containing the objc elements of the array referenced by objv.

int *objcPtr (in)
Points to location where Tcl_ListObjGetElements stores the number of element objects in listPtr.

Tcl_Obj ***objvPtr (out)
A location where Tcl_ListObjGetElements stores a pointer to an array of pointers to the element objects of listPtr.

int objc (in)
The number of Tcl objects that Tcl_NewListObj will insert into a new list object, and Tcl_ListObjReplace will insert into listPtr. For Tcl_SetListObj, the number of Tcl objects to insert into objPtr.

Tcl_Obj *CONST objv[] (in)
An array of pointers to objects. Tcl_NewListObj will insert these objects into a new list object and Tcl_ListObjReplace will insert them into an existing listPtr. Each object will become a separate list element.

int *intPtr (out)
Points to location where Tcl_ListObjLength stores the length of the list.

int index (in)
Index of the list element that Tcl_ListObjIndex is to return. The first element has index 0.

Tcl_Obj **objPtrPtr (out)
Points to place where Tcl_ListObjIndex is to store a pointer to the resulting list element object.

int first (in)
Index of the starting list element that Tcl_ListObjReplace is to replace. The list's first element has index 0.

int count (in)
The number of elements that Tcl_ListObjReplace is to replace.

DESCRIPTION

Tcl list objects have an internal representation that supports the efficient indexing and appending. The procedures described in this man page are used to create, modify, index, and append to Tcl list objects from C code.

Tcl_ListObjAppendList and Tcl_ListObjAppendElement both add one or more objects to the end of the list object referenced by listPtr. Tcl_ListObjAppendList appends each element of the list object referenced by elemListPtr while Tcl_ListObjAppendElement appends the single object referenced by objPtr. Both procedures will convert the object referenced by listPtr to a list object if necessary. If an error occurs during conversion, both procedures return TCL_ERROR and leave an error message in the interpreter's result object if interp is not NULL. Similarly, if elemListPtr does not already refer to a list object, Tcl_ListObjAppendList will attempt to convert it to one and if an error occurs during conversion, will return TCL_ERROR and leave an error message in the interpreter's result object if interp is not NULL. Both procedures invalidate any old string representation of listPtr and, if it was converted to a list object, free any old internal representation. Similarly, Tcl_ListObjAppendList frees any old internal representation of elemListPtr if it converts it to a list object. After appending each element in elemListPtr, Tcl_ListObjAppendList increments the element's reference count since listPtr now also refers to it. For the same reason, Tcl_ListObjAppendElement increments objPtr's reference count. If no error occurs, the two procedures return TCL_OK after appending the objects.

Tcl_NewListObj and Tcl_SetListObj create a new object or modify an existing object to hold the objc elements of the array referenced by objv where each element is a pointer to a Tcl object. If objc is less than or equal to zero, they return an empty object. The new object's string representation is left invalid. The two procedures increment the reference counts of the elements in objc since the list object now refers to them. The new list object returned by Tcl_NewListObj has reference count zero.

Tcl_ListObjGetElements returns a count and a pointer to an array of the elements in a list object. It returns the count by storing it in the address objcPtr. Similarly, it returns the array pointer by storing it in the address objvPtr. The memory pointed to is managed by Tcl and should not be freed by the caller. If listPtr is not already a list object, Tcl_ListObjGetElements will attempt to convert it to one; if the conversion fails, it returns TCL_ERROR and leaves an error message in the interpreter's result object if interp is not NULL. Otherwise it returns TCL_OK after storing the count and array pointer.

Tcl_ListObjLength returns the number of elements in the list object referenced by listPtr. It returns this count by storing an integer in the address intPtr. If the object is not already a list object, Tcl_ListObjLength will attempt to convert it to one; if the conversion fails, it returns TCL_ERROR and leaves an error message in the interpreter's result object if interp is not NULL. Otherwise it returns TCL_OK after storing the list's length.

The procedure Tcl_ListObjIndex returns a pointer to the object at element index in the list referenced by listPtr. It returns this object by storing a pointer to it in the address objPtrPtr. If listPtr does not already refer to a list object, Tcl_ListObjIndex will attempt to convert it to one; if the conversion fails, it returns TCL_ERROR and leaves an error message in the interpreter's result object if interp is not NULL. If the index is out of range, that is, index is negative or greater than or equal to the number of elements in the list, Tcl_ListObjIndex stores a NULL in objPtrPtr and returns TCL_OK. Otherwise it returns TCL_OK after storing the element's object pointer. The reference count for the list element is not incremented; the caller must do that if it needs to retain a pointer to the element.

Tcl_ListObjReplace replaces zero or more elements of the list referenced by listPtr with the objc objects in the array referenced by objv. If listPtr does not point to a list object, Tcl_ListObjReplace will attempt to convert it to one; if the conversion fails, it returns TCL_ERROR and leaves an error message in the interpreter's result object if interp is not NULL. Otherwise, it returns TCL_OK after replacing the objects. If objv is NULL, no new elements are added. If the argument first is zero or negative, it refers to the first element. If first is greater than or equal to the number of elements in the list, then no elements are deleted; the new elements are appended to the list. count gives the number of elements to replace. If count is zero or negative then no elements are deleted; the new elements are simply inserted before the one designated by first. Tcl_ListObjReplace invalidates listPtr's old string representation. The reference counts of any elements inserted from objv are incremented since the resulting list now refers to them. Similarly, the reference counts for any replaced objects are decremented.

Because Tcl_ListObjReplace combines both element insertion and deletion, it can be used to implement a number of list operations. For example, the following code inserts the objc objects referenced by the array of object pointers objv just before the element index of the list referenced by listPtr:

result = Tcl_ListObjReplace(interp, listPtr, index, 0, objc, objv);
Similarly, the following code appends the objc objects referenced by the array objv to the end of the list listPtr:
result = Tcl_ListObjLength(interp, listPtr, &length);
if (result == TCL_OK) {
    result = Tcl_ListObjReplace(interp, listPtr, length, 0, objc, objv);
}
The count list elements starting at first can be deleted by simply calling Tcl_ListObjReplace with a NULL objvPtr:
result = Tcl_ListObjReplace(interp, listPtr, first, count, 0, NULL);

SEE ALSO

Tcl_NewObj, Tcl_DecrRefCount, Tcl_IncrRefCount, Tcl_GetObjResult

KEYWORDS

append, index, insert, internal representation, length, list, list object, list type, object, object type, replace, string representation
Copyright © 1996-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Notifier manual page

NAME
Tcl_CreateEventSource, Tcl_DeleteEventSource, Tcl_SetMaxBlockTime, Tcl_QueueEvent, Tcl_ThreadQueueEvent, Tcl_ThreadAlert, Tcl_GetCurrentThread, Tcl_DeleteEvents, Tcl_InitNotifier, Tcl_FinalizeNotifier, Tcl_WaitForEvent, Tcl_AlertNotifier, Tcl_SetTimer, Tcl_ServiceAll, Tcl_ServiceEvent, Tcl_GetServiceMode, Tcl_SetServiceMode - the event queue and notifier interfaces
SYNOPSIS
ARGUMENTS
INTRODUCTION
NOTIFIER BASICS
CREATING A NEW EVENT SOURCE
TCL_QUEUE_TAIL
TCL_QUEUE_HEAD
TCL_QUEUE_MARK
CREATING A NEW NOTIFIER
EXTERNAL EVENT LOOPS
SEE ALSO
KEYWORDS

NAME

Tcl_CreateEventSource, Tcl_DeleteEventSource, Tcl_SetMaxBlockTime, Tcl_QueueEvent, Tcl_ThreadQueueEvent, Tcl_ThreadAlert, Tcl_GetCurrentThread, Tcl_DeleteEvents, Tcl_InitNotifier, Tcl_FinalizeNotifier, Tcl_WaitForEvent, Tcl_AlertNotifier, Tcl_SetTimer, Tcl_ServiceAll, Tcl_ServiceEvent, Tcl_GetServiceMode, Tcl_SetServiceMode - the event queue and notifier interfaces

SYNOPSIS

#include <tcl.h>
void
Tcl_CreateEventSource(setupProc, checkProc, clientData)
void
Tcl_DeleteEventSource(setupProc, checkProc, clientData)
void
Tcl_SetMaxBlockTime(timePtr)
void
Tcl_QueueEvent(evPtr, position)
void
Tcl_ThreadQueueEvent(threadId, evPtr, position)
void
Tcl_ThreadAlert(threadId, clientData)
Tcl_ThreadId
Tcl_GetCurrentThread()
void
Tcl_DeleteEvents(deleteProc, clientData)
ClientData
Tcl_InitNotifier()
void
Tcl_FinalizeNotifier(clientData)
int
Tcl_WaitForEvent(timePtr)
void
Tcl_AlertNotifier(clientData)
void
Tcl_SetTimer(timePtr)
int
Tcl_ServiceAll()
int
Tcl_ServiceEvent(flags)
int
Tcl_GetServiceMode()
int
Tcl_SetServiceMode(mode)

ARGUMENTS

Tcl_EventSetupProc *setupProc (in)
Procedure to invoke to prepare for event wait in Tcl_DoOneEvent.

Tcl_EventCheckProc *checkProc (in)
Procedure for Tcl_DoOneEvent to invoke after waiting for events. Checks to see if any events have occurred and, if so, queues them.

ClientData clientData (in)
Arbitrary one-word value to pass to setupProc, checkProc, or deleteProc.

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 Tcl_WaitForEvent is NULL, it means there is no maximum wait time: wait forever if necessary.

Tcl_Event *evPtr (in)
An event to add to the event queue. The storage for the event must have been allocated by the caller using Tcl_Alloc or ckalloc.

Tcl_QueuePosition position (in)
Where to add the new event in the queue: TCL_QUEUE_TAIL, TCL_QUEUE_HEAD, or TCL_QUEUE_MARK.

Tcl_ThreadId threadId (in)
A unique identifier for a thread.

Tcl_EventDeleteProc *deleteProc (in)
Procedure to invoke for each queued event in Tcl_DeleteEvents.

int flags (in)
What types of events to service. These flags are the same as those passed to Tcl_DoOneEvent.

int mode (in)
Inidicates whether events should be serviced by Tcl_ServiceAll. Must be one of TCL_SERVICE_NONE or TCL_SERVICE_ALL.

INTRODUCTION

The interfaces described here are used to customize the Tcl event loop. The two most common customizations are to add new sources of events and to merge Tcl's event loop with some other event loop, such as one provided by an application in which Tcl is embedded. Each of these tasks is described in a separate section below.

The procedures in this manual entry are the building blocks out of which the Tcl event notifier is constructed. The event notifier is the lowest layer in the Tcl event mechanism. It consists of three things:

[1]
Event sources: these represent the ways in which events can be generated. For example, there is a timer event source that implements the Tcl_CreateTimerHandler procedure and the after command, and there is a file event source that implements the Tcl_CreateFileHandler procedure on Unix systems. An event source must work with the notifier to detect events at the right times, record them on the event queue, and eventually notify higher-level software that they have occurred. The procedures Tcl_CreateEventSource, Tcl_DeleteEventSource, and Tcl_SetMaxBlockTime, Tcl_QueueEvent, and Tcl_DeleteEvents are used primarily by event sources.

[2]
The event queue: for non-threaded applications, there is a single queue for the whole application, containing events that have been detected but not yet serviced. Event sources place events onto the queue so that they may be processed in order at appropriate times during the event loop. The event queue guarantees a fair discipline of event handling, so that no event source can starve the others. It also allows events to be saved for servicing at a future time. Threaded applications work in a similar manner, except that there is a separate event queue for each thread containing a Tcl interpreter. Tcl_QueueEvent is used (primarily by event sources) to add events to the event queue and Tcl_DeleteEvents is used to remove events from the queue without processing them. In a threaded application, Tcl_QueueEvent adds an event to the current thread's queue, and Tcl_ThreadQueueEvent adds an event to a queue in a specific thread.

[3]
The event loop: in order to detect and process events, the application enters a loop that waits for events to occur, places them on the event queue, and then processes them. Most applications will do this by calling the procedure Tcl_DoOneEvent, which is described in a separate manual entry.

Most Tcl applications need not worry about any of the internals of the Tcl notifier. However, the notifier now has enough flexibility to be retargeted either for a new platform or to use an external event loop (such as the Motif event loop, when Tcl is embedded in a Motif application). The procedures Tcl_WaitForEvent and Tcl_SetTimer are normally implemented by Tcl, but may be replaced with new versions to retarget the notifier (the Tcl_InitNotifier, Tcl_AlertNotifier, Tcl_FinalizeNotifier, Tcl_Sleep, Tcl_CreateFileHandler, and Tcl_DeleteFileHandler must also be replaced; see CREATING A NEW NOTIFIER below for details). The procedures Tcl_ServiceAll, Tcl_ServiceEvent, Tcl_GetServiceMode, and Tcl_SetServiceMode are provided to help connect Tcl's event loop to an external event loop such as Motif's.

NOTIFIER BASICS

The easiest way to understand how the notifier works is to consider what happens when Tcl_DoOneEvent is called. Tcl_DoOneEvent is passed a flags argument that indicates what sort of events it is OK to process and also whether or not to block if no events are ready. Tcl_DoOneEvent does the following things:

[1]
Check the event queue to see if it contains any events that can be serviced. If so, service the first possible event, remove it from the queue, and return. It does this by calling Tcl_ServiceEvent and passing in the flags argument.

[2]
Prepare to block for an event. To do this, Tcl_DoOneEvent invokes a setup procedure in each event source. The event source will perform event-source specific initialization and possibly call Tcl_SetMaxBlockTime to limit how long Tcl_WaitForEvent will block if no new events occur.

[3]
Call Tcl_WaitForEvent. This procedure is implemented differently on different platforms; it waits for an event to occur, based on the information provided by the event sources. It may cause the application to block if timePtr specifies an interval other than 0. Tcl_WaitForEvent returns when something has happened, such as a file becoming readable or the interval given by timePtr expiring. If there are no events for Tcl_WaitForEvent to wait for, so that it would block forever, then it returns immediately and Tcl_DoOneEvent returns 0.

[4]
Call a check procedure in each event source. The check procedure determines whether any events of interest to this source occurred. If so, the events are added to the event queue.

[5]
Check the event queue to see if it contains any events that can be serviced. If so, service the first possible event, remove it from the queue, and return.

[6]
See if there are idle callbacks pending. If so, invoke all of them and return.

[7]
Either return 0 to indicate that no events were ready, or go back to step [2] if blocking was requested by the caller.

CREATING A NEW EVENT SOURCE

An event source consists of three procedures invoked by the notifier, plus additional C procedures that are invoked by higher-level code to arrange for event-driven callbacks. The three procedures called by the notifier consist of the setup and check procedures described above, plus an additional procedure that is invoked when an event is removed from the event queue for servicing.

The procedure Tcl_CreateEventSource creates a new event source. Its arguments specify the setup procedure and check procedure for the event source. SetupProc should match the following prototype:

typedef void Tcl_EventSetupProc(
    ClientData clientData,
    int flags);
The clientData argument will be the same as the clientData argument to Tcl_CreateEventSource; it is typically used to point to private information managed by the event source. The flags argument will be the same as the flags argument passed to Tcl_DoOneEvent except that it will never be 0 (Tcl_DoOneEvent replaces 0 with TCL_ALL_EVENTS). Flags indicates what kinds of events should be considered; if the bit corresponding to this event source isn't set, the event source should return immediately without doing anything. For example, the file event source checks for the TCL_FILE_EVENTS bit.

SetupProc's job is to make sure that the application wakes up when events of the desired type occur. This is typically done in a platform-dependent fashion. For example, under Unix an event source might call Tcl_CreateFileHandler; under Windows it might request notification with a Windows event. For timer-driven event sources such as timer events or any polled event, the event source can call Tcl_SetMaxBlockTime to force the application to wake up after a specified time even if no events have occurred. If no event source calls Tcl_SetMaxBlockTime then Tcl_WaitForEvent will wait as long as necessary for an event to occur; otherwise, it will only wait as long as the shortest interval passed to Tcl_SetMaxBlockTime by one of the event sources. If an event source knows that it already has events ready to report, it can request a zero maximum block time. For example, the setup procedure for the X event source looks to see if there are events already queued. If there are, it calls Tcl_SetMaxBlockTime with a 0 block time so that Tcl_WaitForEvent does not block if there is no new data on the X connection. The timePtr argument to Tcl_WaitForEvent points to a structure that describes a time interval in seconds and microseconds:

typedef struct Tcl_Time {
    long sec;
    long usec;
} Tcl_Time;
The usec field should be less than 1000000.

Information provided to Tcl_SetMaxBlockTime is only used for the next call to Tcl_WaitForEvent; it is discarded after Tcl_WaitForEvent returns. The next time an event wait is done each of the event sources' setup procedures will be called again, and they can specify new information for that event wait.

If the application uses an external event loop rather than Tcl_DoOneEvent, the event sources may need to call Tcl_SetMaxBlockTime at other times. For example, if a new event handler is registered that needs to poll for events, the event source may call Tcl_SetMaxBlockTime to set the block time to zero to force the external event loop to call Tcl. In this case, Tcl_SetMaxBlockTime invokes Tcl_SetTimer with the shortest interval seen since the last call to Tcl_DoOneEvent or Tcl_ServiceAll.

In addition to the generic procedure Tcl_SetMaxBlockTime, other platform-specific procedures may also be available for setupProc, if there is additional information needed by Tcl_WaitForEvent on that platform. For example, on Unix systems the Tcl_CreateFileHandler interface can be used to wait for file events.

The second procedure provided by each event source is its check procedure, indicated by the checkProc argument to Tcl_CreateEventSource. CheckProc must match the following prototype:

typedef void Tcl_EventCheckProc(
    ClientData clientData,
    int flags);
The arguments to this procedure are the same as those for setupProc. CheckProc is invoked by Tcl_DoOneEvent after it has waited for events. Presumably at least one event source is now prepared to queue an event. Tcl_DoOneEvent calls each of the event sources in turn, so they all have a chance to queue any events that are ready. The check procedure does two things. First, it must see if any events have triggered. Different event sources do this in different ways.

If an event source's check procedure detects an interesting event, it must add the event to Tcl's event queue. To do this, the event source calls Tcl_QueueEvent. The evPtr argument is a pointer to a dynamically allocated structure containing the event (see below for more information on memory management issues). Each event source can define its own event structure with whatever information is relevant to that event source. However, the first element of the structure must be a structure of type Tcl_Event, and the address of this structure is used when communicating between the event source and the rest of the notifier. A Tcl_Event has the following definition:

typedef struct {
    Tcl_EventProc *proc;
    struct Tcl_Event *nextPtr;
} Tcl_Event;
The event source must fill in the proc field of the event before calling Tcl_QueueEvent. The nextPtr is used to link together the events in the queue and should not be modified by the event source.

An event may be added to the queue at any of three positions, depending on the position argument to Tcl_QueueEvent:

TCL_QUEUE_TAIL
Add the event at the back of the queue, so that all other pending events will be serviced first. This is almost always the right place for new events.

TCL_QUEUE_HEAD
Add the event at the front of the queue, so that it will be serviced before all other queued events.

TCL_QUEUE_MARK
Add the event at the front of the queue, unless there are other events at the front whose position is TCL_QUEUE_MARK; if so, add the new event just after all other TCL_QUEUE_MARK events. This value of position is used to insert an ordered sequence of events at the front of the queue, such as a series of Enter and Leave events synthesized during a grab or ungrab operation in Tk.

When it is time to handle an event from the queue (steps 1 and 4 above) Tcl_ServiceEvent will invoke the proc specified in the first queued Tcl_Event structure. Proc must match the following prototype:

typedef int Tcl_EventProc(
    Tcl_Event *evPtr,
    int flags);
The first argument to proc is a pointer to the event, which will be the same as the first argument to the Tcl_QueueEvent call that added the event to the queue. The second argument to proc is the flags argument for the current call to Tcl_ServiceEvent; this is used by the event source to return immediately if its events are not relevant.

It is up to proc to handle the event, typically by invoking one or more Tcl commands or C-level callbacks. Once the event source has finished handling the event it returns 1 to indicate that the event can be removed from the queue. If for some reason the event source decides that the event cannot be handled at this time, it may return 0 to indicate that the event should be deferred for processing later; in this case Tcl_ServiceEvent will go on to the next event in the queue and attempt to service it. There are several reasons why an event source might defer an event. One possibility is that events of this type are excluded by the flags argument. For example, the file event source will always return 0 if the TCL_FILE_EVENTS bit isn't set in flags. Another example of deferring events happens in Tk if Tk_RestrictEvents has been invoked to defer certain kinds of window events.

When proc returns 1, Tcl_ServiceEvent will remove the event from the event queue and free its storage. Note that the storage for an event must be allocated by the event source (using Tcl_Alloc or the Tcl macro ckalloc) before calling Tcl_QueueEvent, but it will be freed by Tcl_ServiceEvent, not by the event source.

Threaded applications work in a similar manner, except that there is a separate event queue for each thread containing a Tcl interpreter. Calling Tcl_QueueEvent in a multithreaded application adds an event to the current thread's queue. To add an event to another thread's queue, use Tcl_ThreadQueueEvent. Tcl_ThreadQueueEvent 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 Tcl_GetCurrentThread 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 need to call Tcl_ThreadAlert to "wake up" that thread's notifier to alert it to the new event.

Tcl_DeleteEvents can be used to explicitly remove one or more events from the event queue. Tcl_DeleteEvents calls proc 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. Proc should match the following prototype:

typedef int Tcl_EventDeleteProc(
    Tcl_Event *evPtr,
    ClientData clientData);
The clientData argument will be the same as the clientData argument to Tcl_DeleteEvents; it is typically used to point to private information managed by the event source. The evPtr will point to the next event in the queue.

Tcl_DeleteEventSource deletes an event source. The setupProc, checkProc, and clientData arguments must exactly match those provided to the Tcl_CreateEventSource for the event source to be deleted. If no such source exists, Tcl_DeleteEventSource has no effect.

CREATING A NEW NOTIFIER

The notifier consists of all the procedures described in this manual entry, plus Tcl_DoOneEvent and Tcl_Sleep, which are available on all platforms, and Tcl_CreateFileHandler and Tcl_DeleteFileHandler, which are Unix-specific. Most of these procedures are generic, in that they are the same for all notifiers. However, eight of the procedures are notifier-dependent: Tcl_InitNotifier, Tcl_AlertNotifier, Tcl_FinalizeNotifier, Tcl_SetTimer, Tcl_Sleep, Tcl_WaitForEvent, Tcl_CreateFileHandler and Tcl_DeleteFileHandler. To support a new platform or to integrate Tcl with an application-specific event loop, you must write new versions of these procedures.

Tcl_InitNotifier initializes the notifier state and returns a handle to the notifier state. Tcl calls this procedure when intializing a Tcl interpreter. Similarly, Tcl_FinalizeNotifier shuts down the notifier, and is called by Tcl_Finalize when shutting down a Tcl interpreter.

Tcl_WaitForEvent is the lowest-level procedure in the notifier; it is responsible for waiting for an ``interesting'' event to occur or for a given time to elapse. Before Tcl_WaitForEvent is invoked, each of the event sources' setup procedure will have been invoked. The timePtr argument to Tcl_WaitForEvent gives the maximum time to block for an event, based on calls to Tcl_SetMaxBlockTime made by setup procedures and on other information (such as the TCL_DONT_WAIT bit in flags).

Ideally, Tcl_WaitForEvent should only wait for an event to occur; it should not actually process the event in any way. Later on, the event sources will process the raw events and create Tcl_Events on the event queue in their checkProc procedures. However, on some platforms (such as Windows) this isn't possible; events may be processed in Tcl_WaitForEvent, including queuing Tcl_Events and more (for example, callbacks for native widgets may be invoked). The return value from Tcl_WaitForEvent must be either 0, 1, or -1. On platforms such as Windows where events get processed in Tcl_WaitForEvent, a return value of 1 means that there may be more events still pending that haven't been processed. This is a sign to the caller that it must call Tcl_WaitForEvent again if it wants all pending events to be processed. A 0 return value means that calling Tcl_WaitForEvent again will not have any effect: either this is a platform where Tcl_WaitForEvent only waits without doing any event processing, or Tcl_WaitForEvent knows for sure that there are no additional events to process (e.g. it returned because the time elapsed). Finally, a return value of -1 means that the event loop is no longer operational and the application should probably unwind and terminate. Under Windows this happens when a WM_QUIT message is received; under Unix it happens when Tcl_WaitForEvent would have waited forever because there were no active event sources and the timeout was infinite.

Tcl_AlertNotifier is used in multithreaded applications to allow any thread to "wake up" the notifier to alert it to new events on its queue. Tcl_AlertNotifier requires as an argument the notifier handle returned by Tcl_InitNotifier.

If the notifier will be used with an external event loop, then it must also support the Tcl_SetTimer interface. Tcl_SetTimer is invoked by Tcl_SetMaxBlockTime whenever the maximum blocking time has been reduced. Tcl_SetTimer should arrange for the external event loop to invoke Tcl_ServiceAll after the specified interval even if no events have occurred. This interface is needed because Tcl_WaitForEvent isn't invoked when there is an external event loop. If the notifier will only be used from Tcl_DoOneEvent, then Tcl_SetTimer need not do anything.

On Unix systems, the file event source also needs support from the notifier. The file event source consists of the Tcl_CreateFileHandler and Tcl_DeleteFileHandler procedures, which are described in the Tcl_CreateFileHandler manual page.

The Tcl_Sleep and Tcl_DoOneEvent interfaces are described 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 unix/tclUnixNotfy.c or win/tclWinNotify.c in the Tcl source distribution.

EXTERNAL EVENT LOOPS

The notifier interfaces are designed so that Tcl can be embedded into applications that have their own private event loops. In this case, the application does not call Tcl_DoOneEvent except in the case of recursive event loops such as calls to the Tcl commands update or vwait. Most of the time is spent in the external event loop of the application. In this case the notifier must arrange for the external event loop to call back into Tcl when something happens on the various Tcl event sources. These callbacks should arrange for appropriate Tcl events to be placed on the Tcl event queue.

Because the external event loop is not calling Tcl_DoOneEvent on a regular basis, it is up to the notifier to arrange for Tcl_ServiceEvent to be called whenever events are pending on the Tcl event queue. The easiest way to do this is to invoke Tcl_ServiceAll at the end of each callback from the external event loop. This will ensure that all of the event sources are polled, any queued events are serviced, and any pending idle handlers are processed before returning control to the application. In addition, event sources that need to poll for events can call Tcl_SetMaxBlockTime to force the external event loop to call Tcl even if no events are available on the system event queue.

As a side effect of processing events detected in the main external event loop, Tcl may invoke Tcl_DoOneEvent to start a recursive event loop in commands like vwait. Tcl_DoOneEvent will invoke the external event loop, which will result in callbacks as described in the preceding paragraph, which will result in calls to Tcl_ServiceAll. However, in these cases it is undesirable to service events in Tcl_ServiceAll. Servicing events there is unnecessary because control will immediately return to the external event loop and hence to Tcl_DoOneEvent, which can service the events itself. Furthermore, Tcl_DoOneEvent is supposed to service only a single event, whereas Tcl_ServiceAll normally services all pending events. To handle this situation, Tcl_DoOneEvent sets a flag for Tcl_ServiceAll that causes it to return without servicing any events. This flag is called the service mode; Tcl_DoOneEvent restores it to its previous value before it returns.

In some cases, however, it may be necessary for Tcl_ServiceAll to service events even when it has been invoked from Tcl_DoOneEvent. This happens when there is yet another recursive event loop invoked via an event handler called by Tcl_DoOneEvent (such as one that is part of a native widget). In this case, Tcl_DoOneEvent may not have a chance to service events so Tcl_ServiceAll must service them all. Any recursive event loop that calls an external event loop rather than Tcl_DoOneEvent must reset the service mode so that all events get processed in Tcl_ServiceAll. This is done by invoking the Tcl_SetServiceMode procedure. If Tcl_SetServiceMode is passed TCL_SERVICE_NONE, then calls to Tcl_ServiceAll will return immediately without processing any events. If Tcl_SetServiceMode is passed TCL_SERVICE_ALL, then calls to Tcl_ServiceAll will behave normally. Tcl_SetServiceMode returns the previous value of the service mode, which should be restored when the recursive loop exits. Tcl_GetServiceMode returns the current value of the service mode.

SEE ALSO

Tcl_CreateFileHandler, Tcl_DeleteFileHandler, Tcl_Sleep, Tcl_DoOneEvent, Thread

KEYWORDS

event, notifier, event queue, event sources, file events, timer, idle, service mode, threads
Copyright © 1998-1999 Scriptics Corporation
Copyright © 1995-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Obj manual page

NAME

Tcl_NewObj, Tcl_DuplicateObj, Tcl_IncrRefCount, Tcl_DecrRefCount, Tcl_IsShared, Tcl_InvalidateStringRep - manipulate Tcl objects

SYNOPSIS

#include <tcl.h>
Tcl_Obj *
Tcl_NewObj()
Tcl_Obj *
Tcl_DuplicateObj(objPtr)
Tcl_IncrRefCount(objPtr)
Tcl_DecrRefCount(objPtr)
int
Tcl_IsShared(objPtr)
Tcl_InvalidateStringRep(objPtr)

ARGUMENTS

Tcl_Obj *objPtr (in)
Points to an object; must have been the result of a previous call to Tcl_NewObj.

INTRODUCTION

This man page presents an overview of Tcl objects and how they are used. It also describes generic procedures for managing Tcl objects. These procedures are used to create and copy objects, and increment and decrement the count of references (pointers) to objects. The procedures are used in conjunction with ones that operate on specific types of objects such as Tcl_GetIntFromObj and Tcl_ListObjAppendElement. The individual procedures are described along with the data structures they manipulate.

Tcl's dual-ported objects provide a general-purpose mechanism for storing and exchanging Tcl values. They largely replace the use of strings in Tcl. For example, they are used to store variable values, command arguments, command results, and scripts. Tcl objects behave like strings but also hold an internal representation that can be manipulated more efficiently. For example, a Tcl list is now represented as an object that holds the list's string representation as well as an array of pointers to the objects for each list element. Dual-ported objects avoid most runtime type conversions. They also improve the speed of many operations since an appropriate representation is immediately available. The compiler itself uses Tcl objects to cache the instruction bytecodes resulting from compiling scripts.

The two representations are a cache of each other and are computed lazily. That is, each representation is only computed when necessary, it is computed from the other representation, and, once computed, it is saved. In addition, a change in one representation invalidates the other one. As an example, a Tcl program doing integer calculations can operate directly on a variable's internal machine integer representation without having to constantly convert between integers and strings. Only when it needs a string representing the variable's value, say to print it, will the program regenerate the string representation from the integer. Although objects contain an internal representation, their semantics are defined in terms of strings: an up-to-date string can always be obtained, and any change to the object will be reflected in that string when the object's string representation is fetched. Because of this representation invalidation and regeneration, it is dangerous for extension writers to access Tcl_Obj fields directly. It is better to access Tcl_Obj information using procedures like Tcl_GetStringFromObj and Tcl_GetString.

Objects are allocated on the heap and are referenced using a pointer to their Tcl_Obj structure. Objects are shared as much as possible. This significantly reduces storage requirements because some objects such as long lists are very large. Also, most Tcl values are only read and never modified. This is especially true for procedure arguments, which can be shared between the caller and the called procedure. Assignment and argument binding is done by simply assigning a pointer to the value. Reference counting is used to determine when it is safe to reclaim an object's storage.

Tcl objects are typed. An object's internal representation is controlled by its type. Seven types are predefined in the Tcl core including integer, double, list, and bytecode. Extension writers can extend the set of types by using the procedure Tcl_RegisterObjType .

THE TCL_OBJ STRUCTURE

Each Tcl object is represented by a Tcl_Obj structure which is defined as follows.
typedef struct Tcl_Obj {
    int refCount;
    char *bytes;
    int length;
    Tcl_ObjType *typePtr;
    union {
        long longValue;
        double doubleValue;
        VOID *otherValuePtr;
        struct {
            VOID *ptr1;
            VOID *ptr2;
        } twoPtrValue;
    } internalRep;
} Tcl_Obj;
The bytes and the length members together hold an object's string representation, which is a counted or binary string that may contain binary data with embedded null bytes. bytes points to the first byte of the string representation. The length member gives the number of bytes. The byte array must always have a null after the last byte, at offset length; this allows string representations that do not contain nulls to be treated as conventional null-terminated C strings. C programs use Tcl_GetStringFromObj and Tcl_GetString to get an object's string representation. If bytes is NULL, the string representation is invalid.

An object's type manages its internal representation. The member typePtr points to the Tcl_ObjType structure that describes the type. If typePtr is NULL, the internal representation is invalid.

The internalRep union member holds an object's internal representation. This is either a (long) integer, a double-precision floating point number, a pointer to a value containing additional information needed by the object's type to represent the object, or two arbitrary pointers.

The refCount member is used to tell when it is safe to free an object's storage. It holds the count of active references to the object. Maintaining the correct reference count is a key responsibility of extension writers. Reference counting is discussed below in the section STORAGE MANAGEMENT OF OBJECTS.

Although extension writers can directly access the members of a Tcl_Obj structure, it is much better to use the appropriate procedures and macros. For example, extension writers should never read or update refCount directly; they should use macros such as Tcl_IncrRefCount and Tcl_IsShared instead.

A key property of Tcl objects is that they hold two representations. An object typically starts out containing only a string representation: it is untyped and has a NULL typePtr. An object containing an empty string or a copy of a specified string is created using Tcl_NewObj or Tcl_NewStringObj respectively. An object's string value is gotten with Tcl_GetStringFromObj or Tcl_GetString and changed with Tcl_SetStringObj. If the object is later passed to a procedure like Tcl_GetIntFromObj that requires a specific internal representation, the procedure will create one and set the object's typePtr. The internal representation is computed from the string representation. An object's two representations are duals of each other: changes made to one are reflected in the other. For example, Tcl_ListObjReplace will modify an object's internal representation and the next call to Tcl_GetStringFromObj or Tcl_GetString will reflect that change.

Representations are recomputed lazily for efficiency. A change to one representation made by a procedure such as Tcl_ListObjReplace is not reflected immediately in the other representation. Instead, the other representation is marked invalid so that it is only regenerated if it is needed later. Most C programmers never have to be concerned with how this is done and simply use procedures such as Tcl_GetBooleanFromObj or Tcl_ListObjIndex. Programmers that implement their own object types must check for invalid representations and mark representations invalid when necessary. The procedure Tcl_InvalidateStringRep is used to mark an object's string representation invalid and to free any storage associated with the old string representation.

Objects usually remain one type over their life, but occasionally an object must be converted from one type to another. For example, a C program might build up a string in an object with repeated calls to Tcl_AppendToObj, and then call Tcl_ListObjIndex to extract a list element from the object. The same object holding the same string value can have several different internal representations at different times. Extension writers can also force an object to be converted from one type to another using the Tcl_ConvertToType procedure. Only programmers that create new object types need to be concerned about how this is done. A procedure defined as part of the object type's implementation creates a new internal representation for an object and changes its typePtr. See the man page for Tcl_RegisterObjType to see how to create a new object type.

EXAMPLE OF THE LIFETIME OF AN OBJECT

As an example of the lifetime of an object, consider the following sequence of commands:
set x 123
This assigns to x an untyped object whose bytes member points to 123 and length member contains 3. The object's typePtr member is NULL.
puts "x is $x"
x's string representation is valid (since bytes is non-NULL) and is fetched for the command.
incr x
The incr command first gets an integer from x's object by calling Tcl_GetIntFromObj. This procedure checks whether the object is already an integer object. Since it is not, it converts the object by setting the object's internalRep.longValue member to the integer 123 and setting the object's typePtr to point to the integer Tcl_ObjType structure. Both representations are now valid. incr increments the object's integer internal representation then invalidates its string representation (by calling Tcl_InvalidateStringRep) since the string representation no longer corresponds to the internal representation.
puts "x is now $x"
The string representation of x's object is needed and is recomputed. The string representation is now 124. and both representations are again valid.

STORAGE MANAGEMENT OF OBJECTS

Tcl objects are allocated on the heap and are shared as much as possible to reduce storage requirements. Reference counting is used to determine when an object is no longer needed and can safely be freed. An object just created by Tcl_NewObj or Tcl_NewStringObj has refCount 0. The macro Tcl_IncrRefCount increments the reference count when a new reference to the object is created. The macro Tcl_DecrRefCount decrements the count when a reference is no longer needed and, if the object's reference count drops to zero, frees its storage. An object shared by different code or data structures has refCount greater than 1. Incrementing an object's reference count ensures that it won't be freed too early or have its value change accidently.

As an example, the bytecode interpreter shares argument objects between calling and called Tcl procedures to avoid having to copy objects. It assigns the call's argument objects to the procedure's formal parameter variables. In doing so, it calls Tcl_IncrRefCount to increment the reference count of each argument since there is now a new reference to it from the formal parameter. When the called procedure returns, the interpreter calls Tcl_DecrRefCount to decrement each argument's reference count. When an object's reference count drops less than or equal to zero, Tcl_DecrRefCount reclaims its storage. Most command procedures do not have to be concerned about reference counting since they use an object's value immediately and don't retain a pointer to the object after they return. However, if they do retain a pointer to an object in a data structure, they must be careful to increment its reference count since the retained pointer is a new reference.

Command procedures that directly modify objects such as those for lappend and linsert must be careful to copy a shared object before changing it. They must first check whether the object is shared by calling Tcl_IsShared. If the object is shared they must copy the object by using Tcl_DuplicateObj; this returns a new duplicate of the original object that has refCount 0. If the object is not shared, the command procedure "owns" the object and can safely modify it directly. For example, the following code appears in the command procedure that implements linsert. This procedure modifies the list object passed to it in objv[1] by inserting objc-3 new elements before index.

listPtr = objv[1];
if (Tcl_IsShared(listPtr)) {
    listPtr = Tcl_DuplicateObj(listPtr);
}
result = Tcl_ListObjReplace(interp, listPtr, index, 0, (objc-3), &(objv[3]));
As another example, incr's command procedure must check whether the variable's object is shared before incrementing the integer in its internal representation. If it is shared, it needs to duplicate the object in order to avoid accidently changing values in other data structures.

SEE ALSO

Tcl_ConvertToType, Tcl_GetIntFromObj, Tcl_ListObjAppendElement, Tcl_ListObjIndex, Tcl_ListObjReplace, Tcl_RegisterObjType

KEYWORDS

internal representation, object, object creation, object type, reference counting, string representation, type conversion
Copyright © 1996-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_ObjType manual page

NAME

Tcl_RegisterObjType, Tcl_GetObjType, Tcl_AppendAllObjTypes, Tcl_ConvertToType - manipulate Tcl object types

SYNOPSIS

#include <tcl.h>
Tcl_RegisterObjType(typePtr)
Tcl_ObjType *
Tcl_GetObjType(typeName)
int
Tcl_AppendAllObjTypes(interp, objPtr)
int
Tcl_ConvertToType(interp, objPtr, typePtr)

ARGUMENTS

Tcl_ObjType *typePtr (in)
Points to the structure containing information about the Tcl object type. This storage must must live forever, typically by being statically allocated.

char *typeName (in)
The name of a Tcl object type that Tcl_GetObjType should look up.

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

Tcl_Obj *objPtr (in)
For Tcl_AppendAllObjTypes, this points to the object onto which it appends the name of each object type as a list element. For Tcl_ConvertToType, this points to an object that must have been the result of a previous call to Tcl_NewObj.

DESCRIPTION

The procedures in this man page manage Tcl object types. The are used to register new object types, look up types, and force conversions from one type to another.

Tcl_RegisterObjType registers a new Tcl object type in the table of all object types supported by Tcl. The argument typePtr points to a Tcl_ObjType structure that describes the new type by giving its name and by supplying pointers to four procedures that implement the type. If the type table already contains a type with the same name as in typePtr, it is replaced with the new type. The Tcl_ObjType structure is described in the section THE TCL_OBJTYPE STRUCTURE below.

Tcl_GetObjType returns a pointer to the Tcl_ObjType with name typeName. It returns NULL if no type with that name is registered.

Tcl_AppendAllObjTypes appends the name of each object type as a list element onto the Tcl object referenced by objPtr. The return value is TCL_OK unless there was an error converting objPtr to a list object; in that case TCL_ERROR is returned.

Tcl_ConvertToType converts an object from one type to another if possible. It creates a new internal representation for objPtr appropriate for the target type typePtr and sets its typePtr member to that type. Any internal representation for objPtr's old type is freed. If an error occurs during conversion, it returns TCL_ERROR and leaves an error message in the result object for interp unless interp is NULL. Otherwise, it returns TCL_OK. Passing a NULL interp allows this procedure to be used as a test whether the conversion can be done (and in fact was done).

THE TCL_OBJTYPE STRUCTURE

Extension writers can define new object types by defining four procedures, initializing a Tcl_ObjType structure to describe the type, and calling Tcl_RegisterObjType. The Tcl_ObjType structure is defined as follows:
typedef struct Tcl_ObjType {
    char *name;
    Tcl_FreeInternalRepProc *freeIntRepProc;
    Tcl_DupInternalRepProc *dupIntRepProc;
    Tcl_UpdateStringProc *updateStringProc;
    Tcl_SetFromAnyProc *setFromAnyProc;
} Tcl_ObjType;

The name member describes the name of the type, e.g. int. Extension writers can look up an object type using its name with the Tcl_GetObjType procedure. The remaining four members are pointers to procedures called by the generic Tcl object code:

The setFromAnyProc member contains the address of a function called to create a valid internal representation from an object's string representation.

typedef int (Tcl_SetFromAnyProc) (Tcl_Interp *interp, Tcl_Obj *objPtr);
If an internal representation can't be created from the string, it returns TCL_ERROR and puts a message describing the error in the result object for interp unless interp is NULL. If setFromAnyProc is successful, it stores the new internal representation, sets objPtr's typePtr member to point to setFromAnyProc's Tcl_ObjType, and returns TCL_OK. Before setting the new internal representation, the setFromAnyProc must free any internal representation of objPtr's old type; it does this by calling the old type's freeIntRepProc if it is not NULL. As an example, the setFromAnyProc for the builtin Tcl integer type gets an up-to-date string representation for objPtr by calling Tcl_GetStringFromObj. It parses the string to obtain an integer and, if this succeeds, stores the integer in objPtr's internal representation and sets objPtr's typePtr member to point to the integer type's Tcl_ObjType structure.

The updateStringProc member contains the address of a function called to create a valid string representation from an object's internal representation.

typedef void (Tcl_UpdateStringProc) (Tcl_Obj *objPtr);
objPtr's bytes member is always NULL when it is called. It must always set bytes non-NULL before returning. We require the string representation's byte array to have a null after the last byte, at offset length; this allows string representations that do not contain null bytes to be treated as conventional null character-terminated C strings. Storage for the byte array must be allocated in the heap by Tcl_Alloc. Note that updateStringProcs must allocate enough storage for the string's bytes and the terminating null byte. The updateStringProc for Tcl's builtin list type, for example, builds an array of strings for each element object and then calls Tcl_Merge to construct a string with proper Tcl list structure. It stores this string as the list object's string representation.

The dupIntRepProc member contains the address of a function called to copy an internal representation from one object to another.

typedef void (Tcl_DupInternalRepProc) (Tcl_Obj *srcPtr, Tcl_Obj *dupPtr);
dupPtr's internal representation is made a copy of srcPtr's internal representation. Before the call, srcPtr's internal representation is valid and dupPtr's is not. srcPtr's object type determines what copying its internal representation means. For example, the dupIntRepProc for the Tcl integer type simply copies an integer. The builtin list type's dupIntRepProc allocates a new array that points at the original element objects; the elements are shared between the two lists (and their reference counts are incremented to reflect the new references).

The freeIntRepProc member contains the address of a function that is called when an object is freed.

typedef void (Tcl_FreeInternalRepProc) (Tcl_Obj *objPtr);
The freeIntRepProc function can deallocate the storage for the object's internal representation and do other type-specific processing necessary when an object is freed. For example, Tcl list objects have an internalRep.otherValuePtr that points to an array of pointers to each element in the list. The list type's freeIntRepProc decrements the reference count for each element object (since the list will no longer refer to those objects), then deallocates the storage for the array of pointers. The freeIntRepProc member can be set to NULL to indicate that the internal representation does not require freeing.

SEE ALSO

Tcl_NewObj, Tcl_DecrRefCount, Tcl_IncrRefCount

KEYWORDS

internal representation, object, object type, string representation, type conversion
Copyright © 1996-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_OpenFileChannel manual page

NAME
Tcl_OpenFileChannel, Tcl_OpenCommandChannel, Tcl_MakeFileChannel, Tcl_GetChannel, Tcl_GetChannelNames, Tcl_GetChannelNamesEx, Tcl_RegisterChannel, Tcl_UnregisterChannel, Tcl_Close, Tcl_ReadChars, Tcl_Read, Tcl_GetsObj, Tcl_Gets, Tcl_WriteObj, Tcl_WriteChars, Tcl_Write, Tcl_Flush, Tcl_Seek, Tcl_Tell, Tcl_GetChannelOption, Tcl_SetChannelOption, Tcl_Eof, Tcl_InputBlocked, Tcl_InputBuffered, Tcl_Ungets - buffered I/O facilities using channels
SYNOPSIS
ARGUMENTS
DESCRIPTION
TCL_OPENFILECHANNEL
TCL_OPENCOMMANDCHANNEL
TCL_MAKEFILECHANNEL
TCL_GETCHANNEL
TCL_REGISTERCHANNEL
TCL_UNREGISTERCHANNEL
TCL_CLOSE
TCL_READCHARS AND TCL_READ
TCL_GETSOBJ AND TCL_GETS
TCL_UNGETS
TCL_WRITECHARS, TCL_WRITEOBJ, AND TCL_WRITE
TCL_FLUSH
TCL_SEEK
TCL_TELL
TCL_GETCHANNELOPTION
TCL_SETCHANNELOPTION
TCL_EOF
TCL_INPUTBLOCKED
TCL_INPUTBUFFERED
PLATFORM ISSUES
SEE ALSO
KEYWORDS

NAME

Tcl_OpenFileChannel, Tcl_OpenCommandChannel, Tcl_MakeFileChannel, Tcl_GetChannel, Tcl_GetChannelNames, Tcl_GetChannelNamesEx, Tcl_RegisterChannel, Tcl_UnregisterChannel, Tcl_Close, Tcl_ReadChars, Tcl_Read, Tcl_GetsObj, Tcl_Gets, Tcl_WriteObj, Tcl_WriteChars, Tcl_Write, Tcl_Flush, Tcl_Seek, Tcl_Tell, Tcl_GetChannelOption, Tcl_SetChannelOption, Tcl_Eof, Tcl_InputBlocked, Tcl_InputBuffered, Tcl_Ungets - buffered I/O facilities using channels

SYNOPSIS

#include <tcl.h>
typedef ... Tcl_Channel;
Tcl_Channel
Tcl_OpenFileChannel(interp, fileName, mode, permissions)
Tcl_Channel
Tcl_OpenCommandChannel(interp, argc, argv, flags)
Tcl_Channel
Tcl_MakeFileChannel(handle, readOrWrite)
Tcl_Channel
Tcl_GetChannel(interp, channelName, modePtr)
int
Tcl_GetChannelNames(interp)
int
Tcl_GetChannelNamesEx(interp, pattern)
void
Tcl_RegisterChannel(interp, channel)
int
Tcl_UnregisterChannel(interp, channel)
int
Tcl_Close(interp, channel)
int
Tcl_ReadChars(channel, readObjPtr, charsToRead, appendFlag)
int
Tcl_Read(channel, byteBuf, bytesToRead)
int
Tcl_GetsObj(channel, lineObjPtr)
int
Tcl_Gets(channel, lineRead)
int
Tcl_Ungets(channel, input, inputLen, addAtEnd)
int
Tcl_WriteObj(channel, writeObjPtr)
int
Tcl_WriteChars(channel, charBuf, bytesToWrite)
int
Tcl_Write(channel, byteBuf, bytesToWrite)
int
Tcl_Eof(channel)
int
Tcl_Flush(channel)
int
Tcl_InputBlocked(channel)
int
Tcl_InputBuffered(channel)
int
Tcl_Seek(channel, offset, seekMode)
int
Tcl_Tell(channel)
int
Tcl_GetChannelOption(interp, channel, optionName, optionValue)
int
Tcl_SetChannelOption(interp, channel, optionName, newValue)

ARGUMENTS

Tcl_Interp *interp (in)
Used for error reporting and to look up a channel registered in it.

char *fileName (in)
The name of a local or network file.

char *mode (in)
Specifies how the file is to be accessed. May have any of the values allowed for the mode argument to the Tcl open command. For Tcl_OpenCommandChannel, may be NULL.

int permissions (in)
POSIX-style permission flags such as 0644. If a new file is created, these permissions will be set on the created file.

int argc (in)
The number of elements in argv.

char **argv (in)
Arguments for constructing a command pipeline. These values have the same meaning as the non-switch arguments to the Tcl exec command.

int flags (in)
Specifies the disposition of the stdio handles in pipeline: OR-ed combination of TCL_STDIN, TCL_STDOUT, TCL_STDERR, and TCL_ENFORCE_MODE. If TCL_STDIN is set, stdin for the first child in the pipe is the pipe channel, otherwise it is the same as the standard input of the invoking process; likewise for TCL_STDOUT and TCL_STDERR. If TCL_ENFORCE_MODE is not set, then the pipe can redirect stdio handles to override the stdio handles for which TCL_STDIN, TCL_STDOUT and TCL_STDERR have been set. If it is set, then such redirections cause an error.

ClientData handle (in)
Operating system specific handle for I/O to a file. For Unix this is a file descriptor, for Windows it is a HANDLE.

int readOrWrite (in)
OR-ed combination of TCL_READABLE and TCL_WRITABLE to indicate what operations are valid on handle.

char *channelName (in)
The name of the channel.

int *modePtr (out)
Points at an integer variable that will receive an OR-ed combination of TCL_READABLE and TCL_WRITABLE denoting whether the channel is open for reading and writing.

Tcl_Channel channel (in)
A Tcl channel for input or output. Must have been the return value from a procedure such as Tcl_OpenFileChannel.

Tcl_Obj *readObjPtr (in/out)
A pointer to a Tcl Object in which to store the characters read from the channel.

int charsToRead (in)
The number of characters to read from the channel. If the channel's encoding is binary, this is equivalent to the number of bytes to read from the channel.

int appendFlag (in)
If non-zero, data read from the channel will be appended to the object. Otherwise, the data will replace the existing contents of the object.

char *readBuf (out)
A buffer in which to store the bytes read from the channel.

int bytesToRead (in)
The number of bytes to read from the channel. The buffer readBuf must be large enough to hold this many bytes.

Tcl_Obj *lineObjPtr (in/out)
A pointer to a Tcl object in which to store the line read from the channel. The line read will be appended to the current value of the object.

Tcl_DString *lineRead (in/out)
A pointer to a Tcl dynamic string in which to store the line read from the channel. Must have been initialized by the caller. The line read will be appended to any data already in the dynamic string.

Tcl_Obj *writeObjPtr (in)
A pointer to a Tcl Object whose contents will be output to the channel.

CONST char *charBuf (in)
A buffer containing the characters to output to the channel.

char *byteBuf (in)
A buffer containing the bytes to output to the channel.

int bytesToWrite (in)
The number of bytes to consume from charBuf or byteBuf and output to the channel.

int offset (in)
How far to move the access point in the channel at which the next input or output operation will be applied, measured in bytes from the position given by seekMode. May be either positive or negative.

int seekMode (in)
Relative to which point to seek; used with offset to calculate the new access point for the channel. Legal values are SEEK_SET, SEEK_CUR, and SEEK_END.

char *optionName (in)
The name of an option applicable to this channel, such as -blocking. May have any of the values accepted by the fconfigure command.

Tcl_DString *optionValue (in)
Where to store the value of an option or a list of all options and their values. Must have been initialized by the caller.

char *newValue (in)
New value for the option given by optionName.

char *pattern (in)
The pattern to match on, passed to Tcl_StringMatch, or NULL.

char *input (in)
The input to add to a channel buffer.

int inputLen (in)
Length of the input

int addToEnd (in)
Flag indicating whether the input should be added to the end or beginning of the channel buffer.

DESCRIPTION

The Tcl channel mechanism provides a device-independent and platform-independent mechanism for performing buffered input and output operations on a variety of file, socket, and device types. The channel mechanism is extensible to new channel types, by providing a low level channel driver for the new type; the channel driver interface is described in the manual entry for Tcl_CreateChannel. The channel mechanism provides a buffering scheme modeled after Unix's standard I/O, and it also allows for nonblocking I/O on channels.

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 Tcl_CreateChannel.

TCL_OPENFILECHANNEL

Tcl_OpenFileChannel opens a file specified by fileName and returns a channel handle that can be used to perform input and output on the file. This API is modeled after the fopen procedure of the Unix standard I/O library. The syntax and meaning of all arguments is similar to those given in the Tcl open command when opening a file. If an error occurs while opening the channel, Tcl_OpenFileChannel returns NULL and records a POSIX error code that can be retrieved with Tcl_GetErrno. In addition, if interp is non-NULL, Tcl_OpenFileChannel leaves an error message in interp's result after any error.

The newly created channel is not registered in the supplied interpreter; to register it, use Tcl_RegisterChannel, described below. If one of the standard channels, stdin, stdout or stderr was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel.

TCL_OPENCOMMANDCHANNEL

Tcl_OpenCommandChannel provides a C-level interface to the functions of the exec and open commands. It creates a sequence of subprocesses specified by the argv and argc arguments and returns a channel that can be used to communicate with these subprocesses. The flags argument indicates what sort of communication will exist with the command pipeline.

If the TCL_STDIN flag is set then the standard input for the first subprocess will be tied to the channel: writing to the channel will provide input to the subprocess. If TCL_STDIN is not set, then standard input for the first subprocess will be the same as this application's standard input. If TCL_STDOUT is set then standard output from the last subprocess can be read from the channel; otherwise it goes to this application's standard output. If TCL_STDERR is set, standard error output for all subprocesses is returned to the channel and results in an error when the channel is closed; otherwise it goes to this application's standard error. If TCL_ENFORCE_MODE is not set, then argc and argv can redirect the stdio handles to override TCL_STDIN, TCL_STDOUT, and TCL_STDERR; if it is set, then it is an error for argc and argv to override stdio channels for which TCL_STDIN, TCL_STDOUT, and TCL_STDERR have been set.

If an error occurs while opening the channel, Tcl_OpenCommandChannel returns NULL and records a POSIX error code that can be retrieved with Tcl_GetErrno. In addition, Tcl_OpenCommandChannel leaves an error message in the interpreter's result if interp is not NULL.

The newly created channel is not registered in the supplied interpreter; to register it, use Tcl_RegisterChannel, described below. If one of the standard channels, stdin, stdout or stderr was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel.

TCL_MAKEFILECHANNEL

Tcl_MakeFileChannel makes a Tcl_Channel from an existing, platform-specific, file handle. The newly created channel is not registered in the supplied interpreter; to register it, use Tcl_RegisterChannel, described below. If one of the standard channels, stdin, stdout or stderr was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel.

TCL_GETCHANNEL

Tcl_GetChannel returns a channel given the channelName used to create it with Tcl_CreateChannel and a pointer to a Tcl interpreter in interp. If a channel by that name is not registered in that interpreter, the procedure returns NULL. If the mode argument is not NULL, it points at an integer variable that will receive an OR-ed combination of TCL_READABLE and TCL_WRITABLE describing whether the channel is open for reading and writing.

Tcl_GetChannelNames and Tcl_GetChannelNamesEx write the names of the registered channels to the interpreter's result as a list object. Tcl_GetChannelNamesEx will filter these names according to the pattern. If pattern is NULL, then it will not do any filtering. The return value is TCL_OK if no errors occured writing to the result, otherwise it is TCL_ERROR, and the error message is left in the interpreter's result.

TCL_REGISTERCHANNEL

Tcl_RegisterChannel adds a channel to the set of channels accessible in interp. After this call, Tcl programs executing in that interpreter can refer to the channel in input or output operations using the name given in the call to Tcl_CreateChannel. After this call, the channel becomes the property of the interpreter, and the caller should not call Tcl_Close for the channel; the channel will be closed automatically when it is unregistered from the interpreter.

Code executing outside of any Tcl interpreter can call Tcl_RegisterChannel with interp as NULL, to indicate that it wishes to hold a reference to this channel. Subsequently, the channel can be registered in a Tcl interpreter and it will only be closed when the matching number of calls to Tcl_UnregisterChannel have been made. This allows code executing outside of any interpreter to safely hold a reference to a channel that is also registered in a Tcl interpreter.

TCL_UNREGISTERCHANNEL

Tcl_UnregisterChannel removes a channel from the set of channels accessible in interp. After this call, Tcl programs will no longer be able to use the channel's name to refer to the channel in that interpreter. If this operation removed the last registration of the channel in any interpreter, the channel is also closed and destroyed.

Code not associated with a Tcl interpreter can call Tcl_UnregisterChannel with interp as NULL, to indicate to Tcl that it no longer holds a reference to that channel. If this is the last reference to the channel, it will now be closed.

TCL_CLOSE

Tcl_Close destroys the channel channel, which must denote a currently open channel. The channel should not be registered in any interpreter when Tcl_Close is called. Buffered output is flushed to the channel's output device prior to destroying the channel, and any buffered input is discarded. If this is a blocking channel, the call does not return until all buffered data is successfully sent to the channel's output device. If this is a nonblocking channel and there is buffered output that cannot be written without blocking, the call returns immediately; output is flushed in the background and the channel will be closed once all of the buffered data has been output. In this case errors during flushing are not reported.

If the channel was closed successfully, Tcl_Close returns TCL_OK. If an error occurs, Tcl_Close returns TCL_ERROR and records a POSIX error code that can be retrieved with Tcl_GetErrno. If the channel is being closed synchronously and an error occurs during closing of the channel and interp is not NULL, an error message is left in the interpreter's result.

Note: it is not safe to call Tcl_Close on a channel that has been registered using Tcl_RegisterChannel; see the documentation for Tcl_RegisterChannel, above, for details. If the channel has ever been given as the chan argument in a call to Tcl_RegisterChannel, you should instead use Tcl_UnregisterChannel, which will internally call Tcl_Close when all calls to Tcl_RegisterChannel have been matched by corresponding calls to Tcl_UnregisterChannel.

TCL_READCHARS AND TCL_READ

Tcl_ReadChars consumes bytes from channel, converting the bytes to UTF-8 based on the channel's encoding and storing the produced data in readObjPtr's string representation. The return value of Tcl_ReadChars is the number of characters, up to charsToRead, that were stored in objPtr. If an error occurs while reading, the return value is -1 and Tcl_ReadChars records a POSIX error code that can be retrieved with Tcl_GetErrno.

The return value may be smaller than the value to read, indicating that less data than requested was available. This is called a short read. In blocking mode, this can only happen on an end-of-file. In nonblocking mode, a short read can also occur if there is not enough input currently available: Tcl_ReadChars returns a short count rather than waiting for more data.

If the channel is in blocking mode, a return value of zero indicates an end-of-file condition. If the channel is in nonblocking mode, a return value of zero indicates either that no input is currently available or an end-of-file condition. Use Tcl_Eof and Tcl_InputBlocked to tell which of these conditions actually occurred.

Tcl_ReadChars translates the various end-of-line representations into the canonical \n internal representation according to the current end-of-line recognition mode. End-of-line recognition and the various platform-specific modes are described in the manual entry for the Tcl fconfigure command.

As a performance optimization, when reading from a channel with the encoding binary, the bytes are not converted to UTF-8 as they are read. Instead, they are stored in readObjPtr's internal representation as a byte-array object. The string representation of this object will only be constructed if it is needed (e.g., because of a call to Tcl_GetStringFromObj). In this way, byte-oriented data can be read from a channel, manipulated by calling Tcl_GetByteArrayFromObj and related functions, and then written to a channel without the expense of ever converting to or from UTF-8.

Tcl_Read is similar to Tcl_ReadChars, except that it doesn't do encoding conversions, regardless of the channel's encoding. It is deprecated and exists for backwards compatibility with non-internationalized Tcl extensions. It consumes bytes from channel and stores them in buf, performing end-of-line translations on the way. The return value of Tcl_Read is the number of bytes, up to toRead, written in buf. The buffer produced by Tcl_Read is not NULL terminated. Its contents are valid from the zeroth position up to and excluding the position indicated by the return value.

TCL_GETSOBJ AND TCL_GETS

Tcl_GetsObj consumes bytes from channel, converting the bytes to UTF-8 based on the channel's encoding, until a full line of input has been seen. If the channel's encoding is binary, each byte read from the channel is treated as an individual Unicode character. All of the characters of the line except for the terminating end-of-line character(s) are appended to lineObjPtr's string representation. The end-of-line character(s) are read and discarded.

If a line was successfully read, the return value is greater than or equal to zero and indicates the number of bytes stored in lineObjPtr. If an error occurs, Tcl_GetsObj returns -1 and records a POSIX error code that can be retrieved with Tcl_GetErrno. Tcl_GetsObj also returns -1 if the end of the file is reached; the Tcl_Eof procedure can be used to distinguish an error from an end-of-file condition.

If the channel is in nonblocking mode, the return value can also be -1 if no data was available or the data that was available did not contain an end-of-line character. When -1 is returned, the Tcl_InputBlocked procedure may be invoked to determine if the channel is blocked because of input unavailability.

Tcl_Gets is the same as Tcl_GetsObj except the resulting characters are appended to the appended to the dynamic string given by dsPtr rather than a Tcl object.

TCL_UNGETS

Tcl_Ungets is used to add data to the input queue of a channel, at either the head or tail of the queue. Input is a pointer to the data that is to be added. InputLen gives the length of the input to add. AddAtEnd, in non-zero, indicates that the data is to be added at the end of queue; otherwise it will be added at the head of the queue. If channel has a "sticky" EOF set, no data will be added to the input queue. Tcl_Ungets returns inputLen or -1 if an error occurs.

TCL_WRITECHARS, TCL_WRITEOBJ, AND TCL_WRITE

Tcl_WriteChars accepts bytesToWrite bytes of character data at charBuf. The UTF-8 characters in the buffer are converted to the channel's encoding and queued for output to channel. If bytesToWrite is negative, Tcl_WriteChars expects charBuf to be NULL terminated and it outputs everything up to the NULL.

Data queued for output may not appear on the output device immediately, due to internal buffering. If the data should appear immediately, call Tcl_Flush after the call to Tcl_WriteChars, or set the -buffering option on the channel to none. If you wish the data to appear as soon as a complete line is accepted for output, set the -buffering option on the channel to line mode.

The return value of Tcl_WriteChars is a count of how many bytes were accepted for output to the channel. This is either greater than zero to indicate success or -1 to indicate that an error occurred. If an error occurs, Tcl_WriteChars records a POSIX error code that may be retrieved with Tcl_GetErrno.

Newline characters in the output data are translated to platform-specific end-of-line sequences according to the -translation option for the channel. This is done even if the channel has no encoding.

Tcl_WriteObj is similar to Tcl_WriteChars except it accepts a Tcl object whose contents will be output to the channel. The UTF-8 characters in writeObjPtr's string representation are converted to the channel's encoding and queued for output to channel. As a performance optimization, when writing to a channel with the encoding binary, UTF-8 characters are not converted as they are written. Instead, the bytes in writeObjPtr's internal representation as a byte-array object are written to the channel. The byte-array representation of the object will be constructed if it is needed. In this way, byte-oriented data can be read from a channel, manipulated by calling Tcl_GetByteArrayFromObj and related functions, and then written to a channel without the expense of ever converting to or from UTF-8.

Tcl_Write is similar to Tcl_WriteChars except that it doesn't do encoding conversions, regardless of the channel's encoding. It is deprecated and exists for backwards compatibility with non-internationalized Tcl extensions. It accepts bytesToWrite bytes of data at byteBuf and queues them for output to channel. If bytesToWrite is negative, Tcl_Write expects byteBuf to be NULL terminated and it outputs everything up to the NULL.

TCL_FLUSH

Tcl_Flush causes all of the buffered output data for channel to be written to its underlying file or device as soon as possible. If the channel is in blocking mode, the call does not return until all the buffered data has been sent to the channel or some error occurred. The call returns immediately if the channel is nonblocking; it starts a background flush that will write the buffered data to the channel eventually, as fast as the channel is able to absorb it.

The return value is normally TCL_OK. If an error occurs, Tcl_Flush returns TCL_ERROR and records a POSIX error code that can be retrieved with Tcl_GetErrno.

TCL_SEEK

Tcl_Seek moves the access point in channel where subsequent data will be read or written. Buffered output is flushed to the channel and buffered input is discarded, prior to the seek operation.

Tcl_Seek normally returns the new access point. If an error occurs, Tcl_Seek returns -1 and records a POSIX error code that can be retrieved with Tcl_GetErrno. After an error, the access point may or may not have been moved.

TCL_TELL

Tcl_Tell returns the current access point for a channel. The returned value is -1 if the channel does not support seeking.

TCL_GETCHANNELOPTION

Tcl_GetChannelOption retrieves, in dsPtr, the value of one of the options currently in effect for a channel, or a list of all options and their values. The channel argument identifies the channel for which to query an option or retrieve all options and their values. If optionName is not NULL, it is the name of the option to query; the option's value is copied to the Tcl dynamic string denoted by optionValue. If optionName is NULL, the function stores an alternating list of option names and their values in optionValue, using a series of calls to Tcl_DStringAppendElement. The various preexisting options and their possible values are described in the manual entry for the Tcl fconfigure command. Other options can be added by each channel type. These channel type specific options are described in the manual entry for the Tcl command that creates a channel of that type; for example, the additional options for TCP based channels are described in the manual entry for the Tcl socket command. The procedure normally returns TCL_OK. If an error occurs, it returns TCL_ERROR and calls Tcl_SetErrno to store an appropriate POSIX error code.

TCL_SETCHANNELOPTION

Tcl_SetChannelOption sets a new value for an option on channel. OptionName is the option to set and newValue is the value to set. The procedure normally returns TCL_OK. If an error occurs, it returns TCL_ERROR; in addition, if interp is non-NULL, Tcl_SetChannelOption leaves an error message in the interpreter's result.

TCL_EOF

Tcl_Eof returns a nonzero value if channel encountered an end of file during the last input operation.

TCL_INPUTBLOCKED

Tcl_InputBlocked returns a nonzero value if channel 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.

TCL_INPUTBUFFERED

Tcl_InputBuffered 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.

PLATFORM ISSUES

The handles returned from Tcl_GetChannelHandle depend on the platform and the channel type. On Unix platforms, the handle is always a Unix file descriptor as returned from the open system call. On Windows platforms, the handle is a file HANDLE when the channel was created with Tcl_OpenFileChannel, Tcl_OpenCommandChannel, or Tcl_MakeFileChannel. Other channel types may return a different type of handle on Windows platforms. On the Macintosh platform, the handle is a file reference number as returned from HOpenDF.

SEE ALSO

DString, fconfigure, filename, fopen(2), Tcl_CreateChannel

KEYWORDS

access point, blocking, buffered I/O, channel, channel driver, end of file, flush, input, nonblocking, output, read, seek, write
Copyright © 1996-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_OpenTcpClient manual page

NAME
Tcl_OpenTcpClient, Tcl_MakeTcpClientChannel, Tcl_OpenTcpServer - procedures to open channels using TCP sockets
SYNOPSIS
ARGUMENTS
DESCRIPTION
TCL_OPENTCPCLIENT
TCL_MAKETCPCLIENTCHANNEL
TCL_OPENTCPSERVER
PLATFORM ISSUES
SEE ALSO
KEYWORDS

NAME

Tcl_OpenTcpClient, Tcl_MakeTcpClientChannel, Tcl_OpenTcpServer - procedures to open channels using TCP sockets

SYNOPSIS

#include <tcl.h>
Tcl_Channel
Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async)
Tcl_Channel
Tcl_MakeTcpClientChannel(sock)
Tcl_Channel
Tcl_OpenTcpServer(interp, port, myaddr, proc, clientData)

ARGUMENTS

Tcl_Interp *interp (in)
Tcl interpreter to use for error reporting. If non-NULL and an error occurs, an error message is left in the interpreter's result.

int port (in)
A port number to connect to as a client or to listen on as a server.

char *host (in)
A string specifying a host name or address for the remote end of the connection.

int myport (in)
A port number for the client's end of the socket. If 0, a port number is allocated at random.

char *myaddr (in)
A string specifying the host name or address for network interface to use for the local end of the connection. If NULL, a default interface is chosen.

int async (in)
If nonzero, the client socket is connected asynchronously to the server.

ClientData sock (in)
Platform-specific handle for client TCP socket.

Tcl_TcpAcceptProc *proc (in)
Pointer to a procedure to invoke each time a new connection is accepted via the socket.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

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 Tcl_OpenFileChannel.

TCL_OPENTCPCLIENT

Tcl_OpenTcpClient opens a client TCP socket connected to a port on a specific host, and returns a channel that can be used to communicate with the server. The host to connect to can be specified either as a domain name style name (e.g. www.sunlabs.com), or as a string containing the alphanumeric representation of its four-byte address (e.g. 127.0.0.1). Use the string localhost to connect to a TCP socket on the host on which the function is invoked.

The myaddr and myport arguments allow a client to specify an address for the local end of the connection. If myaddr is NULL, then an interface is chosen automatically by the operating system. If myport is 0, then a port number is chosen at random by the operating system.

If async is zero, the call to Tcl_OpenTcpClient returns only after the client socket has either successfully connected to the server, or the attempted connection has failed. If async is nonzero the socket is connected asynchronously and the returned channel may not yet be connected to the server when the call to Tcl_OpenTcpClient returns. If the channel is in blocking mode and an input or output operation is done on the channel before the connection is completed or fails, that operation will wait until the connection either completes successfully or fails. If the channel is in nonblocking mode, the input or output operation will return immediately and a subsequent call to Tcl_InputBlocked on the channel will return nonzero.

The returned channel is opened for reading and writing. If an error occurs in opening the socket, Tcl_OpenTcpClient returns NULL and records a POSIX error code that can be retrieved with Tcl_GetErrno. In addition, if interp is non-NULL, an error message is left in the interpreter's result.

The newly created channel is not registered in the supplied interpreter; to register it, use Tcl_RegisterChannel. If one of the standard channels, stdin, stdout or stderr was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel.

TCL_MAKETCPCLIENTCHANNEL

Tcl_MakeTcpClientChannel creates a Tcl_Channel around an existing, platform specific, handle for a client TCP socket.

The newly created channel is not registered in the supplied interpreter; to register it, use Tcl_RegisterChannel. If one of the standard channels, stdin, stdout or stderr was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel.

TCL_OPENTCPSERVER

Tcl_OpenTcpServer opens a TCP socket on the local host on a specified port and uses the Tcl event mechanism to accept requests from clients to connect to it. The myaddr argument specifies the network interface. If myaddr is NULL the special address INADDR_ANY should be used to allow connections from any network interface. Each time a client connects to this socket, Tcl creates a channel for the new connection and invokes proc with information about the channel. Proc must match the following prototype:
typedef void Tcl_TcpAcceptProc(
    ClientData clientData,
    Tcl_Channel channel,
    char *hostName,
    int port);

The clientData argument will be the same as the clientData argument to Tcl_OpenTcpServer, channel will be the handle for the new channel, hostName points to a string containing the name of the client host making the connection, and port will contain the client's port number. The new channel is opened for both input and output. If proc raises an error, the connection is closed automatically. Proc has no return value, but if it wishes to reject the connection it can close channel.

Tcl_OpenTcpServer normally returns a pointer to a channel representing the server socket. If an error occurs, Tcl_OpenTcpServer returns NULL and records a POSIX error code that can be retrieved with Tcl_GetErrno. In addition, if the interpreter is non-NULL, an error message is left in the interpreter's result.

The channel returned by Tcl_OpenTcpServer cannot be used for either input or output. It is simply a handle for the socket used to accept connections. The caller can close the channel to shut down the server and disallow further connections from new clients.

TCP server channels operate correctly only in applications that dispatch events through Tcl_DoOneEvent or through Tcl commands such as vwait; otherwise Tcl will never notice that a connection request from a remote client is pending.

The newly created channel is not registered in the supplied interpreter; to register it, use Tcl_RegisterChannel. If one of the standard channels, stdin, stdout or stderr was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel.

PLATFORM ISSUES

On Unix platforms, the socket handle is a Unix file descriptor as returned by the socket system call. On the Windows platform, the socket handle is a SOCKET as defined in the WinSock API. On the Macintosh platform, the socket handle is a StreamPtr.

SEE ALSO

Tcl_OpenFileChannel, Tcl_RegisterChannel, vwait

KEYWORDS

client, server, TCP
Copyright © 1996-7 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_ParseCommand manual page

NAME
Tcl_ParseCommand, Tcl_ParseExpr, Tcl_ParseBraces, Tcl_ParseQuotedString, Tcl_ParseVarName, Tcl_ParseVar, Tcl_FreeParse, Tcl_EvalTokens - parse Tcl scripts and expressions
SYNOPSIS
ARGUMENTS
DESCRIPTION
TCL_PARSE STRUCTURE
TCL_TOKEN_WORD
TCL_TOKEN_SIMPLE_WORD
TCL_TOKEN_TEXT
TCL_TOKEN_BS
TCL_TOKEN_COMMAND
TCL_TOKEN_VARIABLE
TCL_TOKEN_SUB_EXPR
TCL_TOKEN_OPERATOR
KEYWORDS

NAME

Tcl_ParseCommand, Tcl_ParseExpr, Tcl_ParseBraces, Tcl_ParseQuotedString, Tcl_ParseVarName, Tcl_ParseVar, Tcl_FreeParse, Tcl_EvalTokens - parse Tcl scripts and expressions

SYNOPSIS

#include <tcl.h>
int
Tcl_ParseCommand(interp, string, numBytes, nested, parsePtr)
int
Tcl_ParseExpr(interp, string, numBytes, parsePtr)
int
Tcl_ParseBraces(interp, string, numBytes, parsePtr, append, termPtr)
int
Tcl_ParseQuotedString(interp, string, numBytes, parsePtr, append, termPtr)
int
Tcl_ParseVarName(interp, string, numBytes, parsePtr, append)
char *
Tcl_ParseVar(interp, string, termPtr)
Tcl_FreeParse(usedParsePtr)
Tcl_Obj *
Tcl_EvalTokens(interp, tokenPtr, numTokens)

ARGUMENTS

Tcl_Interp *interp (out)
For procedures other than Tcl_FreeParse and Tcl_EvalTokens, used only for error reporting; if NULL, then no error messages are left after errors. For Tcl_EvalTokens, determines the context for evaluating the script and also is used for error reporting; must not be NULL.

char *string (in)
Pointer to first character in string to parse.

int numBytes (in)
Number of bytes in string, not including any terminating null character. If less than 0 then the script consists of all characters in string up to the first null character.

int nested (in)
Non-zero means that the script is part of a command substitution so an unquoted close bracket should be treated as a command terminator. If zero, close brackets have no special meaning.

int append (in)
Non-zero means that *parsePtr already contains valid tokens; the new tokens should be appended to those already present. Zero means that *parsePtr is uninitialized; any information in it is ignored. This argument is normally 0.

Tcl_Parse *parsePtr (out)
Points to structure to fill in with information about the parsed command, expression, variable name, etc. Any previous information in this structure is ignored, unless append is non-zero in a call to Tcl_ParseBraces, Tcl_ParseQuotedString, or Tcl_ParseVarName.

char **termPtr (out)
If not NULL, points to a location where Tcl_ParseBraces, Tcl_ParseQuotedString, and Tcl_ParseVar will store a pointer to the character just after the terminating character (the close-brace, the last character of the variable name, or the close-quote (respectively)) if the parse was successful.

Tcl_Parse *usedParsePtr (in)
Points to structure that was filled in by a previous call to Tcl_ParseCommand, Tcl_ParseExpr, Tcl_ParseVarName, etc.

DESCRIPTION

These procedures parse Tcl commands or portions of Tcl commands such as expressions or references to variables. Each procedure takes a pointer to a script (or portion thereof) and fills in the structure pointed to by parsePtr with a collection of tokens describing the information that was parsed. The procedures normally return TCL_OK. However, if an error occurs then they return TCL_ERROR, leave an error message in interp's result (if interp is not NULL), and leave nothing in parsePtr.

Tcl_ParseCommand is a procedure that parses Tcl scripts. Given a pointer to a script, it parses the first command from the script. If the command was parsed successfully, Tcl_ParseCommand returns TCL_OK and fills in the structure pointed to by parsePtr with information about the structure of the command (see below for details). If an error occurred in parsing the command then TCL_ERROR is returned, an error message is left in interp's result, and no information is left at *parsePtr.

Tcl_ParseExpr parses Tcl expressions. Given a pointer to a script containing an expression, Tcl_ParseCommand parses the expression. If the expression was parsed successfully, Tcl_ParseExpr returns TCL_OK and fills in the structure pointed to by parsePtr with information about the structure of the expression (see below for details). If an error occurred in parsing the command then TCL_ERROR is returned, an error message is left in interp's result, and no information is left at *parsePtr.

Tcl_ParseBraces parses a string or command argument enclosed in braces such as {hello} or {string \t with \t tabs} from the beginning of its argument string. The first character of string must be {. If the braced string was parsed successfully, Tcl_ParseBraces returns TCL_OK, fills in the structure pointed to by parsePtr with information about the structure of the string (see below for details), and stores a pointer to the character just after the terminating } in the location given by *termPtr. If an error occurrs while parsing the string then TCL_ERROR is returned, an error message is left in interp's result, and no information is left at *parsePtr or *termPtr.

Tcl_ParseQuotedString parses a double-quoted string such as "sum is [expr $a+$b]" from the beginning of the argument string. The first character of string must be ". If the double-quoted string was parsed successfully, Tcl_ParseQuotedString returns TCL_OK, fills in the structure pointed to by parsePtr with information about the structure of the string (see below for details), and stores a pointer to the character just after the terminating " in the location given by *termPtr. If an error occurrs while parsing the string then TCL_ERROR is returned, an error message is left in interp's result, and no information is left at *parsePtr or *termPtr.

Tcl_ParseVarName parses a Tcl variable reference such as $abc or $x([expr $index + 1]) from the beginning of its string argument. The first character of string must be $. If a variable name was parsed successfully, Tcl_ParseVarName returns TCL_OK and fills in the structure pointed to by parsePtr with information about the structure of the variable name (see below for details). If an error occurrs while parsing the command then TCL_ERROR is returned, an error message is left in interp's result (if interp isn't NULL), and no information is left at *parsePtr.

Tcl_ParseVar parse a Tcl variable reference such as $abc or $x([expr $index + 1]) from the beginning of its string argument. The first character of string must be $. If the variable name is parsed successfully, Tcl_ParseVar returns a pointer to the string value of the variable. If an error occurs while parsing, then NULL is returned and an error message is left in interp's result.

The information left at *parsePtr by Tcl_ParseCommand, Tcl_ParseExpr, Tcl_ParseBraces, Tcl_ParseQuotedString, and Tcl_ParseVarName may include dynamically allocated memory. If these five parsing procedures return TCL_OK then the caller must invoke Tcl_FreeParse to release the storage at *parsePtr. These procedures ignore any existing information in *parsePtr (unless append is non-zero), so if repeated calls are being made to any of them then Tcl_FreeParse must be invoked once after each call.

Tcl_EvalTokens evaluates a sequence of parse tokens from a Tcl_Parse structure. The tokens typically consist of all the tokens in a word or all the tokens that make up the index for a reference to an array variable. Tcl_EvalTokens performs the substitutions requested by the tokens, concatenates the resulting values, and returns the result in a new Tcl_Obj. The reference count of the object returned as result has been incremented, so the caller must invoke Tcl_DecrRefCount when it is finished with the object. If an error 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 interp's result.

TCL_PARSE STRUCTURE

Tcl_ParseCommand, Tcl_ParseExpr, Tcl_ParseBraces, Tcl_ParseQuotedString, and Tcl_ParseVarName return parse information in two data structures, Tcl_Parse and Tcl_Token:
typedef struct Tcl_Parse {
    char *commentStart;
    int commentSize;
    char *commandStart;
    int commandSize;
    int numWords;
    Tcl_Token *tokenPtr;
    int numTokens;
    ...
} Tcl_Parse;

typedef struct Tcl_Token {
    int type;
    char *start;
    int size;
    int numComponents;
} Tcl_Token;

The first five fields of a Tcl_Parse structure are filled in only by Tcl_ParseCommand. These fields are not used by the other parsing procedures.

Tcl_ParseCommand fills in a Tcl_Parse structure with information that describes one Tcl command and any comments that precede the command. If there are comments, the commentStart field points to the # character that begins the first comment and commentSize indicates the number of bytes in all of the comments preceding the command, including the newline character that terminates the last comment. If the command is not preceded by any comments, commentSize is 0. Tcl_ParseCommand also sets the commandStart field to point to the first character of the first word in the command (skipping any comments and leading space) and commandSize gives the total number of bytes in the command, including the character pointed to by commandStart up to and including the newline, close bracket, or semicolon character that terminates the command. The numWords field gives the total number of words in the command.

All parsing procedures set the remaining fields, tokenPtr and numTokens. The tokenPtr field points to the first in an array of Tcl_Token structures that describe the components of the entity being parsed. The numTokens field gives the total number of tokens present in the array. Each token contains four fields. The type field selects one of several token types that are described below. The start field points to the first character in the token and the size field gives the total number of characters in the token. Some token types, such as TCL_TOKEN_WORD and TCL_TOKEN_VARIABLE, consist of several component tokens, which immediately follow the parent token; the numComponents field describes how many of these there are. The type field has one of the following values:

TCL_TOKEN_WORD
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 the result of concatenating together a sequence of subcomponents, each described by a separate subtoken. The token starts with the first non-blank character of the component (which may be a double-quote or open brace) and includes all characters in the component up to but not including the space, semicolon, close bracket, close quote, or close brace that terminates the component. The numComponents field counts the total number of sub-tokens that make up the word, including sub-tokens of TCL_TOKEN_VARIABLE and TCL_TOKEN_BS tokens.

TCL_TOKEN_SIMPLE_WORD
This token has the same meaning as TCL_TOKEN_WORD, except that the word is guaranteed to consist of a single TCL_TOKEN_TEXT sub-token. The numComponents field is always 1.

TCL_TOKEN_TEXT
The token describes a range of literal text that is part of a word. The numComponents field is always 0.

TCL_TOKEN_BS
The token describes a backslash sequence such as \n or \0xa3. The numComponents field is always 0.

TCL_TOKEN_COMMAND
The token describes a command whose result result must be substituted into the word. The token includes the square brackets that surround the command. The numComponents field is always 0 (the nested command is not parsed; call Tcl_ParseCommand recursively if you want to see its tokens).

TCL_TOKEN_VARIABLE
The token describes a variable substitution, including the $, variable name, and array index (if there is one) up through the close parenthesis that terminates the index. This token is followed by one or more additional tokens that describe the variable name and array index. If numComponents is 1 then the variable is a scalar and the next token is a TCL_TOKEN_TEXT token that gives the variable name. If numComponents is greater than 1 then the variable is an array: the first sub-token is a TCL_TOKEN_TEXT token giving the array name and the remaining sub-tokens are TCL_TOKEN_TEXT, TCL_TOKEN_BS, TCL_TOKEN_COMMAND, and TCL_TOKEN_VARIABLE tokens that must be concatenated to produce the array index. The numComponents field includes nested sub-tokens that are part of TCL_TOKEN_VARIABLE tokens in the array index.

TCL_TOKEN_SUB_EXPR
The token describes one subexpression of an expression (or an entire expression). A subexpression may consist of a value such as an integer literal, variable substitution, or parenthesized subexpression; it may also consist of an operator and its operands. The token starts with the first non-blank character of the subexpression up to but not including the space, brace, close-paren, or bracket that terminates the subexpression. This token is followed by one or more additional tokens that describe the subexpression. If the first sub-token after the TCL_TOKEN_SUB_EXPR token is a TCL_TOKEN_OPERATOR token, the subexpression consists of an operator and its token operands. If the operator has no operands, the subexpression consists of just the TCL_TOKEN_OPERATOR token. Each operand is described by a TCL_TOKEN_SUB_EXPR token. Otherwise, the subexpression is a value described by one of the token types TCL_TOKEN_WORD, TCL_TOKEN_TEXT, TCL_TOKEN_BS, TCL_TOKEN_COMMAND, TCL_TOKEN_VARIABLE, and TCL_TOKEN_SUB_EXPR. The numComponents field counts the total number of sub-tokens that make up the subexpression; this includes the sub-tokens for any nested TCL_TOKEN_SUB_EXPR tokens.

TCL_TOKEN_OPERATOR
The token describes one operator of an expression such as && or hypot. An TCL_TOKEN_OPERATOR token is always preceeded by a TCL_TOKEN_SUB_EXPR token that describes the operator and its operands; the TCL_TOKEN_SUB_EXPR token's numComponents field can be used to determine the number of operands. A binary operator such as * is followed by two TCL_TOKEN_SUB_EXPR tokens that describe its operands. A unary operator like - is followed by a single TCL_TOKEN_SUB_EXPR token for its operand. If the operator is a math function such as log10, the TCL_TOKEN_OPERATOR token will give its name and the following TCL_TOKEN_SUB_EXPR tokens will describe its operands; if there are no operands (as with rand), no TCL_TOKEN_SUB_EXPR tokens follow. There is one trinary operator, ?, that appears in if-then-else subexpressions such as x?y:z; in this case, the ? TCL_TOKEN_OPERATOR token is followed by three TCL_TOKEN_SUB_EXPR tokens for the operands x, y, and z. The numComponents field for a TCL_TOKEN_OPERATOR token is always 0.

After Tcl_ParseCommand returns, the first token pointed to by the tokenPtr field of the Tcl_Parse structure always has type TCL_TOKEN_WORD or TCL_TOKEN_SIMPLE_WORD. It is followed by the sub-tokens that must be concatenated to produce the value of that word. The next token is the TCL_TOKEN_WORD or TCL_TOKEN_SIMPLE_WORD token for the second word, followed by sub-tokens for that word, and so on until all numWords have been accounted for.

After Tcl_ParseExpr returns, the first token pointed to by the tokenPtr field of the Tcl_Parse structure always has type TCL_TOKEN_SUB_EXPR. It is followed by the sub-tokens that must be evaluated to produce the value of the expression. Only the token information in the Tcl_Parse structure is modified: the commentStart, commentSize, commandStart, and commandSize fields are not modified by Tcl_ParseExpr.

After Tcl_ParseBraces returns, the array of tokens pointed to by the tokenPtr field of the Tcl_Parse structure will contain a single TCL_TOKEN_TEXT token if the braced string does not contain any backslash-newlines. If the string does contain backslash-newlines, the array of tokens will contain one or more TCL_TOKEN_TEXT or TCL_TOKEN_BS sub-tokens that must be concatenated to produce the value of the string. If the braced string was just {} (that is, the string was empty), the single TCL_TOKEN_TEXT token will have a size field containing zero; this ensures that at least one token appears to describe the braced string. Only the token information in the Tcl_Parse structure is modified: the commentStart, commentSize, commandStart, and commandSize fields are not modified by Tcl_ParseBraces.

After Tcl_ParseQuotedString returns, the array of tokens pointed to by the tokenPtr field of the Tcl_Parse structure depends on the contents of the quoted string. It will consist of one or more TCL_TOKEN_TEXT, TCL_TOKEN_BS, TCL_TOKEN_COMMAND, and TCL_TOKEN_VARIABLE sub-tokens. The array always contains at least one token; for example, if the argument string is empty, the array returned consists of a single TCL_TOKEN_TEXT token with a zero size field. Only the token information in the Tcl_Parse structure is modified: the commentStart, commentSize, commandStart, and commandSize fields are not modified.

After Tcl_ParseVarName returns, the first token pointed to by the tokenPtr field of the Tcl_Parse structure always has type TCL_TOKEN_VARIABLE. It is followed by the sub-tokens that make up the variable name as described above. The total length of the variable name is contained in the size field of the first token. As in Tcl_ParseExpr, only the token information in the Tcl_Parse structure is modified by Tcl_ParseVarName: the commentStart, commentSize, commandStart, and commandSize fields are not modified.

All of the character pointers in the Tcl_Parse and Tcl_Token structures refer to characters in the string argument passed to Tcl_ParseCommand, Tcl_ParseExpr, Tcl_ParseBraces, Tcl_ParseQuotedString, and Tcl_ParseVarName.

There are additional fields in the Tcl_Parse structure after the numTokens field, but these are for the private use of Tcl_ParseCommand, Tcl_ParseExpr, Tcl_ParseBraces, Tcl_ParseQuotedString, and Tcl_ParseVarName; they should not be referenced by code outside of these procedures.

KEYWORDS

backslash substitution, braces, command, expression, parse, token, variable substitution
Copyright © 1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_PkgRequire manual page

NAME

Tcl_PkgRequire, Tcl_PkgRequireEx, Tcl_PkgPresent, Tcl_PkgPresentEx, Tcl_PkgProvide, Tcl_PkgProvideEx - package version control

SYNOPSIS

#include <tcl.h>
char *
Tcl_PkgRequire(interp, name, version, exact)
char *
Tcl_PkgRequireEx(interp, name, version, exact, clientDataPtr)
char *
Tcl_PkgPresent(interp, name, version, exact)
char *
Tcl_PkgPresentEx(interp, name, version, exact, clientDataPtr)
int
Tcl_PkgProvide(interp, name, version)
int
Tcl_PkgProvideEx(interp, name, version, clientData)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter where package is needed or available.

char *name (in)
Name of package.

char *version (in)
A version string consisting of one or more decimal numbers separated by dots.

int exact (in)
Non-zero means that only the particular version specified by version is acceptable. Zero means that newer versions than version are also acceptable as long as they have the same major version number as version.

ClientData clientData (in)
Arbitrary value to be associated with the package.

ClientData *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.

DESCRIPTION

These procedures provide C-level interfaces to Tcl's package and version management facilities.

Tcl_PkgRequire is equivalent to the package require command, Tcl_PkgPresent is equivalent to the package present command, and Tcl_PkgProvide is equivalent to the package provide command.

See the documentation for the Tcl commands for details on what these procedures do.

If Tcl_PkgPresent or Tcl_PkgRequire complete successfully they return a pointer to the version string for the version of the package that is provided in the interpreter (which may be different than version); if an error occurs they return NULL and leave an error message in the interpreter's result.

Tcl_PkgProvide returns TCL_OK if it completes successfully; if an error occurs it returns TCL_ERROR and leaves an error message in the interpreter's result.

Tcl_PkgProvideEx, Tcl_PkgPresentEx and Tcl_PkgRequireEx allow the setting and retrieving of the client data associated with the package. In all other respects they are equivalent to the matching functions.

KEYWORDS

package, present, provide, require, version
Copyright © 1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Preserve manual page

NAME

Tcl_Preserve, Tcl_Release, Tcl_EventuallyFree - avoid freeing storage while it's being used

SYNOPSIS

#include <tcl.h>
Tcl_Preserve(clientData)
Tcl_Release(clientData)
Tcl_EventuallyFree(clientData, freeProc)

ARGUMENTS

ClientData clientData (in)
Token describing structure to be freed or reallocated. Usually a pointer to memory for structure.

Tcl_FreeProc *freeProc (in)
Procedure to invoke to free clientData.

DESCRIPTION

These three procedures help implement a simple reference count mechanism for managing storage. They are designed to solve a problem having to do with widget deletion, but are also useful in many other situations. When a widget is deleted, its widget record (the structure holding information specific to the widget) must be returned to the storage allocator. However, it's possible that the widget record is in active use by one of the procedures on the stack at the time of the deletion. This can happen, for example, if the command associated with a button widget causes the button to be destroyed: an X event causes an event-handling C procedure in the button to be invoked, which in turn causes the button's associated Tcl command to be executed, which in turn causes the button to be deleted, which in turn causes the button's widget record to be de-allocated. Unfortunately, when the Tcl command returns, the button's event-handling procedure will need to reference the button's widget record. Because of this, the widget record must not be freed as part of the deletion, but must be retained until the event-handling procedure has finished with it. In other situations where the widget is deleted, it may be possible to free the widget record immediately.

Tcl_Preserve and Tcl_Release implement short-term reference counts for their clientData argument. The clientData argument identifies an object and usually consists of the address of a structure. The reference counts guarantee that an object will not be freed until each call to Tcl_Preserve for the object has been matched by calls to Tcl_Release. There may be any number of unmatched Tcl_Preserve calls in effect at once.

Tcl_EventuallyFree is invoked to free up its clientData argument. It checks to see if there are unmatched Tcl_Preserve calls for the object. If not, then Tcl_EventuallyFree calls freeProc immediately. Otherwise Tcl_EventuallyFree records the fact that clientData needs eventually to be freed. When all calls to Tcl_Preserve have been matched with calls to Tcl_Release then freeProc will be called by Tcl_Release to do the cleanup.

All the work of freeing the object is carried out by freeProc. FreeProc must have arguments and result that match the type Tcl_FreeProc:

typedef void Tcl_FreeProc(char *blockPtr);
The blockPtr argument to freeProc will be the same as the clientData argument to Tcl_EventuallyFree. The type of blockPtr (char *) is different than the type of the clientData argument to Tcl_EventuallyFree for historical reasons, but the value is the same.

This mechanism can be used to solve the problem described above by placing Tcl_Preserve and Tcl_Release calls around actions that may cause undesired storage re-allocation. The mechanism is intended only for short-term use (i.e. while procedures are pending on the stack); it will not work efficiently as a 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.

KEYWORDS

free, reference count, storage
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_PrintDouble manual page

NAME

Tcl_PrintDouble - Convert floating value to string

SYNOPSIS

#include <tcl.h>
Tcl_PrintDouble(interp, value, dst)

ARGUMENTS

Tcl_Interp *interp (in)
Before Tcl 8.0, the tcl_precision variable in this interpreter controlled the conversion. As of Tcl 8.0, this argument is ignored and the conversion is controlled by the tcl_precision variable that is now shared by all interpreters.

double value (in)
Floating-point value to be converted.

char *dst (out)
Where to store string representing value. Must have at least TCL_DOUBLE_SPACE characters of storage.

DESCRIPTION

Tcl_PrintDouble generates a string that represents the value of value and stores it in memory at the location given by dst. It uses %g format to generate the string, with one special twist: the string is guaranteed to contain either a ``.'' or an ``e'' so that it doesn't look like an integer. Where %g would generate an integer with no decimal point, Tcl_PrintDouble adds ``.0''.

KEYWORDS

conversion, double-precision, floating-point, string
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_RecordAndEvalObj manual page

NAME

Tcl_RecordAndEvalObj - save command on history list before evaluating

SYNOPSIS

#include <tcl.h>
int
Tcl_RecordAndEvalObj(interp, cmdPtr, flags)

ARGUMENTS

Tcl_Interp *interp (in)
Tcl interpreter in which to evaluate command.

Tcl_Obj *cmdPtr (in)
Points to a Tcl object containing a command (or sequence of commands) to execute.

int flags (in)
An OR'ed combination of flag bits. TCL_NO_EVAL means record the command but don't evaluate it. TCL_EVAL_GLOBAL means evaluate the command at global level instead of the current stack level.

DESCRIPTION

Tcl_RecordAndEvalObj is invoked to record a command as an event on the history list and then execute it using Tcl_EvalObjEx (or Tcl_GlobalEvalObj if the TCL_EVAL_GLOBAL bit is set in flags). It returns a completion code such as TCL_OK just like Tcl_EvalObjEx, as well as a result object containing additional information (a result value or error message) that can be retrieved using Tcl_GetObjResult. If you don't want the command recorded on the history list then you should invoke Tcl_EvalObjEx instead of Tcl_RecordAndEvalObj. Normally Tcl_RecordAndEvalObj is only called with top-level commands typed by the user, since the purpose of history is to allow the user to re-issue recently-invoked commands. If the flags argument contains the TCL_NO_EVAL bit then the command is recorded without being evaluated.

SEE ALSO

Tcl_EvalObjEx, Tcl_GetObjResult

KEYWORDS

command, event, execute, history, interpreter, object, record
Copyright © 1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_RecordAndEval manual page

NAME

Tcl_RecordAndEval - save command on history list before evaluating

SYNOPSIS

#include <tcl.h>
int
Tcl_RecordAndEval(interp, cmd, flags)

ARGUMENTS

Tcl_Interp *interp (in)
Tcl interpreter in which to evaluate command.

char *cmd (in)
Command (or sequence of commands) to execute.

int flags (in)
An OR'ed combination of flag bits. TCL_NO_EVAL means record the command but don't evaluate it. TCL_EVAL_GLOBAL means evaluate the command at global level instead of the current stack level.

DESCRIPTION

Tcl_RecordAndEval is invoked to record a command as an event on the history list and then execute it using Tcl_Eval (or Tcl_GlobalEval if the TCL_EVAL_GLOBAL bit is set in flags). It returns a completion code such as TCL_OK just like Tcl_Eval and it leaves information in the interpreter's result. If you don't want the command recorded on the history list then you should invoke Tcl_Eval instead of Tcl_RecordAndEval. Normally Tcl_RecordAndEval is only called with top-level commands typed by the user, since the purpose of history is to allow the user to re-issue recently-invoked commands. If the flags argument contains the TCL_NO_EVAL bit then the command is recorded without being evaluated.

Note that Tcl_RecordAndEval has been largely replaced by the object-based procedure Tcl_RecordAndEvalObj. That object-based procedure records and optionally executes a command held in a Tcl object instead of a string.

SEE ALSO

Tcl_RecordAndEvalObj

KEYWORDS

command, event, execute, history, interpreter, record
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_RegExpMatch manual page

NAME
Tcl_RegExpMatch, Tcl_RegExpCompile, Tcl_RegExpExec, Tcl_RegExpRange, Tcl_GetRegExpFromObj, Tcl_RegExpMatchObj, Tcl_RegExpExecObj, Tcl_RegExpGetInfo - Pattern matching with regular expressions
SYNOPSIS
ARGUMENTS
DESCRIPTION
TCL_REG_ADVANCED
TCL_REG_EXTENDED
TCL_REG_BASIC
TCL_REG_EXPANDED
TCL_REG_QUOTE
TCL_REG_NOCASE
TCL_REG_NEWLINE
TCL_REG_NLSTOP
TCL_REG_NLANCH
TCL_REG_NOSUB
TCL_REG_CANMATCH
TCL_REG_NOTBOL
TCL_REG_NOTEOL
SEE ALSO
KEYWORDS

NAME

Tcl_RegExpMatch, Tcl_RegExpCompile, Tcl_RegExpExec, Tcl_RegExpRange, Tcl_GetRegExpFromObj, Tcl_RegExpMatchObj, Tcl_RegExpExecObj, Tcl_RegExpGetInfo - Pattern matching with regular expressions

SYNOPSIS

#include <tcl.h>
int
Tcl_RegExpMatchObj(interp, strObj, patObj)
int
Tcl_RegExpMatch(interp, string, pattern)
Tcl_RegExp
Tcl_RegExpCompile(interp, pattern)
int
Tcl_RegExpExec(interp, regexp, string, start)
Tcl_RegExpRange(regexp, index, startPtr, endPtr)
Tcl_RegExp
Tcl_GetRegExpFromObj(interp, patObj, cflags)
int
Tcl_RegExpExecObj(interp, regexp, objPtr, offset, nmatches, eflags)
Tcl_RegExpGetInfo(regexp, infoPtr)

ARGUMENTS

Tcl_Interp *interp (in)
Tcl interpreter to use for error reporting. The interpreter may be NULL if no error reporting is desired.

Tcl_Obj *strObj (in/out)
Refers to the object from which to get the string to search. The internal representation of the object may be converted to a form that can be efficiently searched.

Tcl_Obj *patObj (in/out)
Refers to the object from which to get a regular expression. The compiled regular expression is cached in the object.

char *string (in)
String to check for a match with a regular expression.

char *pattern (in)
String in the form of a regular expression pattern.

Tcl_RegExp regexp (in)
Compiled regular expression. Must have been returned previously by Tcl_GetRegExpFromObj or Tcl_RegExpCompile.

char *start (in)
If string is just a portion of some other string, this argument identifies the beginning of the larger string. If it isn't the same as string, then no ^ matches will be allowed.

int index (in)
Specifies which range is desired: 0 means the range of the entire match, 1 or greater means the range that matched a parenthesized sub-expression.

char **startPtr (out)
The address of the first character in the range is stored here, or NULL if there is no such range.

char **endPtr (out)
The address of the character just after the last one in the range is stored here, or NULL if there is no such range.

int cflags (in)
OR-ed combination of compilation flags. See below for more information.

Tcl_Obj *objPtr (in/out)
An object which contains the string to check for a match with a regular expression.

int offset (in)
The character offset into the string where matching should begin. The value of the offset has no impact on ^ matches. This behavior is controlled by eflags.

int nmatches (in)
The number of matching subexpressions that should be remembered for later use. If this value is 0, then no subexpression match information will be computed. If the value is -1, then all of the matching subexpressions will be remembered. Any other value will be taken as the maximum number of subexpressions to remember.

int eflags (in)
OR-ed combination of the values TCL_REG_NOTBOL and TCL_REG_NOTEOL. See below for more information.

Tcl_RegExpInfo *infoPtr (out)
The address of the location where information about a previous match should be stored by Tcl_RegExpGetInfo.

DESCRIPTION

Tcl_RegExpMatch determines whether its pattern argument matches regexp, where regexp is interpreted as a regular expression using the rules in the re_syntax reference page. If there is a match then Tcl_RegExpMatch returns 1. If there is no match then Tcl_RegExpMatch returns 0. If an error occurs in the matching process (e.g. pattern is not a valid regular expression) then Tcl_RegExpMatch returns -1 and leaves an error message in the interpreter result. Tcl_RegExpMatchObj is similar to Tcl_RegExpMatch except it operates on the Tcl objects strObj and patObj instead of UTF strings. Tcl_RegExpMatchObj is generally more efficient than Tcl_RegExpMatch, so it is the preferred interface.

Tcl_RegExpCompile, Tcl_RegExpExec, and Tcl_RegExpRange provide lower-level access to the regular expression pattern matcher. Tcl_RegExpCompile compiles a regular expression string into the internal form used for efficient pattern matching. The return value is a token for this compiled form, which can be used in subsequent calls to Tcl_RegExpExec or Tcl_RegExpRange. If an error occurs while compiling the regular expression then Tcl_RegExpCompile returns NULL and leaves an error message in the interpreter result. Note: the return value from Tcl_RegExpCompile is only valid up to the next call to Tcl_RegExpCompile; it is not safe to retain these values for long periods of time.

Tcl_RegExpExec executes the regular expression pattern matcher. It returns 1 if string contains a range of characters that match regexp, 0 if no match is found, and -1 if an error occurs. In the case of an error, Tcl_RegExpExec leaves an error message in the interpreter result. When searching a string for multiple matches of a pattern, it is important to distinguish between the start of the original string and the start of the current search. For example, when searching for the second occurrence of a match, the string argument might point to the character just after the first match; however, it is important for the pattern matcher to know that this is not the start of the entire string, so that it doesn't allow ^ atoms in the pattern to match. The start argument provides this information by pointing to the start of the overall string containing string. Start will be less than or equal to string; if it is less than string then no ^ matches will be allowed.

Tcl_RegExpRange may be invoked after Tcl_RegExpExec returns; it provides detailed information about what ranges of the string matched what parts of the pattern. Tcl_RegExpRange returns a pair of pointers in *startPtr and *endPtr that identify a range of characters in the source string for the most recent call to Tcl_RegExpExec. Index indicates which of several ranges is desired: if index is 0, information is returned about the overall range of characters that matched the entire pattern; otherwise, information is returned about the range of characters that matched the index'th parenthesized subexpression within the pattern. If there is no range corresponding to index then NULL is stored in *startPtr and *endPtr.

Tcl_GetRegExpFromObj, Tcl_RegExpExecObj, and Tcl_RegExpGetInfo are object interfaces that provide the most direct control of Henry Spencer's regular expression library. For users that need to modify compilation and execution options directly, it is recommended that you use these interfaces instead of calling the internal regexp functions. These interfaces handle the details of UTF to Unicode translations as well as providing improved performance through caching in the pattern and string objects.

Tcl_GetRegExpFromObj attepts to return a compiled regular expression from the patObj. If the object does not already contain a compiled regular expression it will attempt to create one from the string in the object and assign it to the internal representation of the patObj. The return value of this function is of type Tcl_RegExp. The return value is a token for this compiled form, which can be used in subsequent calls to Tcl_RegExpExecObj or Tcl_RegExpGetInfo. If an error occurs while compiling the regular expression then Tcl_GetRegExpFromObj returns NULL and leaves an error message in the interpreter result. The regular expression token can be used as long as the internal representation of patObj refers to the compiled form. The eflags argument is a bitwise OR of zero or more of the following flags that control the compilation of patObj:

TCL_REG_ADVANCED
Compile advanced regular expressions (`AREs'). This mode corresponds to the normal regular expression syntax accepted by the Tcl regexp and regsub commands.

TCL_REG_EXTENDED
Compile extended regular expressions (`EREs'). This mode corresponds to the regular expression syntax recognized by Tcl 8.0 and earlier versions.

TCL_REG_BASIC
Compile basic regular expressions (`BREs'). This mode corresponds to the regular expression syntax recognized by common Unix utilities like sed and grep. This is the default if no flags are specified.

TCL_REG_EXPANDED
Compile the regular expression (basic, extended, or advanced) using an expanded syntax that allows comments and whitespace. This mode causes non-backslashed non-bracket-expression white space and #-to-end-of-line comments to be ignored.

TCL_REG_QUOTE
Compile a literal string, with all characters treated as ordinary characters.

TCL_REG_NOCASE
Compile for matching that ignores upper/lower case distinctions.

TCL_REG_NEWLINE
Compile for newline-sensitive matching. By default, newline is a completely ordinary character with no special meaning in either regular expressions or strings. With this flag, `[^' bracket expressions and `.' never match newline, `^' matches an empty string after any newline in addition to its normal function, and `$' matches an empty string before any newline in addition to its normal function. REG_NEWLINE is the bitwise OR of REG_NLSTOP and REG_NLANCH.

TCL_REG_NLSTOP
Compile for partial newline-sensitive matching, with the behavior of `[^' bracket expressions and `.' affected, but not the behavior of `^' and `$'. In this mode, `[^' bracket expressions and `.' never match newline.

TCL_REG_NLANCH
Compile for inverse partial newline-sensitive matching, with the behavior of of `^' and `$' (the ``anchors'') affected, but not the behavior of `[^' bracket expressions and `.'. In this mode `^' matches an empty string after any newline in addition to its normal function, and `$' matches an empty string before any newline in addition to its normal function.

TCL_REG_NOSUB
Compile for matching that reports only success or failure, not what was matched. This reduces compile overhead and may improve performance. Subsequent calls to Tcl_RegExpGetInfo or Tcl_RegExpRange will not report any match information.

TCL_REG_CANMATCH
Compile for matching that reports the potential to complete a partial match given more text (see below).

Only one of TCL_REG_EXTENDED, TCL_REG_ADVANCED, TCL_REG_BASIC, and TCL_REG_QUOTE may be specified.

Tcl_RegExpExecObj executes the regular expression pattern matcher. It returns 1 if objPtr contains a range of characters that match regexp, 0 if no match is found, and -1 if an error occurs. In the case of an error, Tcl_RegExpExecObj leaves an error message in the interpreter result. The nmatches value indicates to the matcher how many subexpressions are of interest. If nmatches is 0, then no subexpression match information is recorded, which may allow the matcher to make various optimizations. If the value is -1, then all of the subexpressions in the pattern are remembered. If the value is a positive integer, then only that number of subexpressions will be remembered. Matching begins at the specified Unicode character index given by offset. Unlike Tcl_RegExpExec, the behavior of anchors is not affected by the offset value. Instead the behavior of the anchors is explicitly controlled by the eflags argument, which is a bitwise OR of zero or more of the following flags:

TCL_REG_NOTBOL
The starting character will not be treated as the beginning of a line or the beginning of the string, so `^' will not match there. Note that this flag has no effect on how `\A' matches.

TCL_REG_NOTEOL
The last character in the string will not be treated as the end of a line or the end of the string, so '$' will not match there. Note that this flag has no effect on how `\Z' matches.

Tcl_RegExpGetInfo retrieves information about the last match performed with a given regular expression regexp. The infoPtr argument contains a pointer to a structure that is defined as follows:

typedef struct Tcl_RegExpInfo {
    int nsubs;
    Tcl_RegExpIndices *matches;
    long extendStart;
} Tcl_RegExpInfo;

The nsubs field contains a count of the number of parenthesized subexpressions within the regular expression. If the TCL_REG_NOSUB was used, then this value will be zero. The matches field points to an array of nsubs values that indicate the bounds of each subexpression matched. The first element in the array refers to the range matched by the entire regular expression, and subsequent elements refer to the parenthesized subexpressions in the order that they appear in the pattern. Each element is a structure that is defined as follows:

typedef struct Tcl_RegExpIndices {
    long start;
    long end;
} Tcl_RegExpIndices;

The start and end values are Unicode character indices relative to the offset location within objPtr where matching began. The start index identifies the first character of the matched subexpression. The end index identifies the first character after the matched subexpression. If the subexpression matched the empty string, then start and end will be equal. If the subexpression did not participate in the match, then start and end will be set to -1.

The extendStart field in Tcl_RegExpInfo is only set if the TCL_REG_CANMATCH flag was used. It indicates the first character in the string where a match could occur. If a match was found, this will be the same as the beginning of the current match. If no match was found, then it indicates the earliest point at which a match might occur if additional text is appended to the string.

SEE ALSO

re_syntax

KEYWORDS

match, pattern, regular expression, string, subexpression, Tcl_RegExpIndices, Tcl_RegExpInfo
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
Copyright © 1998-1999 Scriptics Corportation


Tcl Library Procedures - Tcl_SaveResult manual page

NAME

Tcl_SaveResult, Tcl_RestoreResult, Tcl_DiscardResult - save and restore an interpreter's result

SYNOPSIS

#include <tcl.h>
Tcl_SaveResult(interp, statePtr)
Tcl_RestoreResult(interp, statePtr)
Tcl_DiscardResult(statePtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter for which state should be saved.

Tcl_SavedResult *statePtr (in)
Pointer to location where interpreter result should be saved or restored.

DESCRIPTION

These routines allows a C procedure to take a snapshot of the current interpreter result so that it can be restored after a call to Tcl_Eval or some other routine that modifies the interpreter result. These routines are passed a pointer to a structure that is used to store enough information to restore the interpreter result state. This structure can be allocated on the stack of the calling procedure. These routines do not save the state of any error information in the interpreter (e.g. the errorCode or errorInfo variables).

Tcl_SaveResult moves the string and object results of interp into the location specified by statePtr. Tcl_SaveResult clears the result for interp and leaves the result in its normal empty initialized state.

Tcl_RestoreResult moves the string and object results from statePtr back into interp. Any result or error that was already in the interpreter will be cleared. The statePtr is left in an uninitialized state and cannot be used until another call to Tcl_SaveResult.

Tcl_DiscardResult releases the saved interpreter state stored at statePtr. The state structure is left in an uninitialized state and cannot be used until another call to Tcl_SaveResult.

Once Tcl_SaveResult is called to save the interpreter result, either Tcl_RestoreResult or Tcl_DiscardResult must be called to properly clean up the memory associated with the saved state.

KEYWORDS

result, state, interp
Copyright © 1997 by Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_SetErrno manual page

NAME

Tcl_SetErrno, Tcl_GetErrno, Tcl_ErrnoId, Tcl_ErrnoMsg - manipulate errno to store and retrieve error codes

SYNOPSIS

#include <tcl.h>
void
Tcl_SetErrno(errorCode)
int
Tcl_GetErrno()
char *
Tcl_ErrnoId()
char *
Tcl_ErrnoMsg()

ARGUMENTS

int errorCode (in)
A POSIX error code such as ENOENT.

DESCRIPTION

Tcl_SetErrno and Tcl_GetErrno provide portable access to the errno variable, which is used to record a POSIX error code after system calls and other operations such as Tcl_Gets. These procedures are necessary because global variable accesses cannot be made across module boundaries on some platforms.

Tcl_SetErrno sets the errno variable to the value of the errorCode argument C procedures that wish to return error information to their callers via errno should call Tcl_SetErrno rather than setting errno directly.

Tcl_GetErrno returns the current value of errno. Procedures wishing to access errno should call this procedure instead of accessing errno directly.

Tcl_ErrnoId and Tcl_ErrnoMsg return a string representation of the current errno value. Tcl_ErrnoId returns a machine-readable textual identifier such as "EACCES". Tcl_ErrnoMsg returns a human-readable string such as "permission denied". The strings returned by these functions are statically allocated and the caller must not free or modify them.

KEYWORDS

errno, error code, global variables
Copyright © 1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_SetRecursionLimit manual page

NAME

Tcl_SetRecursionLimit - set maximum allowable nesting depth in interpreter

SYNOPSIS

#include <tcl.h>
int
Tcl_SetRecursionLimit(interp, depth)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter whose recursion limit is to be set. Must be greater than zero.

int depth (in)
New limit for nested calls to Tcl_Eval for interp.

DESCRIPTION

At any given time Tcl enforces a limit on the number of recursive calls that may be active for Tcl_Eval and related procedures such as Tcl_GlobalEval. Any call to Tcl_Eval that exceeds this depth is aborted with an error. By default the recursion limit is 1000.

Tcl_SetRecursionLimit may be used to change the maximum allowable nesting depth for an interpreter. The depth argument specifies a new limit for interp, and Tcl_SetRecursionLimit returns the old limit. To read out the old limit without modifying it, invoke Tcl_SetRecursionLimit with depth equal to 0.

The Tcl_SetRecursionLimit only sets the size of the Tcl call stack: it cannot by itself prevent stack overflows on the C stack being used by the application. If your machine has a limit on the size of the C stack, you may get stack overflows before reaching the limit set by Tcl_SetRecursionLimit. If this happens, see if there is a mechanism in your system for increasing the maximum size of the C stack.

KEYWORDS

nesting depth, recursion
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_SetResult manual page

NAME

Tcl_SetObjResult, Tcl_GetObjResult, Tcl_SetResult, Tcl_GetStringResult, Tcl_AppendResult, Tcl_AppendResultVA, Tcl_AppendElement, Tcl_ResetResult, Tcl_FreeResult - manipulate Tcl result

SYNOPSIS

#include <tcl.h>
Tcl_SetObjResult(interp, objPtr)
Tcl_Obj *
Tcl_GetObjResult(interp)
Tcl_SetResult(interp, string, freeProc)
char *
Tcl_GetStringResult(interp)
Tcl_AppendResult(interp, string, string, ... , (char *) NULL)
Tcl_AppendResultVA(interp, argList)
Tcl_AppendElement(interp, string)
Tcl_ResetResult(interp)
Tcl_FreeResult(interp)

ARGUMENTS

Tcl_Interp *interp (out)
Interpreter whose result is to be modified or read.

Tcl_Obj *objPtr (in)
Object value to become result for interp.

char *string (in)
String value to become result for interp or to be appended to the existing result.

Tcl_FreeProc *freeProc (in)
Address of procedure to call to release storage at string, or TCL_STATIC, TCL_DYNAMIC, or TCL_VOLATILE.

va_list argList (in)
An argument list which must have been initialised using TCL_VARARGS_START, and cleared using va_end.

DESCRIPTION

The procedures described here are utilities for manipulating the result value in a Tcl interpreter. The interpreter result may be either a Tcl object or a string. For example, Tcl_SetObjResult and Tcl_SetResult set the interpreter result to, respectively, an object and a string. Similarly, Tcl_GetObjResult and Tcl_GetStringResult return the interpreter result as an object and as a string. The procedures always keep the string and object forms of the interpreter result consistent. For example, if Tcl_SetObjResult is called to set the result to an object, then Tcl_GetStringResult is called, it will return the object's string value.

Tcl_SetObjResult arranges for objPtr to be the result for interp, replacing any existing result. The result is left pointing to the object referenced by objPtr. objPtr's reference count is incremented since there is now a new reference to it from interp. The reference count for any old result object is decremented and the old result object is freed if no references to it remain.

Tcl_GetObjResult returns the result for interp as an object. The object's reference count is not incremented; if the caller needs to retain a long-term pointer to the object they should use Tcl_IncrRefCount to increment its reference count in order to keep it from being freed too early or accidently changed.

Tcl_SetResult arranges for string to be the result for the current Tcl command in interp, replacing any existing result. The freeProc argument specifies how to manage the storage for the string argument; it is discussed in the section THE TCL_FREEPROC ARGUMENT TO TCL_SETRESULT below. If string is NULL, then freeProc is ignored and Tcl_SetResult re-initializes interp's result to point to an empty string.

Tcl_GetStringResult returns the result for interp as an string. If the result was set to an object by a Tcl_SetObjResult call, the object form will be converted to a string and returned. If the object's string representation contains null bytes, this conversion will lose information. For this reason, programmers are encouraged to write their code to use the new object API procedures and to call Tcl_GetObjResult instead.

Tcl_ResetResult clears the result for interp and leaves the result in its normal empty initialized state. If the result is an object, its reference count is decremented and the result is left pointing to an unshared object representing an empty string. If the result is a dynamically allocated string, its memory is free*d and the result is left as a empty string. Tcl_ResetResult also clears the error state managed by Tcl_AddErrorInfo, Tcl_AddObjErrorInfo, and Tcl_SetErrorCode.

OLD STRING PROCEDURES

Use of the following procedures is deprecated since they manipulate the Tcl result as a string. Procedures such as Tcl_SetObjResult that manipulate the result as an object can be significantly more efficient.

Tcl_AppendResult makes it easy to build up Tcl results in pieces. It takes each of its string arguments and appends them in order to the current result associated with interp. If the result is in its initialized empty state (e.g. a command procedure was just invoked or Tcl_ResetResult was just called), then Tcl_AppendResult sets the result to the concatenation of its string arguments. Tcl_AppendResult may be called repeatedly as additional pieces of the result are produced. Tcl_AppendResult takes care of all the storage management issues associated with managing interp's result, such as allocating a larger result area if necessary. It also converts the current interpreter result from an object to a string, if necessary, before appending the argument strings. Any number of string arguments may be passed in a single call; the last argument in the list must be a NULL pointer.

Tcl_AppendResultVA is the same as Tcl_AppendResult except that instead of taking a variable number of arguments it takes an argument list.

Tcl_AppendElement is similar to Tcl_AppendResult in that it allows results to be built up in pieces. However, Tcl_AppendElement takes only a single string argument and it appends that argument to the current result as a proper Tcl list element. Tcl_AppendElement adds backslashes or braces if necessary to ensure that interp's result can be parsed as a list and that string will be extracted as a single element. Under normal conditions, Tcl_AppendElement will add a space character to interp's result just before adding the new list element, so that the list elements in the result are properly separated. However if the new list element is the first in a list or sub-list (i.e. interp's current result is empty, or consists of the single character ``{'', or ends in the characters `` {'') then no space is added.

Tcl_FreeResult performs part of the work of Tcl_ResetResult. It frees up the memory associated with interp's result. It also sets interp->freeProc to zero, but doesn't change interp->result or clear error state. Tcl_FreeResult is most commonly used when a procedure is about to replace one result value with another.

DIRECT ACCESS TO INTERP->RESULT IS DEPRECATED

It used to be legal for programs to directly read and write interp->result to manipulate the interpreter result. Direct access to interp->result 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 Tcl_GetObjResult or Tcl_GetStringResult, and write the result using Tcl_SetObjResult or Tcl_SetResult.

THE TCL_FREEPROC ARGUMENT TO TCL_SETRESULT

Tcl_SetResult's freeProc argument specifies how the Tcl system is to manage the storage for the string argument. If Tcl_SetResult or Tcl_SetObjResult are called at a time when interp holds a string result, they do whatever is necessary to dispose of the old string result (see the Tcl_Interp manual entry for details on this).

If freeProc is TCL_STATIC it means that string refers to an area of static storage that is guaranteed not to be modified until at least the next call to Tcl_Eval. If freeProc is TCL_DYNAMIC it means that string was allocated with a call to Tcl_Alloc and is now the property of the Tcl system. Tcl_SetResult will arrange for the string's storage to be released by calling Tcl_Free when it is no longer needed. If freeProc is TCL_VOLATILE it means that string points to an area of memory that is likely to be overwritten when Tcl_SetResult returns (e.g. it points to something in a stack frame). In this case Tcl_SetResult will make a copy of the string in dynamically allocated storage and arrange for the copy to be the result for the current Tcl command.

If freeProc isn't one of the values TCL_STATIC, TCL_DYNAMIC, and TCL_VOLATILE, then it is the address of a procedure that Tcl should call to free the string. This allows applications to use non-standard storage allocators. When Tcl no longer needs the storage for the string, it will call freeProc. FreeProc should have arguments and result that match the type Tcl_FreeProc:

typedef void Tcl_FreeProc(char *blockPtr);
When freeProc is called, its blockPtr will be set to the value of string passed to Tcl_SetResult.

SEE ALSO

Tcl_AddErrorInfo, Tcl_CreateObjCommand, Tcl_SetErrorCode, Tcl_Interp

KEYWORDS

append, command, element, list, object, result, return value, interpreter
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_SetVar manual page

NAME
Tcl_SetVar2Ex, Tcl_SetVar, Tcl_SetVar2, Tcl_ObjSetVar2, Tcl_GetVar2Ex, Tcl_GetVar, Tcl_GetVar2, Tcl_ObjGetVar2, Tcl_UnsetVar, Tcl_UnsetVar2 - manipulate Tcl variables
SYNOPSIS
ARGUMENTS
DESCRIPTION
TCL_GLOBAL_ONLY
TCL_NAMESPACE_ONLY
TCL_LEAVE_ERR_MSG
TCL_APPEND_VALUE
TCL_LIST_ELEMENT
SEE ALSO
KEYWORDS

NAME

Tcl_SetVar2Ex, Tcl_SetVar, Tcl_SetVar2, Tcl_ObjSetVar2, Tcl_GetVar2Ex, Tcl_GetVar, Tcl_GetVar2, Tcl_ObjGetVar2, Tcl_UnsetVar, Tcl_UnsetVar2 - manipulate Tcl variables

SYNOPSIS

#include <tcl.h>
Tcl_Obj *
Tcl_SetVar2Ex(interp, name1, name2, newValuePtr, flags)
char *
Tcl_SetVar(interp, varName, newValue, flags)
char *
Tcl_SetVar2(interp, name1, name2, newValue, flags)
Tcl_Obj *
Tcl_ObjSetVar2(interp, part1Ptr, part2Ptr, newValuePtr, flags)
Tcl_Obj *
Tcl_GetVar2Ex(interp, name1, name2, flags)
char *
Tcl_GetVar(interp, varName, flags)
char *
Tcl_GetVar2(interp, name1, name2, flags)
Tcl_Obj *
Tcl_ObjGetVar2(interp, part1Ptr, part2Ptr, flags)
int
Tcl_UnsetVar(interp, varName, flags)
int
Tcl_UnsetVar2(interp, name1, name2, flags)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter containing variable.

char *name1 (in)
Contains the name of an array variable (if name2 is non-NULL) or (if name2 is NULL) either the name of a scalar variable or a complete name including both variable name and index. May include :: namespace qualifiers to specify a variable in a particular namespace.

char *name2 (in)
If non-NULL, gives name of element within array; in this case name1 must refer to an array variable.

Tcl_Obj *newValuePtr (in)
Points to a Tcl object containing the new value for the variable.

int flags (in)
OR-ed combination of bits providing additional information. See below for valid values.

char *varName (in)
Name of variable. May include :: namespace qualifiers to specify a variable in a particular namespace. May refer to a scalar variable or an element of an array. If the name references an element of an array, then the name must be in writable memory: Tcl will make temporary modifications to it while looking up the name.

char *newValue (in)
New value for variable, specified as a NULL-terminated string. A copy of this value is stored in the variable.

Tcl_Obj *part1Ptr (in)
Points to a Tcl object containing the variable's name. The name may include a series of :: namespace qualifiers to specify a variable in a particular namespace. May refer to a scalar variable or an element of an array variable.

Tcl_Obj *part2Ptr (in)
If non-NULL, points to an object containing the name of an element within an array and part1Ptr must refer to an array variable.

DESCRIPTION

These procedures are used to create, modify, read, and delete Tcl variables from C code.

Tcl_SetVar2Ex, Tcl_SetVar, Tcl_SetVar2, and Tcl_ObjSetVar2 will create a new variable or modify an existing one. These procedures set the given variable to the value given by newValuePtr or newValue and return a pointer to the variable's new value, which is stored in Tcl's variable structure. Tcl_SetVar2Ex and Tcl_ObjSetVar2 take the new value as a Tcl_Obj and return a pointer to a Tcl_Obj. Tcl_SetVar and Tcl_SetVar2 take the new value as a string and return a string; they are usually less efficient than Tcl_ObjSetVar2. Note that the return value may be different than the newValuePtr or newValue argument, due to modifications made by write traces. If an error occurs in setting the variable (e.g. an array variable is referenced without giving an index into the array) NULL is returned and an error message is left in interp's result if the TCL_LEAVE_ERR_MSG flag bit is set.

Tcl_GetVar2Ex, Tcl_GetVar, Tcl_GetVar2, and Tcl_ObjGetVar2 return the current value of a variable. The arguments to these procedures are treated in the same way as the arguments to the procedures described above. Under normal circumstances, the return value is a pointer to the variable's value. For Tcl_GetVar2Ex and Tcl_ObjGetVar2 the value is returned as a pointer to a Tcl_Obj. For Tcl_GetVar and Tcl_GetVar2 the value is returned as a string; this is usually less efficient, so Tcl_GetVar2Ex or Tcl_ObjGetVar2 are preferred. If an error occurs while reading the variable (e.g. the variable doesn't exist or an array element is specified for a scalar variable), then NULL is returned and an error message is left in interp's result if the TCL_LEAVE_ERR_MSG flag bit is set.

Tcl_UnsetVar and Tcl_UnsetVar2 may be used to remove a variable, so that future attempts to read the variable will return an error. The arguments to these procedures are treated in the same way as the arguments to the procedures above. If the variable is successfully removed then TCL_OK is returned. If the variable cannot be removed because it doesn't exist then TCL_ERROR is returned and an error message is left in interp's result if the TCL_LEAVE_ERR_MSG flag bit is set. If an array element is specified, the given element is removed but the array remains. If an array name is specified without an index, then the entire array is removed.

The name of a variable may be specified to these procedures in four ways:

[1]
If Tcl_SetVar, Tcl_GetVar, or Tcl_UnsetVar is invoked, the variable name is given as a single string, varName. If varName contains an open parenthesis and ends with a close parenthesis, then the value between the parentheses is treated as an index (which can have any string value) and the characters before the first open parenthesis are treated as the name of an array variable. If varName doesn't have parentheses as described above, then the entire string is treated as the name of a scalar variable.

[2]
If the name1 and name2 arguments are provided and name2 is non-NULL, then an array element is specified and the array name and index have already been separated by the caller: name1 contains the name and name2 contains the index. An error is generated if name1 contains an open parenthesis and ends with a close parenthesis (array element) and name2 is non-NULL.

[3]
If name2 is NULL, name1 is treated just like varName in case [1] above (it can be either a scalar or an array element variable name).

The flags argument may be used to specify any of several options to the procedures. It consists of an OR-ed combination of the following bits.

TCL_GLOBAL_ONLY
Under normal circumstances the procedures look up variables as follows. If a procedure call is active in interp, the variable is looked up at the current level of procedure call. Otherwise, the variable is looked up first in the current namespace, then in the global namespace. However, if this bit is set in flags then the variable is looked up only in the global namespace even if there is a procedure call active. If both TCL_GLOBAL_ONLY and TCL_NAMESPACE_ONLY are given, TCL_GLOBAL_ONLY is ignored.

TCL_NAMESPACE_ONLY
If this bit is set in flags then the variable is looked up only in the current namespace; if a procedure is active its variables are ignored, and the global namespace is also ignored unless it is the current namespace.

TCL_LEAVE_ERR_MSG
If an error is returned and this bit is set in flags, then an error message will be left in the interpreter's result, where it can be retrieved with Tcl_GetObjResult or Tcl_GetStringResult. If this flag bit isn't set then no error message is left and the interpreter's result will not be modified.

TCL_APPEND_VALUE
If this bit is set then newValuePtr or newValue is appended to the current value instead of replacing it. If the variable is currently undefined, then the bit is ignored. This bit is only used by the Tcl_Set* procedures.

TCL_LIST_ELEMENT
If this bit is set, then newValue is converted to a valid Tcl list element before setting (or appending to) the variable. A separator space is appended before the new list element unless the list element is going to be the first element in a list or sublist (i.e. the variable's current value is empty, or contains the single character ``{'', or ends in `` }'').

Tcl_GetVar and Tcl_GetVar2 return the current value of a variable. The arguments to these procedures are treated in the same way as the arguments to Tcl_SetVar and Tcl_SetVar2. Under normal circumstances, the return value is a pointer to the variable's value (which is stored in Tcl's variable structure and will not change before the next call to Tcl_SetVar or Tcl_SetVar2). Tcl_GetVar and Tcl_GetVar2 use the flag bits TCL_GLOBAL_ONLY and TCL_LEAVE_ERR_MSG, both of which have the same meaning as for Tcl_SetVar. If an error occurs in reading the variable (e.g. the variable doesn't exist or an array element is specified for a scalar variable), then NULL is returned.

Tcl_UnsetVar and Tcl_UnsetVar2 may be used to remove a variable, so that future calls to Tcl_GetVar or Tcl_GetVar2 for the variable will return an error. The arguments to these procedures are treated in the same way as the arguments to Tcl_GetVar and Tcl_GetVar2. If the variable is successfully removed then TCL_OK is returned. If the variable cannot be removed because it doesn't exist then TCL_ERROR is returned. If an array element is specified, the given element is removed but the array remains. If an array name is specified without an index, then the entire array is removed.

SEE ALSO

Tcl_GetObjResult, Tcl_GetStringResult, Tcl_TraceVar

KEYWORDS

array, get variable, interpreter, object, scalar, set, unset, variable
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Sleep manual page

NAME

Tcl_Sleep - delay execution for a given number of milliseconds

SYNOPSIS

#include <tcl.h>
Tcl_Sleep(ms)

ARGUMENTS

int ms (in)
Number of milliseconds to sleep.

DESCRIPTION

This procedure delays the calling process by the number of milliseconds given by the ms parameter and returns after that time has elapsed. It is typically used for things like flashing a button, where the delay is short and the application needn't do anything while it waits. For longer delays where the application needs to respond to other events during the delay, the procedure Tcl_CreateTimerHandler should be used instead of Tcl_Sleep.

KEYWORDS

sleep, time, wait
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_SourceRCFile manual page

NAME

Tcl_SourceRCFile - source the Tcl rc file

SYNOPSIS

#include <tcl.h>
void
Tcl_SourceRCFile(interp)

ARGUMENTS

Tcl_Interp *interp (in)
Tcl interpreter to source rc file into.

DESCRIPTION

Tcl_SourceRCFile is used to source the Tcl rc file at startup. It is typically invoked by Tcl_Main or Tk_Main. The name of the file sourced is obtained from the global variable tcl_rcFileName in the interpreter given by interp. If this variable is not defined, or if the file it indicates cannot be found, no action is taken.

On the Macintosh, after sourcing the rc file, this function will additionally source the TEXT resource indicated by the global variable tcl_rcRsrcName in interp.

KEYWORDS

application-specific initialization, main program, rc file
Copyright © 1998-2000 by Scriptics Corporation.


Tcl Library Procedures - Tcl_SplitList manual page

NAME

Tcl_SplitList, Tcl_Merge, Tcl_ScanElement, Tcl_ConvertElement, Tcl_ScanCountedElement, Tcl_ConvertCountedElement - manipulate Tcl lists

SYNOPSIS

#include <tcl.h>
int
Tcl_SplitList(interp, list, argcPtr, argvPtr)
char *
Tcl_Merge(argc, argv)
int
Tcl_ScanElement(src, flagsPtr)
int
Tcl_ScanCountedElement(src, length, flagsPtr)
int
Tcl_ConvertElement(src, dst, flags)
int
Tcl_ConvertCountedElement(src, length, dst, flags)

ARGUMENTS

Tcl_Interp *interp (out)
Interpreter to use for error reporting. If NULL, then no error message is left.

char *list (in)
Pointer to a string with proper list structure.

int *argcPtr (out)
Filled in with number of elements in list.

char ***argvPtr (out)
*argvPtr will be filled in with the address of an array of pointers to the strings that are the extracted elements of list. There will be *argcPtr valid entries in the array, followed by a NULL entry.

int argc (in)
Number of elements in argv.

char **argv (in)
Array of strings to merge together into a single list. Each string will become a separate element of the list.

char *src (in)
String that is to become an element of a list.

int *flagsPtr (in)
Pointer to word to fill in with information about src. The value of *flagsPtr must be passed to Tcl_ConvertElement.

int length (in)
Number of bytes in string src.

char *dst (in)
Place to copy converted list element. Must contain enough characters to hold converted string.

int flags (in)
Information about src. Must be value returned by previous call to Tcl_ScanElement, possibly OR-ed with TCL_DONT_USE_BRACES.

DESCRIPTION

These procedures may be used to disassemble and reassemble Tcl lists. Tcl_SplitList breaks a list up into its constituent elements, returning an array of pointers to the elements using argcPtr and argvPtr. While extracting the arguments, Tcl_SplitList obeys the usual rules for backslash substitutions and braces. The area of memory pointed to by *argvPtr is dynamically allocated; in addition to the array of pointers, it 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 Tcl_SplitList with the following code:
int argc, code;
char *string;
char **argv;
    ...
code = Tcl_SplitList(interp, string, &argc, &argv);
Then you should eventually free the storage with a call like the following:
Tcl_Free((char *) argv);

Tcl_SplitList normally returns TCL_OK, which means the list was successfully parsed. If there was a syntax error in list, then TCL_ERROR is returned and the interpreter's result will point to an error message describing the problem (if interp was not NULL). If TCL_ERROR is returned then no memory is allocated and *argvPtr is not modified.

Tcl_Merge is the inverse of Tcl_SplitList: it takes a collection of strings given by argc and argv and generates a result string that has proper list structure. This means that commands like index may be used to extract the original elements again. In addition, if the result of Tcl_Merge is passed to Tcl_Eval, it will be parsed into argc words whose values will be the same as the argv strings passed to Tcl_Merge. Tcl_Merge will modify the list elements with braces and/or backslashes in order to produce proper Tcl list structure. The result string is dynamically allocated using Tcl_Alloc; the caller must eventually release the space using Tcl_Free.

If the result of Tcl_Merge is passed to Tcl_SplitList, the elements returned by Tcl_SplitList will be identical to those passed into Tcl_Merge. However, the converse is not true: if Tcl_SplitList is passed a given string, and the resulting argc and argv are passed to Tcl_Merge, the resulting string may not be the same as the original string passed to Tcl_SplitList. This is because Tcl_Merge may use backslashes and braces differently than the original string.

Tcl_ScanElement and Tcl_ConvertElement are the procedures that do all of the real work of Tcl_Merge. Tcl_ScanElement scans its src argument and determines how to use backslashes and braces when converting it to a list element. It returns an overestimate of the number of characters required to represent src as a list element, and it stores information in *flagsPtr that is needed by Tcl_ConvertElement.

Tcl_ConvertElement is a companion procedure to Tcl_ScanElement. It does the actual work of converting a string to a list element. Its flags argument must be the same as the value returned by Tcl_ScanElement. Tcl_ConvertElement writes a proper list element to memory starting at *dst and returns a count of the total number of characters written, which will be no more than the result returned by Tcl_ScanElement. Tcl_ConvertElement writes out only the actual list element without any leading or trailing spaces: it is up to the caller to include spaces between adjacent list elements.

Tcl_ConvertElement uses one of two different approaches to handle the special characters in src. Wherever possible, it handles special characters by surrounding the string with braces. This produces clean-looking output, but can't be used in some situations, such as when src contains unmatched braces. In these situations, Tcl_ConvertElement handles special characters by generating backslash sequences for them. The caller may insist on the second approach by OR-ing the flag value returned by Tcl_ScanElement with TCL_DONT_USE_BRACES. Although this will produce an uglier result, it is useful in some special situations, such as when Tcl_ConvertElement is being used to generate a portion of an argument for a Tcl command. In this case, surrounding src with curly braces would cause the command not to be parsed correctly.

Tcl_ScanCountedElement and Tcl_ConvertCountedElement are the same as Tcl_ScanElement and Tcl_ConvertElement, except the length of string src is specified by the length argument, and the string may contain embedded nulls.

KEYWORDS

backslash, convert, element, list, merge, split, strings
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_SplitPath manual page

NAME

Tcl_SplitPath, Tcl_JoinPath, Tcl_GetPathType - manipulate platform-dependent file paths

SYNOPSIS

#include <tcl.h>
Tcl_SplitPath(path, argcPtr, argvPtr)
char *
Tcl_JoinPath(argc, argv, resultPtr)
Tcl_PathType
Tcl_GetPathType(path)

ARGUMENTS

char *path (in)
File path in a form appropriate for the current platform (see the filename manual entry for acceptable forms for path names).

int *argcPtr (out)
Filled in with number of path elements in path.

char ***argvPtr (out)
*argvPtr will be filled in with the address of an array of pointers to the strings that are the extracted elements of path. There will be *argcPtr valid entries in the array, followed by a NULL entry.

int argc (in)
Number of elements in argv.

char **argv (in)
Array of path elements to merge together into a single path.

Tcl_DString *resultPtr (in/out)
A pointer to an initialized Tcl_DString to which the result of Tcl_JoinPath will be appended.

DESCRIPTION

These procedures may be used to disassemble and reassemble file paths in a platform independent manner: they provide C-level access to the same functionality as the file split, file join, and file pathtype commands.

Tcl_SplitPath breaks a path into its constituent elements, returning an array of pointers to the elements using argcPtr and argvPtr. The area of memory pointed to by *argvPtr is dynamically allocated; in addition to the array of pointers, it also 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 Tcl_SplitPath with the following code:

int argc;
char *path;
char **argv;
    ...
Tcl_SplitPath(string, &argc, &argv);
Then you should eventually free the storage with a call like the following:
Tcl_Free((char *) argv);

Tcl_JoinPath is the inverse of Tcl_SplitPath: it takes a collection of path elements given by argc and argv and generates a result string that is a properly constructed path. The result string is appended to resultPtr. ResultPtr must refer to an initialized Tcl_DString.

If the result of Tcl_SplitPath is passed to Tcl_JoinPath, the result will refer to the same location, but may not be in the same form. This is because Tcl_SplitPath and Tcl_JoinPath eliminate duplicate path separators and return a normalized form for each platform.

Tcl_GetPathType returns the type of the specified path, where Tcl_PathType is one of TCL_PATH_ABSOLUTE, TCL_PATH_RELATIVE, or TCL_PATH_VOLUME_RELATIVE. See the filename manual entry for a description of the path types for each platform.

KEYWORDS

file, filename, join, path, split, type
Copyright © 1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_StaticPackage manual page

NAME

Tcl_StaticPackage - make a statically linked package available via the load command

SYNOPSIS

#include <tcl.h>
Tcl_StaticPackage(interp, pkgName, initProc, safeInitProc)

ARGUMENTS

Tcl_Interp *interp (in)
If not NULL, points to an interpreter into which the package has already been loaded (i.e., the caller has already invoked the appropriate initialization procedure). NULL means the package hasn't yet been incorporated into any interpreter.

char *pkgName (in)
Name of the package; should be properly capitalized (first letter upper-case, all others lower-case).

Tcl_PackageInitProc *initProc (in)
Procedure to invoke to incorporate this package into a trusted interpreter.

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 can't be used in safe interpreters.

DESCRIPTION

This procedure may be invoked to announce that a package has been linked statically with a Tcl application and, optionally, that it has already been loaded into an interpreter. Once Tcl_StaticPackage has been invoked for a package, it may be loaded into interpreters using the load command. Tcl_StaticPackage is normally invoked only by the Tcl_AppInit procedure for the application, not by packages for themselves (Tcl_StaticPackage should only be invoked for statically loaded packages, and code in the package itself should not need to know whether the package is dynamically or statically loaded).

When the load command is used later to load the package into an interpreter, one of initProc and safeInitProc will be invoked, depending on whether the target interpreter is safe or not. initProc and safeInitProc must both match the following prototype:

typedef int Tcl_PackageInitProc(Tcl_Interp *interp);
The interp argument identifies the interpreter in which the package is to be loaded. The initialization procedure must return TCL_OK or TCL_ERROR to indicate whether or not it completed successfully; in 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 load command that caused the initialization procedure to be invoked.

KEYWORDS

initialization procedure, package, static linking
Copyright © 1995-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_StringObj manual page

NAME

Tcl_NewStringObj, Tcl_NewUnicodeObj, Tcl_SetStringObj, Tcl_SetUnicodeObj, Tcl_GetStringFromObj, Tcl_GetString, Tcl_GetUnicode, Tcl_GetUniChar, Tcl_GetCharLength, Tcl_GetRange, Tcl_AppendToObj, Tcl_AppendUnicodeToObj, Tcl_AppendStringsToObj, Tcl_AppendStringsToObjVA, Tcl_AppendObjToObj, Tcl_SetObjLength, Tcl_ConcatObj - manipulate Tcl objects as strings

SYNOPSIS

#include <tcl.h>
Tcl_Obj *
Tcl_NewStringObj(bytes, length)
Tcl_Obj *
Tcl_NewUnicodeObj(unicode, numChars)
void
Tcl_SetStringObj(objPtr, bytes, length)
void
Tcl_SetUnicodeObj(objPtr, unicode, numChars)
char *
Tcl_GetStringFromObj(objPtr, lengthPtr)
char *
Tcl_GetString(objPtr)
Tcl_UniChar *
Tcl_GetUnicode(objPtr)
Tcl_UniChar
Tcl_GetUniChar(objPtr, index)
int
Tcl_GetCharLength(objPtr)
Tcl_Obj *
Tcl_GetRange(objPtr, first, last)
void
Tcl_AppendToObj(objPtr, bytes, length)
void
Tcl_AppendUnicodeToObj(objPtr, unicode, numChars)
void
Tcl_AppendObjToObj(objPtr, appendObjPtr)
void
Tcl_AppendStringsToObj(objPtr, string, string, ... (char *) NULL)
void
Tcl_AppendStringsToObjVA(objPtr, argList)
void
Tcl_SetObjLength(objPtr, newLength)
Tcl_Obj *
Tcl_ConcatObj(objc, objv)

ARGUMENTS

char *bytes (in)
Points to the first byte of an array of bytes used to set or append to a string object. This byte array may contain embedded null bytes unless length is negative.

int length (in)
The number of bytes to copy from bytes when initializing, setting, or appending to a string object. If negative, all bytes up to the first null are used.

Tcl_UniChar *unicode (in)
Points to the first byte of an array of Unicode characters used to set or append to a string object. This byte array may contain embedded null characters unless numChars is negative.

int numChars (in)
The number of Unicode characters to copy from unicode when initializing, setting, or appending to a string object. If negative, all characters up to the first null character are used.

int index (in)
The index of the Unicode character to return.

int first (in)
The index of the first Unicode character in the Unicode range to be returned as a new object.

int last (in)
The index of the last Unicode character in the Unicode range to be returned as a new object.

Tcl_Obj *objPtr (in/out)
Points to an object to manipulate.

Tcl_Obj *appendObjPtr (in)
The object to append to objPtr in Tcl_AppendObjToObj.

int *lengthPtr (out)
If non-NULL, the location where Tcl_GetStringFromObj will store the the length of an object's string representation.

char *string (in)
Null-terminated string value to append to objPtr.

va_list argList (in)
An argument list which must have been initialised using TCL_VARARGS_START, and cleared using va_end.

int newLength (in)
New length for the string value of objPtr, not including the final NULL character.

int objc (in)
The number of elements to concatenate.

Tcl_Obj *objv[] (in)
The array of objects to concatenate.

DESCRIPTION

The procedures described in this manual entry allow Tcl objects to be manipulated as string values. They use the internal representation of the object to store additional information to make the string manipulations more efficient. In particular, they make a series of append operations efficient by allocating extra storage space for the string so that it doesn't have to be copied for each append. Also, indexing and length computations are optimized because the Unicode string representation is calculated and cached as needed.

Tcl_NewStringObj and Tcl_SetStringObj create a new object or modify an existing object to hold a copy of the string given by bytes and length. Tcl_NewUnicodeObj and Tcl_SetUnicodeObj create a new object or modify an existing object to hold a copy of the Unicode string given by unicode and numChars. Tcl_NewStringObj and Tcl_NewUnicodeObj return a pointer to a newly created object with reference count zero. All four procedures set the object to hold a copy of the specified string. Tcl_SetStringObj and Tcl_SetUnicodeObj free any old string representation as well as any old internal representation of the object.

Tcl_GetStringFromObj and Tcl_GetString return an object's string representation. This is given by the returned byte pointer and (for Tcl_GetStringFromObj) length, which is stored in lengthPtr if it is non-NULL. If the object's UTF string representation is invalid (its byte pointer is NULL), the string representation is regenerated from the object's internal representation. The storage referenced by the returned byte pointer is owned by the object manager and should not be modified by the caller. The procedure Tcl_GetString is used in the common case where the caller does not need the length of the string representation.

Tcl_GetUnicode returns an object's value as a Unicode string. Tcl_GetUniChar returns the index'th character in the object's Unicode representation.

Tcl_GetRange returns a newly created object comprised of the characters between first and last (inclusive) in the object's Unicode representation. If the object's Unicode representation is invalid, the Unicode representation is regenerated from the object's string representation.

Tcl_GetCharLength returns the number of characters (as opposed to bytes) in the string object.

Tcl_AppendToObj appends the data given by bytes and length to the string representation of the object specified by objPtr. If the object has an invalid string representation, then an attempt is made to convert bytes is to the Unicode format. If the conversion is successful, then the converted form of bytes is appended to the object's Unicode representation. Otherwise, the object's Unicode representation is invalidated and converted to the UTF format, and bytes is appended to the object's new string representation.

Tcl_AppendUnicodeToObj appends the Unicode string given by unicode and numChars to the object specified by objPtr. If the object has an invalid Unicode representation, then unicode is converted to the UTF format and appended to the object's string representation. Appends are optimized to handle repeated appends relatively efficiently (it overallocates the string or Unicode space to avoid repeated reallocations and copies of object's string value).

Tcl_AppendObjToObj is similar to Tcl_AppendToObj, but it appends the string or Unicode value (whichever exists and is best suited to be appended to objPtr) of appendObjPtr to objPtr.

Tcl_AppendStringsToObj is similar to Tcl_AppendToObj except that it can be passed more than one value to append and each value must be a null-terminated string (i.e. none of the values may contain internal null characters). Any number of string arguments may be provided, but the last argument must be a NULL pointer to indicate the end of the list.

Tcl_AppendStringsToObjVA is the same as Tcl_AppendStringsToObj except that instead of taking a variable number of arguments it takes an argument list.

The Tcl_SetObjLength procedure changes the length of the string value of its objPtr argument. If the newLength argument is greater than the space allocated for the object's string, then the string space is reallocated and the old value is copied to the new space; the bytes between the old length of the string and the new length may have arbitrary values. If the newLength argument is less than the current length of the object's string, with objPtr->length is reduced without reallocating the string space; the original allocated size for the string is recorded in the object, so that the string length can be enlarged in a subsequent call to Tcl_SetObjLength without reallocating storage. In all cases Tcl_SetObjLength leaves a null character at objPtr->bytes[newLength].

The Tcl_ConcatObj function returns a new string object whose value is the space-separated concatenation of the string representations of all of the objects in the objv array. Tcl_ConcatObj eliminates leading and trailing white space as it copies the string representations of the objv array to the result. If an element of the objv array consists of nothing but white space, then that object is ignored entirely. This white-space removal was added to make the output of the concat command cleaner-looking. Tcl_ConcatObj returns a pointer to a newly-created object whose ref count is zero.

SEE ALSO

Tcl_NewObj, Tcl_IncrRefCount, Tcl_DecrRefCount

KEYWORDS

append, internal representation, object, object type, string object, string type, string representation, concat, concatenate, unicode
Copyright © 1994-1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_StringMatch manual page

NAME

Tcl_StringMatch, Tcl_StringCaseMatch - test whether a string matches a pattern

SYNOPSIS

#include <tcl.h>
int
Tcl_StringMatch(string, pattern)
int
Tcl_StringCaseMatch(string, pattern, nocase)

ARGUMENTS

char *string (in)
String to test.

char *pattern (in)
Pattern to match against string. May contain special characters from the set *?\[].

int nocase (in)
Specifies whether the match should be done case-sensitive (0) or case-insensitive (1).

DESCRIPTION

This utility procedure determines whether a string matches a given pattern. If it does, then Tcl_StringMatch returns 1. Otherwise Tcl_StringMatch returns 0. The algorithm used for matching is the same algorithm used in the ``string match'' Tcl command and is similar to the algorithm used by the C-shell for file name matching; see the Tcl manual entry for details.

In Tcl_StringCaseMatch, the algorithm is the same, but you have the option to make the matching case-insensitive. If you choose this (by passing nocase as 1), then the string and pattern are essentially matched in the lower case.

KEYWORDS

match, pattern, string
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_Main manual page

NAME

Tcl_Main, Tcl_SetMainLoop - main program and event loop definition for Tcl-based applications

SYNOPSIS

#include <tcl.h>
Tcl_Main(argc, argv, appInitProc)
Tcl_SetMainLoop(mainLoopProc)

ARGUMENTS

int argc (in)
Number of elements in argv.

char *argv[] (in)
Array of strings containing command-line arguments.

Tcl_AppInitProc *appInitProc (in)
Address of an application-specific initialization procedure. The value for this argument is usually Tcl_AppInit.

Tcl_MainLoopProc *mainLoopProc (in)
Address of an application-specific event loop procedure.

DESCRIPTION

Tcl_Main acts as the main program for most Tcl-based applications. Starting with Tcl 7.4 it is not called main anymore because it is part of the Tcl library and having a function main in a library (particularly a shared library) causes problems on many systems. Having main in the Tcl library would also make it hard to use Tcl in C++ programs, since C++ programs must have special C++ main functions.

Normally each application contains a small main function that does nothing but invoke Tcl_Main. Tcl_Main then does all the work of creating and running a tclsh-like application.

When it is has finished its own initialization, but before it processes commands, Tcl_Main calls the procedure given by the appInitProc argument. This procedure provides a ``hook'' for the application to perform its own initialization, such as defining application-specific commands. The procedure must have an interface that matches the type Tcl_AppInitProc:

typedef int Tcl_AppInitProc(Tcl_Interp *interp);
AppInitProc is almost always a pointer to Tcl_AppInit; for more details on this procedure, see the documentation for Tcl_AppInit. When the appInitProc is finished, the startup script will be evaluated. If none exists, then an interactive prompt is provided.

Tcl_SetMainLoop allows setting an event loop procedure to be run. This allows, for example, Tk to be dynamically loaded and set its event loop. The event loop will run following the startup script. If you are in interactive mode, setting the main loop procedure will cause the prompt to become fileevent based and then the loop procedure is called. The main loop procedure must have an interface that matches the type Tcl_MainLoopProc:

typedef void Tcl_MainLoopProc(void);

KEYWORDS

application-specific initialization, command-line arguments, main program
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
Copyright © 2000 Ajuba Solutions.


Tcl Library Procedures - TCL_MEM_DEBUG manual page

NAME

TCL_MEM_DEBUG - Compile-time flag to enable Tcl memory debugging.

DESCRIPTION

When Tcl is compiled with TCL_MEM_DEBUG defined, a powerful set of memory debugging aids are included in the compiled binary. This includes C and Tcl functions which can aid with debugging memory leaks, memory allocation overruns, and other memory related errors.

ENABLING MEMORY DEBUGGING

To enable memory debugging, Tcl should be recompiled from scratch with TCL_MEM_DEBUG defined. This will also compile in a non-stub version of Tcl_InitMemory to add the memory command to Tcl.

TCL_MEM_DEBUG must be either left defined for all modules or undefined for all modules that are going to be linked together. If they are not, link errors will occur, with either TclDbCkfree and Tcl_DbCkalloc or Tcl_Ckalloc and Tcl_Ckfree being undefined.

Once memory debugging support has been compiled into Tcl, the C functions Tcl_ValidateAllMemory, and Tcl_DumpActiveMemory, and the Tcl memory command can be used to validate and examine memory usage.

GUARD ZONES

When memory debugging is enabled, whenever a call to ckalloc is made, slightly more memory than requested is allocated so the memory debugging code can keep track of the allocated memory, and eight-byte ``guard zones'' are placed in front of and behind the space that will be returned to the caller. (The sizes of the guard zones are defined by the C #define LOW_GUARD_SIZE and #define HIGH_GUARD_SIZE in the file generic/tclCkalloc.c -- it can be extended if you suspect large overwrite problems, at some cost in performance.) A known pattern is written into the guard zones and, on a call to ckfree, the guard zones of the space being freed are checked to see if either zone has been modified in any way. If one has been, the guard bytes and their new contents are identified, and a ``low guard failed'' or ``high guard failed'' message is issued. The ``guard failed'' message includes the address of the memory packet and the file name and line number of the code that called ckfree. This allows you to detect the common sorts of one-off problems, where not enough space was allocated to contain the data written, for example.

DEBUGGING DIFFICULT MEMORY CORRUPTION PROBLEMS

Normally, Tcl compiled with memory debugging enabled will make it easy to isolate a corruption problem. Turning on memory validation with the memory command can help isolate difficult problems. If you suspect (or know) that corruption is occurring before the Tcl interpreter comes up far enough for you to issue commands, you can set MEM_VALIDATE define, recompile tclCkalloc.c and rebuild Tcl. This will enable memory validation from the first call to ckalloc, again, at a large performance impact.

If you are desperate and validating memory on every call to ckalloc and ckfree isn't enough, you can explicitly call Tcl_ValidateAllMemory directly at any point. It takes a char * and an int which are normally the filename and line number of the caller, but they can actually be anything you want. Remember to remove the calls after you find the problem.

SEE ALSO

memory, Tcl_ValidateAllMemory, Tcl_DumpActiveMemory

KEYWORDS

memory, debug
Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans.
Copyright © 2000 by Scriptics Corporation.


Tcl Library Procedures - Threads manual page

NAME

Tcl_ConditionNotify, Tcl_ConditionWait, Tcl_ConditionFinalize, Tcl_GetThreadData, Tcl_MutexLock, Tcl_MutexUnlock, Tcl_MutexFinalize, Tcl_CreateThread - Tcl thread support.

SYNOPSIS

#include <tcl.h>
void
Tcl_ConditionNotify(condPtr)
void
Tcl_ConditionWait(condPtr, mutexPtr, timePtr)
void
Tcl_ConditionFinalize(condPtr)
Void *
Tcl_GetThreadData(keyPtr, size)
void
Tcl_MutexLock(mutexPtr)
void
Tcl_MutexUnlock(mutexPtr)
void
Tcl_MutexFinalize(mutexPtr)
int
Tcl_CreateThread(idPtr, threadProc, clientData, stackSize, flags)

ARGUMENTS

Tcl_Condition *condPtr (in)
A condition variable, which must be associated with a mutex lock.

Tcl_Condition *mutexPtr (in)
A mutex lock.

Tcl_Time *timePtr (in)
A time limit on the condition wait. NULL to wait forever. Note that a polling value of 0 seconds doesn't make much sense.

Tcl_ThreadDataKey *keyPtr (in)
This identifies a block of thread local storage. The key should be static and process-wide, yet each thread will end up associating a different block of storage with this key.

int *size (in)
The size of the thread local storage block. This amount of data is allocated and initialized to zero the first time each thread calls Tcl_GetThreadData.

Tcl_ThreadId *idPtr (out)
The refered storage will contain the id of the newly created thread as returned by the operating system.

Tcl_ThreadId id (in)
Id of the thread waited upon.

Tcl_ThreadCreateProc threadProc (in)
This procedure will act as the main() of the newly created thread. The specified clientData will be its sole argument.

ClientData clientData (in)
Arbitrary information. Passed as sole argument to the threadProc.

int stackSize (in)
The size of the stack given to the new thread.

int flags (in)
Bitmask containing flags allowing the caller to modify behaviour of the new thread.

int *result (out)
The refered storage is used to place the exit code of the thread waited upon into it.

INTRODUCTION

Beginning with the 8.1 release, the Tcl core is thread safe, which allows you to incorporate Tcl into multithreaded applications without customizing the Tcl core. To enable Tcl multithreading support, you must include the --enable-threads option to configure when you configure and compile your Tcl core.

An important contstraint of the Tcl threads implementation is that only the thread that created a Tcl interpreter can use that interpreter. In other words, multiple threads can not access the same Tcl interpreter. (However, as was the case in previous releases, a single thread can safely create and use multiple interpreters.)

Tcl does provide Tcl_CreateThread for creating threads. The caller can determine the size of the stack given to the new thread and modify the behaviour through the supplied flags. The value TCL_THREAD_STACK_DEFAULT for the stackSize indicates that the default size as specified by the operating system is to be used for the new thread. As for the flags, currently are only the values TCL_THREAD_NOFLAGS and TCL_THREAD_JOINABLE defined. The first of them invokes the default behaviour with no specialities. Using the second value marks the new thread as joinable. This means that another thread can wait for the such marked thread to exit and join it.

Restrictions: On some unix systems the pthread-library does not contain the functionality to specify the stacksize of a thread. The specified value for the stacksize is ignored on these systems. Both Windows and Macintosh currently do not support joinable threads. This flag value is therefore ignored on these platforms.

Tcl does provide Tcl_ExitThread and Tcl_FinalizeThread for terminating threads and invoking optional per-thread exit handlers. See the Tcl_Exit page for more information on these procedures.

Tcl provides Tcl_ThreadQueueEvent and Tcl_ThreadAlert for handling event queueing in multithreaded applications. See the Notifier manual page for more information on these procedures.

In this release, the Tcl language itself provides no support for creating multithreaded scripts (for example, scripts that could spawn a Tcl interpreter in a separate thread). If you need to add this feature at this time, see the tclThreadTest.c file in the Tcl source distribution for an experimental implementation of a Tcl "Thread" package implementing thread creation and management commands at the script level.

DESCRIPTION

A mutex is a lock that is used to serialize all threads through a piece of code by calling Tcl_MutexLock and Tcl_MutexUnlock. If one thread holds a mutex, any other thread calling Tcl_MutexLock will block until Tcl_MutexUnlock is called. A mutex can be destroyed after its use by calling Tcl_MutexFinalize. The result of locking a mutex twice from the same thread is undefined. On some platforms it will result in a deadlock. The Tcl_MutexLock, Tcl_MutexUnlock and Tcl_MutexFinalize procedures are defined as empty macros if not compiling with threads enabled.

A condition variable is used as a signaling mechanism: a thread can lock a mutex and then wait on a condition variable with Tcl_ConditionWait. This atomically releases the mutex lock and blocks the waiting thread until another thread calls Tcl_ConditionNotify. The caller of Tcl_ConditionNotify should have the associated mutex held by previously calling Tcl_MutexLock, but this is not enforced. Notifying the condition variable unblocks all threads waiting on the condition variable, but they do not proceed until the mutex is released with Tcl_MutexUnlock. The implementation of Tcl_ConditionWait automatically locks the mutex before returning.

The caller of Tcl_ConditionWait should be prepared for spurious notifications by calling Tcl_ConditionWait within a while loop that tests some invariant.

A condition variable can be destroyed after its use by calling Tcl_ConditionFinalize.

The Tcl_ConditionNotify, Tcl_ConditionWait and Tcl_ConditionFinalize procedures are defined as empty macros if not compiling with threads enabled.

The Tcl_GetThreadData call returns a pointer to a block of thread-private data. Its argument is a key that is shared by all threads and a size for the block of storage. The storage is automatically allocated and initialized to all zeros the first time each thread asks for it. The storage is automatically deallocated by Tcl_FinalizeThread.

INITIALIZATION

All of these synchronization objects are self initializing. They are implemented as opaque pointers that should be NULL upon first use. The mutexes and condition variables are either cleaned up by process exit handlers (if living that long) or explicitly by calls to Tcl_MutexFinalize or Tcl_ConditionFinalize. Thread local storage is reclaimed during Tcl_FinalizeThread.

CREATING THREADS

The API to create threads is not finalized at this time. There are private facilities to create threads that contain a new Tcl interpreter, and to send scripts among threads. Dive into tclThreadTest.c and tclThread.c for examples.

SEE ALSO

Tcl_GetCurrentThread, Tcl_ThreadQueueEvent, Tcl_ThreadAlert, Tcl_ExitThread, Tcl_FinalizeThread, Tcl_CreateThreadExitHandler, Tcl_DeleteThreadExitHandler

KEYWORDS

thread, mutex, condition variable, thread local storage
Copyright © 1999 Scriptics Corporation
Copyright © 1998 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_UtfToUpper manual page

NAME

Tcl_UniCharToUpper, Tcl_UniCharToLower, Tcl_UniCharToTitle, Tcl_UtfToUpper, Tcl_UtfToLower, Tcl_UtfToTitle - routines for manipulating the case of Unicode characters and UTF-8 strings.

SYNOPSIS

#include <tcl.h>
Tcl_UniChar
Tcl_UniCharToUpper(ch)
Tcl_UniChar
Tcl_UniCharToLower(ch)
Tcl_UniChar
Tcl_UniCharToTitle(ch)
int
Tcl_UtfToUpper(str)
int
Tcl_UtfToLower(str)
int
Tcl_UtfToTitle(str)

ARGUMENTS

int ch (in)
The Tcl_UniChar to be converted.

char *str (in/out)
Pointer to UTF-8 string to be converted in place.

DESCRIPTION

The first three routines convert the case of individual Unicode characters:

If ch represents a lower-case character, Tcl_UniCharToUpper returns the corresponding upper-case character. If no upper-case character is defined, it returns the character unchanged.

If ch represents an upper-case character, Tcl_UniCharToLower returns the corresponding lower-case character. If no lower-case character is defined, it returns the character unchanged.

If ch represents a lower-case character, Tcl_UniCharToTitle returns the corresponding title-case character. If no title-case character is defined, it returns the corresponding upper-case character. If no upper-case character is defined, it returns the character unchanged. Title-case is defined for a small number of characters that have a different appearance when they are at the beginning of a capitalized word.

The next three routines convert the case of UTF-8 strings in place in memory:

Tcl_UtfToUpper changes every UTF-8 character in str to upper-case. Because changing the case of a character may change its size, the byte offset of each character in the resulting string may differ from its original location. Tcl_UtfToUpper writes a null byte at the end of the converted string. Tcl_UtfToUpper returns the new length of the string in bytes. This new length is guaranteed to be no longer than the original string length.

Tcl_UtfToLower is the same as Tcl_UtfToUpper except it turns each character in the string into its lower-case equivalent.

Tcl_UtfToTitle is the same as Tcl_UtfToUpper except it turns the first character in the string into its title-case equivalent and all following characters into their lower-case equivalents.

BUGS

At this time, the case conversions are only defined for the ISO8859-1 characters. Unicode characters above 0x00ff are not modified by these routines.

KEYWORDS

utf, unicode, toupper, tolower, totitle, case
Copyright © 1997 by Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_TraceVar manual page

NAME
Tcl_TraceVar, Tcl_TraceVar2, Tcl_UntraceVar, Tcl_UntraceVar2, Tcl_VarTraceInfo, Tcl_VarTraceInfo2 - monitor accesses to a variable
SYNOPSIS
ARGUMENTS
DESCRIPTION
TCL_GLOBAL_ONLY
TCL_TRACE_READS
TCL_TRACE_WRITES
TCL_TRACE_UNSETS
TCL_TRACE_ARRAY
TWO-PART NAMES
ACCESSING VARIABLES DURING TRACES
CALLBACK TIMING
WHOLE-ARRAY TRACES
MULTIPLE TRACES
ERROR RETURNS
RESTRICTIONS
UNDEFINED VARIABLES
TCL_TRACE_DESTROYED FLAG
TCL_INTERP_DESTROYED
BUGS
KEYWORDS

NAME

Tcl_TraceVar, Tcl_TraceVar2, Tcl_UntraceVar, Tcl_UntraceVar2, Tcl_VarTraceInfo, Tcl_VarTraceInfo2 - monitor accesses to a variable

SYNOPSIS

#include <tcl.h>
int
Tcl_TraceVar(interp, varName, flags, proc, clientData)
int
Tcl_TraceVar2(interp, name1, name2, flags, proc, clientData)
Tcl_UntraceVar(interp, varName, flags, proc, clientData)
Tcl_UntraceVar2(interp, name1, name2, flags, proc, clientData)
ClientData
Tcl_VarTraceInfo(interp, varName, flags, proc, prevClientData)
ClientData
Tcl_VarTraceInfo2(interp, name1, name2, flags, proc, prevClientData)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter containing variable.

char *varName (in)
Name of variable. May refer to a scalar variable, to an array variable with no index, or to an array variable with a parenthesized index. If the name references an element of an array, then it must be in writable memory: Tcl will make temporary modifications to it while looking up the name.

int flags (in)
OR-ed combination of the values TCL_TRACE_READS, TCL_TRACE_WRITES, and TCL_TRACE_UNSETS, TCL_TRACE_ARRAY, and TCL_GLOBAL_ONLY. Not all flags are used by all procedures. See below for more information.

Tcl_VarTraceProc *proc (in)
Procedure to invoke whenever one of the traced operations occurs.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

char *name1 (in)
Name of scalar or array variable (without array index).

char *name2 (in)
For a trace on an element of an array, gives the index of the element. For traces on scalar variables or on whole arrays, is NULL.

ClientData prevClientData (in)
If non-NULL, gives last value returned by Tcl_VarTraceInfo or Tcl_VarTraceInfo2, so this call will return information about next trace. If NULL, this call will return information about first trace.

DESCRIPTION

Tcl_TraceVar allows a C procedure to monitor and control access to a Tcl variable, so that the C procedure is invoked whenever the variable is read or written or unset. If the trace is created successfully then Tcl_TraceVar returns TCL_OK. If an error occurred (e.g. varName specifies an element of an array, but the actual variable isn't an array) then TCL_ERROR is returned and an error message is left in the interpreter's result.

The flags argument to Tcl_TraceVar indicates when the trace procedure is to be invoked and provides information for setting up the trace. It consists of an OR-ed combination of any of the following values:

TCL_GLOBAL_ONLY
Normally, the variable will be looked up at the current level of procedure call; if this bit is set then the variable will be looked up at global level, ignoring any active procedures.

TCL_TRACE_READS
Invoke proc whenever an attempt is made to read the variable.

TCL_TRACE_WRITES
Invoke proc whenever an attempt is made to modify the variable.

TCL_TRACE_UNSETS
Invoke proc whenever the variable is unset. A variable may be unset either explicitly by an unset command, or implicitly when a procedure returns (its local variables are automatically unset) or when the interpreter is deleted (all variables are automatically unset).

TCL_TRACE_ARRAY
Invoke proc whenever the array command is invoked. This gives the trace procedure a chance to update the array before array names or array get is called. Note that this is called before an array set, but that will trigger write traces.

Whenever one of the specified operations occurs on the variable, proc will be invoked. It should have arguments and result that match the type Tcl_VarTraceProc:

typedef char *Tcl_VarTraceProc(
    ClientData clientData,
    Tcl_Interp *interp,
    char *name1,
    char *name2,
    int flags);
The clientData and interp parameters will have the same values as those passed to Tcl_TraceVar when the trace was created. ClientData typically points to an application-specific data structure that describes what to do when proc is invoked. Name1 and name2 give the name of the traced variable in the normal two-part form (see the description of Tcl_TraceVar2 below for details). Flags is an OR-ed combination of bits providing several pieces of information. One of the bits TCL_TRACE_READS, TCL_TRACE_WRITES, TCL_TRACE_ARRAY, or TCL_TRACE_UNSETS will be set in flags to indicate which operation is being performed on the variable. The bit TCL_GLOBAL_ONLY will be set whenever the variable being accessed is a global one not accessible from the current level of procedure call: the trace procedure will need to pass this flag back to variable-related procedures like Tcl_GetVar if it attempts to access the variable. The bit TCL_TRACE_DESTROYED will be set in flags if the trace is about to be destroyed; this information may be useful to proc so that it can clean up its own internal data structures (see the section TCL_TRACE_DESTROYED below for more details). Lastly, the bit TCL_INTERP_DESTROYED will be set if the entire interpreter is being destroyed. When this bit is set, proc must be especially careful in the things it does (see the section TCL_INTERP_DESTROYED below). The trace procedure's return value should normally be NULL; see ERROR RETURNS below for information on other possibilities.

Tcl_UntraceVar may be used to remove a trace. If the variable specified by interp, varName, and flags has a trace set with flags, proc, and clientData, then the corresponding trace is removed. If no such trace exists, then the call to Tcl_UntraceVar has no effect. The same bits are valid for flags as for calls to Tcl_TraceVar.

Tcl_VarTraceInfo may be used to retrieve information about traces set on a given variable. The return value from Tcl_VarTraceInfo is the clientData associated with a particular trace. The trace must be on the variable specified by the interp, varName, and flags arguments (only the TCL_GLOBAL_ONLY bit from flags is used; other bits are ignored) and its trace procedure must the same as the proc argument. If the prevClientData argument is NULL then the return value corresponds to the first (most recently created) matching trace, or NULL if there are no matching traces. If the prevClientData argument isn't NULL, then it should be the return value from a previous call to Tcl_VarTraceInfo. In this case, the new return value will correspond to the next matching trace after the one whose clientData matches prevClientData, or NULL if no trace matches prevClientData or if there are no more matching traces after it. This mechanism makes it possible to step through all of the traces for a given variable that have the same proc.

TWO-PART NAMES

The procedures Tcl_TraceVar2, Tcl_UntraceVar2, and Tcl_VarTraceInfo2 are identical to Tcl_TraceVar, Tcl_UntraceVar, and Tcl_VarTraceInfo, respectively, except that the name of the variable consists of two parts. Name1 gives the name of a scalar variable or array, and name2 gives the name of an element within an array. When name2 is NULL, name1 may contain both an array and an element name: if the name contains an open parenthesis and ends with a close parenthesis, then the value between the parentheses is treated as an element name (which can have any string value) and the characters before the first open parenthesis are treated as the name of an array variable. If name2 is NULL and name1 does not refer to an array element it means that either the variable is a scalar or the trace is to be set on the entire array rather than an individual element (see WHOLE-ARRAY TRACES below for more information).

ACCESSING VARIABLES DURING TRACES

During read, write, and array traces, the trace procedure can read, write, or unset the traced variable using Tcl_GetVar2, Tcl_SetVar2, and other procedures. While proc is executing, traces are temporarily disabled for the variable, so that calls to Tcl_GetVar2 and Tcl_SetVar2 will not cause proc or other trace procedures to be invoked again. Disabling only occurs for the variable whose trace procedure is active; accesses to other variables will still be traced. However, if a variable is unset during a read or write trace then unset traces will be invoked.

During unset traces the variable has already been completely expunged. It is possible for the trace procedure to read or write the variable, but this will be a new version of the variable. Traces are not disabled during unset traces as they are for read and write traces, but existing traces have been removed from the variable before any trace procedures are invoked. If new traces are set by unset trace procedures, these traces will be invoked on accesses to the variable by the trace procedures.

CALLBACK TIMING

When read tracing has been specified for a variable, the trace procedure will be invoked whenever the variable's value is read. This includes set Tcl commands, $-notation in Tcl commands, and invocations of the Tcl_GetVar and Tcl_GetVar2 procedures. Proc is invoked just before the variable's value is returned. It may modify the value of the variable to affect what is returned by the traced access. If it unsets the variable then the access will return an error just as if the variable never existed.

When write tracing has been specified for a variable, the trace procedure will be invoked whenever the variable's value is modified. This includes set commands, commands that modify variables as side effects (such as catch and scan), and calls to the Tcl_SetVar and Tcl_SetVar2 procedures). Proc will be invoked after the variable's value has been modified, but before the new value of the variable has been returned. It may modify the value of the variable to override the change and to determine the value actually returned by the traced access. If it deletes the variable then the traced access will return an empty string.

When array tracing has been specified, the trace procedure will be invoked at the beginning of the array command implementation, before any of the operations like get, set, or names have been invoked. The trace procedure can modify the array elements with Tcl_SetVar and Tcl_SetVar2.

When unset tracing has been specified, the trace procedure will be invoked whenever the variable is destroyed. The traces will be called after the variable has been completely unset.

WHOLE-ARRAY TRACES

If a call to Tcl_TraceVar or Tcl_TraceVar2 specifies the name of an array variable without an index into the array, then the trace will be set on the array as a whole. This means that proc will be invoked whenever any element of the array is accessed in the ways specified by flags. When an array is unset, a whole-array trace will be invoked just once, with name1 equal to the name of the array and name2 NULL; it will not be invoked once for each element.

MULTIPLE TRACES

It is possible for multiple traces to exist on the same variable. When this happens, all of the trace procedures will be invoked on each access, in order from most-recently-created to least-recently-created. When there exist whole-array traces for an array as well as traces on individual elements, the whole-array traces are invoked before the individual-element traces. If a read or write trace unsets the variable then all of the unset traces will be invoked but the remainder of the read and write traces will be skipped.

ERROR RETURNS

Under normal conditions trace procedures should return NULL, indicating successful completion. If proc returns a non-NULL value it signifies that an error occurred. The return value must be a pointer to a static character string containing an error message. If a trace procedure returns an error, no further traces are invoked for the access and the traced access aborts with the given message. Trace procedures can use this facility to make variables read-only, for example (but note that the value of the variable will already have been modified before the trace procedure is called, so the trace procedure will have to restore the correct value).

The return value from proc is only used during read and write tracing. During unset traces, the return value is ignored and all relevant trace procedures will always be invoked.

RESTRICTIONS

A trace procedure can be called at any time, even when there is a partially-formed result in the interpreter's result area. If the trace procedure does anything that could damage this result (such as calling Tcl_Eval) then it must save the original values of the interpreter's result and freeProc fields and restore them before it returns.

UNDEFINED VARIABLES

It is legal to set a trace on an undefined variable. The variable will still appear to be undefined until the first time its value is set. If an undefined variable is traced and then unset, the unset will fail with an error (``no such variable''), but the trace procedure will still be invoked.

TCL_TRACE_DESTROYED FLAG

In an unset callback to proc, the TCL_TRACE_DESTROYED bit is set in flags if the trace is being removed as part of the deletion. Traces on a variable are always removed whenever the variable is deleted; the only time TCL_TRACE_DESTROYED isn't set is for a whole-array trace invoked when only a single element of an array is unset.

TCL_INTERP_DESTROYED

When an interpreter is destroyed, unset traces are called for all of its variables. The TCL_INTERP_DESTROYED bit will be set in the flags argument passed to the trace procedures. Trace procedures must be extremely careful in what they do if the TCL_INTERP_DESTROYED bit is set. It is not safe for the procedures to invoke any Tcl procedures on the interpreter, since its state is partially deleted. All that trace procedures should do under these circumstances is to clean up and free their own internal data structures.

BUGS

Tcl doesn't do any error checking to prevent trace procedures from misusing the interpreter during traces with TCL_INTERP_DESTROYED set.

Array traces are not yet integrated with the Tcl "info exists" command, nor is there Tcl-level access to array traces.

KEYWORDS

clientData, trace, variable
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_TranslateFileName manual page

NAME

Tcl_TranslateFileName - convert file name to native form and replace tilde with home directory

SYNOPSIS

#include <tcl.h>
char *
Tcl_TranslateFileName(interp, name, bufferPtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which to report an error, if any.

char *name (in)
File name, which may start with a ``~''.

Tcl_DString *bufferPtr (in/out)
If needed, this dynamic string is used to store the new file name. At the time of the call it should be uninitialized or free. The caller must eventually call Tcl_DStringFree to free up anything stored here.

DESCRIPTION

This utility procedure translates a file name to a form suitable for passing to the local operating system. It converts network names into native form and does tilde substitution.

If Tcl_TranslateFileName has to do tilde substitution or translate the name then it uses the dynamic string at *bufferPtr to hold the new string it generates. After Tcl_TranslateFileName returns a non-NULL result, the caller must eventually invoke Tcl_DStringFree to free any information placed in *bufferPtr. The caller need not know whether or not Tcl_TranslateFileName actually used the string; Tcl_TranslateFileName initializes *bufferPtr even if it doesn't use it, so the call to Tcl_DStringFree will be safe in either case.

If an error occurs (e.g. because there was no user by the given name) then NULL is returned and an error message will be left in the interpreter's result. When an error occurs, Tcl_TranslateFileName frees the dynamic string itself so that the caller need not call Tcl_DStringFree.

The caller is responsible for making sure that the interpreter's result has its default empty value when Tcl_TranslateFileName is invoked.

SEE ALSO

filename

KEYWORDS

file name, home directory, tilde, translate, user
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1998 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_UpVar manual page

NAME

Tcl_UpVar, Tcl_UpVar2 - link one variable to another

SYNOPSIS

#include <tcl.h>
int
Tcl_UpVar(interp, frameName, sourceName, destName, flags)
int
Tcl_UpVar2(interp, frameName, name1, name2, destName, flags)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter containing variables; also used for error reporting.

char *frameName (in)
Identifies the stack frame containing source variable. May have any of the forms accepted by the upvar command, such as #0 or 1.

char *sourceName (in)
Name of source variable, in the frame given by frameName. May refer to a scalar variable or to an array variable with a parenthesized index.

char *destName (in)
Name of destination variable, which is to be linked to source variable so that references to destName refer to the other variable. Must not currently exist except as an upvar-ed variable.

int flags (in)
Either TCL_GLOBAL_ONLY or 0; if non-zero, then destName is a global variable; otherwise it is a local to the current procedure (or global if no procedure is active).

char *name1 (in)
First part of source variable's name (scalar name, or name of array without array index).

char *name2 (in)
If source variable is an element of an array, gives the index of the element. For scalar source variables, is NULL.

DESCRIPTION

Tcl_UpVar and Tcl_UpVar2 provide the same functionality as the upvar command: they make a link from a source variable to a destination variable, so that references to the destination are passed transparently through to the source. The name of the source variable may be specified either as a single string such as xyx or a(24) (by calling Tcl_UpVar) or in two parts where the array name has been separated from the element name (by calling Tcl_UpVar2). The destination variable name is specified in a single string; it may not be an array element.

Both procedures return either TCL_OK or TCL_ERROR, and they leave an error message in the interpreter's result if an error occurs.

As with the upvar command, the source variable need not exist; if it does exist, unsetting it later does not destroy the link. The destination variable may exist at the time of the call, but if so it must exist as a linked variable.

KEYWORDS

linked variable, upvar, variable
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tcl Library Procedures - Utf manual page

NAME

Tcl_UniChar, Tcl_UniCharToUtf, Tcl_UtfToUniChar, Tcl_UniCharToUtfDString, Tcl_UtfToUniCharDString, Tcl_UniCharLen, Tcl_UniCharNcmp, Tcl_UtfCharComplete, Tcl_NumUtfChars, Tcl_UtfFindFirst, Tcl_UtfFindLast, Tcl_UtfNext, Tcl_UtfPrev, Tcl_UniCharAtIndex, Tcl_UtfAtIndex, Tcl_UtfBackslash - routines for manipulating UTF-8 strings.

SYNOPSIS

#include <tcl.h>
typedef ... Tcl_UniChar;
int
Tcl_UniCharToUtf(ch, buf)
int
Tcl_UtfToUniChar(src, chPtr)
char *
Tcl_UniCharToUtfDString(uniStr, numChars, dstPtr)
Tcl_UniChar *
Tcl_UtfToUniCharDString(src, len, dstPtr)
int
Tcl_UniCharLen(uniStr)
int
Tcl_UniCharNcmp(uniStr, uniStr, num)
int
Tcl_UtfNcmp(src, src, num)
int
Tcl_UtfNcasecmp(src, src, num)
int
Tcl_UtfCharComplete(src, len)
int
Tcl_NumUtfChars(src, len)
char *
Tcl_UtfFindFirst(src, ch)
char *
Tcl_UtfFindLast(src, ch)
char *
Tcl_UtfNext(src)
char *
Tcl_UtfPrev(src, start)
Tcl_UniChar
Tcl_UniCharAtIndex(src, index)
char *
Tcl_UtfAtIndex(src, index)
int
Tcl_UtfBackslash(src, readPtr, dst)

ARGUMENTS

char *buf (out)
Buffer in which the UTF-8 representation of the Tcl_UniChar is stored. At most TCL_UTF_MAX bytes are stored in the buffer.

int ch (in)
The Tcl_UniChar to be converted or examined.

Tcl_UniChar *chPtr (out)
Filled with the Tcl_UniChar represented by the head of the UTF-8 string.

CONST char *src (in)
Pointer to a UTF-8 string.

CONST Tcl_UniChar *uniStr (in)
A NULL-terminated Unicode string.

int len (in)
The length of the UTF-8 string in bytes (not UTF-8 characters). If negative, all bytes up to the first null byte are used.

int numChars (in)
The length of the Unicode string in characters. Must be greater than or equal to 0.

Tcl_DString *dstPtr (in/out)
A pointer to a previously-initialized Tcl_DString.

unsigned long num (in)
The number of characters to compare.

CONST char *start (in)
Pointer to the beginning of a UTF-8 string.

int index (in)
The index of a character (not byte) in the UTF-8 string.

int *readPtr (out)
If non-NULL, filled with the number of bytes in the backslash sequence, including the backslash character.

char *dst (out)
Buffer in which the bytes represented by the backslash sequence are stored. At most TCL_UTF_MAX bytes are stored in the buffer.

DESCRIPTION

These routines convert between UTF-8 strings and Tcl_UniChars. A Tcl_UniChar is a Unicode character represented as an unsigned, fixed-size quantity. A UTF-8 character is a Unicode character represented as a varying-length sequence of up to TCL_UTF_MAX bytes. A multibyte UTF-8 sequence consists of a lead byte followed by some number of trail bytes.

TCL_UTF_MAX is the maximum number of bytes that it takes to represent one Unicode character in the UTF-8 representation.

Tcl_UniCharToUtf stores the Tcl_UniChar ch as a UTF-8 string in starting at buf. The return value is the number of bytes stored in buf.

Tcl_UtfToUniChar reads one UTF-8 character starting at src and stores it as a Tcl_UniChar in *chPtr. The return value is the number of bytes read from src.. The caller must ensure that the source buffer is long enough such that this routine does not run off the end and dereference non-existent or random memory; if the source buffer is known to be null terminated, this will not happen. If the input is not in proper UTF-8 format, Tcl_UtfToUniChar will store the first byte of src in *chPtr as a Tcl_UniChar between 0x0000 and 0x00ff and return 1.

Tcl_UniCharToUtfDString converts the given Unicode string to UTF-8, storing the result in a previously-initialized Tcl_DString. You must specify the length of the given Unicode string. The return value is a pointer to the UTF-8 representation of the Unicode string. Storage for the return value is appended to the end of the Tcl_DString.

Tcl_UtfToUniCharDString coverts the given UTF-8 string to Unicode, storing the result in the previously-initialized Tcl_Dstring. you may either specify the length of the given UTF-8 string or "-1", in which case Tcl_UtfToUniCharDString uses strlen to calculate the length. The return value is a pointer to the Unicode representation of the UTF-8 string. Storage for the return value is appended to the end of the Tcl_DString. The Unicode string is terminated with a Unicode NULL character.

Tcl_UniCharLen corresponds to strlen for Unicode characters. It accepts a NULL-terminated Unicode string and returns the number of Unicode characters (not bytes) in that string.

Tcl_UniCharNcmp corresponds to strncmp for Unicode characters. It accepts two NULL-terminated Unicode strings and the number of characters to compare. (Both strings are assumed to be at least len characters long.) Tcl_UniCharNcmp compares the two strings character-by-character according to the Unicode character ordering. It returns an integer greater than, equal to, or less than 0 if the first string is greater than, equal to, or less than the second string respectively.

Tcl_UtfNcmp corresponds to strncmp for UTF-8 strings. It accepts two NULL-terminated UTF-8 strings and the number of characters to compare. (Both strings are assumed to be at least len characters long.) Tcl_UtfNcmp compares the two strings character-by-character according to the Unicode character ordering. It returns an integer greater than, equal to, or less than 0 if the first string is greater than, equal to, or less than the second string respectively.

Tcl_UtfNcasecmp corresponds to strncasecmp for UTF-8 strings. It is similar to Tcl_UtfNcmp except comparisons ignore differences in case when comparing upper, lower or title case characters.

Tcl_UtfCharComplete returns 1 if the source UTF-8 string src of length len bytes is long enough to be decoded by Tcl_UtfToUniChar, or 0 otherwise. This function does not guarantee that the UTF-8 string is properly formed. This routine is used by procedures that are operating on a byte at a time and need to know if a full Tcl_UniChar has been seen.

Tcl_NumUtfChars corresponds to strlen for UTF-8 strings. It returns the number of Tcl_UniChars that are represented by the UTF-8 string src. The length of the source string is len bytes. If the length is negative, all bytes up to the first NULL byte are used.

Tcl_UtfFindFirst corresponds to strchr for UTF-8 strings. It returns a pointer to the first occurance of the Tcl_UniChar ch in the NULL-terminated UTF-8 string src. The NULL terminator is considered part of the UTF-8 string.

Tcl_UtfFindLast corresponds to strrchr for UTF-8 strings. It returns a pointer to the last occurance of the Tcl_UniChar ch in the NULL terminated UTF-8 string src. The NULL terminator is considered part of the UTF-8 string.

Given src, a pointer to some location in a UTF-8 string, Tcl_UtfNext returns a pointer to the next UTF-8 character in the string. The caller must not ask for the next character after the last character in the string.

Given src, a pointer to some location in a UTF-8 string, Tcl_UtfPrev returns a pointer to the previous UTF-8 character in the string. This function will not back up to a position before start, the start of the UTF-8 string. If src was already at start, the return value will be start.

Tcl_UniCharAtIndex corresponds to a C string array dereference or the Pascal Ord() function. It returns the Tcl_UniChar represented at the specified character (not byte) index in the UTF-8 string src. The source string must contain at least index characters. Behavior is undefined if a negative index is given.

Tcl_UtfAtIndex returns a pointer to the specified character (not byte) index in the UTF-8 string src. The source string must contain at least index characters. This is equivalent to calling Tcl_UtfNext index times. If a negative index is given, the return pointer points to the first character in the source string.

Tcl_UtfBackslash is a utility procedure used by several of the Tcl commands. It parses a backslash sequence and stores the properly formed UTF-8 character represented by the backslash sequence in the output buffer dst. At most TCL_UTF_MAX bytes are stored in the buffer. Tcl_UtfBackslash modifies *readPtr to contain the number of bytes in the backslash sequence, including the backslash character. The return value is the number of bytes stored in the output buffer.

See the Tcl manual entry for information on the valid backslash sequences. All of the sequences described in the Tcl manual entry are supported by Tcl_UtfBackslash.

KEYWORDS

utf, unicode, backslash
Copyright © 1997 Sun Microsystems, Inc.


Tcl Library Procedures - Tcl_WrongNumArgs manual page

NAME

Tcl_WrongNumArgs - generate standard error message for wrong number of arguments

SYNOPSIS

#include <tcl.h>
Tcl_WrongNumArgs(interp, objc, objv, message)

ARGUMENTS

Tcl_Interp interp (in)
Interpreter in which error will be reported: error message gets stored in its result object.

int objc (in)
Number of leading arguments from objv to include in error message.

Tcl_Obj *CONST objv[] (in)
Arguments to command that had the wrong number of arguments.

char *message (in)
Additional error information to print after leading arguments from objv. This typically gives the acceptable syntax of the command. This argument may be NULL.

DESCRIPTION

Tcl_WrongNumArgs is a utility procedure that is invoked by command procedures when they discover that they have received the wrong number of arguments. Tcl_WrongNumArgs generates a standard error message and stores it in the result object of interp. The message includes the objc initial elements of objv plus message. For example, if objv consists of the values foo and bar, objc is 1, and message is ``fileName count'' then interp's result object will be set to the following string:
wrong # args: should be "foo fileName count"
If objc is 2, the result will be set to the following string:
wrong # args: should be "foo bar fileName count"
Objc is usually 1, but may be 2 or more for commands like string and the Tk widget commands, which use the first argument as a subcommand.

Some of the objects in the objv array may be abbreviations for a subcommand. The command Tcl_GetIndexFromObj will convert the abbreviated string object into an indexObject. If an error occurs in the parsing of the subcommand we would like to use the full subcommand name rather than the abbreviation. If the Tcl_WrongNumArgs command finds any indexObjects in the objv array it will use the full subcommand name in the error message instead of the abbreviated name that was origionally passed in. Using the above example, lets assume that bar is actually an abbreviation for barfly and the object is now an indexObject becasue it was passed to Tcl_GetIndexFromObj. In this case the error message would be:

wrong # args: should be "foo barfly fileName count"

SEE ALSO

Tcl_GetIndexFromObj

KEYWORDS

command, error message, wrong number of arguments
Copyright © 1994-1997 Sun Microsystems, Inc.


Tk Built-In Commands - bell manual page

NAME

bell - Ring a display's bell

SYNOPSIS

bell ?-displayof window?

DESCRIPTION

This command rings the bell on the display for window and returns an empty string. If the -displayof option is omitted, the display of the application's main window is used by default. The command uses the current bell-related settings for the display, which may be modified with programs such as xset.

This command also resets the screen saver for the screen. Some screen savers will ignore this, but others will reset so that the screen becomes visible again.

KEYWORDS

beep, bell, ring
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - bind manual page

NAME
bind - Arrange for X events to invoke Tcl scripts
SYNOPSIS
bind tag
bind tag sequence
bind tag sequence script
bind tag sequence +script
INTRODUCTION
EVENT PATTERNS
MODIFIERS
EVENT TYPES
Activate
Deactivate
MouseWheel
BINDING SCRIPTS AND SUBSTITUTIONS
%%
%#
%a
%b
%c
%d
%f
%h
%k
%m
%o
%p
%s
%t
%w
%x
%y
%A
%B
%D
%E
%K
%N
%R
%S
%T
%W
%X
%Y
MULTIPLE MATCHES
MULTI-EVENT SEQUENCES AND IGNORED EVENTS
ERRORS
SEE ALSO
KEYWORDS

NAME

bind - Arrange for X events to invoke Tcl scripts

SYNOPSIS

bind tag
bind tag sequence
bind tag sequence script
bind tag sequence +script

INTRODUCTION

The bind command associates Tcl scripts with X events. If all three arguments are specified, bind will arrange for script (a Tcl script) to be evaluated whenever the event(s) given by sequence occur in the window(s) identified by tag. If script is prefixed with a ``+'', then it is appended to any existing binding for sequence; otherwise script replaces any existing binding. If script is an empty string then the current binding for sequence is destroyed, leaving sequence unbound. In all of the cases where a script argument is provided, bind returns an empty string.

If sequence is specified without a script, then the script currently bound to sequence is returned, or an empty string is returned if there is no binding for sequence. If neither sequence nor script is specified, then the return value is a list whose elements are all the sequences for which there exist bindings for tag.

The tag argument determines which window(s) the binding applies to. If tag begins with a dot, as in .a.b.c, then it must be the path name for a window; otherwise it may be an arbitrary string. Each window has an associated list of tags, and a binding applies to a particular window if its tag is among those specified for the window. Although the bindtags command may be used to assign an arbitrary set of binding tags to a window, the default binding tags provide the following behavior:

If a tag is the name of an internal window the binding applies to that window.

If the tag is the name of a toplevel window the binding applies to the toplevel window and all its internal windows.

If the tag is the name of a class of widgets, such as Button, the binding applies to all widgets in that class;

If tag has the value all, the binding applies to all windows in the application.

EVENT PATTERNS

The sequence argument specifies a sequence of one or more event patterns, with optional white space between the patterns. Each event pattern may take one of three forms. In the simplest case it is a single printing ASCII character, such as a or [. The character may not be a space character or the character <. This form of pattern matches a KeyPress event for the particular character. The second form of pattern is longer but more general. It has the following syntax:
<modifier-modifier-type-detail>
The entire event pattern is surrounded by angle brackets. Inside the angle brackets are zero or more modifiers, an event type, and an extra piece of information (detail) identifying a particular button or keysym. Any of the fields may be omitted, as long as at least one of type and detail is present. The fields must be separated by white space or dashes.

The third form of pattern is used to specify a user-defined, named virtual event. It has the following syntax:

<<name>>
The entire virtual event pattern is surrounded by double angle brackets. Inside the angle brackets is the user-defined name of the virtual event. Modifiers, such as Shift or Control, may not be combined with a virtual event to modify it. Bindings on a virtual event may be created before the virtual event is defined, and if the definition of a virtual event changes dynamically, all windows bound to that virtual event will respond immediately to the new definition.

MODIFIERS

Modifiers consist of any of the following values:
Control	Mod2, M2
Shift	Mod3, M3
Lock	Mod4, M4
Button1, B1	Mod5, M5
Button2, B2	Meta, M
Button3, B3	Alt
Button4, B4	Double
Button5, B5	Triple
Mod1, M1	Quadruple
Where more than one value is listed, separated by commas, the values are equivalent. Most of the modifiers have the obvious X meanings. For example, Button1 requires that button 1 be depressed when the event occurs. For a binding to match a given event, the modifiers in the event must include all of those specified in the event pattern. An event may also contain additional modifiers not specified in the binding. For example, if button 1 is pressed while the shift and control keys are down, the pattern <Control-Button-1> will match the event, but <Mod1-Button-1> will not. If no modifiers are specified, then any combination of modifiers may be present in the event.

Meta and M refer to whichever of the M1 through M5 modifiers is associated with the meta key(s) on the keyboard (keysyms Meta_R and Meta_L). If there are no meta keys, or if they are not associated with any modifiers, then Meta and M will not match any events. Similarly, the Alt modifier refers to whichever modifier is associated with the alt key(s) on the keyboard (keysyms Alt_L and Alt_R).

The Double, Triple and Quadruple modifiers are a convenience for specifying double mouse clicks and other repeated events. They cause a particular event pattern to be repeated 2, 3 or 4 times, and also place a time and space requirement on the sequence: for a sequence of events to match a Double, Triple or Quadruple pattern, all of the events must occur close together in time and without substantial mouse motion in between. For example, <Double-Button-1> is equivalent to <Button-1><Button-1> with the extra time and space requirement.

EVENT TYPES

The type field may be any of the standard X event types, with a few extra abbreviations. The type field will also accept a couple non-standard X event types that were added to better support the Macintosh and Windows platforms. Below is a list of all the valid types; where two names appear together, they are synonyms.
Activate	Enter	Map
ButtonPress, Button	Expose	Motion
ButtonRelease	FocusIn	MouseWheel
Circulate	FocusOut	Property
Colormap	Gravity	Reparent
Configure	KeyPress, Key	Unmap
Deactivate	KeyRelease	Visibility
Destroy	Leave

Most of the above events have the same fields and behaviors as events in the X Windowing system. You can find more detailed descriptions of these events in any X window programming book. A couple of the events are extensions to the X event system to support features unique to the Macintosh and Windows platforms. We provide a little more detail on these events here. These include:

Activate

Deactivate
These two events are sent to every sub-window of a toplevel when they change state. In addition to the focus Window, the Macintosh platform and Windows platforms have a notion of an active window (which often has but is not required to have the focus). On the Macintosh, widgets in the active window have a different appearance than widgets in deactive windows. The Activate event is sent to all the sub-windows in a toplevel when it changes from being deactive to active. Likewise, the Deactive event is sent when the window's state changes from active to deactive. There are no useful percent substitutions you would make when binding to these events.

MouseWheel
Some mice on the Windows platform support a mouse wheel which is used for scrolling documents without using the scrollbars. By rolling the wheel, the system will generate MouseWheel events that the application can use to scroll. Like Key events the event is always routed to the window that currently has focus. When the event is received you can use the %D substitution to get the delta field for the event which is a integer value of motion that the mouse wheel has moved. The smallest value for which the system will report is defined by the OS. On Windows 95 & 98 machines this value is at least 120 before it is reported. However, higher resolution devices may be available in the future. The sign of the value determines which direction your widget should scroll. Positive values should scroll up and negative values should scroll down.

The last part of a long event specification is detail. In the case of a ButtonPress or ButtonRelease event, it is the number of a button (1-5). If a button number is given, then only an event on that particular button will match; if no button number is given, then an event on any button will match. Note: giving a specific button number is different than specifying a button modifier; in the first case, it refers to a button being pressed or released, while in the second it refers to some other button that is already depressed when the matching event occurs. If a button number is given then type may be omitted: if will default to ButtonPress. For example, the specifier <1> is equivalent to <ButtonPress-1>.

If the event type is KeyPress or KeyRelease, then detail may be specified in the form of an X keysym. Keysyms are textual specifications for particular keys on the keyboard; they include all the alphanumeric ASCII characters (e.g. ``a'' is the keysym for the ASCII character ``a''), plus descriptions for non-alphanumeric characters (``comma'' is the keysym for the comma character), plus descriptions for all the non-ASCII keys on the keyboard (``Shift_L'' is the keysm for the left shift key, and ``F1'' is the keysym for the F1 function key, if it exists). The complete list of keysyms is not presented here; it is available in other X documentation and may vary from system to system. If necessary, you can use the %K notation described below to print out the keysym name for a particular key. If a keysym detail is given, then the type field may be omitted; it will default to KeyPress. For example, <Control-comma> is equivalent to <Control-KeyPress-comma>.

BINDING SCRIPTS AND SUBSTITUTIONS

The script argument to bind is a Tcl script, which will be executed whenever the given event sequence occurs. Command will be executed in the same interpreter that the bind command was executed in, and it will run at global level (only global variables will be accessible). If script contains any % characters, then the script will not be executed directly. Instead, a new script will be generated by replacing each %, and the character following it, with information from the current event. The replacement depends on the character following the %, as defined in the list below. Unless otherwise indicated, the replacement string is the decimal value of the given field from the current event. Some of the substitutions are only valid for certain types of events; if they are used for other types of events the value substituted is undefined.

%%
Replaced with a single percent.

%#
The number of the last client request processed by the server (the serial field from the event). Valid for all event types.

%a
The above field from the event, formatted as a hexadecimal number. Valid only for Configure events.

%b
The number of the button that was pressed or released. Valid only for ButtonPress and ButtonRelease events.

%c
The count field from the event. Valid only for Expose events.

%d
The detail field from the event. The %d is replaced by a string identifying the detail. For Enter, Leave, FocusIn, and FocusOut events, the string will be one of the following:
NotifyAncestor	NotifyNonlinearVirtual
NotifyDetailNone	NotifyPointer
NotifyInferior	NotifyPointerRoot
NotifyNonlinear	NotifyVirtual
For events other than these, the substituted string is undefined.

%f
The focus field from the event (0 or 1). Valid only for Enter and Leave events.

%h
The height field from the event. Valid for the Configure and Expose events.

%k
The keycode field from the event. Valid only for KeyPress and KeyRelease events.

%m
The mode field from the event. The substituted string is one of NotifyNormal, NotifyGrab, NotifyUngrab, or NotifyWhileGrabbed. Valid only for Enter, FocusIn, FocusOut, and Leave events.

%o
The override_redirect field from the event. Valid only for Map, Reparent, and Configure events.

%p
The place field from the event, substituted as one of the strings PlaceOnTop or PlaceOnBottom. Valid only for Circulate events.

%s
The state field from the event. For ButtonPress, ButtonRelease, Enter, KeyPress, KeyRelease, Leave, and Motion events, a decimal string is substituted. For Visibility, one of the strings VisibilityUnobscured, VisibilityPartiallyObscured, and VisibilityFullyObscured is substituted.

%t
The time field from the event. Valid only for events that contain a time field.

%w
The width field from the event. Valid only for Configure and Expose events.

%x
The x field from the event. Valid only for events containing an x field.

%y
The y field from the event. Valid only for events containing a y field.

%A
Substitutes the ASCII character corresponding to the event, or the empty string if the event doesn't correspond to an ASCII character (e.g. the shift key was pressed). XLookupString does all the work of translating from the event to an ASCII character. Valid only for KeyPress and KeyRelease events.

%B
The border_width field from the event. Valid only for Configure events.

%D
This reports the delta value of a MouseWheel event. The delta value represents the rotation units the mouse wheel has been moved. On Windows 95 & 98 systems the smallest value for the delta is 120. Future systems may support higher resolution values for the delta. The sign of the value represents the direction the mouse wheel was scrolled.

%E
The send_event field from the event. Valid for all event types.

%K
The keysym corresponding to the event, substituted as a textual string. Valid only for KeyPress and KeyRelease events.

%N
The keysym corresponding to the event, substituted as a decimal number. Valid only for KeyPress and KeyRelease events.

%R
The root window identifier from the event. Valid only for events containing a root field.

%S
The subwindow window identifier from the event, formatted as a hexadecimal number. Valid only for events containing a subwindow field.

%T
The type field from the event. Valid for all event types.

%W
The path name of the window to which the event was reported (the window field from the event). Valid for all event types.

%X
The x_root field from the event. If a virtual-root window manager is being used then the substituted value is the corresponding x-coordinate in the virtual root. Valid only for ButtonPress, ButtonRelease, KeyPress, KeyRelease, and Motion events.

%Y
The y_root field from the event. If a virtual-root window manager is being used then the substituted value is the corresponding y-coordinate in the virtual root. Valid only for ButtonPress, ButtonRelease, KeyPress, KeyRelease, and Motion events.

The replacement string for a %-replacement is formatted as a proper Tcl list element. This means that it will be surrounded with braces if it contains spaces, or special characters such as $ and { may be preceded by backslashes. This guarantees that the string will be passed through the Tcl parser when the binding script is evaluated. Most replacements are numbers or well-defined strings such as Above; for these replacements no special formatting is ever necessary. The most common case where reformatting occurs is for the %A substitution. For example, if script is

insert %A
and the character typed is an open square bracket, then the script actually executed will be
insert \[
This will cause the insert to receive the original replacement string (open square bracket) as its first argument. If the extra backslash hadn't been added, Tcl would not have been able to parse the script correctly.

MULTIPLE MATCHES

It is possible for several bindings to match a given X event. If the bindings are associated with different tag's, then each of the bindings will be executed, in order. By default, a binding for the widget will be executed first, followed by a class binding, a binding for its toplevel, and an all binding. The bindtags command may be used to change this order for a particular window or to associate additional binding tags with the window.

The continue and break commands may be used inside a binding script to control the processing of matching scripts. If continue is invoked, then the current binding script is terminated but Tk will continue processing binding scripts associated with other tag's. If the break command is invoked within a binding script, then that script terminates and no other scripts will be invoked for the event.

If more than one binding matches a particular event and they have the same tag, then the most specific binding is chosen and its script is evaluated. The following tests are applied, in order, to determine which of several matching sequences is more specific: (a) an event pattern that specifies a specific button or key is more specific than one that doesn't; (b) a longer sequence (in terms of number of events matched) is more specific than a shorter sequence; (c) if the modifiers specified in one pattern are a subset of the modifiers in another pattern, then the pattern with more modifiers is more specific. (d) a virtual event whose physical pattern matches the sequence is less specific than the same physical pattern that is not associated with a virtual event. (e) given a sequence that matches two or more virtual events, one of the virtual events will be chosen, but the order is undefined.

If the matching sequences contain more than one event, then tests (c)-(e) are applied in order from the most recent event to the least recent event in the sequences. If these tests fail to determine a winner, then the most recently registered sequence is the winner.

If there are two (or more) virtual events that are both triggered by the same sequence, and both of those virtual events are bound to the same window tag, then only one of the virtual events will be triggered, and it will be picked at random:

event add <<Paste>> <Control-y>
event add <<Paste>> <Button-2>
event add <<Scroll>> <Button-2>
bind Entry <<Paste>> {puts Paste}
bind Entry <<Scroll>> {puts Scroll}
If the user types Control-y, the <<Paste>> binding will be invoked, but if the user presses button 2 then one of either the <<Paste>> or the <<Scroll>> bindings will be invoked, but exactly which one gets invoked is undefined.

If an X event does not match any of the existing bindings, then the event is ignored. An unbound event is not considered to be an error.

MULTI-EVENT SEQUENCES AND IGNORED EVENTS

When a sequence specified in a bind command contains more than one event pattern, then its script is executed whenever the recent events (leading up to and including the current event) match the given sequence. This means, for example, that if button 1 is clicked repeatedly the sequence <Double-ButtonPress-1> will match each button press but the first. If extraneous events that would prevent a match occur in the middle of an event sequence then the extraneous events are ignored unless they are KeyPress or ButtonPress events. For example, <Double-ButtonPress-1> will match a sequence of presses of button 1, even though there will be ButtonRelease events (and possibly Motion events) between the ButtonPress events. Furthermore, a KeyPress event may be preceded by any number of other KeyPress events for modifier keys without the modifier keys preventing a match. For example, the event sequence aB will match a press of the a key, a release of the a key, a press of the Shift key, and a press of the b key: the press of Shift is ignored because it is a modifier key. Finally, if several Motion events occur in a row, only the last one is used for purposes of matching binding sequences.

ERRORS

If an error occurs in executing the script for a binding then the bgerror mechanism is used to report the error. The bgerror command will be executed at global level (outside the context of any Tcl procedure).

SEE ALSO

bgerror, keysyms

KEYWORDS

form, manual
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
Copyright © 1998 by Scriptics Corporation.


Tk Built-In Commands - bindtags manual page

NAME

bindtags - Determine which bindings apply to a window, and order of evaluation

SYNOPSIS

bindtags window ?tagList?

DESCRIPTION

When a binding is created with the bind command, it is associated either with a particular window such as .a.b.c, a class name such as Button, the keyword all, or any other string. All of these forms are called binding tags. Each window contains a list of binding tags that determine how events are processed for the window. When an event occurs in a window, it is applied to each of the window's tags in order: for each tag, the most specific binding that matches the given tag and event is executed. See the bind command for more information on the matching process.

By default, each window has four binding tags consisting of the name of the window, the window's class name, the name of the window's nearest toplevel ancestor, and all, in that order. Toplevel windows have only three tags by default, since the toplevel name is the same as that of the window. The bindtags command allows the binding tags for a window to be read and modified.

If bindtags is invoked with only one argument, then the current set of binding tags for window is returned as a list. If the tagList argument is specified to bindtags, then it must be a proper list; the tags for window are changed to the elements of the list. The elements of tagList may be arbitrary strings; however, any tag starting with a dot is treated as the name of a window; if no window by that name exists at the time an event is processed, then the tag is ignored for that event. The order of the elements in tagList determines the order in which binding scripts are executed in response to events. For example, the command

bindtags .b {all . Button .b}
reverses the order in which binding scripts will be evaluated for a button named .b so that all bindings are invoked first, following by bindings for .b's toplevel (``.''), followed by class bindings, followed by bindings for .b. If tagList is an empty list then the binding tags for window are returned to the default state described above.

The bindtags command may be used to introduce arbitrary additional binding tags for a window, or to remove standard tags. For example, the command

bindtags .b {.b TrickyButton . all}
replaces the Button tag for .b with TrickyButton. This means that the default widget bindings for buttons, which are associated with the Button tag, will no longer apply to .b, but any bindings associated with TrickyButton (perhaps some new button behavior) will apply.

SEE ALSO

bind

KEYWORDS

binding, event, tag
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - bitmap manual page

NAME
bitmap - Images that display two colors
SYNOPSIS
image create bitmap ?name? ?options?
DESCRIPTION
CREATING BITMAPS
-background color
-data string
-file name
-foreground color
-maskdata string
-maskfile name
IMAGE COMMAND
imageName cget option
imageName configure ?option? ?value option value ...?
KEYWORDS

NAME

bitmap - Images that display two colors

SYNOPSIS

image create bitmap ?name? ?options?

DESCRIPTION

A bitmap is an image whose pixels can display either of two colors or be transparent. A bitmap image is defined by four things: a background color, a foreground color, and two bitmaps, called the source and the mask. Each of the bitmaps specifies 0/1 values for a rectangular array of pixels, and the two bitmaps must have the same dimensions. For pixels where the mask is zero, the image displays nothing, producing a transparent effect. For other pixels, the image displays the foreground color if the source data is one and the background color if the source data is zero.

CREATING BITMAPS

Like all images, bitmaps are created using the image create command. Bitmaps support the following options:

-background color
Specifies a background color for the image in any of the standard ways accepted by Tk. If this option is set to an empty string then the background pixels will be transparent. This effect is achieved by using the source bitmap as the mask bitmap, ignoring any -maskdata or -maskfile options.

-data string
Specifies the contents of the source bitmap as a string. The string must adhere to X11 bitmap format (e.g., as generated by the bitmap program). If both the -data and -file options are specified, the -data option takes precedence.

-file name
name gives the name of a file whose contents define the source bitmap. The file must adhere to X11 bitmap format (e.g., as generated by the bitmap program).

-foreground color
Specifies a foreground color for the image in any of the standard ways accepted by Tk.

-maskdata string
Specifies the contents of the mask as a string. The string must adhere to X11 bitmap format (e.g., as generated by the bitmap program). If both the -maskdata and -maskfile options are specified, the -maskdata option takes precedence.

-maskfile name
name gives the name of a file whose contents define the mask. The file must adhere to X11 bitmap format (e.g., as generated by the bitmap program).

IMAGE COMMAND

When a bitmap image is created, Tk also creates a new command whose name is the same as the image. This command may be used to invoke various operations on the image. It has the following general form:
imageName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for bitmap images:

imageName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the image create bitmap command.

imageName configure ?option? ?value option value ...?
Query or modify the configuration options for the image. If no option is specified, returns a list describing all of the available options for imageName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the image create bitmap command.

KEYWORDS

bitmap, image
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - button manual page

NAME
button - Create and manipulate button widgets
SYNOPSIS
button pathName ?options?
STANDARD OPTIONS
-activebackground, activeBackground, Foreground
-activeforeground, activeForeground, Background
-anchor, anchor, Anchor
-background or -bg, background, Background
-bitmap, bitmap, Bitmap
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-image, image, Image
-justify, justify, Justify
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-underline, underline, Underline
-wraplength, wrapLength, WrapLength
WIDGET-SPECIFIC OPTIONS
-command, command, Command
-default, default, Default
-height, height, Height
-state, state, State
-width, width, Width
DESCRIPTION
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName flash
pathName invoke
DEFAULT BINDINGS
KEYWORDS

NAME

button - Create and manipulate button widgets

SYNOPSIS

button pathName ?options?

STANDARD OPTIONS

-activebackground, activeBackground, Foreground
-activeforeground, activeForeground, Background
-anchor, anchor, Anchor
-background or -bg, background, Background
-bitmap, bitmap, Bitmap
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-image, image, Image
-justify, justify, Justify
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-underline, underline, Underline
-wraplength, wrapLength, WrapLength

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -command
Database Name: command
Database Class: Command
Specifies a Tcl command to associate with the button. This command is typically invoked when mouse button 1 is released over the button window.

Command-Line Name: -default
Database Name: default
Database Class: Default
Specifies one of three states for the default ring: normal, active, or disabled. In active state, the button is drawn with the platform specific appearance for a default button. In normal state, the button is drawn with the platform specific appearance for a non-default button, leaving enough space to draw the default button appearance. The normal and active states will result in buttons of the same size. In disabled state, the button is drawn with the non-default button appearance without leaving space for the default appearance. The disabled state may result in a smaller button than the active state. ring.

Command-Line Name: -height
Database Name: height
Database Class: Height
Specifies a desired height for the button. If an image or bitmap is being displayed in the button then the value is in screen units (i.e. any of the forms acceptable to Tk_GetPixels); for text it is in lines of text. If this option isn't specified, the button's desired height is computed from the size of the image or bitmap or text being displayed in it.

Command-Line Name: -state
Database Name: state
Database Class: State
Specifies one of three states for the button: normal, active, or disabled. In normal state the button is displayed using the foreground and background options. The active state is typically used when the pointer is over the button. In active state the button is displayed using the activeForeground and activeBackground options. Disabled state means that the button should be insensitive: the default bindings will refuse to activate the widget and will ignore mouse button presses. In this state the disabledForeground and background options determine how the button is displayed.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies a desired width for the button. If an image or bitmap is being displayed in the button then the value is in screen units (i.e. any of the forms acceptable to Tk_GetPixels); for text it is in characters. If this option isn't specified, the button's desired width is computed from the size of the image or bitmap or text being displayed in it.

DESCRIPTION

The button command creates a new window (given by the pathName argument) and makes it into a button widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the button such as its colors, font, text, and initial relief. The button command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A button is a widget that displays a textual string, bitmap or image. If text is displayed, it must all be in a single font, but it can occupy multiple lines on the screen (if it contains newlines or if wrapping occurs because of the wrapLength option) and one of the characters may optionally be underlined using the underline option. It can display itself in either of three different ways, according to the state option; it can be made to appear raised, sunken, or flat; and it can be made to flash. When a user invokes the button (by pressing mouse button 1 with the cursor over the button), then the Tcl command specified in the -command option is invoked.

WIDGET COMMAND

The button command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for button widgets:

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the button command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the button command.

pathName flash
Flash the button. This is accomplished by redisplaying the button several times, alternating between active and normal colors. At the end of the flash the button is left in the same normal/active state as when the command was invoked. This command is ignored if the button's state is disabled.

pathName invoke
Invoke the Tcl command associated with the button, if there is one. The return value is the return value from the Tcl command, or an empty string if there is no command associated with the button. This command is ignored if the button's state is disabled.

DEFAULT BINDINGS

Tk automatically creates class bindings for buttons that give them default behavior:

[1]
A button activates whenever the mouse passes over it and deactivates whenever the mouse leaves the button. Under Windows, this binding is only active when mouse button 1 has been pressed over the button.

[2]
A button's relief is changed to sunken whenever mouse button 1 is pressed over the button, and the relief is restored to its original value when button 1 is later released.

[3]
If mouse button 1 is pressed over a button and later released over the button, the button is invoked. However, if the mouse is not over the button when button 1 is released, then no invocation occurs.

[4]
When a button has the input focus, the space key causes the button to be invoked.

If the button's state is disabled then none of the above actions occur: the button is completely non-responsive.

The behavior of buttons can be changed by defining new bindings for individual widgets or by redefining the class bindings.

KEYWORDS

button, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - canvas manual page

NAME
canvas - Create and manipulate canvas widgets
SYNOPSIS
canvas pathName ?options?
STANDARD OPTIONS
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-insertbackground, insertBackground, Foreground
-insertborderwidth, insertBorderWidth, BorderWidth
-insertofftime, insertOffTime, OffTime
-insertontime, insertOnTime, OnTime
-insertwidth, insertWidth, InsertWidth
-relief, relief, Relief
-selectbackground, selectBackground, Foreground
-selectborderwidth, selectBorderWidth, BorderWidth
-selectforeground, selectForeground, Background
-state
-takefocus, takeFocus, TakeFocus
-xscrollcommand, xScrollCommand, ScrollCommand
-yscrollcommand, yScrollCommand, ScrollCommand
WIDGET-SPECIFIC OPTIONS
-closeenough, closeEnough, CloseEnough
-confine, confine, Confine
-height, height, Height
-scrollregion, scrollRegion, ScrollRegion
-state, state, State
-width, width, width
-xscrollincrement, xScrollIncrement, ScrollIncrement
-yscrollincrement, yScrollIncrement, ScrollIncrement
INTRODUCTION
DISPLAY LIST
ITEM IDS AND TAGS
COORDINATES
TRANSFORMATIONS
INDICES
number
end
insert
sel.first
sel.last
@x,y
DASH PATTERNS
WIDGET COMMAND
pathName addtag tag searchSpec ?arg arg ...?
above tagOrId
all
below tagOrId
closest x y ?halo? ?start?
enclosed x1 y1 x2 y2
overlapping x1 y1 x2 y2
withtag tagOrId
pathName bbox tagOrId ?tagOrId tagOrId ...?
pathName bind tagOrId ?sequence? ?command?
pathName canvasx screenx ?gridspacing?
pathName canvasy screeny ?gridspacing?
pathName cget option
pathName configure ?option? ?value? ?option value ...?
pathName coords tagOrId ?x0 y0 ...?
pathName coords tagOrId ?coordList?
pathName create type x y ?x y ...? ?option value ...?
pathName create type coordList ?option value ...?
pathName dchars tagOrId first ?last?
pathName delete ?tagOrId tagOrId ...?
pathName dtag tagOrId ?tagToDelete?
pathName find searchCommand ?arg arg ...?
pathName focus ?tagOrId?
pathName gettags tagOrId
pathName icursor tagOrId index
pathName index tagOrId index
pathName insert tagOrId beforeThis string
pathName itemcget tagOrId option
pathName itemconfigure tagOrId ?option? ?value? ?option value ...?
pathName lower tagOrId ?belowThis?
pathName move tagOrId xAmount yAmount
pathName postscript ?option value option value ...?
-colormap varName
-colormode mode
-file fileName
-fontmap varName
-height size
-pageanchor anchor
-pageheight size
-pagewidth size
-pagex position
-pagey position
-rotate boolean
-width size
-x position
-y position
pathName raise tagOrId ?aboveThis?
pathName scale tagOrId xOrigin yOrigin xScale yScale
pathName scan option args
pathName scan mark x y
pathName scan dragto x y ?gain?.
pathName select option ?tagOrId arg?
pathName select adjust tagOrId index
pathName select clear
pathName select from tagOrId index
pathName select item
pathName select to tagOrId index
pathName type tagOrId
pathName xview ?args?
pathName xview
pathName xview moveto fraction
pathName xview scroll number what
pathName yview ?args?
pathName yview
pathName yview moveto fraction
pathName yview scroll number what
OVERVIEW OF ITEM TYPES
COMMON ITEM OPTIONS
-dash pattern
-activedash pattern
-disableddash pattern
-dashoffset offset
-fill color
-activefill color
-disabledfill color
-outline color
-activeoutline color
-disabledoutline color
-offset offset
-outlinestipple bitmap
-activeoutlinestipple bitmap
-disabledoutlinestipple bitmap
-stipple bitmap
-activestipple bitmap
-disabledstipple bitmap
-state state
-tags tagList
-width outlineWidth
-activewidth outlineWidth
-disabledwidth outlineWidth
ARC ITEMS
-extent degrees
-start degrees
-style type
BITMAP ITEMS
-anchor anchorPos
-background color
-activebackground bitmap
-disabledbackground bitmap
-bitmap bitmap
-activebitmap bitmap
-disabledbitmap bitmap
-foreground color
-activeforeground bitmap
-disabledforeground bitmap
IMAGE ITEMS
-anchor anchorPos
-image name
-activeimage name
-disabledimage name
LINE ITEMS
-arrow where
-arrowshape shape
-capstyle style
-joinstyle style
-smooth boolean
-splinesteps number
OVAL ITEMS
POLYGON ITEMS
-joinstyle style
-smooth boolean
-splinesteps number
RECTANGLE ITEMS
TEXT ITEMS
-anchor anchorPos
-font fontName
-justify how
-text string
-width lineLength
WINDOW ITEMS
-anchor anchorPos
-height pixels
-width pixels
-window pathName
APPLICATION-DEFINED ITEM TYPES
BINDINGS
CREDITS
KEYWORDS

NAME

canvas - Create and manipulate canvas widgets

SYNOPSIS

canvas pathName ?options?

STANDARD OPTIONS

-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-insertbackground, insertBackground, Foreground
-insertborderwidth, insertBorderWidth, BorderWidth
-insertofftime, insertOffTime, OffTime
-insertontime, insertOnTime, OnTime
-insertwidth, insertWidth, InsertWidth
-relief, relief, Relief
-selectbackground, selectBackground, Foreground
-selectborderwidth, selectBorderWidth, BorderWidth
-selectforeground, selectForeground, Background
-state
-takefocus, takeFocus, TakeFocus
-xscrollcommand, xScrollCommand, ScrollCommand
-yscrollcommand, yScrollCommand, ScrollCommand

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -closeenough
Database Name: closeEnough
Database Class: CloseEnough
Specifies a floating-point value indicating how close the mouse cursor must be to an item before it is considered to be ``inside'' the item. Defaults to 1.0.

Command-Line Name: -confine
Database Name: confine
Database Class: Confine
Specifies a boolean value that indicates whether or not it should be allowable to set the canvas's view outside the region defined by the scrollRegion argument. Defaults to true, which means that the view will be constrained within the scroll region.

Command-Line Name: -height
Database Name: height
Database Class: Height
Specifies a desired window height that the canvas widget should request from its geometry manager. The value may be specified in any of the forms described in the COORDINATES section below.

Command-Line Name: -scrollregion
Database Name: scrollRegion
Database Class: ScrollRegion
Specifies a list with four coordinates describing the left, top, right, and bottom coordinates of a rectangular region. This region is used for scrolling purposes and is considered to be the boundary of the information in the canvas. Each of the coordinates may be specified in any of the forms given in the COORDINATES section below.

Command-Line Name: -state
Database Name: state
Database Class: State
Modifies the default state of the canvas where state may be set to one of: normal, disabled, or hidden. Individual canvas objects all have their own state option which may override the default state. Many options can take separate specifications such that the appearance of the item can be different in different situations. The options that start with active control the appearence when the mouse pointer is over it, while the option starting with disabled controls the appearence when the state is disabled. Canvas items which are disabled will not react to canvas bindings.

Command-Line Name: -width
Database Name: width
Database Class: width
Specifies a desired window width that the canvas widget should request from its geometry manager. The value may be specified in any of the forms described in the COORDINATES section below.

Command-Line Name: -xscrollincrement
Database Name: xScrollIncrement
Database Class: ScrollIncrement
Specifies an increment for horizontal scrolling, in any of the usual forms permitted for screen distances. If the value of this option is greater than zero, the horizontal view in the window will be constrained so that the canvas x coordinate at the left edge of the window is always an even multiple of xScrollIncrement; furthermore, the units for scrolling (e.g., the change in view when the left and right arrows of a scrollbar are selected) will also be xScrollIncrement. If the value of this option is less than or equal to zero, then horizontal scrolling is unconstrained.

Command-Line Name: -yscrollincrement
Database Name: yScrollIncrement
Database Class: ScrollIncrement
Specifies an increment for vertical scrolling, in any of the usual forms permitted for screen distances. If the value of this option is greater than zero, the vertical view in the window will be constrained so that the canvas y coordinate at the top edge of the window is always an even multiple of yScrollIncrement; furthermore, the units for scrolling (e.g., the change in view when the top and bottom arrows of a scrollbar are selected) will also be yScrollIncrement. If the value of this option is less than or equal to zero, then vertical scrolling is unconstrained.

INTRODUCTION

The canvas command creates a new window (given by the pathName argument) and makes it into a canvas widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the canvas such as its colors and 3-D relief. The canvas command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

Canvas widgets implement structured graphics. A canvas displays any number of items, which may be things like rectangles, circles, lines, and text. Items may be manipulated (e.g. moved or re-colored) and commands may be associated with items in much the same way that the bind command allows commands to be bound to widgets. For example, a particular command may be associated with the <Button-1> event so that the command is invoked whenever button 1 is pressed with the mouse cursor over an item. This means that items in a canvas can have behaviors defined by the Tcl scripts bound to them.

DISPLAY LIST

The items in a canvas are ordered for purposes of display, with the first item in the display list being displayed first, followed by the next item in the list, and so on. Items later in the display list obscure those that are earlier in the display list and are sometimes referred to as being ``on top'' of earlier items. When a new item is created it is placed at the end of the display list, on top of everything else. Widget commands may be used to re-arrange the order of the display list.

Window items are an exception to the above rules. The underlying window systems require them always to be drawn on top of other items. In addition, the stacking order of window items is not affected by any of the canvas widget commands; you must use the raise and lower Tk commands instead.

ITEM IDS AND TAGS

Items in a canvas widget may be named in either of two ways: by id or by tag. Each item has a unique identifying number which is assigned to that item when it is created. The id of an item never changes and id numbers are never re-used within the lifetime of a canvas widget.

Each item may also have any number of tags associated with it. A tag is just a string of characters, and it may take any form except that of an integer. For example, ``x123'' is OK but ``123'' isn't. The same tag may be associated with many different items. This is commonly done to group items in various interesting ways; for example, all selected items might be given the tag ``selected''.

The tag all is implicitly associated with every item in the canvas; it may be used to invoke operations on all the items in the canvas.

The tag current is managed automatically by Tk; it applies to the current item, which is the topmost item whose drawn area covers the position of the mouse cursor. If the mouse is not in the canvas widget or is not over an item, then no item has the current tag.

When specifying items in canvas widget commands, if the specifier is an integer then it is assumed to refer to the single item with that id. If the specifier is not an integer, then it is assumed to refer to all of the items in the canvas that have a tag matching the specifier. The symbol tagOrId is used below to indicate that an argument specifies either an id that selects a single item or a tag that selects zero or more items.

tagOrId may contain a logical expressions of tags by using operators: '&&', '||', '^' '!', and parenthezised subexpressions. For example:

.c find withtag {(a&&!b)||(!a&&b)}
or equivalently:
.c find withtag {a^b}
will find only those items with either "a" or "b" tags, but not both.

Some widget commands only operate on a single item at a time; if tagOrId is specified in a way that names multiple items, then the normal behavior is for the command to use the first (lowest) of these items in the display list that is suitable for the command. Exceptions are noted in the widget command descriptions below.

COORDINATES

All coordinates related to canvases are stored as floating-point numbers. Coordinates and distances are specified in screen units, which are floating-point numbers optionally followed by one of several letters. If no letter is supplied then the distance is in pixels. If the letter is m then the distance is in millimeters on the screen; if it is c then the distance is in centimeters; i means inches, and p means printers points (1/72 inch). Larger y-coordinates refer to points lower on the screen; larger x-coordinates refer to points farther to the right. Coordinates can be specified either as an even number of parameters, or as a single list parameter containing an even number of x and y coordinate values.

TRANSFORMATIONS

Normally the origin of the canvas coordinate system is at the upper-left corner of the window containing the canvas. It is possible to adjust the origin of the canvas coordinate system relative to the origin of the window using the xview and yview widget commands; this is typically used for scrolling. Canvases do not support scaling or rotation of the canvas coordinate system relative to the window coordinate system.

Individual items may be moved or scaled using widget commands described below, but they may not be rotated.

INDICES

Text items support the notion of an index for identifying particular positions within the item. In a similar fashion, line and polygon items support index for identifying, inserting and deleting subsets of their coordinates. Indices are used for commands such as inserting or deleting a range of characters or coordinates, and setting the insertion cursor position. An index may be specified in any of a number of ways, and different types of items may support different forms for specifying indices. Text items support the following forms for an index; if you define new types of text-like items, it would be advisable to support as many of these forms as practical. Note that it is possible to refer to the character just after the last one in the text item; this is necessary for such tasks as inserting new text at the end of the item. Lines and Polygons don't support the insertion cursor and the selection. Their indixes are supposed to be even always, because coordinates always appear in pairs.

number
A decimal number giving the position of the desired character within the text item. 0 refers to the first character, 1 to the next character, and so on. If indexes are odd for lines and polygons, they will be automatically decremented by one. A number less than 0 is treated as if it were zero, and a number greater than the length of the text item is treated as if it were equal to the length of the text item. For polygons, numbers less than 0 or greater then the length of the coordinate list will be adjusted by adding or substracting the length until the result is between zero and the length, inclusive.

end
Refers to the character or coordinate just after the last one in the item (same as the number of characters or coordinates in the item).

insert
Refers to the character just before which the insertion cursor is drawn in this item. Not valid for lines and polygons.

sel.first
Refers to the first selected character in the item. If the selection isn't in this item then this form is illegal.

sel.last
Refers to the last selected character in the item. If the selection isn't in this item then this form is illegal.

@x,y
Refers to the character or coordinate at the point given by x and y, where x and y are specified in the coordinate system of the canvas. If x and y lie outside the coordinates covered by the text item, then they refer to the first or last character in the line that is closest to the given point.

DASH PATTERNS

Many items support the notion of an dash pattern for outlines.

The first possible syntax is a list of integers. Each element represents the number of pixels of a line segment. Only the odd segments are drawn using the "outline" color. The other segments are drawn transparant.

The second possible syntax is a character list containing only
5 possible characters [.,-_ ]. The space can be used
to enlarge the space between other line elements, and can not
occur as the first position in the string. Some examples:
    -dash .	= -dash {2 4}
    -dash -     = -dash {6 4}
    -dash -.    = -dash {6 4 2 4}
    -dash -..   = -dash {6 4 2 4 2 4}
    -dash {. }  = -dash {2 8}
    -dash ,	= -dash {4 4}

The main difference of this syntax with the previous is that it it shape-conserving. This means that all values in the dash list will be multiplied by the line width before display. This assures that "." will always be displayed as a dot and "-" always as a dash regardless of the line width.

On systems which support only a limited set of dash patterns, the dash pattern will be displayed as the closest dash pattern that is available. For example, on Windows only the first 4 of the above examples are available. The last 2 examples will be displayed identically to the first one.

WIDGET COMMAND

The canvas command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following widget commands are possible for canvas widgets:

pathName addtag tag searchSpec ?arg arg ...?
For each item that meets the constraints specified by searchSpec and the args, add tag to the list of tags associated with the item if it isn't already present on that list. It is possible that no items will satisfy the constraints given by searchSpec and args, in which case the command has no effect. This command returns an empty string as result. SearchSpec and arg's may take any of the following forms:

above tagOrId
Selects the item just after (above) the one given by tagOrId in the display list. If tagOrId denotes more than one item, then the last (topmost) of these items in the display list is used.

all
Selects all the items in the canvas.

below tagOrId
Selects the item just before (below) the one given by tagOrId in the display list. If tagOrId denotes more than one item, then the first (lowest) of these items in the display list is used.

closest x y ?halo? ?start?
Selects the item closest to the point given by x and y. If more than one item is at the same closest distance (e.g. two items overlap the point), then the top-most of these items (the last one in the display list) is used. If halo is specified, then it must be a non-negative value. Any item closer than halo to the point is considered to overlap it. The start argument may be used to step circularly through all the closest items. If start is specified, it names an item using a tag or id (if by tag, it selects the first item in the display list with the given tag). Instead of selecting the topmost closest item, this form will select the topmost closest item that is below start in the display list; if no such item exists, then the selection behaves as if the start argument had not been specified.

enclosed x1 y1 x2 y2
Selects all the items completely enclosed within the rectangular region given by x1, y1, x2, and y2. X1 must be no greater then x2 and y1 must be no greater than y2.

overlapping x1 y1 x2 y2
Selects all the items that overlap or are enclosed within the rectangular region given by x1, y1, x2, and y2. X1 must be no greater then x2 and y1 must be no greater than y2.

withtag tagOrId
Selects all the items given by tagOrId.

pathName bbox tagOrId ?tagOrId tagOrId ...?
Returns a list with four elements giving an approximate bounding box for all the items named by the tagOrId arguments. The list has the form ``x1 y1 x2 y2'' such that the drawn areas of all the named elements are within the region bounded by x1 on the left, x2 on the right, y1 on the top, and y2 on the bottom. The return value may overestimate the actual bounding box by a few pixels. If no items match any of the tagOrId arguments or if the matching items have empty bounding boxes (i.e. they have nothing to display) then an empty string is returned.

pathName bind tagOrId ?sequence? ?command?
This command associates command with all the items given by tagOrId such that whenever the event sequence given by sequence occurs for one of the items the command will be invoked. This widget command is similar to the bind command except that it operates on items in a canvas rather than entire widgets. See the bind manual entry for complete details on the syntax of sequence and the substitutions performed on command before invoking it. If all arguments are specified then a new binding is created, replacing any existing binding for the same sequence and tagOrId (if the first character of command is ``+'' then command augments an existing binding rather than replacing it). In this case the return value is an empty string. If command is omitted then the command returns the command associated with tagOrId and sequence (an error occurs if there is no such binding). If both command and sequence are omitted then the command returns a list of all the sequences for which bindings have been defined for tagOrId.

The only events for which bindings may be specified are those related to the mouse and keyboard (such as Enter, Leave, ButtonPress, Motion, and KeyPress) or virtual events. The handling of events in canvases uses the current item defined in ITEM IDS AND TAGS above. Enter and Leave events trigger for an item when it becomes the current item or ceases to be the current item; note that these events are different than Enter and Leave events for windows. Mouse-related events are directed to the current item, if any. Keyboard-related events are directed to the focus item, if any (see the focus widget command below for more on this). If a virtual event is used in a binding, that binding can trigger only if the virtual event is defined by an underlying mouse-related or keyboard-related event.

It is possible for multiple bindings to match a particular event. This could occur, for example, if one binding is associated with the item's id and another is associated with one of the item's tags. When this occurs, all of the matching bindings are invoked. A binding associated with the all tag is invoked first, followed by one binding for each of the item's tags (in order), followed by a binding associated with the item's id. If there are multiple matching bindings for a single tag, then only the most specific binding is invoked. A continue command in a binding script terminates that script, and a break command terminates that script and skips any remaining scripts for the event, just as for the bind command.

If bindings have been created for a canvas window using the bind command, then they are invoked in addition to bindings created for the canvas's items using the bind widget command. The bindings for items will be invoked before any of the bindings for the window as a whole.

pathName canvasx screenx ?gridspacing?
Given a window x-coordinate in the canvas screenx, this command returns the canvas x-coordinate that is displayed at that location. If gridspacing is specified, then the canvas coordinate is rounded to the nearest multiple of gridspacing units.

pathName canvasy screeny ?gridspacing?
Given a window y-coordinate in the canvas screeny this command returns the canvas y-coordinate that is displayed at that location. If gridspacing is specified, then the canvas coordinate is rounded to the nearest multiple of gridspacing units.

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the canvas command.

pathName configure ?option? ?value? ?option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the canvas command.

pathName coords tagOrId ?x0 y0 ...?

pathName coords tagOrId ?coordList?
Query or modify the coordinates that define an item. If no coordinates are specified, this command returns a list whose elements are the coordinates of the item named by tagOrId. If coordinates are specified, then they replace the current coordinates for the named item. If tagOrId refers to multiple items, then the first one in the display list is used.

pathName create type x y ?x y ...? ?option value ...?

pathName create type coordList ?option value ...?
Create a new item in pathName of type type. The exact format of the arguments after type depends on type, but usually they consist of the coordinates for one or more points, followed by specifications for zero or more item options. See the subsections on individual item types below for more on the syntax of this command. This command returns the id for the new item.

pathName dchars tagOrId first ?last?
For each item given by tagOrId, delete the characters, or coordinates, in the range given by first and last, inclusive. If some of the items given by tagOrId don't support indexing operations then they ignore dchars. Text items interpret first and last as indices to a character, line and polygon items interpret them indices to a coordinate (an x,y pair). Indices are described in INDICES above. If last is omitted, it defaults to first. This command returns an empty string.

pathName delete ?tagOrId tagOrId ...?
Delete each of the items given by each tagOrId, and return an empty string.

pathName dtag tagOrId ?tagToDelete?
For each of the items given by tagOrId, delete the tag given by tagToDelete from the list of those associated with the item. If an item doesn't have the tag tagToDelete then the item is unaffected by the command. If tagToDelete is omitted then it defaults to tagOrId. This command returns an empty string.

pathName find searchCommand ?arg arg ...?
This command returns a list consisting of all the items that meet the constraints specified by searchCommand and arg's. SearchCommand and args have any of the forms accepted by the addtag command. The items are returned in stacking order, with the lowest item first.

pathName focus ?tagOrId?
Set the keyboard focus for the canvas widget to the item given by tagOrId. If tagOrId refers to several items, then the focus is set to the first such item in the display list that supports the insertion cursor. If tagOrId doesn't refer to any items, or if none of them support the insertion cursor, then the focus isn't changed. If tagOrId is an empty string, then the focus item is reset so that no item has the focus. If tagOrId is not specified then the command returns the id for the item that currently has the focus, or an empty string if no item has the focus.

Once the focus has been set to an item, the item will display the insertion cursor and all keyboard events will be directed to that item. The focus item within a canvas and the focus window on the screen (set with the focus command) are totally independent: a given item doesn't actually have the input focus unless (a) its canvas is the focus window and (b) the item is the focus item within the canvas. In most cases it is advisable to follow the focus widget command with the focus command to set the focus window to the canvas (if it wasn't there already).

pathName gettags tagOrId
Return a list whose elements are the tags associated with the item given by tagOrId. If tagOrId refers to more than one item, then the tags are returned from the first such item in the display list. If tagOrId doesn't refer to any items, or if the item contains no tags, then an empty string is returned.

pathName icursor tagOrId index
Set the position of the insertion cursor for the item(s) given by tagOrId to just before the character whose position is given by index. If some or all of the items given by tagOrId don't support an insertion cursor then this command has no effect on them. See INDICES above for a description of the legal forms for index. Note: the insertion cursor is only displayed in an item if that item currently has the keyboard focus (see the widget command focus, below), but the cursor position may be set even when the item doesn't have the focus. This command returns an empty string.

pathName index tagOrId index
This command returns a decimal string giving the numerical index within tagOrId corresponding to index. Index gives a textual description of the desired position as described in INDICES above. Text items interpret index as an index to a character, line and polygon items interpret it as an index to a coordinate (an x,y pair). The return value is guaranteed to lie between 0 and the number of characters, or coordinates, within the item, inclusive. If tagOrId refers to multiple items, then the index is processed in the first of these items that supports indexing operations (in display list order).

pathName insert tagOrId beforeThis string
For each of the items given by tagOrId, if the item supports text or coordinate, insertion then string is inserted into the item's text just before the character, or coordinate, whose index is beforeThis. Text items interpret beforethis as an index to a character, line and polygon items interpret it as an index to a coordinate (an x,y pair). For lines and polygons the string must be a valid coordinate sequence. See INDICES above for information about the forms allowed for beforeThis. This command returns an empty string.

pathName itemcget tagOrId option
Returns the current value of the configuration option for the item given by tagOrId whose name is option. This command is similar to the cget widget command except that it applies to a particular item rather than the widget as a whole. Option may have any of the values accepted by the create widget command when the item was created. If tagOrId is a tag that refers to more than one item, the first (lowest) such item is used.

pathName itemconfigure tagOrId ?option? ?value? ?option value ...?
This command is similar to the configure widget command except that it modifies item-specific options for the items given by tagOrId instead of modifying options for the overall canvas widget. If no option is specified, returns a list describing all of the available options for the first item given by tagOrId (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s) in each of the items given by tagOrId; in this case the command returns an empty string. The options and values are the same as those permissible in the create widget command when the item(s) were created; see the sections describing individual item types below for details on the legal options.

pathName lower tagOrId ?belowThis?
Move all of the items given by tagOrId to a new position in the display list just before the item given by belowThis. If tagOrId refers to more than one item then all are moved but the relative order of the moved items will not be changed. BelowThis is a tag or id; if it refers to more than one item then the first (lowest) of these items in the display list is used as the destination location for the moved items. Note: this command has no effect on window items. Window items always obscure other item types, and the stacking order of window items is determined by the raise and lower commands, not the raise and lower widget commands for canvases. This command returns an empty string.

pathName move tagOrId xAmount yAmount
Move each of the items given by tagOrId in the canvas coordinate space by adding xAmount to the x-coordinate of each point associated with the item and yAmount to the y-coordinate of each point associated with the item. This command returns an empty string.

pathName postscript ?option value option value ...?
Generate a Postscript representation for part or all of the canvas. If the -file option is specified then the Postscript is written to a file and an empty string is returned; otherwise the Postscript is returned as the result of the command. If the interpreter that owns the canvas is marked as safe, the operation will fail because safe interpreters are not allowed to write files. If the -channel option is specified, the argument denotes the name of a channel already opened for writing. The Postscript is written to that channel, and the channel is left open for further writing at the end of the operation. The Postscript is created in Encapsulated Postscript form using version 3.0 of the Document Structuring Conventions. Note: by default Postscript is only generated for information that appears in the canvas's window on the screen. If the canvas is freshly created it may still have its initial size of 1x1 pixel so nothing will appear in the Postscript. To get around this problem either invoke the "update" command to wait for the canvas window to reach its final size, or else use the -width and -height options to specify the area of the canvas to print. The option-value argument pairs provide additional information to control the generation of Postscript. The following options are supported:

-colormap varName
VarName must be the name of an array variable that specifies a color mapping to use in the Postscript. Each element of varName must consist of Postscript code to set a particular color value (e.g. ``1.0 1.0 0.0 setrgbcolor''). When outputting color information in the Postscript, Tk checks to see if there is an element of varName with the same name as the color. If so, Tk uses the value of the element as the Postscript command to set the color. If this option hasn't been specified, or if there isn't an entry in varName for a given color, then Tk uses the red, green, and blue intensities from the X color.

-colormode mode
Specifies how to output color information. Mode must be either color (for full color output), gray (convert all colors to their gray-scale equivalents) or mono (convert all colors to black or white).

-file fileName
Specifies the name of the file in which to write the Postscript. If this option isn't specified then the Postscript is returned as the result of the command instead of being written to a file.

-fontmap varName
VarName must be the name of an array variable that specifies a font mapping to use in the Postscript. Each element of varName must consist of a Tcl list with two elements, which are the name and point size of a Postscript font. When outputting Postscript commands for a particular font, Tk checks to see if varName contains an element with the same name as the font. If there is such an element, then the font information contained in that element is used in the Postscript. Otherwise Tk attempts to guess what Postscript font to use. Tk's guesses generally only work for well-known fonts such as Times and Helvetica and Courier, and only if the X font name does not omit any dashes up through the point size. For example, -*-Courier-Bold-R-Normal--*-120-* will work but *Courier-Bold-R-Normal*120* will not; Tk needs the dashes to parse the font name).

-height size
Specifies the height of the area of the canvas to print. Defaults to the height of the canvas window.

-pageanchor anchor
Specifies which point of the printed area of the canvas should appear over the positioning point on the page (which is given by the -pagex and -pagey options). For example, -pageanchor n means that the top center of the area of the canvas being printed (as it appears in the canvas window) should be over the positioning point. Defaults to center.

-pageheight size
Specifies that the Postscript should be scaled in both x and y so that the printed area is size high on the Postscript page. Size consists of a floating-point number followed by c for centimeters, i for inches, m for millimeters, or p or nothing for printer's points (1/72 inch). Defaults to the height of the printed area on the screen. If both -pageheight and -pagewidth are specified then the scale factor from -pagewidth is used (non-uniform scaling is not implemented).

-pagewidth size
Specifies that the Postscript should be scaled in both x and y so that the printed area is size wide on the Postscript page. Size has the same form as for -pageheight. Defaults to the width of the printed area on the screen. If both -pageheight and -pagewidth are specified then the scale factor from -pagewidth is used (non-uniform scaling is not implemented).

-pagex position
Position gives the x-coordinate of the positioning point on the Postscript page, using any of the forms allowed for -pageheight. Used in conjunction with the -pagey and -pageanchor options to determine where the printed area appears on the Postscript page. Defaults to the center of the page.

-pagey position
Position gives the y-coordinate of the positioning point on the Postscript page, using any of the forms allowed for -pageheight. Used in conjunction with the -pagex and -pageanchor options to determine where the printed area appears on the Postscript page. Defaults to the center of the page.

-rotate boolean
Boolean specifies whether the printed area is to be rotated 90 degrees. In non-rotated output the x-axis of the printed area runs along the short dimension of the page (``portrait'' orientation); in rotated output the x-axis runs along the long dimension of the page (``landscape'' orientation). Defaults to non-rotated.

-width size
Specifies the width of the area of the canvas to print. Defaults to the width of the canvas window.

-x position
Specifies the x-coordinate of the left edge of the area of the canvas that is to be printed, in canvas coordinates, not window coordinates. Defaults to the coordinate of the left edge of the window.

-y position
Specifies the y-coordinate of the top edge of the area of the canvas that is to be printed, in canvas coordinates, not window coordinates. Defaults to the coordinate of the top edge of the window.

pathName raise tagOrId ?aboveThis?
Move all of the items given by tagOrId to a new position in the display list just after the item given by aboveThis. If tagOrId refers to more than one item then all are moved but the relative order of the moved items will not be changed. AboveThis is a tag or id; if it refers to more than one item then the last (topmost) of these items in the display list is used as the destination location for the moved items. Note: this command has no effect on window items. Window items always obscure other item types, and the stacking order of window items is determined by the raise and lower commands, not the raise and lower widget commands for canvases. This command returns an empty string.

pathName scale tagOrId xOrigin yOrigin xScale yScale
Rescale all of the items given by tagOrId in canvas coordinate space. XOrigin and yOrigin identify the origin for the scaling operation and xScale and yScale identify the scale factors for x- and y-coordinates, respectively (a scale factor of 1.0 implies no change to that coordinate). For each of the points defining each item, the x-coordinate is adjusted to change the distance from xOrigin by a factor of xScale. Similarly, each y-coordinate is adjusted to change the distance from yOrigin by a factor of yScale. This command returns an empty string.

pathName scan option args
This command is used to implement scanning on canvases. It has two forms, depending on option:

pathName scan mark x y
Records x and y and the canvas's current view; used in conjunction with later scan dragto commands. Typically this command is associated with a mouse button press in the widget and x and y are the coordinates of the mouse. It returns an empty string.

pathName scan dragto x y ?gain?.
This command computes the difference between its x and y arguments (which are typically mouse coordinates) and the x and y arguments to the last scan mark command for the widget. It then adjusts the view by gain times the difference in coordinates, where gain defaults to 10. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the canvas at high speed through its window. The return value is an empty string.

pathName select option ?tagOrId arg?
Manipulates the selection in one of several ways, depending on option. The command may take any of the forms described below. In all of the descriptions below, tagOrId must refer to an item that supports indexing and selection; if it refers to multiple items then the first of these that supports indexing and the selection is used. Index gives a textual description of a position within tagOrId, as described in INDICES above.

pathName select adjust tagOrId index
Locate the end of the selection in tagOrId nearest to the character given by index, and adjust that end of the selection to be at index (i.e. including but not going beyond index). The other end of the selection is made the anchor point for future select to commands. If the selection isn't currently in tagOrId then this command behaves the same as the select to widget command. Returns an empty string.

pathName select clear
Clear the selection if it is in this widget. If the selection isn't in this widget then the command has no effect. Returns an empty string.

pathName select from tagOrId index
Set the selection anchor point for the widget to be just before the character given by index in the item given by tagOrId. This command doesn't change the selection; it just sets the fixed end of the selection for future select to commands. Returns an empty string.

pathName select item
Returns the id of the selected item, if the selection is in an item in this canvas. If the selection is not in this canvas then an empty string is returned.

pathName select to tagOrId index
Set the selection to consist of those characters of tagOrId between the selection anchor point and index. The new selection will include the character given by index; it will include the character given by the anchor point only if index is greater than or equal to the anchor point. The anchor point is determined by the most recent select adjust or select from command for this widget. If the selection anchor point for the widget isn't currently in tagOrId, then it is set to the same character given by index. Returns an empty string.

pathName type tagOrId
Returns the type of the item given by tagOrId, such as rectangle or text. If tagOrId refers to more than one item, then the type of the first item in the display list is returned. If tagOrId doesn't refer to any items at all then an empty string is returned.

pathName xview ?args?
This command is used to query and change the horizontal position of the information displayed in the canvas's window. It can take any of the following forms:

pathName xview
Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the horizontal span that is visible in the window. For example, if the first element is .2 and the second element is .6, 20% of the canvas's area (as defined by the -scrollregion option) is off-screen to the left, the middle 40% is visible in the window, and 40% of the canvas is off-screen to the right. These are the same values passed to scrollbars via the -xscrollcommand option.

pathName xview moveto fraction
Adjusts the view in the window so that fraction of the total width of the canvas is off-screen to the left. Fraction must be a fraction between 0 and 1.

pathName xview scroll number what
This command shifts the view in the window left or right according to number and what. Number must be an integer. What must be either units or pages or an abbreviation of one of these. If what is units, the view adjusts left or right in units of the xScrollIncrement option, if it is greater than zero, or in units of one-tenth the window's width otherwise. If what is pages then the view adjusts in units of nine-tenths the window's width. If number is negative then information farther to the left becomes visible; if it is positive then information farther to the right becomes visible.

pathName yview ?args?
This command is used to query and change the vertical position of the information displayed in the canvas's window. It can take any of the following forms:

pathName yview
Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the vertical span that is visible in the window. For example, if the first element is .6 and the second element is 1.0, the lowest 40% of the canvas's area (as defined by the -scrollregion option) is visible in the window. These are the same values passed to scrollbars via the -yscrollcommand option.

pathName yview moveto fraction
Adjusts the view in the window so that fraction of the canvas's area is off-screen to the top. Fraction is a fraction between 0 and 1.

pathName yview scroll number what
This command adjusts the view in the window up or down according to number and what. Number must be an integer. What must be either units or pages. If what is units, the view adjusts up or down in units of the yScrollIncrement option, if it is greater than zero, or in units of one-tenth the window's height otherwise. If what is pages then the view adjusts in units of nine-tenths the window's height. If number is negative then higher information becomes visible; if it is positive then lower information becomes visible.

OVERVIEW OF ITEM TYPES

The sections below describe the various types of items supported by canvas widgets. Each item type is characterized by two things: first, the form of the create command used to create instances of the type; and second, a set of configuration options for items of that type, which may be used in the create and itemconfigure widget commands. Most items don't support indexing or selection or the commands related to them, such as index and insert. Where items do support these facilities, it is noted explicitly in the descriptions below. At present, text, line and polygon items provide this support. For lines and polygons the indexing facility is used to manipulate the coordinates of the item.

COMMON ITEM OPTIONS

Many items share a common set of options. These options are explained here, and then referred to be each widget type for brevity.

-dash pattern

-activedash pattern

-disableddash pattern
This option specifies dash patterns for the normal, active state, and disabled state of an item. pattern may have any of the forms accepted by Tk_GetDash. If the dash options are omitted then the default is a solid outline. See "DASH PATTERNS" for more information.

-dashoffset offset
The starting offset in pixels into the pattern provided by the -dash option. -dashoffset is ignored if there is no -dash pattern. The offset may have any of the forms described in the COORDINATES section above.

-fill color

-activefill color

-disabledfill color
Specifies the color to be used to fill item's area. in its normal, active, and disabled states, Color may have any of the forms accepted by Tk_GetColor. If color is an empty string (the default), then then the item will not be filled. For the line item, it specifies the color of the line drawn. For the text item, it specifies the foreground color of the text.

-outline color

-activeoutline color

-disabledoutline color
This option specifies the color that should be used to draw the outline of the item in its normal, active and disabled states. Color may have any of the forms accepted by Tk_GetColor. This option defaults to black. If color is specified as an empty string then no outline is drawn for the item.

-offset offset
Specifies the offset of stipples. The offset value can be of the form x,y or side, where side can be n, ne, e, se, s, sw, w, nw, or center. In the first case the origin is the origin of the toplevel of the current window. For the canvas itself and canvas objects the origin is the canvas origin, but putting # in front of the coordinate pair indicates using the toplevel origin instead. For canvas objects, the -offset option is used for stippling as well. For the line and polygon canvas items you can also specify an index as argument, which connects the stipple origin to one of the coordinate points of the line/polygon.

-outlinestipple bitmap

-activeoutlinestipple bitmap

-disabledoutlinestipple bitmap
This option specifies stipple patterns that should be used to draw the outline of the item in its normal, active and disabled states. Indicates that the outline for the item should be drawn with a stipple pattern; bitmap specifies the stipple pattern to use, in any of the forms accepted by Tk_GetBitmap. If the -outline option hasn't been specified then this option has no effect. If bitmap is an empty string (the default), then the outline is drawn in a solid fashion.

-stipple bitmap

-activestipple bitmap

-disabledstipple bitmap
This option specifies stipple patterns that should be used to fill the the item in its normal, active and disabled states. bitmap specifies the stipple pattern to use, in any of the forms accepted by Tk_GetBitmap. If the -fill option hasn't been specified then this option has no effect. If bitmap is an empty string (the default), then filling is done in a solid fashion. For the text item, it affects the actual text.

-state state
This allows an item to override the canvas widget's global state option. It takes the same values: normal, disabled or hidden.

-tags tagList
Specifies a set of tags to apply to the item. TagList consists of a list of tag names, which replace any existing tags for the item. TagList may be an empty list.

-width outlineWidth

-activewidth outlineWidth

-disabledwidth outlineWidth
Specifies the width of the outline to be drawn around the item's region, in its normal, active and disabled states. outlineWidth may be in any of the forms described in the COORDINATES section above. If the -outline option has been specified as an empty string then this option has no effect. This option defaults to 1.0. For arcs, wide outlines will be drawn centered on the edges of the arc's region.

ARC ITEMS

Items of type arc appear on the display as arc-shaped regions. An arc is a section of an oval delimited by two angles (specified by the -start and -extent options) and displayed in one of several ways (specified by the -style option). Arcs are created with widget commands of the following form:
pathName create arc x1 y1 x2 y2 ?option value option value ...?
pathName create arc coordList ?option value option value ...?
The arguments x1, y1, x2, and y2 or coordList give the coordinates of two diagonally opposite corners of a rectangular region enclosing the oval that defines the arc. After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration.
The following standard options are supported by arcs:
-dash
-activedash
-disableddash
-dashoffset
-fill
-activefill
-disabledfill
-offset
-outline
-activeoutline
-disabledoutline
-outlinestipple
-activeoutlinestipple
-disabledoutlinestipple
-stipple
-activestipple
-disabledstipple
-state
-tags
-width
-activewidth
-disabledwidth
The following extra options are supported for arcs:

-extent degrees
Specifies the size of the angular range occupied by the arc. The arc's range extends for degrees degrees counter-clockwise from the starting angle given by the -start option. Degrees may be negative. If it is greater than 360 or less than -360, then degrees modulo 360 is used as the extent.

-start degrees
Specifies the beginning of the angular range occupied by the arc. Degrees is given in units of degrees measured counter-clockwise from the 3-o'clock position; it may be either positive or negative.

-style type
Specifies how to draw the arc. If type is pieslice (the default) then the arc's region is defined by a section of the oval's perimeter plus two line segments, one between the center of the oval and each end of the perimeter section. If type is chord then the arc's region is defined by a section of the oval's perimeter plus a single line segment connecting the two end points of the perimeter section. If type is arc then the arc's region consists of a section of the perimeter alone. In this last case the -fill option is ignored.

BITMAP ITEMS

Items of type bitmap appear on the display as images with two colors, foreground and background. Bitmaps are created with widget commands of the following form:
pathName create bitmap x y ?option value option value ...?
pathName create bitmap coordList ?option value option value ...?
The arguments x and y or coordList specify the coordinates of a point used to position the bitmap on the display (see the -anchor option below for more information on how bitmaps are displayed). After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration.
The following standard options are supported by bitmaps:
-state
-tags
The following extra options are supported for bitmaps:

-anchor anchorPos
AnchorPos tells how to position the bitmap relative to the positioning point for the item; it may have any of the forms accepted by Tk_GetAnchor. For example, if anchorPos is center then the bitmap is centered on the point; if anchorPos is n then the bitmap will be drawn so that its top center point is at the positioning point. This option defaults to center.

-background color

-activebackground bitmap

-disabledbackground bitmap
Specifies the color to use for each of the bitmap's '0' valued pixels in its normal, active and disabled states. Color may have any of the forms accepted by Tk_GetColor. If this option isn't specified, or if it is specified as an empty string, then nothing is displayed where the bitmap pixels are 0; this produces a transparent effect.

-bitmap bitmap

-activebitmap bitmap

-disabledbitmap bitmap
Specifies the bitmaps to display in the item in its normal, active and disabled states. Bitmap may have any of the forms accepted by Tk_GetBitmap.

-foreground color

-activeforeground bitmap

-disabledforeground bitmap
Specifies the color to use for each of the bitmap's '1' valued pixels in its normal, active and disabled states. Color may have any of the forms accepted by Tk_GetColor and defaults to black.

IMAGE ITEMS

Items of type image are used to display images on a canvas. Images are created with widget commands of the following form:
pathName create image x y ?option value option value ...?
pathName create image coordList ?option value option value ...?
The arguments x and y or coordList specify the coordinates of a point used to position the image on the display (see the -anchor option below for more information). After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration.
The following standard options are supported by images:
-state
-tags
The following extra options are supported for images:

-anchor anchorPos
AnchorPos tells how to position the image relative to the positioning point for the item; it may have any of the forms accepted by Tk_GetAnchor. For example, if anchorPos is center then the image is centered on the point; if anchorPos is n then the image will be drawn so that its top center point is at the positioning point. This option defaults to center.

-image name

-activeimage name

-disabledimage name
Specifies the name of the images to display in the item in is normal, active and disabled states. This image must have been created previously with the image create command.

LINE ITEMS

Items of type line appear on the display as one or more connected line segments or curves. Line items support coordinate indexing operations using the canvas widget commands: dchars, index, insert. Lines are created with widget commands of the following form:
pathName create line x1 y1... xn yn ?option value option value ...?
pathName create line coordList ?option value option value ...?
The arguments x1 through yn or coordList give the coordinates for a series of two or more points that describe a series of connected line segments. After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration.
The following standard options are supported by lines:
-dash
-activedash
-disableddash
-dashoffset
-fill
-activefill
-disabledfill
-stipple
-activestipple
-disabledstipple
-state
-tags
-width
-activewidth
-disabledwidth
The following extra options are supported for lines:

-arrow where
Indicates whether or not arrowheads are to be drawn at one or both ends of the line. Where must have one of the values none (for no arrowheads), first (for an arrowhead at the first point of the line), last (for an arrowhead at the last point of the line), or both (for arrowheads at both ends). This option defaults to none.

-arrowshape shape
This option indicates how to draw arrowheads. The shape argument must be a list with three elements, each specifying a distance in any of the forms described in the COORDINATES section above. The first element of the list gives the distance along the line from the neck of the arrowhead to its tip. The second element gives the distance along the line from the trailing points of the arrowhead to the tip, and the third element gives the distance from the outside edge of the line to the trailing points. If this option isn't specified then Tk picks a ``reasonable'' shape.

-capstyle style
Specifies the ways in which caps are to be drawn at the endpoints of the line. Style may have any of the forms accepted by Tk_GetCapStyle (butt, projecting, or round). If this option isn't specified then it defaults to butt. Where arrowheads are drawn the cap style is ignored.

-joinstyle style
Specifies the ways in which joints are to be drawn at the vertices of the line. Style may have any of the forms accepted by Tk_GetCapStyle (bevel, miter, or round). If this option isn't specified then it defaults to miter. If the line only contains two points then this option is irrelevant.

-smooth boolean
Boolean must have one of the forms accepted by Tk_GetBoolean. It indicates whether or not the line should be drawn as a curve. If so, the line is rendered as a set of parabolic splines: one spline is drawn for the first and second line segments, one for the second and third, and so on. Straight-line segments can be generated within a curve by duplicating the end-points of the desired line segment.

-splinesteps number
Specifies the degree of smoothness desired for curves: each spline will be approximated with number line segments. This option is ignored unless the -smooth option is true.

OVAL ITEMS

Items of type oval appear as circular or oval regions on the display. Each oval may have an outline, a fill, or both. Ovals are created with widget commands of the following form:
pathName create oval x1 y1 x2 y2 ?option value option value ...?
pathName create oval coordList ?option value option value ...?
The arguments x1, y1, x2, and y2 or coordList give the coordinates of two diagonally opposite corners of a rectangular region enclosing the oval. The oval will include the top and left edges of the rectangle not the lower or right edges. If the region is square then the resulting oval is circular; otherwise it is elongated in shape. After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration.
The following standard options are supported by ovals:
-dash
-activedash
-disableddash
-dashoffset
-fill
-activefill
-disabledfill
-offset
-outline
-activeoutline
-disabledoutline
-outlinestipple
-activeoutlinestipple
-disabledoutlinestipple
-stipple
-activestipple
-disabledstipple
-state
-tags
-width
-activewidth
-disabledwidth

POLYGON ITEMS

Items of type polygon appear as polygonal or curved filled regions on the display. Polygon items support coordinate indexing operations using the canvas widget commands: dchars, index, insert. Polygons are created with widget commands of the following form:
pathName create polygon x1 y1 ... xn yn ?option value option value ...?
pathName create polygon coordList ?option value option value ...?
The arguments x1 through yn or coordList specify the coordinates for three or more points that define a polygon. The first point should not be repeated as the last to close the shape; Tk will automatically close the periphery between the first and last points. After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration.
The following standard options are supported by polygons:
-dash
-activedash
-disableddash
-dashoffset
-fill
-activefill
-disabledfill
-offset
-outline
-activeoutline
-disabledoutline
-outlinestipple
-activeoutlinestipple
-disabledoutlinestipple
-stipple
-activestipple
-disabledstipple
-state
-tags
-width
-activewidth
-disabledwidth
The following extra options are supported for polygons:

-joinstyle style
Specifies the ways in which joints are to be drawn at the vertices of the outline. Style may have any of the forms accepted by Tk_GetCapStyle (bevel, miter, or round). If this option isn't specified then it defaults to miter.

-smooth boolean
Boolean must have one of the forms accepted by Tk_GetBoolean It indicates whether or not the polygon should be drawn with a curved perimeter. If so, the outline of the polygon becomes a set of parabolic splines, one spline for the first and second line segments, one for the second and third, and so on. Straight-line segments can be generated in a smoothed polygon by duplicating the end-points of the desired line segment.

-splinesteps number
Specifies the degree of smoothness desired for curves: each spline will be approximated with number line segments. This option is ignored unless the -smooth option is true.

Polygon items are different from other items such as rectangles, ovals and arcs in that interior points are considered to be ``inside'' a polygon (e.g. for purposes of the find closest and find overlapping widget commands) even if it is not filled. For most other item types, an interior point is considered to be inside the item only if the item is filled or if it has neither a fill nor an outline. If you would like an unfilled polygon whose interior points are not considered to be inside the polygon, use a line item instead.

RECTANGLE ITEMS

Items of type rectangle appear as rectangular regions on the display. Each rectangle may have an outline, a fill, or both. Rectangles are created with widget commands of the following form:
pathName create rectangle x1 y1 x2 y2 ?option value option value ...?
pathName create rectangle coordList ?option value option value ...?
The arguments x1, y1, x2, and y2 or coordList give the coordinates of two diagonally opposite corners of the rectangle (the rectangle will include its upper and left edges but not its lower or right edges). After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration.
The following standard options are supported by rectangles:
-dash
-activedash
-disableddash
-dashoffset
-fill
-activefill
-disabledfill
-offset
-outline
-activeoutline
-disabledoutline
-outlinestipple
-activeoutlinestipple
-disabledoutlinestipple
-stipple
-activestipple
-disabledstipple
-state
-tags
-width
-activewidth
-disabledwidth

TEXT ITEMS

A text item displays a string of characters on the screen in one or more lines. Text items support indexing and selection, along with the following text-related canvas widget commands: dchars, focus, icursor, index, insert, select. Text items are created with widget commands of the following form:
pathName create text x y ?option value option value ...?
pathName create text coordList ?option value option value ...?
The arguments x and y or coordList specify the coordinates of a point used to position the text on the display (see the options below for more information on how text is displayed). After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration.
The following standard options are supported by text items:
-fill
-activefill
-disabledfill
-stipple
-activestipple
-disabledstipple
-state
-tags
The following extra options are supported for text items:

-anchor anchorPos
AnchorPos tells how to position the text relative to the positioning point for the text; it may have any of the forms accepted by Tk_GetAnchor. For example, if anchorPos is center then the text is centered on the point; if anchorPos is n then the text will be drawn such that the top center point of the rectangular region occupied by the text will be at the positioning point. This option defaults to center.

-font fontName
Specifies the font to use for the text item. FontName may be any string acceptable to Tk_GetFont. If this option isn't specified, it defaults to a system-dependent font.

-justify how
Specifies how to justify the text within its bounding region. How must be one of the values left, right, or center. This option will only matter if the text is displayed as multiple lines. If the option is omitted, it defaults to left.

-text string
String specifies the characters to be displayed in the text item. Newline characters cause line breaks. The characters in the item may also be changed with the insert and delete widget commands. This option defaults to an empty string.

-width lineLength
Specifies a maximum line length for the text, in any of the forms described in the COORDINATES section above. If this option is zero (the default) the text is broken into lines only at newline characters. However, if this option is non-zero then any line that would be longer than lineLength is broken just before a space character to make the line shorter than lineLength; the space character is treated as if it were a newline character.

WINDOW ITEMS

Items of type window cause a particular window to be displayed at a given position on the canvas. Window items are created with widget commands of the following form:
pathName create window x y ?option value option value ...?
pathName create window coordList ?option value option value ...?
The arguments x and y or coordList specify the coordinates of a point used to position the window on the display (see the -anchor option below for more information on how bitmaps are displayed). After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration.
The following standard options are supported by window items:
-state
-tags
The following extra options are supported for window items:

-anchor anchorPos
AnchorPos tells how to position the window relative to the positioning point for the item; it may have any of the forms accepted by Tk_GetAnchor. For example, if anchorPos is center then the window is centered on the point; if anchorPos is n then the window will be drawn so that its top center point is at the positioning point. This option defaults to center.

-height pixels
Specifies the height to assign to the item's window. Pixels may have any of the forms described in the COORDINATES section above. If this option isn't specified, or if it is specified as an empty string, then the window is given whatever height it requests internally.

-width pixels
Specifies the width to assign to the item's window. Pixels may have any of the forms described in the COORDINATES section above. If this option isn't specified, or if it is specified as an empty string, then the window is given whatever width it requests internally.

-window pathName
Specifies the window to associate with this item. The window specified by pathName must either be a child of the canvas widget or a child of some ancestor of the canvas widget. PathName may not refer to a top-level window.

Note: due to restrictions in the ways that windows are managed, it is not possible to draw other graphical items (such as lines and images) on top of window items. A window item always obscures any graphics that overlap it, regardless of their order in the display list.

APPLICATION-DEFINED ITEM TYPES

It is possible for individual applications to define new item types for canvas widgets using C code. See the documentation for Tk_CreateItemType.

BINDINGS

In the current implementation, new canvases are not given any default behavior: you'll have to execute explicit Tcl commands to give the canvas its behavior.

CREDITS

Tk's canvas widget is a blatant ripoff of ideas from Joel Bartlett's ezd program. Ezd provides structured graphics in a Scheme environment and preceded canvases by a year or two. Its simple mechanisms for placing and animating graphical objects inspired the functions of canvases.

KEYWORDS

canvas, widget
Copyright © 1992-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
Copyright © 1997-1999 Scriptics Corporation.


Tk Built-In Commands - checkbutton manual page

NAME
checkbutton - Create and manipulate checkbutton widgets
SYNOPSIS
checkbutton pathName ?options?
STANDARD OPTIONS
-activebackground, activeBackground, Foreground
-activeforeground, activeForeground, Background
-anchor, anchor, Anchor
-background or -bg, background, Background
-bitmap, bitmap, Bitmap
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-image, image, Image
-justify, justify, Justify
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-underline, underline, Underline
-wraplength, wrapLength, WrapLength
WIDGET-SPECIFIC OPTIONS
-command, command, Command
-height, height, Height
-indicatoron, indicatorOn, IndicatorOn
-offvalue, offValue, Value
-onvalue, onValue, Value
-selectcolor, selectColor, Background
-selectimage, selectImage, SelectImage
-state, state, State
-variable, variable, Variable
-width, width, Width
DESCRIPTION
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName deselect
pathName flash
pathName invoke
pathName select
pathName toggle
BINDINGS
KEYWORDS

NAME

checkbutton - Create and manipulate checkbutton widgets

SYNOPSIS

checkbutton pathName ?options?

STANDARD OPTIONS

-activebackground, activeBackground, Foreground
-activeforeground, activeForeground, Background
-anchor, anchor, Anchor
-background or -bg, background, Background
-bitmap, bitmap, Bitmap
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-image, image, Image
-justify, justify, Justify
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-underline, underline, Underline
-wraplength, wrapLength, WrapLength

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -command
Database Name: command
Database Class: Command
Specifies a Tcl command to associate with the button. This command is typically invoked when mouse button 1 is released over the button window. The button's global variable (-variable option) will be updated before the command is invoked.

Command-Line Name: -height
Database Name: height
Database Class: Height
Specifies a desired height for the button. If an image or bitmap is being displayed in the button then the value is in screen units (i.e. any of the forms acceptable to Tk_GetPixels); for text it is in lines of text. If this option isn't specified, the button's desired height is computed from the size of the image or bitmap or text being displayed in it.

Command-Line Name: -indicatoron
Database Name: indicatorOn
Database Class: IndicatorOn
Specifies whether or not the indicator should be drawn. Must be a proper boolean value. If false, the relief option is ignored and the widget's relief is always sunken if the widget is selected and raised otherwise.

Command-Line Name: -offvalue
Database Name: offValue
Database Class: Value
Specifies value to store in the button's associated variable whenever this button is deselected. Defaults to ``0''.

Command-Line Name: -onvalue
Database Name: onValue
Database Class: Value
Specifies value to store in the button's associated variable whenever this button is selected. Defaults to ``1''.

Command-Line Name: -selectcolor
Database Name: selectColor
Database Class: Background
Specifies a background color to use when the button is selected. If indicatorOn is true then the color applies to the indicator. Under Windows, this color is used as the background for the indicator regardless of the select state. If indicatorOn is false, this color is used as the background for the entire widget, in place of background or activeBackground, whenever the widget is selected. If specified as an empty string then no special color is used for displaying when the widget is selected.

Command-Line Name: -selectimage
Database Name: selectImage
Database Class: SelectImage
Specifies an image to display (in place of the image option) when the checkbutton is selected. This option is ignored unless the image option has been specified.

Command-Line Name: -state
Database Name: state
Database Class: State
Specifies one of three states for the checkbutton: normal, active, or disabled. In normal state the checkbutton is displayed using the foreground and background options. The active state is typically used when the pointer is over the checkbutton. In active state the checkbutton is displayed using the activeForeground and activeBackground options. Disabled state means that the checkbutton should be insensitive: the default bindings will refuse to activate the widget and will ignore mouse button presses. In this state the disabledForeground and background options determine how the checkbutton is displayed.

Command-Line Name: -variable
Database Name: variable
Database Class: Variable
Specifies name of global variable to set to indicate whether or not this button is selected. Defaults to the name of the button within its parent (i.e. the last element of the button window's path name).

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies a desired width for the button. If an image or bitmap is being displayed in the button then the value is in screen units (i.e. any of the forms acceptable to Tk_GetPixels); for text it is in characters. If this option isn't specified, the button's desired width is computed from the size of the image or bitmap or text being displayed in it.

DESCRIPTION

The checkbutton command creates a new window (given by the pathName argument) and makes it into a checkbutton widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the checkbutton such as its colors, font, text, and initial relief. The checkbutton command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A checkbutton is a widget that displays a textual string, bitmap or image and a square called an indicator. If text is displayed, it must all be in a single font, but it can occupy multiple lines on the screen (if it contains newlines or if wrapping occurs because of the wrapLength option) and one of the characters may optionally be underlined using the underline option. A checkbutton has all of the behavior of a simple button, including the following: it can display itself in either of three different ways, according to the state option; it can be made to appear raised, sunken, or flat; it can be made to flash; and it invokes a Tcl command whenever mouse button 1 is clicked over the checkbutton.

In addition, checkbuttons can be selected. If a checkbutton is selected then the indicator is normally drawn with a selected appearance, and a Tcl variable associated with the checkbutton is set to a particular value (normally 1). Under Unix, the indicator is drawn with a sunken relief and a special color. Under Windows, the indicator is drawn with a check mark inside. If the checkbutton is not selected, then the indicator is drawn with a deselected appearance, and the associated variable is set to a different value (typically 0). Under Unix, the indicator is drawn with a raised relief and no special color. Under Windows, the indicator is drawn without a check mark inside. By default, the name of the variable associated with a checkbutton is the same as the name used to create the checkbutton. The variable name, and the ``on'' and ``off'' values stored in it, may be modified with options on the command line or in the option database. Configuration options may also be used to modify the way the indicator is displayed (or whether it is displayed at all). By default a checkbutton is configured to select and deselect itself on alternate button clicks. In addition, each checkbutton monitors its associated variable and automatically selects and deselects itself when the variables value changes to and from the button's ``on'' value.

WIDGET COMMAND

The checkbutton command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for checkbutton widgets:

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the checkbutton command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the checkbutton command.

pathName deselect
Deselects the checkbutton and sets the associated variable to its ``off'' value.

pathName flash
Flashes the checkbutton. This is accomplished by redisplaying the checkbutton several times, alternating between active and normal colors. At the end of the flash the checkbutton is left in the same normal/active state as when the command was invoked. This command is ignored if the checkbutton's state is disabled.

pathName invoke
Does just what would have happened if the user invoked the checkbutton with the mouse: toggle the selection state of the button and invoke the Tcl command associated with the checkbutton, if there is one. The return value is the return value from the Tcl command, or an empty string if there is no command associated with the checkbutton. This command is ignored if the checkbutton's state is disabled.

pathName select
Selects the checkbutton and sets the associated variable to its ``on'' value.

pathName toggle
Toggles the selection state of the button, redisplaying it and modifying its associated variable to reflect the new state.

BINDINGS

Tk automatically creates class bindings for checkbuttons that give them the following default behavior:

[1]
On Unix systems, a checkbutton activates whenever the mouse passes over it and deactivates whenever the mouse leaves the checkbutton. On Mac and Windows systems, when mouse button 1 is pressed over a checkbutton, the button activates whenever the mouse pointer is inside the button, and deactivates whenever the mouse pointer leaves the button.

[2]
When mouse button 1 is pressed over a checkbutton, it is invoked (its selection state toggles and the command associated with the button is invoked, if there is one).

[3]
When a checkbutton has the input focus, the space key causes the checkbutton to be invoked. Under Windows, there are additional key bindings; plus (+) and equal (=) select the button, and minus (-) deselects the button.

If the checkbutton's state is disabled then none of the above actions occur: the checkbutton is completely non-responsive.

The behavior of checkbuttons can be changed by defining new bindings for individual widgets or by redefining the class bindings.

KEYWORDS

checkbutton, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tk_chooseColor manual page

NAME

tk_chooseColor - pops up a dialog box for the user to select a color.

SYNOPSIS

tk_chooseColor ?option value ...?

DESCRIPTION

The procedure tk_chooseColor pops up a dialog box for the user to select a color. The following option-value pairs are possible as command line arguments:

-initialcolor color
Specifies the color to display in the color dialog when it pops up. color must be in a form acceptable to the Tk_GetColor function.

-parent window
Makes window the logical parent of the color dialog. The color dialog is displayed on top of its parent window.

-title titleString
Specifies a string to display as the title of the dialog box. If this option is not specified, then a default title will be displayed.

If the user selects a color, tk_chooseColor will return the name of the color in a form acceptable to Tk_GetColor. If the user cancels the operation, both commands will return the empty string.

EXAMPLE

button .b -fg [tk_chooseColor -initialcolor gray -title "Choose color"]

KEYWORDS

color selection dialog
Copyright © 1996 Sun Microsystems, Inc.


Tk Built-In Commands - tk_chooseDirectory manual page

NAME
tk_chooseDirectory - pops up a dialog box for the user to select a directory.
SYNOPSIS
tk_chooseDirectory ?option value ...?
DESCRIPTION
-initialdir dirname
-parent window
-title titleString
-mustexist boolean
SEE ALSO
KEYWORDS

NAME

tk_chooseDirectory - pops up a dialog box for the user to select a directory.

SYNOPSIS

tk_chooseDirectory ?option value ...?

DESCRIPTION

The procedure tk_chooseDirectory pops up a dialog box for the user to select a directory. The following option-value pairs are possible as command line arguments:

-initialdir dirname
Specifies that the directories in directory should be displayed when the dialog pops up. If this parameter is not specified, then the directories in the current working directory are displayed. If the parameter specifies a relative path, the return value will convert the relative path to an absolute path. This option may not always work on the Macintosh. This is not a bug. Rather, the General Controls control panel on the Mac allows the end user to override the application default directory.

-parent window
Makes window the logical parent of the dialog. The dialog is displayed on top of its parent window.

-title titleString
Specifies a string to display as the title of the dialog box. If this option is not specified, then a default title will be displayed.

-mustexist boolean
Specifies whether the user may specify non-existant directories. If this parameter is true, then the user may only select directories that already exist. The default value is false.

SEE ALSO

tk_getOpenFile, tk_getSaveFile

KEYWORDS

directory selection dialog
Copyright © 1998-2000 by Scriptics Corporation.


Tk Built-In Commands - clipboard manual page

NAME

clipboard - Manipulate Tk clipboard

SYNOPSIS

clipboard option ?arg arg ...?

DESCRIPTION

This command provides a Tcl interface to the Tk clipboard, which stores data for later retrieval using the selection mechanism. In order to copy data into the clipboard, clipboard clear must be called, followed by a sequence of one or more calls to clipboard append. To ensure that the clipboard is updated atomically, all appends should be completed before returning to the event loop.

The first argument to clipboard determines the format of the rest of the arguments and the behavior of the command. The following forms are currently supported:

clipboard clear ?-displayof window?
Claims ownership of the clipboard on window's display and removes any previous contents. Window defaults to ``.''. Returns an empty string.

clipboard append ?-displayof window? ?-format format? ?-type type? ?- -? data
Appends data to the clipboard on window's display in the form given by type with the representation given by format and claims ownership of the clipboard on window's display.

Type specifies the form in which the selection is to be returned (the desired ``target'' for conversion, in ICCCM terminology), and should be an atom name such as STRING or FILE_NAME; see the Inter-Client Communication Conventions Manual for complete details. Type defaults to STRING.

The format argument specifies the representation that should be used to transmit the selection to the requester (the second column of Table 2 of the ICCCM), and defaults to STRING. If format is STRING, the selection is transmitted as 8-bit ASCII characters. If format is ATOM, then the data is divided into fields separated by white space; each field is converted to its atom value, and the 32-bit atom value is transmitted instead of the atom name. For any other format, data is divided into fields separated by white space and each field is converted to a 32-bit integer; an array of integers is transmitted to the selection requester. Note that strings passed to clipboard append are concatenated before conversion, so the caller must take care to ensure appropriate spacing across string boundaries. All items appended to the clipboard with the same type must have the same format.

The format argument is needed only for compatibility with clipboard requesters that don't use Tk. If the Tk toolkit is being used to retrieve the CLIPBOARD selection then the value is converted back to a string at the requesting end, so format is irrelevant.

A - - argument may be specified to mark the end of options: the next argument will always be used as data. This feature may be convenient if, for example, data starts with a -.

KEYWORDS

clear, format, clipboard, append, selection, type
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - colors manual page

NAME

colors - symbolic color names recognized by Tk

DESCRIPTION

Tk recognizes many symbolic color names (eg, red) when specifying colors. The symbolic names recognized by Tk and their 8-bit RGB values are:
alice blue                 240   248   248
AliceBlue                  240   248   248
antique white              250   235   235
AntiqueWhite               250   235   235
AntiqueWhite1              255   239   239
AntiqueWhite2              238   223   223
AntiqueWhite3              205   192   192
AntiqueWhite4              139   131   131
aquamarine                 127   255   255
aquamarine1                127   255   255
aquamarine2                118   238   238
aquamarine3                102   205   205
aquamarine4                 69   139   139
azure                      240   255   255
azure1                     240   255   255
azure2                     224   238   238
azure3                     193   205   205
azure4                     131   139   139
beige                      245   245   245
bisque                     255   228   228
bisque1                    255   228   228
bisque2                    238   213   213
bisque3                    205   183   183
bisque4                    139   125   125
black                        0     0     0
blanched almond            255   235   235
BlanchedAlmond             255   235   235
blue                         0     0     0
blue violet                138    43    43
blue1                        0     0     0
blue2                        0     0     0
blue3                        0     0     0
blue4                        0     0     0
BlueViolet                 138    43    43
brown                      165    42    42
brown1                     255    64    64
brown2                     238    59    59
brown3                     205    51    51
brown4                     139    35    35
burlywood                  222   184   184
burlywood1                 255   211   211
burlywood2                 238   197   197
burlywood3                 205   170   170
burlywood4                 139   115   115
cadet blue                  95   158   158
CadetBlue                   95   158   158
CadetBlue1                 152   245   245
CadetBlue2                 142   229   229
CadetBlue3                 122   197   197
CadetBlue4                  83   134   134
chartreuse                 127   255   255
chartreuse1                127   255   255
chartreuse2                118   238   238
chartreuse3                102   205   205
chartreuse4                 69   139   139
chocolate                  210   105   105
chocolate1                 255   127   127
chocolate2                 238   118   118
chocolate3                 205   102   102
chocolate4                 139    69    69
coral                      255   127   127
coral1                     255   114   114
coral2                     238   106   106
coral3                     205    91    91
coral4                     139    62    62
cornflower blue            100   149   149
CornflowerBlue             100   149   149
cornsilk                   255   248   248
cornsilk1                  255   248   248
cornsilk2                  238   232   232
cornsilk3                  205   200   200
cornsilk4                  139   136   136
cyan                         0   255   255
cyan1                        0   255   255
cyan2                        0   238   238
cyan3                        0   205   205
cyan4                        0   139   139
dark blue                    0     0     0
dark cyan                    0   139   139
dark goldenrod             184   134   134
dark gray                  169   169   169
dark green                   0   100   100
dark grey                  169   169   169
dark khaki                 189   183   183
dark magenta               139     0     0
dark olive green            85   107   107
dark orange                255   140   140
dark orchid                153    50    50
dark red                   139     0     0
dark salmon                233   150   150
dark sea green             143   188   188
dark slate blue             72    61    61
dark slate gray             47    79    79
dark slate grey             47    79    79
dark turquoise               0   206   206
dark violet                148     0     0
DarkBlue                     0     0     0
DarkCyan                     0   139   139
DarkGoldenrod              184   134   134
DarkGoldenrod1             255   185   185
DarkGoldenrod2             238   173   173
DarkGoldenrod3             205   149   149
DarkGoldenrod4             139   101   101
DarkGray                   169   169   169
DarkGreen                    0   100   100
DarkGrey                   169   169   169
DarkKhaki                  189   183   183
DarkMagenta                139     0     0
DarkOliveGreen              85   107   107
DarkOliveGreen1            202   255   255
DarkOliveGreen2            188   238   238
DarkOliveGreen3            162   205   205
DarkOliveGreen4            110   139   139
DarkOrange                 255   140   140
DarkOrange1                255   127   127
DarkOrange2                238   118   118
DarkOrange3                205   102   102
DarkOrange4                139    69    69
DarkOrchid                 153    50    50
DarkOrchid1                191    62    62
DarkOrchid2                178    58    58
DarkOrchid3                154    50    50
DarkOrchid4                104    34    34
DarkRed                    139     0     0
DarkSalmon                 233   150   150
DarkSeaGreen               143   188   188
DarkSeaGreen1              193   255   255
DarkSeaGreen2              180   238   238
DarkSeaGreen3              155   205   205
DarkSeaGreen4              105   139   139
DarkSlateBlue               72    61    61
DarkSlateGray               47    79    79
DarkSlateGray1             151   255   255
DarkSlateGray2             141   238   238
DarkSlateGray3             121   205   205
DarkSlateGray4              82   139   139
DarkSlateGrey               47    79    79
DarkTurquoise                0   206   206
DarkViolet                 148     0     0
deep pink                  255    20    20
deep sky blue                0   191   191
DeepPink                   255    20    20
DeepPink1                  255    20    20
DeepPink2                  238    18    18
DeepPink3                  205    16    16
DeepPink4                  139    10    10
DeepSkyBlue                  0   191   191
DeepSkyBlue1                 0   191   191
DeepSkyBlue2                 0   178   178
DeepSkyBlue3                 0   154   154
DeepSkyBlue4                 0   104   104
dim gray                   105   105   105
dim grey                   105   105   105
DimGray                    105   105   105
DimGrey                    105   105   105
dodger blue                 30   144   144
DodgerBlue                  30   144   144
DodgerBlue1                 30   144   144
DodgerBlue2                 28   134   134
DodgerBlue3                 24   116   116
DodgerBlue4                 16    78    78
firebrick                  178    34    34
firebrick1                 255    48    48
firebrick2                 238    44    44
firebrick3                 205    38    38
firebrick4                 139    26    26
floral white               255   250   250
FloralWhite                255   250   250
forest green                34   139   139
ForestGreen                 34   139   139
gainsboro                  220   220   220
ghost white                248   248   248
GhostWhite                 248   248   248
gold                       255   215   215
gold1                      255   215   215
gold2                      238   201   201
gold3                      205   173   173
gold4                      139   117   117
goldenrod                  218   165   165
goldenrod1                 255   193   193
goldenrod2                 238   180   180
goldenrod3                 205   155   155
goldenrod4                 139   105   105
gray                       190   190   190
gray0                        0     0     0
gray1                        3     3     3
gray2                        5     5     5
gray3                        8     8     8
gray4                       10    10    10
gray5                       13    13    13
gray6                       15    15    15
gray7                       18    18    18
gray8                       20    20    20
gray9                       23    23    23
gray10                      26    26    26
gray11                      28    28    28
gray12                      31    31    31
gray13                      33    33    33
gray14                      36    36    36
gray15                      38    38    38
gray16                      41    41    41
gray17                      43    43    43
gray18                      46    46    46
gray19                      48    48    48
gray20                      51    51    51
gray21                      54    54    54
gray22                      56    56    56
gray23                      59    59    59
gray24                      61    61    61
gray25                      64    64    64
gray26                      66    66    66
gray27                      69    69    69
gray28                      71    71    71
gray29                      74    74    74
gray30                      77    77    77
gray31                      79    79    79
gray32                      82    82    82
gray33                      84    84    84
gray34                      87    87    87
gray35                      89    89    89
gray36                      92    92    92
gray37                      94    94    94
gray38                      97    97    97
gray39                      99    99    99
gray40                     102   102   102
gray41                     105   105   105
gray42                     107   107   107
gray43                     110   110   110
gray44                     112   112   112
gray45                     115   115   115
gray46                     117   117   117
gray47                     120   120   120
gray48                     122   122   122
gray49                     125   125   125
gray50                     127   127   127
gray51                     130   130   130
gray52                     133   133   133
gray53                     135   135   135
gray54                     138   138   138
gray55                     140   140   140
gray56                     143   143   143
gray57                     145   145   145
gray58                     148   148   148
gray59                     150   150   150
gray60                     153   153   153
gray61                     156   156   156
gray62                     158   158   158
gray63                     161   161   161
gray64                     163   163   163
gray65                     166   166   166
gray66                     168   168   168
gray67                     171   171   171
gray68                     173   173   173
gray69                     176   176   176
gray70                     179   179   179
gray71                     181   181   181
gray72                     184   184   184
gray73                     186   186   186
gray74                     189   189   189
gray75                     191   191   191
gray76                     194   194   194
gray77                     196   196   196
gray78                     199   199   199
gray79                     201   201   201
gray80                     204   204   204
gray81                     207   207   207
gray82                     209   209   209
gray83                     212   212   212
gray84                     214   214   214
gray85                     217   217   217
gray86                     219   219   219
gray87                     222   222   222
gray88                     224   224   224
gray89                     227   227   227
gray90                     229   229   229
gray91                     232   232   232
gray92                     235   235   235
gray93                     237   237   237
gray94                     240   240   240
gray95                     242   242   242
gray96                     245   245   245
gray97                     247   247   247
gray98                     250   250   250
gray99                     252   252   252
gray100                    255   255   255
green                        0   255   255
green yellow               173   255   255
green1                       0   255   255
green2                       0   238   238
green3                       0   205   205
green4                       0   139   139
GreenYellow                173   255   255
grey                       190   190   190
grey0                        0     0     0
grey1                        3     3     3
grey2                        5     5     5
grey3                        8     8     8
grey4                       10    10    10
grey5                       13    13    13
grey6                       15    15    15
grey7                       18    18    18
grey8                       20    20    20
grey9                       23    23    23
grey10                      26    26    26
grey11                      28    28    28
grey12                      31    31    31
grey13                      33    33    33
grey14                      36    36    36
grey15                      38    38    38
grey16                      41    41    41
grey17                      43    43    43
grey18                      46    46    46
grey19                      48    48    48
grey20                      51    51    51
grey21                      54    54    54
grey22                      56    56    56
grey23                      59    59    59
grey24                      61    61    61
grey25                      64    64    64
grey26                      66    66    66
grey27                      69    69    69
grey28                      71    71    71
grey29                      74    74    74
grey30                      77    77    77
grey31                      79    79    79
grey32                      82    82    82
grey33                      84    84    84
grey34                      87    87    87
grey35                      89    89    89
grey36                      92    92    92
grey37                      94    94    94
grey38                      97    97    97
grey39                      99    99    99
grey40                     102   102   102
grey41                     105   105   105
grey42                     107   107   107
grey43                     110   110   110
grey44                     112   112   112
grey45                     115   115   115
grey46                     117   117   117
grey47                     120   120   120
grey48                     122   122   122
grey49                     125   125   125
grey50                     127   127   127
grey51                     130   130   130
grey52                     133   133   133
grey53                     135   135   135
grey54                     138   138   138
grey55                     140   140   140
grey56                     143   143   143
grey57                     145   145   145
grey58                     148   148   148
grey59                     150   150   150
grey60                     153   153   153
grey61                     156   156   156
grey62                     158   158   158
grey63                     161   161   161
grey64                     163   163   163
grey65                     166   166   166
grey66                     168   168   168
grey67                     171   171   171
grey68                     173   173   173
grey69                     176   176   176
grey70                     179   179   179
grey71                     181   181   181
grey72                     184   184   184
grey73                     186   186   186
grey74                     189   189   189
grey75                     191   191   191
grey76                     194   194   194
grey77                     196   196   196
grey78                     199   199   199
grey79                     201   201   201
grey80                     204   204   204
grey81                     207   207   207
grey82                     209   209   209
grey83                     212   212   212
grey84                     214   214   214
grey85                     217   217   217
grey86                     219   219   219
grey87                     222   222   222
grey88                     224   224   224
grey89                     227   227   227
grey90                     229   229   229
grey91                     232   232   232
grey92                     235   235   235
grey93                     237   237   237
grey94                     240   240   240
grey95                     242   242   242
grey96                     245   245   245
grey97                     247   247   247
grey98                     250   250   250
grey99                     252   252   252
grey100                    255   255   255
honeydew                   240   255   255
honeydew1                  240   255   255
honeydew2                  224   238   238
honeydew3                  193   205   205
honeydew4                  131   139   139
hot pink                   255   105   105
HotPink                    255   105   105
HotPink1                   255   110   110
HotPink2                   238   106   106
HotPink3                   205    96    96
HotPink4                   139    58    58
indian red                 205    92    92
IndianRed                  205    92    92
IndianRed1                 255   106   106
IndianRed2                 238    99    99
IndianRed3                 205    85    85
IndianRed4                 139    58    58
ivory                      255   255   255
ivory1                     255   255   255
ivory2                     238   238   238
ivory3                     205   205   205
ivory4                     139   139   139
khaki                      240   230   230
khaki1                     255   246   246
khaki2                     238   230   230
khaki3                     205   198   198
khaki4                     139   134   134
lavender                   230   230   230
lavender blush             255   240   240
LavenderBlush              255   240   240
LavenderBlush1             255   240   240
LavenderBlush2             238   224   224
LavenderBlush3             205   193   193
LavenderBlush4             139   131   131
lawn green                 124   252   252
LawnGreen                  124   252   252
lemon chiffon              255   250   250
LemonChiffon               255   250   250
LemonChiffon1              255   250   250
LemonChiffon2              238   233   233
LemonChiffon3              205   201   201
LemonChiffon4              139   137   137
light blue                 173   216   216
light coral                240   128   128
light cyan                 224   255   255
light goldenrod            238   221   221
light goldenrod yellow     250   250   250
light gray                 211   211   211
light green                144   238   238
light grey                 211   211   211
light pink                 255   182   182
light salmon               255   160   160
light sea green             32   178   178
light sky blue             135   206   206
light slate blue           132   112   112
light slate gray           119   136   136
light slate grey           119   136   136
light steel blue           176   196   196
light yellow               255   255   255
LightBlue                  173   216   216
LightBlue1                 191   239   239
LightBlue2                 178   223   223
LightBlue3                 154   192   192
LightBlue4                 104   131   131
LightCoral                 240   128   128
LightCyan                  224   255   255
LightCyan1                 224   255   255
LightCyan2                 209   238   238
LightCyan3                 180   205   205
LightCyan4                 122   139   139
LightGoldenrod             238   221   221
LightGoldenrod1            255   236   236
LightGoldenrod2            238   220   220
LightGoldenrod3            205   190   190
LightGoldenrod4            139   129   129
LightGoldenrodYellow       250   250   250
LightGray                  211   211   211
LightGreen                 144   238   238
LightGrey                  211   211   211
LightPink                  255   182   182
LightPink1                 255   174   174
LightPink2                 238   162   162
LightPink3                 205   140   140
LightPink4                 139    95    95
LightSalmon                255   160   160
LightSalmon1               255   160   160
LightSalmon2               238   149   149
LightSalmon3               205   129   129
LightSalmon4               139    87    87
LightSeaGreen               32   178   178
LightSkyBlue               135   206   206
LightSkyBlue1              176   226   226
LightSkyBlue2              164   211   211
LightSkyBlue3              141   182   182
LightSkyBlue4               96   123   123
LightSlateBlue             132   112   112
LightSlateGray             119   136   136
LightSlateGrey             119   136   136
LightSteelBlue             176   196   196
LightSteelBlue1            202   225   225
LightSteelBlue2            188   210   210
LightSteelBlue3            162   181   181
LightSteelBlue4            110   123   123
LightYellow                255   255   255
LightYellow1               255   255   255
LightYellow2               238   238   238
LightYellow3               205   205   205
LightYellow4               139   139   139
lime green                  50   205   205
LimeGreen                   50   205   205
linen                      250   240   240
magenta                    255     0     0
magenta1                   255     0     0
magenta2                   238     0     0
magenta3                   205     0     0
magenta4                   139     0     0
maroon                     176    48    48
maroon1                    255    52    52
maroon2                    238    48    48
maroon3                    205    41    41
maroon4                    139    28    28
medium aquamarine          102   205   205
medium blue                  0     0     0
medium orchid              186    85    85
medium purple              147   112   112
medium sea green            60   179   179
medium slate blue          123   104   104
medium spring green          0   250   250
medium turquoise            72   209   209
medium violet red          199    21    21
MediumAquamarine           102   205   205
MediumBlue                   0     0     0
MediumOrchid               186    85    85
MediumOrchid1              224   102   102
MediumOrchid2              209    95    95
MediumOrchid3              180    82    82
MediumOrchid4              122    55    55
MediumPurple               147   112   112
MediumPurple1              171   130   130
MediumPurple2              159   121   121
MediumPurple3              137   104   104
MediumPurple4               93    71    71
MediumSeaGreen              60   179   179
MediumSlateBlue            123   104   104
MediumSpringGreen            0   250   250
MediumTurquoise             72   209   209
MediumVioletRed            199    21    21
midnight blue               25    25    25
MidnightBlue                25    25    25
mint cream                 245   255   255
MintCream                  245   255   255
misty rose                 255   228   228
MistyRose                  255   228   228
MistyRose1                 255   228   228
MistyRose2                 238   213   213
MistyRose3                 205   183   183
MistyRose4                 139   125   125
moccasin                   255   228   228
navajo white               255   222   222
NavajoWhite                255   222   222
NavajoWhite1               255   222   222
NavajoWhite2               238   207   207
NavajoWhite3               205   179   179
NavajoWhite4               139   121   121
navy                         0     0     0
navy blue                    0     0     0
NavyBlue                     0     0     0
old lace                   253   245   245
OldLace                    253   245   245
olive drab                 107   142   142
OliveDrab                  107   142   142
OliveDrab1                 192   255   255
OliveDrab2                 179   238   238
OliveDrab3                 154   205   205
OliveDrab4                 105   139   139
orange                     255   165   165
orange red                 255    69    69
orange1                    255   165   165
orange2                    238   154   154
orange3                    205   133   133
orange4                    139    90    90
OrangeRed                  255    69    69
OrangeRed1                 255    69    69
OrangeRed2                 238    64    64
OrangeRed3                 205    55    55
OrangeRed4                 139    37    37
orchid                     218   112   112
orchid1                    255   131   131
orchid2                    238   122   122
orchid3                    205   105   105
orchid4                    139    71    71
pale goldenrod             238   232   232
pale green                 152   251   251
pale turquoise             175   238   238
pale violet red            219   112   112
PaleGoldenrod              238   232   232
PaleGreen                  152   251   251
PaleGreen1                 154   255   255
PaleGreen2                 144   238   238
PaleGreen3                 124   205   205
PaleGreen4                  84   139   139
PaleTurquoise              175   238   238
PaleTurquoise1             187   255   255
PaleTurquoise2             174   238   238
PaleTurquoise3             150   205   205
PaleTurquoise4             102   139   139
PaleVioletRed              219   112   112
PaleVioletRed1             255   130   130
PaleVioletRed2             238   121   121
PaleVioletRed3             205   104   104
PaleVioletRed4             139    71    71
papaya whip                255   239   239
PapayaWhip                 255   239   239
peach puff                 255   218   218
PeachPuff                  255   218   218
PeachPuff1                 255   218   218
PeachPuff2                 238   203   203
PeachPuff3                 205   175   175
PeachPuff4                 139   119   119
peru                       205   133   133
pink                       255   192   192
pink1                      255   181   181
pink2                      238   169   169
pink3                      205   145   145
pink4                      139    99    99
plum                       221   160   160
plum1                      255   187   187
plum2                      238   174   174
plum3                      205   150   150
plum4                      139   102   102
powder blue                176   224   224
PowderBlue                 176   224   224
purple                     160    32    32
purple1                    155    48    48
purple2                    145    44    44
purple3                    125    38    38
purple4                     85    26    26
red                        255     0     0
red1                       255     0     0
red2                       238     0     0
red3                       205     0     0
red4                       139     0     0
rosy brown                 188   143   143
RosyBrown                  188   143   143
RosyBrown1                 255   193   193
RosyBrown2                 238   180   180
RosyBrown3                 205   155   155
RosyBrown4                 139   105   105
royal blue                  65   105   105
RoyalBlue                   65   105   105
RoyalBlue1                  72   118   118
RoyalBlue2                  67   110   110
RoyalBlue3                  58    95    95
RoyalBlue4                  39    64    64
saddle brown               139    69    69
SaddleBrown                139    69    69
salmon                     250   128   128
salmon1                    255   140   140
salmon2                    238   130   130
salmon3                    205   112   112
salmon4                    139    76    76
sandy brown                244   164   164
SandyBrown                 244   164   164
sea green                   46   139   139
SeaGreen                    46   139   139
SeaGreen1                   84   255   255
SeaGreen2                   78   238   238
SeaGreen3                   67   205   205
SeaGreen4                   46   139   139
seashell                   255   245   245
seashell1                  255   245   245
seashell2                  238   229   229
seashell3                  205   197   197
seashell4                  139   134   134
sienna                     160    82    82
sienna1                    255   130   130
sienna2                    238   121   121
sienna3                    205   104   104
sienna4                    139    71    71
sky blue                   135   206   206
SkyBlue                    135   206   206
SkyBlue1                   135   206   206
SkyBlue2                   126   192   192
SkyBlue3                   108   166   166
SkyBlue4                    74   112   112
slate blue                 106    90    90
slate gray                 112   128   128
slate grey                 112   128   128
SlateBlue                  106    90    90
SlateBlue1                 131   111   111
SlateBlue2                 122   103   103
SlateBlue3                 105    89    89
SlateBlue4                  71    60    60
SlateGray                  112   128   128
SlateGray1                 198   226   226
SlateGray2                 185   211   211
SlateGray3                 159   182   182
SlateGray4                 108   123   123
SlateGrey                  112   128   128
snow                       255   250   250
snow1                      255   250   250
snow2                      238   233   233
snow3                      205   201   201
snow4                      139   137   137
spring green                 0   255   255
SpringGreen                  0   255   255
SpringGreen1                 0   255   255
SpringGreen2                 0   238   238
SpringGreen3                 0   205   205
SpringGreen4                 0   139   139
steel blue                  70   130   130
SteelBlue                   70   130   130
SteelBlue1                  99   184   184
SteelBlue2                  92   172   172
SteelBlue3                  79   148   148
SteelBlue4                  54   100   100
tan                        210   180   180
tan1                       255   165   165
tan2                       238   154   154
tan3                       205   133   133
tan4                       139    90    90
thistle                    216   191   191
thistle1                   255   225   225
thistle2                   238   210   210
thistle3                   205   181   181
thistle4                   139   123   123
tomato                     255    99    99
tomato1                    255    99    99
tomato2                    238    92    92
tomato3                    205    79    79
tomato4                    139    54    54
turquoise                   64   224   224
turquoise1                   0   245   245
turquoise2                   0   229   229
turquoise3                   0   197   197
turquoise4                   0   134   134
violet                     238   130   130
violet red                 208    32    32
VioletRed                  208    32    32
VioletRed1                 255    62    62
VioletRed2                 238    58    58
VioletRed3                 205    50    50
VioletRed4                 139    34    34
wheat                      245   222   222
wheat1                     255   231   231
wheat2                     238   216   216
wheat3                     205   186   186
wheat4                     139   126   126
white                      255   255   255
white smoke                245   245   245
WhiteSmoke                 245   245   245
yellow                     255   255   255
yellow green               154   205   205
yellow1                    255   255   255
yellow2                    238   238   238
yellow3                    205   205   205
yellow4                    139   139   139
YellowGreen                154   205   205

KEYWORDS

color, option
Copyright © 1998-2000 by Scriptics Corporation.


Tk Built-In Commands - cursors manual page

NAME

cursors - mouse cursors available in Tk

DESCRIPTION

The -cursor widget option allows a Tk programmer to change the mouse cursor for a particular widget. The cursor names recognized by Tk on all platforms are:
X_cursor
arrow
based_arrow_down
based_arrow_up
boat
bogosity
bottom_left_corner
bottom_right_corner
bottom_side
bottom_tee
box_spiral
center_ptr
circle
clock
coffee_mug
cross
cross_reverse
crosshair
diamond_cross
dot
dotbox
double_arrow
draft_large
draft_small
draped_box
exchange
fleur
gobbler
gumby
hand1
hand2
heart
icon
iron_cross
left_ptr
left_side
left_tee
leftbutton
ll_angle
lr_angle
man
middlebutton
mouse
pencil
pirate
plus
question_arrow
right_ptr
right_side
right_tee
rightbutton
rtl_logo
sailboat
sb_down_arrow
sb_h_double_arrow
sb_left_arrow
sb_right_arrow
sb_up_arrow
sb_v_double_arrow
shuttle
sizing
spider
spraycan
star
target
tcross
top_left_arrow
top_left_corner
top_right_corner
top_side
top_tee
trek
ul_angle
umbrella
ur_angle
watch
xterm

PORTABILITY ISSUES

Windows
On Windows systems, the following cursors are mapped to native cursors:
arrow
center_ptr
crosshair
fleur
ibeam
icon
sb_h_double_arrow
sb_v_double_arrow
watch
xterm
And the following additional cursors are available:
no
starting
size
size_ne_sw
size_ns
size_nw_se
size_we
uparrow
wait
The no cursor can be specified to eliminate the cursor.

Macintosh
On Macintosh systems, the following cursors are mapped to native cursors:
arrow
cross
crosshair
ibeam
plus
watch
xterm
And the following additional cursors are available:
text
cross-hair

KEYWORDS

cursor, option
Copyright © 1998-2000 by Scriptics Corporation.


Built-In Commands - destroy manual page

NAME

destroy - Destroy one or more windows

SYNOPSIS

destroy ?window window ...?

DESCRIPTION

This command deletes the windows given by the window arguments, plus all of their descendants. If a window ``.'' is deleted then the entire application will be destroyed. The windows are destroyed in order, and if an error occurs in destroying a window the command aborts without destroying the remaining windows. No error is returned if window does not exist.

KEYWORDS

application, destroy, window
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tk_dialog manual page

NAME
tk_dialog - Create modal dialog and wait for response
SYNOPSIS
tk_dialog window title text bitmap default string string ...
DESCRIPTION
window
title
text
bitmap
default
string
KEYWORDS

NAME

tk_dialog - Create modal dialog and wait for response

SYNOPSIS

tk_dialog window title text bitmap default string string ...

DESCRIPTION

This procedure is part of the Tk script library. Its arguments describe a dialog box:

window
Name of top-level window to use for dialog. Any existing window by this name is destroyed.

title
Text to appear in the window manager's title bar for the dialog.

text
Message to appear in the top portion of the dialog box.

bitmap
If non-empty, specifies a bitmap to display in the top portion of the dialog, to the left of the text. If this is an empty string then no bitmap is displayed in the dialog.

default
If this is an integer greater than or equal to zero, then it gives the index of the button that is to be the default button for the dialog (0 for the leftmost button, and so on). If less than zero or an empty string then there won't be any default button.

string
There will be one button for each of these arguments. Each string specifies text to display in a button, in order from left to right.

After creating a dialog box, tk_dialog waits for the user to select one of the buttons either by clicking on the button with the mouse or by typing return to invoke the default button (if any). Then it returns the index of the selected button: 0 for the leftmost button, 1 for the button next to it, and so on. If the dialog's window is destroyed before the user selects one of the buttons, then -1 is returned.

While waiting for the user to respond, tk_dialog sets a local grab. This prevents the user from interacting with the application in any way except to invoke the dialog box.

KEYWORDS

bitmap, dialog, modal
Copyright © 1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - entry manual page

NAME
entry - Create and manipulate entry widgets
SYNOPSIS
entry pathName ?options?
STANDARD OPTIONS
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-exportselection, exportSelection, ExportSelection
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-insertbackground, insertBackground, Foreground
-insertborderwidth, insertBorderWidth, BorderWidth
-insertofftime, insertOffTime, OffTime
-insertontime, insertOnTime, OnTime
-insertwidth, insertWidth, InsertWidth
-justify, justify, Justify
-relief, relief, Relief
-selectbackground, selectBackground, Foreground
-selectborderwidth, selectBorderWidth, BorderWidth
-selectforeground, selectForeground, Background
-takefocus, takeFocus, TakeFocus
-textvariable, textVariable, Variable
-xscrollcommand, xScrollCommand, ScrollCommand
WIDGET-SPECIFIC OPTIONS
-invalidcommand or -invcmd, invalidCommand, InvalidCommand
-show, show, Show
-state, state, State
-validate, validate, Validate
-validatecommand or -vcmd, validateCommand, ValidateCommand
-width, width, Width
DESCRIPTION
VALIDATION
none
focus
focusin
focusout
key
all
%d
%i
%P
%s
%S
%v
%V
%W
WIDGET COMMAND
number
anchor
end
insert
sel.first
sel.last
@number
pathName bbox index
pathName cget option
pathName configure ?option? ?value option value ...?
pathName delete first ?last?
pathName get
pathName icursor index
pathName index index
pathName insert index string
pathName scan option args
pathName scan mark x
pathName scan dragto x
pathName selection option arg
pathName selection adjust index
pathName selection clear
pathName selection from index
pathName selection present
pathName selection range start end
pathName selection to index
.VS 8.3
pathName xview args
pathName xview
pathName xview index
pathName xview moveto fraction
pathName xview scroll number what
DEFAULT BINDINGS
KEYWORDS

NAME

entry - Create and manipulate entry widgets

SYNOPSIS

entry pathName ?options?

STANDARD OPTIONS

-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-exportselection, exportSelection, ExportSelection
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-insertbackground, insertBackground, Foreground
-insertborderwidth, insertBorderWidth, BorderWidth
-insertofftime, insertOffTime, OffTime
-insertontime, insertOnTime, OnTime
-insertwidth, insertWidth, InsertWidth
-justify, justify, Justify
-relief, relief, Relief
-selectbackground, selectBackground, Foreground
-selectborderwidth, selectBorderWidth, BorderWidth
-selectforeground, selectForeground, Background
-takefocus, takeFocus, TakeFocus
-textvariable, textVariable, Variable
-xscrollcommand, xScrollCommand, ScrollCommand

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -invalidcommand or -invcmd
Database Name: invalidCommand
Database Class: InvalidCommand
Specifies a script to eval when validateCommand returns 0. Setting it to {} disables this feature (the default). The best use of this option is to set it to bell. See Validation below for more information.

Command-Line Name: -show
Database Name: show
Database Class: Show
If this option is specified, then the true contents of the entry are not displayed in the window. Instead, each character in the entry's value will be displayed as the first character in the value of this option, such as ``*''. This is useful, for example, if the entry is to be used to enter a password. If characters in the entry are selected and copied elsewhere, the information copied will be what is displayed, not the true contents of the entry.

Command-Line Name: -state
Database Name: state
Database Class: State
Specifies one of two states for the entry: normal or disabled. If the entry is disabled then the value may not be changed using widget commands and no insertion cursor will be displayed, even if the input focus is in the widget.

Command-Line Name: -validate
Database Name: validate
Database Class: Validate
Specifies the mode in which validation should operate: none, focus, focusin, focusout, key, or all. It defaults to none. When you want validation, you must explicitly state which mode you wish to use. See Validation below for more.

Command-Line Name: -validatecommand or -vcmd
Database Name: validateCommand
Database Class: ValidateCommand
Specifies a script to eval when you want to validate the input into the entry widget. Setting it to {} disables this feature (the default). This command must return a valid tcl boolean value. If it returns 0 (or the valid tcl boolean equivalent) then it means you reject the new edition and it will not occur and the invalidCommand will be evaluated if it is set. If it returns 1, then the new edition occurs. See Validation below for more information.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies an integer value indicating the desired width of the entry window, in average-size characters of the widget's font. If the value is less than or equal to zero, the widget picks a size just large enough to hold its current text.

DESCRIPTION

The entry command creates a new window (given by the pathName argument) and makes it into an entry widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the entry such as its colors, font, and relief. The entry command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

An entry is a widget that displays a one-line text string and allows that string to be edited using widget commands described below, which are typically bound to keystrokes and mouse actions. When first created, an entry's string is empty. A portion of the entry may be selected as described below. If an entry is exporting its selection (see the exportSelection option), then it will observe the standard X11 protocols for handling the selection; entry selections are available as type STRING. Entries also observe the standard Tk rules for dealing with the input focus. When an entry has the input focus it displays an insertion cursor to indicate where new characters will be inserted.

Entries are capable of displaying strings that are too long to fit entirely within the widget's window. In this case, only a portion of the string will be displayed; commands described below may be used to change the view in the window. Entries use the standard xScrollCommand mechanism for interacting with scrollbars (see the description of the xScrollCommand option for details). They also support scanning, as described below.

VALIDATION

Validation works by setting the validateCommand option to a script which will be evaluated according to the validate option as follows:

none
Default. This means no validation will occur.

focus
validateCommand will be called when the entry receives or loses focus.

focusin
validateCommand will be called when the entry receives focus.

focusout
validateCommand will be called when the entry loses focus.

key
validateCommand will be called when the entry is edited.

all
validateCommand will be called for all above conditions.

It is posible to perform percent substitutions on the validateCommand and invalidCommand, just as you would in a bind script. The following substitutions are recognized:

%d
Type of action: 1 for insert, 0 for delete, or -1 for focus, forced or textvariable validation.

%i
Index of char string to be inserted/deleted, if any, otherwise -1.

%P
The value of the entry should edition occur. If you are configuring the entry widget to have a new textvariable, this will be the value of that textvariable.

%s
The current value of entry before edition.

%S
The text string being inserted/deleted, if any, {} otherwise.

%v
The type of validation currently set.

%V
The type of validation that triggered the callback (key, focusin, focusout, forced).

%W
The name of the entry widget.

In general, the textVariable and validateCommand can be dangerous to mix. Any problems have been overcome so that using the validateCommand will not interfere with the traditional behavior of the entry widget. Using the textVariable for read-only purposes will never cause problems. The danger comes when you try set the textVariable to something that the validateCommand would not accept, which causes validate to become none (the invalidCommand will not be triggered). The same happens when an error occurs evaluating the validateCommand.

Primarily, an error will occur when the validateCommand or invalidCommand encounters an error in its script while evaluating or validateCommand does not return a valid tcl boolean value. The validate option will also set itself to none when you edit the entry widget from within either the validateCommand or the invalidCommand. Such editions will override the one that was being validated. If you wish to edit the entry widget (for example set it to {}) during validation and still have the validate option set, you should include the command

after idle {%W config -validate %v}
in the validateCommand or invalidCommand (whichever one you were editing the entry widget from). It is also recommended to not set an associated textVariable during validation, as that can cause the entry widget to become out of sync with the textVariable.

WIDGET COMMAND

The entry command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command.

Many of the widget commands for entries take one or more indices as arguments. An index specifies a particular character in the entry's string, in any of the following ways:

number
Specifies the character as a numerical index, where 0 corresponds to the first character in the string.

anchor
Indicates the anchor point for the selection, which is set with the select from and select adjust widget commands.

end
Indicates the character just after the last one in the entry's string. This is equivalent to specifying a numerical index equal to the length of the entry's string.

insert
Indicates the character adjacent to and immediately following the insertion cursor.

sel.first
Indicates the first character in the selection. It is an error to use this form if the selection isn't in the entry window.

sel.last
Indicates the character just after the last one in the selection. It is an error to use this form if the selection isn't in the entry window.

@number
In this form, number is treated as an x-coordinate in the entry's window; the character spanning that x-coordinate is used. For example, ``@0'' indicates the left-most character in the window.

Abbreviations may be used for any of the forms above, e.g. ``e'' or ``sel.f''. In general, out-of-range indices are automatically rounded to the nearest legal value.

The following commands are possible for entry widgets:

pathName bbox index
Returns a list of four numbers describing the bounding box of the character given by index. The first two elements of the list give the x and y coordinates of the upper-left corner of the screen area covered by the character (in pixels relative to the widget) and the last two elements give the width and height of the character, in pixels. The bounding box may refer to a region outside the visible area of the window.

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the entry command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the entry command.

pathName delete first ?last?
Delete one or more elements of the entry. First is the index of the first character to delete, and last is the index of the character just after the last one to delete. If last isn't specified it defaults to first+1, i.e. a single character is deleted. This command returns an empty string.

pathName get
Returns the entry's string.

pathName icursor index
Arrange for the insertion cursor to be displayed just before the character given by index. Returns an empty string.

pathName index index
Returns the numerical index corresponding to index.

pathName insert index string
Insert the characters of string just before the character indicated by index. Returns an empty string.

pathName scan option args
This command is used to implement scanning on entries. It has two forms, depending on option:

pathName scan mark x
Records x and the current view in the entry window; used in conjunction with later scan dragto commands. Typically this command is associated with a mouse button press in the widget. It returns an empty string.

pathName scan dragto x
This command computes the difference between its x argument and the x argument to the last scan mark command for the widget. It then adjusts the view left or right by 10 times the difference in x-coordinates. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the entry at high speed through the window. The return value is an empty string.

pathName selection option arg
This command is used to adjust the selection within an entry. It has several forms, depending on option:

pathName selection adjust index
Locate the end of the selection nearest to the character given by index, and adjust that end of the selection to be at index (i.e including but not going beyond index). The other end of the selection is made the anchor point for future select to commands. If the selection isn't currently in the entry, then a new selection is created to include the characters between index and the most recent selection anchor point, inclusive. Returns an empty string.

pathName selection clear
Clear the selection if it is currently in this widget. If the selection isn't in this widget then the command has no effect. Returns an empty string.

pathName selection from index
Set the selection anchor point to just before the character given by index. Doesn't change the selection. Returns an empty string.

pathName selection present
Returns 1 if there is are characters selected in the entry, 0 if nothing is selected.

pathName selection range start end
Sets the selection to include the characters starting with the one indexed by start and ending with the one just before end. If end refers to the same character as start or an earlier one, then the entry's selection is cleared.

pathName selection to index
If index is before the anchor point, set the selection to the characters from index up to but not including the anchor point. If index is the same as the anchor point, do nothing. If index is after the anchor point, set the selection to the characters from the anchor point up to but not including index. The anchor point is determined by the most recent select from or select adjust command in this widget. If the selection isn't in this widget then a new selection is created using the most recent anchor point specified for the widget. Returns an empty string.

.VS 8.3
pathName validate This command is used to force an evaluation of the validateCommand independent of the conditions specified by the validate option. This is done by temporarily setting the validate option to all. It returns 0 or 1.

pathName xview args
This command is used to query and change the horizontal position of the text in the widget's window. It can take any of the following forms:

pathName xview
Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the horizontal span that is visible in the window. For example, if the first element is .2 and the second element is .6, 20% of the entry's text is off-screen to the left, the middle 40% is visible in the window, and 40% of the text is off-screen to the right. These are the same values passed to scrollbars via the -xscrollcommand option.

pathName xview index
Adjusts the view in the window so that the character given by index is displayed at the left edge of the window.

pathName xview moveto fraction
Adjusts the view in the window so that the character fraction of the way through the text appears at the left edge of the window. Fraction must be a fraction between 0 and 1.

pathName xview scroll number what
This command shifts the view in the window left or right according to number and what. Number must be an integer. What must be either units or pages or an abbreviation of one of these. If what is units, the view adjusts left or right by number average-width characters on the display; if it is pages then the view adjusts by number screenfuls. If number is negative then characters farther to the left become visible; if it is positive then characters farther to the right become visible.

DEFAULT BINDINGS

Tk automatically creates class bindings for entries that give them the following default behavior. In the descriptions below, ``word'' refers to a contiguous group of letters, digits, or ``_'' characters, or any single character other than these.

[1]
Clicking mouse button 1 positions the insertion cursor just before the character underneath the mouse cursor, sets the input focus to this widget, and clears any selection in the widget. Dragging with mouse button 1 strokes out a selection between the insertion cursor and the character under the mouse.

[2]
Double-clicking with mouse button 1 selects the word under the mouse and positions the insertion cursor at the beginning of the word. Dragging after a double click will stroke out a selection consisting of whole words.

[3]
Triple-clicking with mouse button 1 selects all of the text in the entry and positions the insertion cursor before the first character.

[4]
The ends of the selection can be adjusted by dragging with mouse button 1 while the Shift key is down; this will adjust the end of the selection that was nearest to the mouse cursor when button 1 was pressed. If the button is double-clicked before dragging then the selection will be adjusted in units of whole words.

[5]
Clicking mouse button 1 with the Control key down will position the insertion cursor in the entry without affecting the selection.

[6]
If any normal printing characters are typed in an entry, they are inserted at the point of the insertion cursor.

[7]
The view in the entry can be adjusted by dragging with mouse button 2. If mouse button 2 is clicked without moving the mouse, the selection is copied into the entry at the position of the mouse cursor.

[8]
If the mouse is dragged out of the entry on the left or right sides while button 1 is pressed, the entry will automatically scroll to make more text visible (if there is more text off-screen on the side where the mouse left the window).

[9]
The Left and Right keys move the insertion cursor one character to the left or right; they also clear any selection in the entry and set the selection anchor. If Left or Right is typed with the Shift key down, then the insertion cursor moves and the selection is extended to include the new character. Control-Left and Control-Right move the insertion cursor by words, and Control-Shift-Left and Control-Shift-Right move the insertion cursor by words and also extend the selection. Control-b and Control-f behave the same as Left and Right, respectively. Meta-b and Meta-f behave the same as Control-Left and Control-Right, respectively.

[10]
The Home key, or Control-a, will move the insertion cursor to the beginning of the entry and clear any selection in the entry. Shift-Home moves the insertion cursor to the beginning of the entry and also extends the selection to that point.

[11]
The End key, or Control-e, will move the insertion cursor to the end of the entry and clear any selection in the entry. Shift-End moves the cursor to the end and extends the selection to that point.

[12]
The Select key and Control-Space set the selection anchor to the position of the insertion cursor. They don't affect the current selection. Shift-Select and Control-Shift-Space adjust the selection to the current position of the insertion cursor, selecting from the anchor to the insertion cursor if there was not any selection previously.

[13]
Control-/ selects all the text in the entry.

[14]
Control-\ clears any selection in the entry.

[15]
The F16 key (labelled Copy on many Sun workstations) or Meta-w copies the selection in the widget to the clipboard, if there is a selection.

[16]
The F20 key (labelled Cut on many Sun workstations) or Control-w copies the selection in the widget to the clipboard and deletes the selection. If there is no selection in the widget then these keys have no effect.

[17]
The F18 key (labelled Paste on many Sun workstations) or Control-y inserts the contents of the clipboard at the position of the insertion cursor.

[18]
The Delete key deletes the selection, if there is one in the entry. If there is no selection, it deletes the character to the right of the insertion cursor.

[19]
The BackSpace key and Control-h delete the selection, if there is one in the entry. If there is no selection, it deletes the character to the left of the insertion cursor.

[20]
Control-d deletes the character to the right of the insertion cursor.

[21]
Meta-d deletes the word to the right of the insertion cursor.

[22]
Control-k deletes all the characters to the right of the insertion cursor.

[23]
Control-t reverses the order of the two characters to the right of the insertion cursor.

If the entry is disabled using the -state option, then the entry's view can still be adjusted and text in the entry can still be selected, but no insertion cursor will be displayed and no text modifications will take place.

The behavior of entries can be changed by defining new bindings for individual widgets or by redefining the class bindings.

KEYWORDS

entry, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
Copyright © 1998-2000 Scriptics Corporation.


Tk Built-In Commands - event manual page

NAME
event - Miscellaneous event facilities: define virtual events and generate events
SYNOPSIS
event option ?arg arg ...?
DESCRIPTION
event add <<virtual>> sequence ?sequence ...?
event delete <<virtual>> ?sequence sequence ...?
event generate window event ?option value option value ...?
event info ?<<virtual>>?
EVENT FIELDS
-above window
-borderwidth size
-button number
-count number
-delta number
-detail detail
-focus boolean
-height size
-keycode number
-keysym name
-mode notify
-override boolean
-place where
-root window
-rootx coord
-rooty coord
-sendevent boolean
-serial number
-state state
-subwindow window
-time integer
-warp boolean
-width size
-when when
now
tail
head
mark
-x coord
-y coord
VIRTUAL EVENT EXAMPLES
SEE ALSO
KEYWORDS

NAME

event - Miscellaneous event facilities: define virtual events and generate events

SYNOPSIS

event option ?arg arg ...?

DESCRIPTION

The event command provides several facilities for dealing with window system events, such as defining virtual events and synthesizing events. The command has several different forms, determined by the first argument. The following forms are currently supported:

event add <<virtual>> sequence ?sequence ...?
Associates the virtual event virtual with the physical event sequence(s) given by the sequence arguments, so that the virtual event will trigger whenever any one of the sequences occurs. Virtual may be any string value and sequence may have any of the values allowed for the sequence argument to the bind command. If virtual is already defined, the new physical event sequences add to the existing sequences for the event.

event delete <<virtual>> ?sequence sequence ...?
Deletes each of the sequences from those associated with the virtual event given by virtual. Virtual may be any string value and sequence may have any of the values allowed for the sequence argument to the bind command. Any sequences not currently associated with virtual are ignored. If no sequence argument is provided, all physical event sequences are removed for virtual, so that the virtual event will not trigger anymore.

event generate window event ?option value option value ...?
Generates a window event and arranges for it to be processed just as if it had come from the window system. Window gives the path name of the window for which the event will be generated; it may also be an identifier (such as returned by winfo id) as long as it is for a window in the current application. Event provides a basic description of the event, such as <Shift-Button-2> or <<Paste>>. If Window is empty the whole screen is meant, and coordinates are relative to the screen. Event may have any of the forms allowed for the sequence argument of the bind command except that it must consist of a single event pattern, not a sequence. Option-value pairs may be used to specify additional attributes of the event, such as the x and y mouse position; see EVENT FIELDS below. If the -when option is not specified, the event is processed immediately: all of the handlers for the event will complete before the event generate command returns. If the -when option is specified then it determines when the event is processed. Certain events, such as key events, require that the window has focus to receive the event properly.

event info ?<<virtual>>?
Returns information about virtual events. If the <<virtual>> argument is omitted, the return value is a list of all the virtual events that are currently defined. If <<virtual>> is specified then the return value is a list whose elements are the physical event sequences currently defined for the given virtual event; if the virtual event is not defined then an empty string is returned.

EVENT FIELDS

The following options are supported for the event generate command. These correspond to the ``%'' expansions allowed in binding scripts for the bind command.

-above window
Window specifies the above field for the event, either as a window path name or as an integer window id. Valid for Configure events. Corresponds to the %a substitution for binding scripts.

-borderwidth size
Size must be a screen distance; it specifies the border_width field for the event. Valid for Configure events. Corresponds to the %B substitution for binding scripts.

-button number
Number must be an integer; it specifies the detail field for a ButtonPress or ButtonRelease event, overriding any button number provided in the base event argument. Corresponds to the %b substitution for binding scripts.

-count number
Number must be an integer; it specifies the count field for the event. Valid for Expose events. Corresponds to the %c substitution for binding scripts.

-delta number
Number must be an integer; it specifies the delta field for the MouseWheel event. The delta refers to the direction and magnitude the mouse wheel was rotated. Note the value is not a screen distance but are units of motion in the mouse wheel. Typically these values are multiples of 120. For example, 120 should scroll the text widget up 4 lines and -240 would scroll the text widget down 8 lines. Of course, other widgets may define different behaviors for mouse wheel motion. This field corresponds to the %D substitution for binding scripts.

-detail detail
Detail specifies the detail field for the event and must be one of the following:
NotifyAncestor	NotifyNonlinearVirtual
NotifyDetailNone	NotifyPointer
NotifyInferior	NotifyPointerRoot
NotifyNonlinear	NotifyVirtual
Valid for Enter, Leave, FocusIn and FocusOut events. Corresponds to the %d substitution for binding scripts.

-focus boolean
Boolean must be a boolean value; it specifies the focus field for the event. Valid for Enter and Leave events. Corresponds to the %f substitution for binding scripts.

-height size
Size must be a screen distance; it specifies the height field for the event. Valid for Configure events. Corresponds to the %h substitution for binding scripts.

-keycode number
Number must be an integer; it specifies the keycode field for the event. Valid for KeyPress and KeyRelease events. Corresponds to the %k substitution for binding scripts.

-keysym name
Name must be the name of a valid keysym, such as g, space, or Return; its corresponding keycode value is used as the keycode field for event, overriding any detail specified in the base event argument. Valid for KeyPress and KeyRelease events. Corresponds to the %K substitution for binding scripts.

-mode notify
Notify specifies the mode field for the event and must be one of NotifyNormal, NotifyGrab, NotifyUngrab, or NotifyWhileGrabbed. Valid for Enter, Leave, FocusIn, and FocusOut events. Corresponds to the %m substitution for binding scripts.

-override boolean
Boolean must be a boolean value; it specifies the override_redirect field for the event. Valid for Map, Reparent, and Configure events. Corresponds to the %o substitution for binding scripts.

-place where
Where specifies the place field for the event; it must be either PlaceOnTop or PlaceOnBottom. Valid for Circulate events. Corresponds to the %p substitution for binding scripts.

-root window
Window must be either a window path name or an integer window identifier; it specifies the root field for the event. Valid for KeyPress, KeyRelease, ButtonPress, ButtonRelease, Enter, Leave, and Motion events. Corresponds to the %R substitution for binding scripts.

-rootx coord
Coord must be a screen distance; it specifies the x_root field for the event. Valid for KeyPress, KeyRelease, ButtonPress, ButtonRelease, Enter, Leave, and Motion events. Corresponds to the %X substitution for binding scripts.

-rooty coord
Coord must be a screen distance; it specifies th y_root field for the event. Valid for KeyPress, KeyRelease, ButtonPress, ButtonRelease, Enter, Leave, and Motion events. Corresponds to the %Y substitution for binding scripts.

-sendevent boolean
Boolean must be a boolean value; it specifies the send_event field for the event. Valid for all events. Corresponds to the %E substitution for binding scripts.

-serial number
Number must be an integer; it specifies the serial field for the event. Valid for all events. Corresponds to the %# substitution for binding scripts.

-state state
State specifies the state field for the event. For KeyPress, KeyRelease, ButtonPress, ButtonRelease, Enter, Leave, and Motion events it must be an integer value. For Visibility events it must be one of VisibilityUnobscured, VisibilityPartiallyObscured, or VisibilityFullyObscured. This option overrides any modifiers such as Meta or Control specified in the base event. Corresponds to the %s substitution for binding scripts.

-subwindow window
Window specifies the subwindow field for the event, either as a path name for a Tk widget or as an integer window identifier. Valid for KeyPress, KeyRelease, ButtonPress, ButtonRelease, Enter, Leave, and Motion events. Similar to %S substitution for binding scripts.

-time integer
Integer must be an integer value; it specifies the time field for the event. Valid for KeyPress, KeyRelease, ButtonPress, ButtonRelease, Enter, Leave, Motion, and Property events. Corresponds to the %t substitution for binding scripts.

-warp boolean
boolean must be a boolean value; it specifies whether the screen pointer should be warped as well. Valid for KeyPress, KeyRelease, ButtonPress, ButtonRelease, and Motion events. The pointer will only warp to a window if it is mapped.

-width size
Size must be a screen distance; it specifies the width field for the event. Valid for Configure events. Corresponds to the %w substitution for binding scripts.

-when when
When determines when the event will be processed; it must have one of the following values:

now
Process the event immediately, before the command returns. This also happens if the -when option is omitted.

tail
Place the event on Tcl's event queue behind any events already queued for this application.

head
Place the event at the front of Tcl's event queue, so that it will be handled before any other events already queued.

mark
Place the event at the front of Tcl's event queue but behind any other events already queued with -when mark. This option is useful when generating a series of events that should be processed in order but at the front of the queue.

-x coord
Coord must be a screen distance; it specifies the x field for the event. Valid for KeyPress, KeyRelease, ButtonPress, ButtonRelease, Motion, Enter, Leave, Expose, Configure, Gravity, and Reparent events. Corresponds to the the %x substitution for binding scripts. If Window is empty the coordinate is relative to the screen, and this option corresponds to the %X substitution for binding scripts.

-y coord
Coord must be a screen distance; it specifies the y field for the event. Valid for KeyPress, KeyRelease, ButtonPress, ButtonRelease, Motion, Enter, Leave, Expose, Configure, Gravity, and Reparent events. Corresponds to the the %y substitution for binding scripts. If Window is empty the coordinate is relative to the screen, and this option corresponds to the %Y substitution for binding scripts.

Any options that are not specified when generating an event are filled with the value 0, except for serial, which is filled with the next X event serial number.

VIRTUAL EVENT EXAMPLES

In order for a virtual event binding to trigger, two things must happen. First, the virtual event must be defined with the event add command. Second, a binding must be created for the virtual event with the bind command. Consider the following virtual event definitions:
event add <<Paste>> <Control-y>
event add <<Paste>> <Button-2>
event add <<Save>> <Control-X><Control-S>
event add <<Save>> <Shift-F12>
In the bind command, a virtual event can be bound like any other builtin event type as follows:
bind Entry <<Paste>> {%W insert [selection get]}
The double angle brackets are used to specify that a virtual event is being bound. If the user types Control-y or presses button 2, or if a <<Paste>> virtual event is synthesized with event generate, then the <<Paste>> binding will be invoked.

If a virtual binding has the exact same sequence as a separate physical binding, then the physical binding will take precedence. Consider the following example:

event add <<Paste>> <Control-y> <Meta-Control-y>
bind Entry <Control-y> {puts Control-y}
bind Entry <<Paste>> {puts Paste}
When the user types Control-y the <Control-y> binding will be invoked, because a physical event is considered more specific than a virtual event, all other things being equal. However, when the user types Meta-Control-y the <<Paste>> binding will be invoked, because the Meta modifier in the physical pattern associated with the virtual binding is more specific than the <Control-y> sequence for the physical event.

Bindings on a virtual event may be created before the virtual event exists. Indeed, the virtual event never actually needs to be defined, for instance, on platforms where the specific virtual event would meaningless or ungeneratable.

When a definition of a virtual event changes at run time, all windows will respond immediately to the new definition. Starting from the preceding example, if the following code is executed:

bind <Entry> <Control-y> {}
event add <<Paste>> <Key-F6>
the behavior will change such in two ways. First, the shadowed <<Paste>> binding will emerge. Typing Control-y will no longer invoke the <Control-y> binding, but instead invoke the virtual event <<Paste>>. Second, pressing the F6 key will now also invoke the <<Paste>> binding.

SEE ALSO

bind

KEYWORDS

event, binding, define, handle, virtual event
Copyright © 1996 Sun Microsystems, Inc.
Copyright © 1998-2000 Ajuba Solutions.


Tk Built-In Commands - focus manual page

NAME
focus - Manage the input focus
SYNOPSIS
focus
focus window
focus option ?arg arg ...?
DESCRIPTION
focus
focus window
focus -displayof window
focus -force window
focus -lastfor window
QUIRKS
KEYWORDS

NAME

focus - Manage the input focus

SYNOPSIS

focus
focus window
focus option ?arg arg ...?

DESCRIPTION

The focus command is used to manage the Tk input focus. At any given time, one window on each display is designated as the focus window; any key press or key release events for the display are sent to that window. It is normally up to the window manager to redirect the focus among the top-level windows of a display. For example, some window managers automatically set the input focus to a top-level window whenever the mouse enters it; others redirect the input focus only when the user clicks on a window. Usually the window manager will set the focus only to top-level windows, leaving it up to the application to redirect the focus among the children of the top-level.

Tk remembers one focus window for each top-level (the most recent descendant of that top-level to receive the focus); when the window manager gives the focus to a top-level, Tk automatically redirects it to the remembered window. Within a top-level Tk uses an explicit focus model by default. Moving the mouse within a top-level does not normally change the focus; the focus changes only when a widget decides explicitly to claim the focus (e.g., because of a button click), or when the user types a key such as Tab that moves the focus.

The Tcl procedure tk_focusFollowsMouse may be invoked to create an implicit focus model: it reconfigures Tk so that the focus is set to a window whenever the mouse enters it. The Tcl procedures tk_focusNext and tk_focusPrev implement a focus order among the windows of a top-level; they are used in the default bindings for Tab and Shift-Tab, among other things.

The focus command can take any of the following forms:

focus
Returns the path name of the focus window on the display containing the application's main window, or an empty string if no window in this application has the focus on that display. Note: it is better to specify the display explicitly using -displayof (see below) so that the code will work in applications using multiple displays.

focus window
If the application currently has the input focus on window's display, this command resets the input focus for window's display to window and returns an empty string. If the application doesn't currently have the input focus on window's display, window will be remembered as the focus for its top-level; the next time the focus arrives at the top-level, Tk will redirect it to window. If window is an empty string then the command does nothing.

focus -displayof window
Returns the name of the focus window on the display containing window. If the focus window for window's display isn't in this application, the return value is an empty string.

focus -force window
Sets the focus of window's display to window, even if the application doesn't currently have the input focus for the display. This command should be used sparingly, if at all. In normal usage, an application should not claim the focus for itself; instead, it should wait for the window manager to give it the focus. If window is an empty string then the command does nothing.

focus -lastfor window
Returns the name of the most recent window to have the input focus among all the windows in the same top-level as window. If no window in that top-level has ever had the input focus, or if the most recent focus window has been deleted, then the name of the top-level is returned. The return value is the window that will receive the input focus the next time the window manager gives the focus to the top-level.

QUIRKS

When an internal window receives the input focus, Tk doesn't actually set the X focus to that window; as far as X is concerned, the focus will stay on the top-level window containing the window with the focus. However, Tk generates FocusIn and FocusOut events just as if the X focus were on the internal window. This approach gets around a number of problems that would occur if the X focus were actually moved; the fact that the X focus is on the top-level is invisible unless you use C code to query the X server directly.

KEYWORDS

events, focus, keyboard, top-level, window manager
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tk_focusNext manual page

NAME

tk_focusNext, tk_focusPrev, tk_focusFollowsMouse - Utility procedures for managing the input focus.

SYNOPSIS

tk_focusNext window
tk_focusPrev window
tk_focusFollowsMouse

DESCRIPTION

tk_focusNext is a utility procedure used for keyboard traversal. It returns the ``next'' window after window in focus order. The focus order is determined by the stacking order of windows and the structure of the window hierarchy. Among siblings, the focus order is the same as the stacking order, with the lowest window being first. If a window has children, the window is visited first, followed by its children (recursively), followed by its next sibling. Top-level windows other than window are skipped, so that tk_focusNext never returns a window in a different top-level from window.

After computing the next window, tk_focusNext examines the window's -takefocus option to see whether it should be skipped. If so, tk_focusNext continues on to the next window in the focus order, until it eventually finds a window that will accept the focus or returns back to window.

tk_focusPrev is similar to tk_focusNext except that it returns the window just before window in the focus order.

tk_focusFollowsMouse changes the focus model for the application to an implicit one where the window under the mouse gets the focus. After this procedure is called, whenever the mouse enters a window Tk will automatically give it the input focus. The focus command may be used to move the focus to a window other than the one under the mouse, but as soon as the mouse moves into a new window the focus will jump to that window. Note: at present there is no built-in support for returning the application to an explicit focus model; to do this you'll have to write a script that deletes the bindings created by tk_focusFollowsMouse.

KEYWORDS

focus, keyboard traversal, top-level
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - font manual page

NAME
font - Create and inspect fonts.
SYNOPSIS
font option ?arg arg ...?
DESCRIPTION
font actual font ?-displayof window? ?option?
font configure fontname ?option? ?value option value ...?
font create ?fontname? ?option value ...?
font delete fontname ?fontname ...?
font families ?-displayof window?
font measure font ?-displayof window? text
font metrics font ?-displayof window? ?option?
font names
FONT DESCRIPTION
[1] fontname
[2] systemfont
[3] family ?size? ?style? ?style ...?
[4] X-font names (XLFD)
[5] option value ?option value ...?
FONT METRICS
-ascent
-descent
-linespace
-fixed
FONT OPTIONS
-family name
-size size
-weight weight
-slant slant
-underline boolean
-overstrike boolean
PLATFORM-SPECIFIC ISSUES
X Windows:
MS Windows:
Macintosh:
SEE ALSO
KEYWORDS

NAME

font - Create and inspect fonts.

SYNOPSIS

font option ?arg arg ...?

DESCRIPTION

The font command provides several facilities for dealing with fonts, such as defining named fonts and inspecting the actual attributes of a font. The command has several different forms, determined by the first argument. The following forms are currently supported:

font actual font ?-displayof window? ?option?
Returns information about the the actual attributes that are obtained when font is used on window's display; the actual attributes obtained may differ from the attributes requested due to platform-dependant limitations, such as the availability of font families and pointsizes. font is a font description; see FONT DESCRIPTIONS below. If the window argument is omitted, it defaults to the main window. If option is specified, returns the value of that attribute; if it is omitted, the return value is a list of all the attributes and their values. See FONT OPTIONS below for a list of the possible attributes.

font configure fontname ?option? ?value option value ...?
Query or modify the desired attributes for the named font called fontname. If no option is specified, returns a list describing all the options and their values for fontname. If a single option is specified with no value, then returns the current value of that attribute. If one or more option-value pairs are specified, then the command modifies the given named font to have the given values; in this case, all widgets using that font will redisplay themselves using the new attributes for the font. See FONT OPTIONS below for a list of the possible attributes.

font create ?fontname? ?option value ...?
Creates a new named font and returns its name. fontname specifies the name for the font; if it is omitted, then Tk generates a new name of the form font x, where x is an integer. There may be any number of option-value pairs, which provide the desired attributes for the new named font. See FONT OPTIONS below for a list of the possible attributes.

font delete fontname ?fontname ...?
Delete the specified named fonts. If there are widgets using the named font, the named font won't actually be deleted until all the instances are released. Those widgets will continue to display using the last known values for the named font. If a deleted named font is subsequently recreated with another call to font create, the widgets will use the new named font and redisplay themselves using the new attributes of that font.

font families ?-displayof window?
The return value is a list of the case-insensitive names of all font families that exist on window's display. If the window argument is omitted, it defaults to the main window.

font measure font ?-displayof window? text
Measures the amount of space the string text would use in the given font when displayed in window. font is a font description; see FONT DESCRIPTIONS below. If the window argument is omitted, it defaults to the main window. The return value is the total width in pixels of text, not including the extra pixels used by highly exagerrated characters such as cursive ``f''. If the string contains newlines or tabs, those characters are not expanded or treated specially when measuring the string.

font metrics font ?-displayof window? ?option?
Returns information about the metrics (the font-specific data), for font when it is used on window's display. font is a font description; see FONT DESCRIPTIONS below. If the window argument is omitted, it defaults to the main window. If option is specified, returns the value of that metric; if it is omitted, the return value is a list of all the metrics and their values. See FONT METRICS below for a list of the possible metrics.

font names
The return value is a list of all the named fonts that are currently defined.

FONT DESCRIPTION

The following formats are accepted as a font description anywhere font is specified as an argument above; these same forms are also permitted when specifying the -font option for widgets.

[1] fontname
The name of a named font, created using the font create command. When a widget uses a named font, it is guaranteed that this will never cause an error, as long as the named font exists, no matter what potentially invalid or meaningless set of attributes the named font has. If the named font cannot be displayed with exactly the specified attributes, some other close font will be substituted automatically.

[2] systemfont
The platform-specific name of a font, interpreted by the graphics server. This also includes, under X, an XLFD (see [4]) for which a single ``*'' character was used to elide more than one field in the middle of the name. See PLATFORM-SPECIFIC issues for a list of the system fonts.

[3] family ?size? ?style? ?style ...?
A properly formed list whose first element is the desired font family and whose optional second element is the desired size. The interpretation of the size attribute follows the same rules described for -size in FONT OPTIONS below. Any additional optional arguments following the size are font styles. Possible values for the style arguments are as follows:
normal	bold	roman	italic
underline	overstrike

[4] X-font names (XLFD)
A Unix-centric font name of the form -foundry-family-weight-slant-setwidth-addstyle-pixel-point-resx-resy-spacing-width-charset-encoding. The ``*'' character may be used to skip individual fields that the user does not care about. There must be exactly one ``*'' for each field skipped, except that a ``*'' at the end of the XLFD skips any remaining fields; the shortest valid XLFD is simply ``*'', signifying all fields as defaults. Any fields that were skipped are given default values. For compatibility, an XLFD always chooses a font of the specified pixel size (not point size); although this interpretation is not strictly correct, all existing applications using XLFDs assumed that one ``point'' was in fact one pixel and would display incorrectly (generally larger) if the correct size font were actually used.

[5] option value ?option value ...?
A properly formed list of option-value pairs that specify the desired attributes of the font, in the same format used when defining a named font; see FONT OPTIONS below.

When font description font is used, the system attempts to parse the description according to each of the above five rules, in the order specified. Cases [1] and [2] must match the name of an existing named font or of a system font. Cases [3], [4], and [5] are accepted on all platforms and the closest available font will be used. In some situations it may not be possible to find any close font (e.g., the font family was a garbage value); in that case, some system-dependant default font is chosen. If the font description does not match any of the above patterns, an error is generated.

FONT METRICS

The following options are used by the font metrics command to query font-specific data determined when the font was created. These properties are for the whole font itself and not for individual characters drawn in that font. In the following definitions, the ``baseline'' of a font is the horizontal line where the bottom of most letters line up; certain letters, such as lower-case ``g'' stick below the baseline.

-ascent
The amount in pixels that the tallest letter sticks up above the baseline of the font, plus any extra blank space added by the designer of the font.

-descent
The largest amount in pixels that any letter sticks down below the baseline of the font, plus any extra blank space added by the designer of the font.

-linespace
Returns how far apart vertically in pixels two lines of text using the same font should be placed so that none of the characters in one line overlap any of the characters in the other line. This is generally the sum of the ascent above the baseline line plus the descent below the baseline.

-fixed
Returns a boolean flag that is ``1'' if this is a fixed-width font, where each normal character is the the same width as all the other characters, or is ``0'' if this is a proportionally-spaced font, where individual characters have different widths. The widths of control characters, tab characters, and other non-printing characters are not included when calculating this value.

FONT OPTIONS

The following options are supported on all platforms, and are used when constructing a named font or when specifying a font using style [5] as above:

-family name
The case-insensitive font family name. Tk guarantees to support the font families named Courier (a monospaced ``typewriter'' font), Times (a serifed ``newspaper'' font), and Helvetica (a sans-serif ``European'' font). The most closely matching native font family will automatically be substituted when one of the above font families is used. The name may also be the name of a native, platform-specific font family; in that case it will work as desired on one platform but may not display correctly on other platforms. If the family is unspecified or unrecognized, a platform-specific default font will be chosen.

-size size
The desired size of the font. If the size argument is a positive number, it is interpreted as a size in points. If size is a negative number, its absolute value is interpreted as a size in pixels. If a font cannot be displayed at the specified size, a nearby size will be chosen. If size is unspecified or zero, a platform-dependent default size will be chosen.

Sizes should normally be specified in points so the application will remain the same ruler size on the screen, even when changing screen resolutions or moving scripts across platforms. However, specifying pixels is useful in certain circumstances such as when a piece of text must line up with respect to a fixed-size bitmap. The mapping between points and pixels is set when the application starts, based on properties of the installed monitor, but it can be overridden by calling the tk scaling command.

-weight weight
The nominal thickness of the characters in the font. The value normal specifies a normal weight font, while bold specifies a bold font. The closest available weight to the one specified will be chosen. The default weight is normal.

-slant slant
The amount the characters in the font are slanted away from the vertical. Valid values for slant are roman and italic. A roman font is the normal, upright appearance of a font, while an italic font is one that is tilted some number of degrees from upright. The closest available slant to the one specified will be chosen. The default slant is roman.

-underline boolean
The value is a boolean flag that specifies whether characters in this font should be underlined. The default value for underline is false.

-overstrike boolean
The value is a boolean flag that specifies whether a horizontal line should be drawn through the middle of characters in this font. The default value for overstrike is false.

PLATFORM-SPECIFIC ISSUES

The following named system fonts are supported:

X Windows:
All valid X font names, including those listed by xlsfonts(1), are available.

MS Windows:
system	ansi	device
systemfixed	ansifixed	oemfixed

Macintosh:
system	application

SEE ALSO

options

KEYWORDS

font
Copyright © 1996 Sun Microsystems, Inc.


Tk Built-In Commands - frame manual page

NAME
frame - Create and manipulate frame widgets
SYNOPSIS
frame pathName ?options?
STANDARD OPTIONS
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
WIDGET-SPECIFIC OPTIONS
-background, background, Background
-class, class, Class
-colormap, colormap, Colormap
-container, container, Container
-height, height, Height
-visual, visual, Visual
-width, width, Width
DESCRIPTION
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
BINDINGS
KEYWORDS

NAME

frame - Create and manipulate frame widgets

SYNOPSIS

frame pathName ?options?

STANDARD OPTIONS

-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -background
Database Name: background
Database Class: Background
This option is the same as the standard background option except that its value may also be specified as an empty string. In this case, the widget will display no background or border, and no colors will be consumed from its colormap for its background and border.

Command-Line Name: -class
Database Name: class
Database Class: Class
Specifies a class for the window. This class will be used when querying the option database for the window's other options, and it will also be used later for other purposes such as bindings. The class option may not be changed with the configure widget command.

Command-Line Name: -colormap
Database Name: colormap
Database Class: Colormap
Specifies a colormap to use for the window. The value may be either new, in which case a new colormap is created for the window and its children, or the name of another window (which must be on the same screen and have the same visual as pathName), in which case the new window will use the colormap from the specified window. If the colormap option is not specified, the new window uses the same colormap as its parent. This option may not be changed with the configure widget command.

Command-Line Name: -container
Database Name: container
Database Class: Container
The value must be a boolean. If true, it means that this window will be used as a container in which some other application will be embedded (for example, a Tk toplevel can be embedded using the -use option). The window will support the appropriate window manager protocols for things like geometry requests. The window should not have any children of its own in this application. This option may not be changed with the configure widget command.

Command-Line Name: -height
Database Name: height
Database Class: Height
Specifies the desired height for the window in any of the forms acceptable to Tk_GetPixels. If this option is less than or equal to zero then the window will not request any size at all.

Command-Line Name: -visual
Database Name: visual
Database Class: Visual
Specifies visual information for the new window in any of the forms accepted by Tk_GetVisual. If this option is not specified, the new window will use the same visual as its parent. The visual option may not be modified with the configure widget command.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies the desired width for the window in any of the forms acceptable to Tk_GetPixels. If this option is less than or equal to zero then the window will not request any size at all.

DESCRIPTION

The frame command creates a new window (given by the pathName argument) and makes it into a frame widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the frame such as its background color and relief. The frame command returns the path name of the new window.

A frame is a simple widget. Its primary purpose is to act as a spacer or container for complex window layouts. The only features of a frame are its background color and an optional 3-D border to make the frame appear raised or sunken.

WIDGET COMMAND

The frame command creates a new Tcl command whose name is the same as the path name of the frame's window. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
PathName is the name of the command, which is the same as the frame widget's path name. Option and the args determine the exact behavior of the command. The following commands are possible for frame widgets:

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the frame command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the frame command.

BINDINGS

When a new frame is created, it has no default event bindings: frames are not intended to be interactive.

KEYWORDS

frame, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tk_getOpenFile manual page

NAME
tk_getOpenFile, tk_getSaveFile - pop up a dialog box for the user to select a file to open or save.
SYNOPSIS
tk_getOpenFile ?option value ...?
tk_getSaveFile ?option value ...?
DESCRIPTION
-defaultextension extension
-filetypes filePatternList
-initialdir directory
-initialfile filename
-parent window
-title titleString
SPECIFYING FILE PATTERNS
SPECIFYING EXTENSIONS
EXAMPLE
SEE ALSO
KEYWORDS

NAME

tk_getOpenFile, tk_getSaveFile - pop up a dialog box for the user to select a file to open or save.

SYNOPSIS

tk_getOpenFile ?option value ...?
tk_getSaveFile ?option value ...?

DESCRIPTION

The procedures tk_getOpenFile and tk_getSaveFile pop up a dialog box for the user to select a file to open or save. The tk_getOpenFile command is usually associated with the Open command in the File menu. Its purpose is for the user to select an existing file only. If the user enters an non-existent file, the dialog box gives the user an error prompt and requires the user to give an alternative selection. If an application allows the user to create new files, it should do so by providing a separate New menu command.

The tk_getSaveFile command is usually associated with the Save as command in the File menu. If the user enters a file that already exists, the dialog box prompts the user for confirmation whether the existing file should be overwritten or not.

The following option-value pairs are possible as command line arguments to these two commands:

-defaultextension extension
Specifies a string that will be appended to the filename if the user enters a filename without an extension. The defaut value is the empty string, which means no extension will be appended to the filename in any case. This option is ignored on the Macintosh platform, which does not require extensions to filenames.

-filetypes filePatternList
If a File types listbox exists in the file dialog on the particular platform, this option gives the filetypes in this listbox. When the user choose a filetype in the listbox, only the files of that type are listed. If this option is unspecified, or if it is set to the empty list, or if the File types listbox is not supported by the particular platform then all files are listed regardless of their types. See the section SPECIFYING FILE PATTERNS below for a discussion on the contents of filePatternList.

-initialdir directory
Specifies that the files in directory should be displayed when the dialog pops up. If this parameter is not specified, then the files in the current working directory are displayed. If the parameter specifies a relative path, the return value will convert the relative path to an absolute path. This option may not always work on the Macintosh. This is not a bug. Rather, the General Controls control panel on the Mac allows the end user to override the application default directory.

-initialfile filename
Specifies a filename to be displayed in the dialog when it pops up. This option is ignored on the Macintosh platform.

-parent window
Makes window the logical parent of the file dialog. The file dialog is displayed on top of its parent window.

-title titleString
Specifies a string to display as the title of the dialog box. If this option is not specified, then a default title is displayed.

If the user selects a file, both tk_getOpenFile and tk_getSaveFile return the full pathname of this file. If the user cancels the operation, both commands return the empty string.

SPECIFYING FILE PATTERNS

The filePatternList value given by the -filetypes option is a list of file patterns. Each file pattern is a list of the form
typeName {extension ?extension ...?} ?{macType ?macType ...?}?
typeName is the name of the file type described by this file pattern and is the text string that appears in the File types listbox. extension is a file extension for this file pattern. macType is a four-character Macintosh file type. The list of macTypes is optional and may be omitted for applications that do not need to execute on the Macintosh platform.

Several file patterns may have the same typeName, in which case they refer to the same file type and share the same entry in the listbox. When the user selects an entry in the listbox, all the files that match at least one of the file patterns corresponding to that entry are listed. Usually, each file pattern corresponds to a distinct type of file. The use of more than one file patterns for one type of file is necessary on the Macintosh platform only.

On the Macintosh platform, a file matches a file pattern if its name matches at least one of the extension(s) AND it belongs to at least one of the macType(s) of the file pattern. For example, the C Source Files file pattern in the sample code matches with files that have a .c extension AND belong to the macType TEXT. To use the OR rule instead, you can use two file patterns, one with the extensions only and the other with the macType only. The GIF Files file type in the sample code matches files that EITHER have a .gif extension OR belong to the macType GIFF.

On the Unix and Windows platforms, a file matches a file pattern if its name matches at at least one of the extension(s) of the file pattern. The macTypes are ignored.

SPECIFYING EXTENSIONS

On the Unix and Macintosh platforms, extensions are matched using glob-style pattern matching. On the Windows platforms, extensions are matched by the underlying operating system. The types of possible extensions are: (1) the special extension * matches any file; (2) the special extension "" matches any files that do not have an extension (i.e., the filename contains no full stop character); (3) any character string that does not contain any wild card characters (* and ?).

Due to the different pattern matching rules on the various platforms, to ensure portability, wild card characters are not allowed in the extensions, except as in the special extension *. Extensions without a full stop character (e.g, ~) are allowed but may not work on all platforms.

EXAMPLE

set types {
    {{Text Files}       {.txt}        }
    {{TCL Scripts}      {.tcl}        }
    {{C Source Files}   {.c}      TEXT}
    {{GIF Files}        {.gif}        }
    {{GIF Files}        {}        GIFF}
    {{All Files}        *             }
}
set filename [tk_getOpenFile -filetypes $types]

if {$filename != ""} {
    # Open the file ...
}

SEE ALSO

tk_chooseDirectory

KEYWORDS

file selection dialog
Copyright © 1996 Sun Microsystems, Inc.


Built-In Commands - grab manual page

NAME
grab - Confine pointer and keyboard events to a window sub-tree
SYNOPSIS
grab ?-global? window
grab option ?arg arg ...?
DESCRIPTION
grab ?-global? window
grab current ?window?
grab release window
grab set ?-global? window
grab status window
BUGS
KEYWORDS

NAME

grab - Confine pointer and keyboard events to a window sub-tree

SYNOPSIS

grab ?-global? window
grab option ?arg arg ...?

DESCRIPTION

This command implements simple pointer and keyboard grabs for Tk. Tk's grabs are different than the grabs described in the Xlib documentation. When a grab is set for a particular window, Tk restricts all pointer events to the grab window and its descendants in Tk's window hierarchy. Whenever the pointer is within the grab window's subtree, the pointer will behave exactly the same as if there had been no grab at all and all events will be reported in the normal fashion. When the pointer is outside window's tree, button presses and releases and mouse motion events are reported to window, and window entry and window exit events are ignored. The grab subtree ``owns'' the pointer: windows outside the grab subtree will be visible on the screen but they will be insensitive until the grab is released. The tree of windows underneath the grab window can include top-level windows, in which case all of those top-level windows and their descendants will continue to receive mouse events during the grab.

Two forms of grabs are possible: local and global. A local grab affects only the grabbing application: events will be reported to other applications as if the grab had never occurred. Grabs are local by default. A global grab locks out all applications on the screen, so that only the given subtree of the grabbing application will be sensitive to pointer events (mouse button presses, mouse button releases, pointer motions, window entries, and window exits). During global grabs the window manager will not receive pointer events either.

During local grabs, keyboard events (key presses and key releases) are delivered as usual: the window manager controls which application receives keyboard events, and if they are sent to any window in the grabbing application then they are redirected to the focus window. During a global grab Tk grabs the keyboard so that all keyboard events are always sent to the grabbing application. The focus command is still used to determine which window in the application receives the keyboard events. The keyboard grab is released when the grab is released.

Grabs apply to particular displays. If an application has windows on multiple displays then it can establish a separate grab on each display. The grab on a particular display affects only the windows on that display. It is possible for different applications on a single display to have simultaneous local grabs, but only one application can have a global grab on a given display at once.

The grab command can take any of the following forms:

grab ?-global? window
Same as grab set, described below.

grab current ?window?
If window is specified, returns the name of the current grab window in this application for window's display, or an empty string if there is no such window. If window is omitted, the command returns a list whose elements are all of the windows grabbed by this application for all displays, or an empty string if the application has no grabs.

grab release window
Releases the grab on window if there is one, otherwise does nothing. Returns an empty string.

grab set ?-global? window
Sets a grab on window. If -global is specified then the grab is global, otherwise it is local. If a grab was already in effect for this application on window's display then it is automatically released. If there is already a grab on window and it has the same global/local form as the requested grab, then the command does nothing. Returns an empty string.

grab status window
Returns none if no grab is currently set on window, local if a local grab is set on window, and global if a global grab is set.

BUGS

It took an incredibly complex and gross implementation to produce the simple grab effect described above. Given the current implementation, it isn't safe for applications to use the Xlib grab facilities at all except through the Tk grab procedures. If applications try to manipulate X's grab mechanisms directly, things will probably break.

If a single process is managing several different Tk applications, only one of those applications can have a local grab for a given display at any given time. If the applications are in different processes, this restriction doesn't exist.

KEYWORDS

grab, keyboard events, pointer events, window
Copyright © 1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - grid manual page

NAME
grid - Geometry manager that arranges widgets in a grid
SYNOPSIS
grid option arg ?arg ...?
DESCRIPTION
grid slave ?slave ...? ?options?
grid bbox master ?column row? ?column2 row2?
grid columnconfigure master index ?-option value...?
grid configure slave ?slave ...? ?options?
-column n
-columnspan n
-in other
-ipadx amount
-ipady amount
-padx amount
-pady amount
-row n
-rowspan n
-sticky style
grid forget slave ?slave ...?
grid info slave
grid location master x y
grid propagate master ?boolean?
grid rowconfigure master index ?-option value...?
grid remove slave ?slave ...?
grid size master
grid slaves master ?-option value?
RELATIVE PLACEMENT
-
x
^
THE GRID ALGORITHM
GEOMETRY PROPAGATION
RESTRICTIONS ON MASTER WINDOWS
STACKING ORDER
CREDITS
KEYWORDS

NAME

grid - Geometry manager that arranges widgets in a grid

SYNOPSIS

grid option arg ?arg ...?

DESCRIPTION

The grid command is used to communicate with the grid geometry manager that arranges widgets in rows and columns inside of another window, called the geometry master (or master window). The grid command can have any of several forms, depending on the option argument:

grid slave ?slave ...? ?options?
If the first argument to grid is a window name (any value starting with ``.''), then the command is processed in the same way as grid configure.

grid bbox master ?column row? ?column2 row2?
With no arguments, the bounding box (in pixels) of the grid is returned. The return value consists of 4 integers. The first two are the pixel offset from the master window (x then y) of the top-left corner of the grid, and the second two integers are the width and height of the grid, also in pixels. If a single column and row is specified on the command line, then the bounding box for that cell is returned, where the top left cell is numbered from zero. If both column and row arguments are specified, then the bounding box spanning the rows and columns indicated is returned.

grid columnconfigure master index ?-option value...?
Query or set the column properties of the index column of the geometry master, master. The valid options are -minsize, -weight and -pad. If one or more options are provided, then index may be given as a list of column indeces to which the configuration options will operate on. The -minsize option sets the minimum size, in screen units, that will be permitted for this column. The -weight option (an integer value) sets the relative weight for apportioning any extra spaces among columns. A weight of zero (0) indicates the column will not deviate from its requested size. A column whose weight is two will grow at twice the rate as a column of weight one when extra space is allocated to the layout. The -pad option specifies the number of screen units that will be added to the largest window contained completely in that column when the grid geometry manager requests a size from the containing window. If only an option is specified, with no value, the current value of that option is returned. If only the master window and index is specified, all the current settings are returned in an list of "-option value" pairs.

grid configure slave ?slave ...? ?options?
The arguments consist of the names of one or more slave windows followed by pairs of arguments that specify how to manage the slaves. The characters -, x and ^, can be specified instead of a window name to alter the default location of a slave, as described in the ``RELATIVE PLACEMENT'' section, below. The following options are supported:

-column n
Insert the slave so that it occupies the nth column in the grid. Column numbers start with 0. If this option is not supplied, then the slave is arranged just to the right of previous slave specified on this call to grid, or column "0" if it is the first slave. For each x that immediately precedes the slave, the column position is incremented by one. Thus the x represents a blank column for this row in the grid.

-columnspan n
Insert the slave so that it occupies n columns in the grid. The default is one column, unless the window name is followed by a -, in which case the columnspan is incremented once for each immediately following -.

-in other
Insert the slave(s) in the master window given by other. The default is the first slave's parent window.

-ipadx amount
The amount specifies how much horizontal internal padding to leave on each side of the slave(s). This is space is added inside the slave(s) border. The amount must be a valid screen distance, such as 2 or .5c. It defaults to 0.

-ipady amount
The amount specifies how much vertical internal padding to leave on on the top and bottom of the slave(s). This space is added inside the slave(s) border. The amount defaults to 0.

-padx amount
The amount specifies how much horizontal external padding to leave on each side of the slave(s), in screen units. The amount defaults to 0. This space is added outside the slave(s) border.

-pady amount
The amount specifies how much vertical external padding to leave on the top and bottom of the slave(s), in screen units. The amount defaults to 0. This space is added outside the slave(s) border.

-row n
Insert the slave so that it occupies the nth row in the grid. Row numbers start with 0. If this option is not supplied, then the slave is arranged on the same row as the previous slave specified on this call to grid, or the first unoccupied row if this is the first slave.

-rowspan n
Insert the slave so that it occupies n rows in the grid. The default is one row. If the next grid command contains ^ characters instead of slaves that line up with the columns of this slave, then the rowspan of this slave is extended by one.

-sticky style
If a slave's cell is larger than its requested dimensions, this option may be used to position (or stretch) the slave within its cell. Style is a string that contains zero or more of the characters n, s, e or w. The string can optionally contains spaces or commas, but they are ignored. Each letter refers to a side (north, south, east, or west) that the slave will "stick" to. If both n and s (or e and w) are specified, the slave will be stretched to fill the entire height (or width) of its cavity. The sticky option subsumes the combination of -anchor and -fill that is used by pack. The default is {}, which causes the slave to be centered in its cavity, at its requested size.

If any of the slaves are already managed by the geometry manager then any unspecified options for them retain their previous values rather than receiving default values.

grid forget slave ?slave ...?
Removes each of the slaves from grid for its master and unmaps their windows. The slaves will no longer be managed by the grid geometry manager. The configuration options for that window are forgotten, so that if the slave is managed once more by the grid geometry manager, the initial default settings are used.

grid info slave
Returns a list whose elements are the current configuration state of the slave given by slave in the same option-value form that might be specified to grid configure. The first two elements of the list are ``-in master'' where master is the slave's master.

grid location master x y
Given x and y values in screen units relative to the master window, the column and row number at that x and y location is returned. For locations that are above or to the left of the grid, -1 is returned.

grid propagate master ?boolean?
If boolean has a true boolean value such as 1 or on then propagation is enabled for master, which must be a window name (see ``GEOMETRY PROPAGATION'' below). If boolean has a false boolean value then propagation is disabled for master. In either of these cases an empty string is returned. If boolean is omitted then the command returns 0 or 1 to indicate whether propagation is currently enabled for master. Propagation is enabled by default.

grid rowconfigure master index ?-option value...?
Query or set the row properties of the index row of the geometry master, master. The valid options are -minsize, -weight and -pad. If one or more options are provided, then index may be given as a list of row indeces to which the configuration options will operate on. The -minsize option sets the minimum size, in screen units, that will be permitted for this row. The -weight option (an integer value) sets the relative weight for apportioning any extra spaces among rows. A weight of zero (0) indicates the row will not deviate from its requested size. A row whose weight is two will grow at twice the rate as a row of weight one when extra space is allocated to the layout. The -pad option specifies the number of screen units that will be added to the largest window contained completely in that row when the grid geometry manager requests a size from the containing window. If only an option is specified, with no value, the current value of that option is returned. If only the master window and index is specified, all the current settings are returned in an list of "-option value" pairs.

grid remove slave ?slave ...?
Removes each of the slaves from grid for its master and unmaps their windows. The slaves will no longer be managed by the grid geometry manager. However, the configuration options for that window are remembered, so that if the slave is managed once more by the grid geometry manager, the previous values are retained.

grid size master
Returns the size of the grid (in columns then rows) for master. The size is determined either by the slave occupying the largest row or column, or the largest column or row with a minsize, weight, or pad that is non-zero.

grid slaves master ?-option value?
If no options are supplied, a list of all of the slaves in master are returned, most recently manages first. Option can be either -row or -column which causes only the slaves in the row (or column) specified by value to be returned.

RELATIVE PLACEMENT

The grid command contains a limited set of capabilities that permit layouts to be created without specifying the row and column information for each slave. This permits slaves to be rearranged, added, or removed without the need to explicitly specify row and column information. When no column or row information is specified for a slave, default values are chosen for column, row, columnspan and rowspan at the time the slave is managed. The values are chosen based upon the current layout of the grid, the position of the slave relative to other slaves in the same grid command, and the presence of the characters -, ^, and ^ in grid command where slave names are normally expected.

-
This increases the columnspan of the slave to the left. Several -'s in a row will successively increase the columnspan. A - may not follow a ^ or a x.

x
This leaves an empty column between the slave on the left and the slave on the right.

^
This extends the rowspan of the slave above the ^'s in the grid. The number of ^'s in a row must match the number of columns spanned by the slave above it.

THE GRID ALGORITHM

The grid geometry manager lays out its slaves in three steps. In the first step, the minimum size needed to fit all of the slaves is computed, then (if propagation is turned on), a request is made of the master window to become that size. In the second step, the requested size is compared against the actual size of the master. If the sizes are different, then spaces is added to or taken away from the layout as needed. For the final step, each slave is positioned in its row(s) and column(s) based on the setting of its sticky flag.

To compute the minimum size of a layout, the grid geometry manager first looks at all slaves whose columnspan and rowspan values are one, and computes the nominal size of each row or column to be either the minsize for that row or column, or the sum of the padding plus the size of the largest slave, whichever is greater. Then the slaves whose rowspans or columnspans are greater than one are examined. If a group of rows or columns need to be increased in size in order to accommodate these slaves, then extra space is added to each row or column in the group according to its weight. For each group whose weights are all zero, the additional space is apportioned equally.

For masters whose size is larger than the requested layout, the additional space is apportioned according to the row and column weights. If all of the weights are zero, the layout is centered within its master. For masters whose size is smaller than the requested layout, space is taken away from columns and rows according to their weights. However, once a column or row shrinks to its minsize, its weight is taken to be zero. If more space needs to be removed from a layout than would be permitted, as when all the rows or columns are at there minimum sizes, the layout is clipped on the bottom and right.

GEOMETRY PROPAGATION

The grid geometry manager normally computes how large a master must be to just exactly meet the needs of its slaves, and it sets the requested width and height of the master to these dimensions. This causes geometry information to propagate up through a window hierarchy to a top-level window so that the entire sub-tree sizes itself to fit the needs of the leaf windows. However, the grid propagate command may be used to turn off propagation for one or more masters. If propagation is disabled then grid will not set the requested width and height of the master window. This may be useful if, for example, you wish for a master window to have a fixed size that you specify.

RESTRICTIONS ON MASTER WINDOWS

The master for each slave must either be the slave's parent (the default) or a descendant of the slave's parent. This restriction is necessary to guarantee that the slave can be placed over any part of its master that is visible without danger of the slave being clipped by its parent. In addition, all slaves in one call to grid must have the same master.

STACKING ORDER

If the master for a slave is not its parent then you must make sure that the slave is higher in the stacking order than the master. Otherwise the master will obscure the slave and it will appear as if the slave hasn't been managed correctly. The easiest way to make sure the slave is higher than the master is to create the master window first: the most recently created window will be highest in the stacking order.

CREDITS

The grid command is based on ideas taken from the GridBag geometry manager written by Doug. Stein, and the blt_table geometry manager, written by George Howlett.

KEYWORDS

geometry manager, location, grid, cell, propagation, size, pack
Copyright © 1996 Sun Microsystems, Inc.


Tk Built-In Commands - image manual page

NAME
image - Create and manipulate images
SYNOPSIS
image option ?arg arg ...?
DESCRIPTION
image create type ?name? ?option value ...?
image delete ?name name ...?
image height name
image names
image type name
image types
image width name
BUILT-IN IMAGE TYPES
bitmap
photo
KEYWORDS

NAME

image - Create and manipulate images

SYNOPSIS

image option ?arg arg ...?

DESCRIPTION

The image command is used to create, delete, and query images. It can take several different forms, depending on the option argument. The legal forms are:

image create type ?name? ?option value ...?
Creates a new image and returns its name. type specifies the type of the image, which must be one of the types currently defined (e.g., bitmap). name specifies the name for the image; if it is omitted then Tk picks a name of the form image x, where x is an integer. There may be any number of option-value pairs, which provide configuration options for the new image. The legal set of options is defined separately for each image type; see below for details on the options for built-in image types. If an image already exists by the given name then it is replaced with the new image and any instances of that image will redisplay with the new contents. It is important to note that the image command will silently overwrite any procedure that may currently be defined by the given name, so choose the name wisely. It is recommended to use a separate namespace for image names (e.g., ::img::logo, ::img::large).

image delete ?name name ...?
Deletes each of the named images and returns an empty string. If there are instances of the images displayed in widgets, the images won't actually be deleted until all of the instances are released. However, the association between the instances and the image manager will be dropped. Existing instances will retain their sizes but redisplay as empty areas. If a deleted image is recreated with another call to image create, the existing instances will use the new image.

image height name
Returns a decimal string giving the height of image name in pixels.

image names
Returns a list containing the names of all existing images.

image type name
Returns the type of image name (the value of the type argument to image create when the image was created).

image types
Returns a list whose elements are all of the valid image types (i.e., all of the values that may be supplied for the type argument to image create).

image width name
Returns a decimal string giving the width of image name in pixels.

BUILT-IN IMAGE TYPES

The following image types are defined by Tk so they will be available in any Tk application. Individual applications or extensions may define additional types.

bitmap
Each pixel in the image displays a foreground color, a background color, or nothing. See the bitmap manual entry for more information.

photo
Displays a variety of full-color images, using dithering to approximate colors on displays with limited color capabilities. See the photo manual entry for more information.

KEYWORDS

height, image, types of images, width
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - keysyms manual page

NAME

keysyms - keysyms recognized by Tk

DESCRIPTION

Tk recognizes many keysyms when specifying key bindings (eg, bind . <Key-keysym>). The following list enumerates the keysyms that will be recognized by Tk. Note that not all keysyms will be valid on all platforms. For example, on Unix systems, the presence of a particular keysym is dependant on the configuration of the keyboard modifier map. This list shows keysyms along with their decimal and hexidecimal values.

space                               32     0x0020
exclam                              33     0x0021
quotedbl                            34     0x0022
numbersign                          35     0x0023
dollar                              36     0x0024
percent                             37     0x0025
ampersand                           38     0x0026
quoteright                          39     0x0027
parenleft                           40     0x0028
parenright                          41     0x0029
asterisk                            42     0x002a
plus                                43     0x002b
comma                               44     0x002c
minus                               45     0x002d
period                              46     0x002e
slash                               47     0x002f
0                                   48     0x0030
1                                   49     0x0031
2                                   50     0x0032
3                                   51     0x0033
4                                   52     0x0034
5                                   53     0x0035
6                                   54     0x0036
7                                   55     0x0037
8                                   56     0x0038
9                                   57     0x0039
colon                               58     0x003a
semicolon                           59     0x003b
less                                60     0x003c
equal                               61     0x003d
greater                             62     0x003e
question                            63     0x003f
at                                  64     0x0040
A                                   65     0x0041
B                                   66     0x0042
C                                   67     0x0043
D                                   68     0x0044
E                                   69     0x0045
F                                   70     0x0046
G                                   71     0x0047
H                                   72     0x0048
I                                   73     0x0049
J                                   74     0x004a
K                                   75     0x004b
L                                   76     0x004c
M                                   77     0x004d
N                                   78     0x004e
O                                   79     0x004f
P                                   80     0x0050
Q                                   81     0x0051
R                                   82     0x0052
S                                   83     0x0053
T                                   84     0x0054
U                                   85     0x0055
V                                   86     0x0056
W                                   87     0x0057
X                                   88     0x0058
Y                                   89     0x0059
Z                                   90     0x005a
bracketleft                         91     0x005b
backslash                           92     0x005c
bracketright                        93     0x005d
asciicircum                         94     0x005e
underscore                          95     0x005f
quoteleft                           96     0x0060
a                                   97     0x0061
b                                   98     0x0062
c                                   99     0x0063
d                                  100     0x0064
e                                  101     0x0065
f                                  102     0x0066
g                                  103     0x0067
h                                  104     0x0068
i                                  105     0x0069
j                                  106     0x006a
k                                  107     0x006b
l                                  108     0x006c
m                                  109     0x006d
n                                  110     0x006e
o                                  111     0x006f
p                                  112     0x0070
q                                  113     0x0071
r                                  114     0x0072
s                                  115     0x0073
t                                  116     0x0074
u                                  117     0x0075
v                                  118     0x0076
w                                  119     0x0077
x                                  120     0x0078
y                                  121     0x0079
z                                  122     0x007a
braceleft                          123     0x007b
bar                                124     0x007c
braceright                         125     0x007d
asciitilde                         126     0x007e
nobreakspace                       160     0x00a0
exclamdown                         161     0x00a1
cent                               162     0x00a2
sterling                           163     0x00a3
currency                           164     0x00a4
yen                                165     0x00a5
brokenbar                          166     0x00a6
section                            167     0x00a7
diaeresis                          168     0x00a8
copyright                          169     0x00a9
ordfeminine                        170     0x00aa
guillemotleft                      171     0x00ab
notsign                            172     0x00ac
hyphen                             173     0x00ad
registered                         174     0x00ae
macron                             175     0x00af
degree                             176     0x00b0
plusminus                          177     0x00b1
twosuperior                        178     0x00b2
threesuperior                      179     0x00b3
acute                              180     0x00b4
mu                                 181     0x00b5
paragraph                          182     0x00b6
periodcentered                     183     0x00b7
cedilla                            184     0x00b8
onesuperior                        185     0x00b9
masculine                          186     0x00ba
guillemotright                     187     0x00bb
onequarter                         188     0x00bc
onehalf                            189     0x00bd
threequarters                      190     0x00be
questiondown                       191     0x00bf
Agrave                             192     0x00c0
Aacute                             193     0x00c1
Acircumflex                        194     0x00c2
Atilde                             195     0x00c3
Adiaeresis                         196     0x00c4
Aring                              197     0x00c5
AE                                 198     0x00c6
Ccedilla                           199     0x00c7
Egrave                             200     0x00c8
Eacute                             201     0x00c9
Ecircumflex                        202     0x00ca
Ediaeresis                         203     0x00cb
Igrave                             204     0x00cc
Iacute                             205     0x00cd
Icircumflex                        206     0x00ce
Idiaeresis                         207     0x00cf
Eth                                208     0x00d0
Ntilde                             209     0x00d1
Ograve                             210     0x00d2
Oacute                             211     0x00d3
Ocircumflex                        212     0x00d4
Otilde                             213     0x00d5
Odiaeresis                         214     0x00d6
multiply                           215     0x00d7
Ooblique                           216     0x00d8
Ugrave                             217     0x00d9
Uacute                             218     0x00da
Ucircumflex                        219     0x00db
Udiaeresis                         220     0x00dc
Yacute                             221     0x00dd
Thorn                              222     0x00de
ssharp                             223     0x00df
agrave                             224     0x00e0
aacute                             225     0x00e1
acircumflex                        226     0x00e2
atilde                             227     0x00e3
adiaeresis                         228     0x00e4
aring                              229     0x00e5
ae                                 230     0x00e6
ccedilla                           231     0x00e7
egrave                             232     0x00e8
eacute                             233     0x00e9
ecircumflex                        234     0x00ea
ediaeresis                         235     0x00eb
igrave                             236     0x00ec
iacute                             237     0x00ed
icircumflex                        238     0x00ee
idiaeresis                         239     0x00ef
eth                                240     0x00f0
ntilde                             241     0x00f1
ograve                             242     0x00f2
oacute                             243     0x00f3
ocircumflex                        244     0x00f4
otilde                             245     0x00f5
odiaeresis                         246     0x00f6
division                           247     0x00f7
oslash                             248     0x00f8
ugrave                             249     0x00f9
uacute                             250     0x00fa
ucircumflex                        251     0x00fb
udiaeresis                         252     0x00fc
yacute                             253     0x00fd
thorn                              254     0x00fe
ydiaeresis                         255     0x00ff
Aogonek                            417     0x01a1
breve                              418     0x01a2
Lstroke                            419     0x01a3
Lcaron                             421     0x01a5
Sacute                             422     0x01a6
Scaron                             425     0x01a9
Scedilla                           426     0x01aa
Tcaron                             427     0x01ab
Zacute                             428     0x01ac
Zcaron                             430     0x01ae
Zabovedot                          431     0x01af
aogonek                            433     0x01b1
ogonek                             434     0x01b2
lstroke                            435     0x01b3
lcaron                             437     0x01b5
sacute                             438     0x01b6
caron                              439     0x01b7
scaron                             441     0x01b9
scedilla                           442     0x01ba
tcaron                             443     0x01bb
zacute                             444     0x01bc
doubleacute                        445     0x01bd
zcaron                             446     0x01be
zabovedot                          447     0x01bf
Racute                             448     0x01c0
Abreve                             451     0x01c3
Cacute                             454     0x01c6
Ccaron                             456     0x01c8
Eogonek                            458     0x01ca
Ecaron                             460     0x01cc
Dcaron                             463     0x01cf
Nacute                             465     0x01d1
Ncaron                             466     0x01d2
Odoubleacute                       469     0x01d5
Rcaron                             472     0x01d8
Uring                              473     0x01d9
Udoubleacute                       475     0x01db
Tcedilla                           478     0x01de
racute                             480     0x01e0
abreve                             483     0x01e3
cacute                             486     0x01e6
ccaron                             488     0x01e8
eogonek                            490     0x01ea
ecaron                             492     0x01ec
dcaron                             495     0x01ef
nacute                             497     0x01f1
ncaron                             498     0x01f2
odoubleacute                       501     0x01f5
rcaron                             504     0x01f8
uring                              505     0x01f9
udoubleacute                       507     0x01fb
tcedilla                           510     0x01fe
abovedot                           511     0x01ff
Hstroke                            673     0x02a1
Hcircumflex                        678     0x02a6
Iabovedot                          681     0x02a9
Gbreve                             683     0x02ab
Jcircumflex                        684     0x02ac
hstroke                            689     0x02b1
hcircumflex                        694     0x02b6
idotless                           697     0x02b9
gbreve                             699     0x02bb
jcircumflex                        700     0x02bc
Cabovedot                          709     0x02c5
Ccircumflex                        710     0x02c6
Gabovedot                          725     0x02d5
Gcircumflex                        728     0x02d8
Ubreve                             733     0x02dd
Scircumflex                        734     0x02de
cabovedot                          741     0x02e5
ccircumflex                        742     0x02e6
gabovedot                          757     0x02f5
gcircumflex                        760     0x02f8
ubreve                             765     0x02fd
scircumflex                        766     0x02fe
kappa                              930     0x03a2
Rcedilla                           931     0x03a3
Itilde                             933     0x03a5
Lcedilla                           934     0x03a6
Emacron                            938     0x03aa
Gcedilla                           939     0x03ab
Tslash                             940     0x03ac
rcedilla                           947     0x03b3
itilde                             949     0x03b5
lcedilla                           950     0x03b6
emacron                            954     0x03ba
gacute                             955     0x03bb
tslash                             956     0x03bc
ENG                                957     0x03bd
eng                                959     0x03bf
Amacron                            960     0x03c0
Iogonek                            967     0x03c7
Eabovedot                          972     0x03cc
Imacron                            975     0x03cf
Ncedilla                           977     0x03d1
Omacron                            978     0x03d2
Kcedilla                           979     0x03d3
Uogonek                            985     0x03d9
Utilde                             989     0x03dd
Umacron                            990     0x03de
amacron                            992     0x03e0
iogonek                            999     0x03e7
eabovedot                         1004     0x03ec
imacron                           1007     0x03ef
ncedilla                          1009     0x03f1
omacron                           1010     0x03f2
kcedilla                          1011     0x03f3
uogonek                           1017     0x03f9
utilde                            1021     0x03fd
umacron                           1022     0x03fe
overline                          1150     0x047e
kana_fullstop                     1185     0x04a1
kana_openingbracket               1186     0x04a2
kana_closingbracket               1187     0x04a3
kana_comma                        1188     0x04a4
kana_middledot                    1189     0x04a5
kana_WO                           1190     0x04a6
kana_a                            1191     0x04a7
kana_i                            1192     0x04a8
kana_u                            1193     0x04a9
kana_e                            1194     0x04aa
kana_o                            1195     0x04ab
kana_ya                           1196     0x04ac
kana_yu                           1197     0x04ad
kana_yo                           1198     0x04ae
kana_tu                           1199     0x04af
prolongedsound                    1200     0x04b0
kana_A                            1201     0x04b1
kana_I                            1202     0x04b2
kana_U                            1203     0x04b3
kana_E                            1204     0x04b4
kana_O                            1205     0x04b5
kana_KA                           1206     0x04b6
kana_KI                           1207     0x04b7
kana_KU                           1208     0x04b8
kana_KE                           1209     0x04b9
kana_KO                           1210     0x04ba
kana_SA                           1211     0x04bb
kana_SHI                          1212     0x04bc
kana_SU                           1213     0x04bd
kana_SE                           1214     0x04be
kana_SO                           1215     0x04bf
kana_TA                           1216     0x04c0
kana_TI                           1217     0x04c1
kana_TU                           1218     0x04c2
kana_TE                           1219     0x04c3
kana_TO                           1220     0x04c4
kana_NA                           1221     0x04c5
kana_NI                           1222     0x04c6
kana_NU                           1223     0x04c7
kana_NE                           1224     0x04c8
kana_NO                           1225     0x04c9
kana_HA                           1226     0x04ca
kana_HI                           1227     0x04cb
kana_HU                           1228     0x04cc
kana_HE                           1229     0x04cd
kana_HO                           1230     0x04ce
kana_MA                           1231     0x04cf
kana_MI                           1232     0x04d0
kana_MU                           1233     0x04d1
kana_ME                           1234     0x04d2
kana_MO                           1235     0x04d3
kana_YA                           1236     0x04d4
kana_YU                           1237     0x04d5
kana_YO                           1238     0x04d6
kana_RA                           1239     0x04d7
kana_RI                           1240     0x04d8
kana_RU                           1241     0x04d9
kana_RE                           1242     0x04da
kana_RO                           1243     0x04db
kana_WA                           1244     0x04dc
kana_N                            1245     0x04dd
voicedsound                       1246     0x04de
semivoicedsound                   1247     0x04df
Arabic_comma                      1452     0x05ac
Arabic_semicolon                  1467     0x05bb
Arabic_question_mark              1471     0x05bf
Arabic_hamza                      1473     0x05c1
Arabic_maddaonalef                1474     0x05c2
Arabic_hamzaonalef                1475     0x05c3
Arabic_hamzaonwaw                 1476     0x05c4
Arabic_hamzaunderalef             1477     0x05c5
Arabic_hamzaonyeh                 1478     0x05c6
Arabic_alef                       1479     0x05c7
Arabic_beh                        1480     0x05c8
Arabic_tehmarbuta                 1481     0x05c9
Arabic_teh                        1482     0x05ca
Arabic_theh                       1483     0x05cb
Arabic_jeem                       1484     0x05cc
Arabic_hah                        1485     0x05cd
Arabic_khah                       1486     0x05ce
Arabic_dal                        1487     0x05cf
Arabic_thal                       1488     0x05d0
Arabic_ra                         1489     0x05d1
Arabic_zain                       1490     0x05d2
Arabic_seen                       1491     0x05d3
Arabic_sheen                      1492     0x05d4
Arabic_sad                        1493     0x05d5
Arabic_dad                        1494     0x05d6
Arabic_tah                        1495     0x05d7
Arabic_zah                        1496     0x05d8
Arabic_ain                        1497     0x05d9
Arabic_ghain                      1498     0x05da
Arabic_tatweel                    1504     0x05e0
Arabic_feh                        1505     0x05e1
Arabic_qaf                        1506     0x05e2
Arabic_kaf                        1507     0x05e3
Arabic_lam                        1508     0x05e4
Arabic_meem                       1509     0x05e5
Arabic_noon                       1510     0x05e6
Arabic_heh                        1511     0x05e7
Arabic_waw                        1512     0x05e8
Arabic_alefmaksura                1513     0x05e9
Arabic_yeh                        1514     0x05ea
Arabic_fathatan                   1515     0x05eb
Arabic_dammatan                   1516     0x05ec
Arabic_kasratan                   1517     0x05ed
Arabic_fatha                      1518     0x05ee
Arabic_damma                      1519     0x05ef
Arabic_kasra                      1520     0x05f0
Arabic_shadda                     1521     0x05f1
Arabic_sukun                      1522     0x05f2
Serbian_dje                       1697     0x06a1
Macedonia_gje                     1698     0x06a2
Cyrillic_io                       1699     0x06a3
Ukranian_je                       1700     0x06a4
Macedonia_dse                     1701     0x06a5
Ukranian_i                        1702     0x06a6
Ukranian_yi                       1703     0x06a7
Serbian_je                        1704     0x06a8
Serbian_lje                       1705     0x06a9
Serbian_nje                       1706     0x06aa
Serbian_tshe                      1707     0x06ab
Macedonia_kje                     1708     0x06ac
Byelorussian_shortu               1710     0x06ae
Serbian_dze                       1711     0x06af
numerosign                        1712     0x06b0
Serbian_DJE                       1713     0x06b1
Macedonia_GJE                     1714     0x06b2
Cyrillic_IO                       1715     0x06b3
Ukranian_JE                       1716     0x06b4
Macedonia_DSE                     1717     0x06b5
Ukranian_I                        1718     0x06b6
Ukranian_YI                       1719     0x06b7
Serbian_JE                        1720     0x06b8
Serbian_LJE                       1721     0x06b9
Serbian_NJE                       1722     0x06ba
Serbian_TSHE                      1723     0x06bb
Macedonia_KJE                     1724     0x06bc
Byelorussian_SHORTU               1726     0x06be
Serbian_DZE                       1727     0x06bf
Cyrillic_yu                       1728     0x06c0
Cyrillic_a                        1729     0x06c1
Cyrillic_be                       1730     0x06c2
Cyrillic_tse                      1731     0x06c3
Cyrillic_de                       1732     0x06c4
Cyrillic_ie                       1733     0x06c5
Cyrillic_ef                       1734     0x06c6
Cyrillic_ghe                      1735     0x06c7
Cyrillic_ha                       1736     0x06c8
Cyrillic_i                        1737     0x06c9
Cyrillic_shorti                   1738     0x06ca
Cyrillic_ka                       1739     0x06cb
Cyrillic_el                       1740     0x06cc
Cyrillic_em                       1741     0x06cd
Cyrillic_en                       1742     0x06ce
Cyrillic_o                        1743     0x06cf
Cyrillic_pe                       1744     0x06d0
Cyrillic_ya                       1745     0x06d1
Cyrillic_er                       1746     0x06d2
Cyrillic_es                       1747     0x06d3
Cyrillic_te                       1748     0x06d4
Cyrillic_u                        1749     0x06d5
Cyrillic_zhe                      1750     0x06d6
Cyrillic_ve                       1751     0x06d7
Cyrillic_softsign                 1752     0x06d8
Cyrillic_yeru                     1753     0x06d9
Cyrillic_ze                       1754     0x06da
Cyrillic_sha                      1755     0x06db
Cyrillic_e                        1756     0x06dc
Cyrillic_shcha                    1757     0x06dd
Cyrillic_che                      1758     0x06de
Cyrillic_hardsign                 1759     0x06df
Cyrillic_YU                       1760     0x06e0
Cyrillic_A                        1761     0x06e1
Cyrillic_BE                       1762     0x06e2
Cyrillic_TSE                      1763     0x06e3
Cyrillic_DE                       1764     0x06e4
Cyrillic_IE                       1765     0x06e5
Cyrillic_EF                       1766     0x06e6
Cyrillic_GHE                      1767     0x06e7
Cyrillic_HA                       1768     0x06e8
Cyrillic_I                        1769     0x06e9
Cyrillic_SHORTI                   1770     0x06ea
Cyrillic_KA                       1771     0x06eb
Cyrillic_EL                       1772     0x06ec
Cyrillic_EM                       1773     0x06ed
Cyrillic_EN                       1774     0x06ee
Cyrillic_O                        1775     0x06ef
Cyrillic_PE                       1776     0x06f0
Cyrillic_YA                       1777     0x06f1
Cyrillic_ER                       1778     0x06f2
Cyrillic_ES                       1779     0x06f3
Cyrillic_TE                       1780     0x06f4
Cyrillic_U                        1781     0x06f5
Cyrillic_ZHE                      1782     0x06f6
Cyrillic_VE                       1783     0x06f7
Cyrillic_SOFTSIGN                 1784     0x06f8
Cyrillic_YERU                     1785     0x06f9
Cyrillic_ZE                       1786     0x06fa
Cyrillic_SHA                      1787     0x06fb
Cyrillic_E                        1788     0x06fc
Cyrillic_SHCHA                    1789     0x06fd
Cyrillic_CHE                      1790     0x06fe
Cyrillic_HARDSIGN                 1791     0x06ff
Greek_ALPHAaccent                 1953     0x07a1
Greek_EPSILONaccent               1954     0x07a2
Greek_ETAaccent                   1955     0x07a3
Greek_IOTAaccent                  1956     0x07a4
Greek_IOTAdiaeresis               1957     0x07a5
Greek_IOTAaccentdiaeresis         1958     0x07a6
Greek_OMICRONaccent               1959     0x07a7
Greek_UPSILONaccent               1960     0x07a8
Greek_UPSILONdieresis             1961     0x07a9
Greek_UPSILONaccentdieresis       1962     0x07aa
Greek_OMEGAaccent                 1963     0x07ab
Greek_alphaaccent                 1969     0x07b1
Greek_epsilonaccent               1970     0x07b2
Greek_etaaccent                   1971     0x07b3
Greek_iotaaccent                  1972     0x07b4
Greek_iotadieresis                1973     0x07b5
Greek_iotaaccentdieresis          1974     0x07b6
Greek_omicronaccent               1975     0x07b7
Greek_upsilonaccent               1976     0x07b8
Greek_upsilondieresis             1977     0x07b9
Greek_upsilonaccentdieresis       1978     0x07ba
Greek_omegaaccent                 1979     0x07bb
Greek_ALPHA                       1985     0x07c1
Greek_BETA                        1986     0x07c2
Greek_GAMMA                       1987     0x07c3
Greek_DELTA                       1988     0x07c4
Greek_EPSILON                     1989     0x07c5
Greek_ZETA                        1990     0x07c6
Greek_ETA                         1991     0x07c7
Greek_THETA                       1992     0x07c8
Greek_IOTA                        1993     0x07c9
Greek_KAPPA                       1994     0x07ca
Greek_LAMBDA                      1995     0x07cb
Greek_MU                          1996     0x07cc
Greek_NU                          1997     0x07cd
Greek_XI                          1998     0x07ce
Greek_OMICRON                     1999     0x07cf
Greek_PI                          2000     0x07d0
Greek_RHO                         2001     0x07d1
Greek_SIGMA                       2002     0x07d2
Greek_TAU                         2004     0x07d4
Greek_UPSILON                     2005     0x07d5
Greek_PHI                         2006     0x07d6
Greek_CHI                         2007     0x07d7
Greek_PSI                         2008     0x07d8
Greek_OMEGA                       2009     0x07d9
Greek_alpha                       2017     0x07e1
Greek_beta                        2018     0x07e2
Greek_gamma                       2019     0x07e3
Greek_delta                       2020     0x07e4
Greek_epsilon                     2021     0x07e5
Greek_zeta                        2022     0x07e6
Greek_eta                         2023     0x07e7
Greek_theta                       2024     0x07e8
Greek_iota                        2025     0x07e9
Greek_kappa                       2026     0x07ea
Greek_lambda                      2027     0x07eb
Greek_mu                          2028     0x07ec
Greek_nu                          2029     0x07ed
Greek_xi                          2030     0x07ee
Greek_omicron                     2031     0x07ef
Greek_pi                          2032     0x07f0
Greek_rho                         2033     0x07f1
Greek_sigma                       2034     0x07f2
Greek_finalsmallsigma             2035     0x07f3
Greek_tau                         2036     0x07f4
Greek_upsilon                     2037     0x07f5
Greek_phi                         2038     0x07f6
Greek_chi                         2039     0x07f7
Greek_psi                         2040     0x07f8
Greek_omega                       2041     0x07f9
leftradical                       2209     0x08a1
topleftradical                    2210     0x08a2
horizconnector                    2211     0x08a3
topintegral                       2212     0x08a4
botintegral                       2213     0x08a5
vertconnector                     2214     0x08a6
topleftsqbracket                  2215     0x08a7
botleftsqbracket                  2216     0x08a8
toprightsqbracket                 2217     0x08a9
botrightsqbracket                 2218     0x08aa
topleftparens                     2219     0x08ab
botleftparens                     2220     0x08ac
toprightparens                    2221     0x08ad
botrightparens                    2222     0x08ae
leftmiddlecurlybrace              2223     0x08af
rightmiddlecurlybrace             2224     0x08b0
topleftsummation                  2225     0x08b1
botleftsummation                  2226     0x08b2
topvertsummationconnector         2227     0x08b3
botvertsummationconnector         2228     0x08b4
toprightsummation                 2229     0x08b5
botrightsummation                 2230     0x08b6
rightmiddlesummation              2231     0x08b7
lessthanequal                     2236     0x08bc
notequal                          2237     0x08bd
greaterthanequal                  2238     0x08be
integral                          2239     0x08bf
therefore                         2240     0x08c0
variation                         2241     0x08c1
infinity                          2242     0x08c2
nabla                             2245     0x08c5
approximate                       2248     0x08c8
similarequal                      2249     0x08c9
ifonlyif                          2253     0x08cd
implies                           2254     0x08ce
identical                         2255     0x08cf
radical                           2262     0x08d6
includedin                        2266     0x08da
includes                          2267     0x08db
intersection                      2268     0x08dc
union                             2269     0x08dd
logicaland                        2270     0x08de
logicalor                         2271     0x08df
partialderivative                 2287     0x08ef
function                          2294     0x08f6
leftarrow                         2299     0x08fb
uparrow                           2300     0x08fc
rightarrow                        2301     0x08fd
downarrow                         2302     0x08fe
blank                             2527     0x09df
soliddiamond                      2528     0x09e0
checkerboard                      2529     0x09e1
ht                                2530     0x09e2
ff                                2531     0x09e3
cr                                2532     0x09e4
lf                                2533     0x09e5
nl                                2536     0x09e8
vt                                2537     0x09e9
lowrightcorner                    2538     0x09ea
uprightcorner                     2539     0x09eb
upleftcorner                      2540     0x09ec
lowleftcorner                     2541     0x09ed
crossinglines                     2542     0x09ee
horizlinescan1                    2543     0x09ef
horizlinescan3                    2544     0x09f0
horizlinescan5                    2545     0x09f1
horizlinescan7                    2546     0x09f2
horizlinescan9                    2547     0x09f3
leftt                             2548     0x09f4
rightt                            2549     0x09f5
bott                              2550     0x09f6
topt                              2551     0x09f7
vertbar                           2552     0x09f8
emspace                           2721     0x0aa1
enspace                           2722     0x0aa2
em3space                          2723     0x0aa3
em4space                          2724     0x0aa4
digitspace                        2725     0x0aa5
punctspace                        2726     0x0aa6
thinspace                         2727     0x0aa7
hairspace                         2728     0x0aa8
emdash                            2729     0x0aa9
endash                            2730     0x0aaa
signifblank                       2732     0x0aac
ellipsis                          2734     0x0aae
doubbaselinedot                   2735     0x0aaf
onethird                          2736     0x0ab0
twothirds                         2737     0x0ab1
onefifth                          2738     0x0ab2
twofifths                         2739     0x0ab3
threefifths                       2740     0x0ab4
fourfifths                        2741     0x0ab5
onesixth                          2742     0x0ab6
fivesixths                        2743     0x0ab7
careof                            2744     0x0ab8
figdash                           2747     0x0abb
leftanglebracket                  2748     0x0abc
decimalpoint                      2749     0x0abd
rightanglebracket                 2750     0x0abe
marker                            2751     0x0abf
oneeighth                         2755     0x0ac3
threeeighths                      2756     0x0ac4
fiveeighths                       2757     0x0ac5
seveneighths                      2758     0x0ac6
trademark                         2761     0x0ac9
signaturemark                     2762     0x0aca
trademarkincircle                 2763     0x0acb
leftopentriangle                  2764     0x0acc
rightopentriangle                 2765     0x0acd
emopencircle                      2766     0x0ace
emopenrectangle                   2767     0x0acf
leftsinglequotemark               2768     0x0ad0
rightsinglequotemark              2769     0x0ad1
leftdoublequotemark               2770     0x0ad2
rightdoublequotemark              2771     0x0ad3
prescription                      2772     0x0ad4
minutes                           2774     0x0ad6
seconds                           2775     0x0ad7
latincross                        2777     0x0ad9
hexagram                          2778     0x0ada
filledrectbullet                  2779     0x0adb
filledlefttribullet               2780     0x0adc
filledrighttribullet              2781     0x0add
emfilledcircle                    2782     0x0ade
emfilledrect                      2783     0x0adf
enopencircbullet                  2784     0x0ae0
enopensquarebullet                2785     0x0ae1
openrectbullet                    2786     0x0ae2
opentribulletup                   2787     0x0ae3
opentribulletdown                 2788     0x0ae4
openstar                          2789     0x0ae5
enfilledcircbullet                2790     0x0ae6
enfilledsqbullet                  2791     0x0ae7
filledtribulletup                 2792     0x0ae8
filledtribulletdown               2793     0x0ae9
leftpointer                       2794     0x0aea
rightpointer                      2795     0x0aeb
club                              2796     0x0aec
diamond                           2797     0x0aed
heart                             2798     0x0aee
maltesecross                      2800     0x0af0
dagger                            2801     0x0af1
doubledagger                      2802     0x0af2
checkmark                         2803     0x0af3
ballotcross                       2804     0x0af4
musicalsharp                      2805     0x0af5
musicalflat                       2806     0x0af6
malesymbol                        2807     0x0af7
femalesymbol                      2808     0x0af8
telephone                         2809     0x0af9
telephonerecorder                 2810     0x0afa
phonographcopyright               2811     0x0afb
caret                             2812     0x0afc
singlelowquotemark                2813     0x0afd
doublelowquotemark                2814     0x0afe
cursor                            2815     0x0aff
leftcaret                         2979     0x0ba3
rightcaret                        2982     0x0ba6
downcaret                         2984     0x0ba8
upcaret                           2985     0x0ba9
overbar                           3008     0x0bc0
downtack                          3010     0x0bc2
upshoe                            3011     0x0bc3
downstile                         3012     0x0bc4
underbar                          3014     0x0bc6
jot                               3018     0x0bca
quad                              3020     0x0bcc
uptack                            3022     0x0bce
circle                            3023     0x0bcf
upstile                           3027     0x0bd3
downshoe                          3030     0x0bd6
rightshoe                         3032     0x0bd8
leftshoe                          3034     0x0bda
lefttack                          3036     0x0bdc
righttack                         3068     0x0bfc
hebrew_aleph                      3296     0x0ce0
hebrew_beth                       3297     0x0ce1
hebrew_gimmel                     3298     0x0ce2
hebrew_daleth                     3299     0x0ce3
hebrew_he                         3300     0x0ce4
hebrew_waw                        3301     0x0ce5
hebrew_zayin                      3302     0x0ce6
hebrew_het                        3303     0x0ce7
hebrew_teth                       3304     0x0ce8
hebrew_yod                        3305     0x0ce9
hebrew_finalkaph                  3306     0x0cea
hebrew_kaph                       3307     0x0ceb
hebrew_lamed                      3308     0x0cec
hebrew_finalmem                   3309     0x0ced
hebrew_mem                        3310     0x0cee
hebrew_finalnun                   3311     0x0cef
hebrew_nun                        3312     0x0cf0
hebrew_samekh                     3313     0x0cf1
hebrew_ayin                       3314     0x0cf2
hebrew_finalpe                    3315     0x0cf3
hebrew_pe                         3316     0x0cf4
hebrew_finalzadi                  3317     0x0cf5
hebrew_zadi                       3318     0x0cf6
hebrew_kuf                        3319     0x0cf7
hebrew_resh                       3320     0x0cf8
hebrew_shin                       3321     0x0cf9
hebrew_taf                        3322     0x0cfa
BackSpace                        65288     0xff08
Tab                              65289     0xff09
Linefeed                         65290     0xff0a
Clear                            65291     0xff0b
Return                           65293     0xff0d
Pause                            65299     0xff13
Scroll_Lock                      65300     0xff14
Sys_Req                          65301     0xff15
Escape                           65307     0xff1b
Multi_key                        65312     0xff20
Kanji                            65313     0xff21
Home                             65360     0xff50
Left                             65361     0xff51
Up                               65362     0xff52
Right                            65363     0xff53
Down                             65364     0xff54
Prior                            65365     0xff55
Next                             65366     0xff56
End                              65367     0xff57
Begin                            65368     0xff58
Win_L                            65371     0xff5b
Win_R                            65372     0xff5c
App                              65373     0xff5d
Select                           65376     0xff60
Print                            65377     0xff61
Execute                          65378     0xff62
Insert                           65379     0xff63
Undo                             65381     0xff65
Redo                             65382     0xff66
Menu                             65383     0xff67
Find                             65384     0xff68
Cancel                           65385     0xff69
Help                             65386     0xff6a
Break                            65387     0xff6b
Hebrew_switch                    65406     0xff7e
Num_Lock                         65407     0xff7f
KP_Space                         65408     0xff80
KP_Tab                           65417     0xff89
KP_Enter                         65421     0xff8d
KP_F1                            65425     0xff91
KP_F2                            65426     0xff92
KP_F3                            65427     0xff93
KP_F4                            65428     0xff94
KP_Multiply                      65450     0xffaa
KP_Add                           65451     0xffab
KP_Separator                     65452     0xffac
KP_Subtract                      65453     0xffad
KP_Decimal                       65454     0xffae
KP_Divide                        65455     0xffaf
KP_0                             65456     0xffb0
KP_1                             65457     0xffb1
KP_2                             65458     0xffb2
KP_3                             65459     0xffb3
KP_4                             65460     0xffb4
KP_5                             65461     0xffb5
KP_6                             65462     0xffb6
KP_7                             65463     0xffb7
KP_8                             65464     0xffb8
KP_9                             65465     0xffb9
KP_Equal                         65469     0xffbd
F1                               65470     0xffbe
F2                               65471     0xffbf
F3                               65472     0xffc0
F4                               65473     0xffc1
F5                               65474     0xffc2
F6                               65475     0xffc3
F7                               65476     0xffc4
F8                               65477     0xffc5
F9                               65478     0xffc6
F10                              65479     0xffc7
L1                               65480     0xffc8
L2                               65481     0xffc9
L3                               65482     0xffca
L4                               65483     0xffcb
L5                               65484     0xffcc
L6                               65485     0xffcd
L7                               65486     0xffce
L8                               65487     0xffcf
L9                               65488     0xffd0
L10                              65489     0xffd1
R1                               65490     0xffd2
R2                               65491     0xffd3
R3                               65492     0xffd4
R4                               65493     0xffd5
R5                               65494     0xffd6
R6                               65495     0xffd7
R7                               65496     0xffd8
R8                               65497     0xffd9
R9                               65498     0xffda
R10                              65499     0xffdb
R11                              65500     0xffdc
R12                              65501     0xffdd
F33                              65502     0xffde
R14                              65503     0xffdf
R15                              65504     0xffe0
Shift_L                          65505     0xffe1
Shift_R                          65506     0xffe2
Control_L                        65507     0xffe3
Control_R                        65508     0xffe4
Caps_Lock                        65509     0xffe5
Shift_Lock                       65510     0xffe6
Meta_L                           65511     0xffe7
Meta_R                           65512     0xffe8
Alt_L                            65513     0xffe9
Alt_R                            65514     0xffea
Super_L                          65515     0xffeb
Super_R                          65516     0xffec
Hyper_L                          65517     0xffed
Hyper_R                          65518     0xffee
Delete                           65535     0xffff

SEE ALSO

bind

KEYWORDS

keysym, bind, binding
Copyright © 1998-2000 by Scriptics Corporation.


Tk Built-In Commands - label manual page

NAME
label - Create and manipulate label widgets
SYNOPSIS
label pathName ?options?
STANDARD OPTIONS
-activebackground -activeforeground -anchor
-background -bitmap -borderwidth
-cursor -disabledforeground -font
-foreground -highlightbackground -highlightcolor
-highlightthickness -image -justify
-padx -pady -relief
-takefocus -text -textvariable
-underline -wraplength
WIDGET-SPECIFIC OPTIONS
-height, height, Height
-state, state, State
-width, width, Width
DESCRIPTION
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
BINDINGS
KEYWORDS

NAME

label - Create and manipulate label widgets

SYNOPSIS

label pathName ?options?

STANDARD OPTIONS

-activebackground -activeforeground -anchor
-background -bitmap -borderwidth
-cursor -disabledforeground -font
-foreground -highlightbackground -highlightcolor
-highlightthickness -image -justify
-padx -pady -relief
-takefocus -text -textvariable
-underline -wraplength

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -height
Database Name: height
Database Class: Height
Specifies a desired height for the label. If an image or bitmap is being displayed in the label then the value is in screen units (i.e. any of the forms acceptable to Tk_GetPixels); for text it is in lines of text. If this option isn't specified, the label's desired height is computed from the size of the image or bitmap or text being displayed in it.

Command-Line Name: -state
Database Name: state
Database Class: State
Specifies one of three states for the label: normal, active, or disabled. In normal state the button is displayed using the foreground and background options. In active state the label is displayed using the activeForeground and activeBackground options. In the disabled state the disabledForeground and background options determine how the button is displayed.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies a desired width for the label. If an image or bitmap is being displayed in the label then the value is in screen units (i.e. any of the forms acceptable to Tk_GetPixels); for text it is in characters. If this option isn't specified, the label's desired width is computed from the size of the image or bitmap or text being displayed in it.

DESCRIPTION

The label command creates a new window (given by the pathName argument) and makes it into a label widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the label such as its colors, font, text, and initial relief. The label command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A label is a widget that displays a textual string, bitmap or image. If text is displayed, it must all be in a single font, but it can occupy multiple lines on the screen (if it contains newlines or if wrapping occurs because of the wrapLength option) and one of the characters may optionally be underlined using the underline option. The label can be manipulated in a few simple ways, such as changing its relief or text, using the commands described below.

WIDGET COMMAND

The label command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for label widgets:

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the label command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the label command.

BINDINGS

When a new label is created, it has no default event bindings: labels are not intended to be interactive.

KEYWORDS

label, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - listbox manual page

NAME
listbox - Create and manipulate listbox widgets
SYNOPSIS
listbox pathName ?options?
STANDARD OPTIONS
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-exportselection, exportSelection, ExportSelection
-font, font, Font
-foreground or -fg, foreground, Foreground
-height
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-listvar
-relief, relief, Relief
-selectbackground, selectBackground, Foreground
-selectborderwidth, selectBorderWidth, BorderWidth
-selectforeground, selectForeground, Background
-setgrid, setGrid, SetGrid
-takefocus, takeFocus, TakeFocus
-width
-xscrollcommand, xScrollCommand, ScrollCommand
-yscrollcommand, yScrollCommand, ScrollCommand
WIDGET-SPECIFIC OPTIONS
-height, height, Height
-listvar, listVariable, Variable
-selectmode, selectMode, SelectMode
-width, width, Width
DESCRIPTION
INDICES
number
active
anchor
end
@x,y
WIDGET COMMAND
pathName activate index
pathName bbox index
pathName cget option
pathName configure ?option? ?value option value ...?
pathName curselection
pathName delete first ?last?
pathName get first ?last?
pathName index index
pathName insert index ?element element ...?
pathName itemcget index option
pathName itemconfigure index ?option? ?value? ?option value ...?
-background color
-foreground color
-selectbackground color
-selectforeground color
pathName nearest y
pathName scan option args
pathName scan mark x y
pathName scan dragto x y.
pathName see index
pathName selection option arg
pathName selection anchor index
pathName selection clear first ?last?
pathName selection includes index
pathName selection set first ?last?
pathName size
pathName xview args
pathName xview
pathName xview index
pathName xview moveto fraction
pathName xview scroll number what
pathName yview ?args?
pathName yview
pathName yview index
pathName yview moveto fraction
pathName yview scroll number what
DEFAULT BINDINGS
KEYWORDS

NAME

listbox - Create and manipulate listbox widgets

SYNOPSIS

listbox pathName ?options?

STANDARD OPTIONS

-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-exportselection, exportSelection, ExportSelection
-font, font, Font
-foreground or -fg, foreground, Foreground
-height
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-listvar
-relief, relief, Relief
-selectbackground, selectBackground, Foreground
-selectborderwidth, selectBorderWidth, BorderWidth
-selectforeground, selectForeground, Background
-setgrid, setGrid, SetGrid
-takefocus, takeFocus, TakeFocus
-width
-xscrollcommand, xScrollCommand, ScrollCommand
-yscrollcommand, yScrollCommand, ScrollCommand

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -height
Database Name: height
Database Class: Height
Specifies the desired height for the window, in lines. If zero or less, then the desired height for the window is made just large enough to hold all the elements in the listbox.

Command-Line Name: -listvar
Database Name: listVariable
Database Class: Variable
Specifies the name of a variable. The value of the variable is a list to be displayed inside the widget; if the variable value changes then the widget will automatically update itself to reflect the new value. Attempts to assign a bad list value to a variable in use as a listvar will cause an error. Attempts to unset a variable in use as a listvar will fail but will not generate an error.

Command-Line Name: -selectmode
Database Name: selectMode
Database Class: SelectMode
Specifies one of several styles for manipulating the selection. The value of the option may be arbitrary, but the default bindings expect it to be either single, browse, multiple, or extended; the default value is browse.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies the desired width for the window in characters. If the font doesn't have a uniform width then the width of the character ``0'' is used in translating from character units to screen units. If zero or less, then the desired width for the window is made just large enough to hold all the elements in the listbox.

DESCRIPTION

The listbox command creates a new window (given by the pathName argument) and makes it into a listbox widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the listbox such as its colors, font, text, and relief. The listbox command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A listbox is a widget that displays a list of strings, one per line. When first created, a new listbox has no elements. Elements may be added or deleted using widget commands described below. In addition, one or more elements may be selected as described below. If a listbox is exporting its selection (see exportSelection option), then it will observe the standard X11 protocols for handling the selection. Listbox selections are available as type STRING; the value of the selection will be the text of the selected elements, with newlines separating the elements.

It is not necessary for all the elements to be displayed in the listbox window at once; commands described below may be used to change the view in the window. Listboxes allow scrolling in both directions using the standard xScrollCommand and yScrollCommand options. They also support scanning, as described below.

INDICES

Many of the widget commands for listboxes take one or more indices as arguments. An index specifies a particular element of the listbox, in any of the following ways:

number
Specifies the element as a numerical index, where 0 corresponds to the first element in the listbox.

active
Indicates the element that has the location cursor. This element will be displayed with an underline when the listbox has the keyboard focus, and it is specified with the activate widget command.

anchor
Indicates the anchor point for the selection, which is set with the selection anchor widget command.

end
Indicates the end of the listbox. For most commands this refers to the last element in the listbox, but for a few commands such as index and insert it refers to the element just after the last one.

@x,y
Indicates the element that covers the point in the listbox window specified by x and y (in pixel coordinates). If no element covers that point, then the closest element to that point is used.

In the widget command descriptions below, arguments named index, first, and last always contain text indices in one of the above forms.

WIDGET COMMAND

The listbox command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for listbox widgets:

pathName activate index
Sets the active element to the one indicated by index. If index is outside the range of elements in the listbox then the closest element is activated. The active element is drawn with an underline when the widget has the input focus, and its index may be retrieved with the index active.

pathName bbox index
Returns a list of four numbers describing the bounding box of the text in the element given by index. The first two elements of the list give the x and y coordinates of the upper-left corner of the screen area covered by the text (specified in pixels relative to the widget) and the last two elements give the width and height of the area, in pixels. If no part of the element given by index is visible on the screen, or if index refers to a non-existent element, then the result is an empty string; if the element is partially visible, the result gives the full area of the element, including any parts that are not visible.

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the listbox command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the listbox command.

pathName curselection
Returns a list containing the numerical indices of all of the elements in the listbox that are currently selected. If there are no elements selected in the listbox then an empty string is returned.

pathName delete first ?last?
Deletes one or more elements of the listbox. First and last are indices specifying the first and last elements in the range to delete. If last isn't specified it defaults to first, i.e. a single element is deleted.

pathName get first ?last?
If last is omitted, returns the contents of the listbox element indicated by first, or an empty string if first refers to a non-existent element. If last is specified, the command returns a list whose elements are all of the listbox elements between first and last, inclusive. Both first and last may have any of the standard forms for indices.

pathName index index
Returns the integer index value that corresponds to index. If index is end the return value is a count of the number of elements in the listbox (not the index of the last element).

pathName insert index ?element element ...?
Inserts zero or more new elements in the list just before the element given by index. If index is specified as end then the new elements are added to the end of the list. Returns an empty string.

pathName itemcget index option
Returns the current value of the item configuration option given by option. Option may have any of the values accepted by the listbox itemconfigure command.

pathName itemconfigure index ?option? ?value? ?option value ...?
Query or modify the configuration options of an item in the listbox. If no option is specified, returns a list describing all of the available options for the item (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. The following options are currently supported for items:

-background color
Color specifies the background color to use when displaying the item. It may have any of the forms accepted by Tk_GetColor.

-foreground color
Color specifies the foreground color to use when displaying the item. It may have any of the forms accepted by Tk_GetColor.

-selectbackground color
color specifies the background color to use when displaying the item while it is selected. It may have any of the forms accepted by Tk_GetColor.

-selectforeground color
color specifies the foreground color to use when displaying the item while it is selected. It may have any of the forms accepted by Tk_GetColor.

pathName nearest y
Given a y-coordinate within the listbox window, this command returns the index of the (visible) listbox element nearest to that y-coordinate.

pathName scan option args
This command is used to implement scanning on listboxes. It has two forms, depending on option:

pathName scan mark x y
Records x and y and the current view in the listbox window; used in conjunction with later scan dragto commands. Typically this command is associated with a mouse button press in the widget. It returns an empty string.

pathName scan dragto x y.
This command computes the difference between its x and y arguments and the x and y arguments to the last scan mark command for the widget. It then adjusts the view by 10 times the difference in coordinates. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the list at high speed through the window. The return value is an empty string.

pathName see index
Adjust the view in the listbox so that the element given by index is visible. If the element is already visible then the command has no effect; if the element is near one edge of the window then the listbox scrolls to bring the element into view at the edge; otherwise the listbox scrolls to center the element.

pathName selection option arg
This command is used to adjust the selection within a listbox. It has several forms, depending on option:

pathName selection anchor index
Sets the selection anchor to the element given by index. If index refers to a non-existent element, then the closest element is used. The selection anchor is the end of the selection that is fixed while dragging out a selection with the mouse. The index anchor may be used to refer to the anchor element.

pathName selection clear first ?last?
If any of the elements between first and last (inclusive) are selected, they are deselected. The selection state is not changed for elements outside this range.

pathName selection includes index
Returns 1 if the element indicated by index is currently selected, 0 if it isn't.

pathName selection set first ?last?
Selects all of the elements in the range between first and last, inclusive, without affecting the selection state of elements outside that range.

pathName size
Returns a decimal string indicating the total number of elements in the listbox.

pathName xview args
This command is used to query and change the horizontal position of the information in the widget's window. It can take any of the following forms:

pathName xview
Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the horizontal span that is visible in the window. For example, if the first element is .2 and the second element is .6, 20% of the listbox's text is off-screen to the left, the middle 40% is visible in the window, and 40% of the text is off-screen to the right. These are the same values passed to scrollbars via the -xscrollcommand option.

pathName xview index
Adjusts the view in the window so that the character position given by index is displayed at the left edge of the window. Character positions are defined by the width of the character 0.

pathName xview moveto fraction
Adjusts the view in the window so that fraction of the total width of the listbox text is off-screen to the left. fraction must be a fraction between 0 and 1.

pathName xview scroll number what
This command shifts the view in the window left or right according to number and what. Number must be an integer. What must be either units or pages or an abbreviation of one of these. If what is units, the view adjusts left or right by number character units (the width of the 0 character) on the display; if it is pages then the view adjusts by number screenfuls. If number is negative then characters farther to the left become visible; if it is positive then characters farther to the right become visible.

pathName yview ?args?
This command is used to query and change the vertical position of the text in the widget's window. It can take any of the following forms:

pathName yview
Returns a list containing two elements, both of which are real fractions between 0 and 1. The first element gives the position of the listbox element at the top of the window, relative to the listbox as a whole (0.5 means it is halfway through the listbox, for example). The second element gives the position of the listbox element just after the last one in the window, relative to the listbox as a whole. These are the same values passed to scrollbars via the -yscrollcommand option.

pathName yview index
Adjusts the view in the window so that the element given by index is displayed at the top of the window.

pathName yview moveto fraction
Adjusts the view in the window so that the element given by fraction appears at the top of the window. Fraction is a fraction between 0 and 1; 0 indicates the first element in the listbox, 0.33 indicates the element one-third the way through the listbox, and so on.

pathName yview scroll number what
This command adjusts the view in the window up or down according to number and what. Number must be an integer. What must be either units or pages. If what is units, the view adjusts up or down by number lines; if it is pages then the view adjusts by number screenfuls. If number is negative then earlier elements become visible; if it is positive then later elements become visible.

DEFAULT BINDINGS

Tk automatically creates class bindings for listboxes that give them Motif-like behavior. Much of the behavior of a listbox is determined by its selectMode option, which selects one of four ways of dealing with the selection.

If the selection mode is single or browse, at most one element can be selected in the listbox at once. In both modes, clicking button 1 on an element selects it and deselects any other selected item. In browse mode it is also possible to drag the selection with button 1.

If the selection mode is multiple or extended, any number of elements may be selected at once, including discontiguous ranges. In multiple mode, clicking button 1 on an element toggles its selection state without affecting any other elements. In extended mode, pressing button 1 on an element selects it, deselects everything else, and sets the anchor to the element under the mouse; dragging the mouse with button 1 down extends the selection to include all the elements between the anchor and the element under the mouse, inclusive.

Most people will probably want to use browse mode for single selections and extended mode for multiple selections; the other modes appear to be useful only in special situations.

Any time the selection changes in the listbox, the virtual event <<ListboxSelect>> will be generated. It is easiest to bind to this event to be made aware of any changes to listbox selection.

In addition to the above behavior, the following additional behavior is defined by the default bindings:

[1]
In extended mode, the selected range can be adjusted by pressing button 1 with the Shift key down: this modifies the selection to consist of the elements between the anchor and the element under the mouse, inclusive. The un-anchored end of this new selection can also be dragged with the button down.

[2]
In extended mode, pressing button 1 with the Control key down starts a toggle operation: the anchor is set to the element under the mouse, and its selection state is reversed. The selection state of other elements isn't changed. If the mouse is dragged with button 1 down, then the selection state of all elements between the anchor and the element under the mouse is set to match that of the anchor element; the selection state of all other elements remains what it was before the toggle operation began.

[3]
If the mouse leaves the listbox window with button 1 down, the window scrolls away from the mouse, making information visible that used to be off-screen on the side of the mouse. The scrolling continues until the mouse re-enters the window, the button is released, or the end of the listbox is reached.

[4]
Mouse button 2 may be used for scanning. If it is pressed and dragged over the listbox, the contents of the listbox drag at high speed in the direction the mouse moves.

[5]
If the Up or Down key is pressed, the location cursor (active element) moves up or down one element. If the selection mode is browse or extended then the new active element is also selected and all other elements are deselected. In extended mode the new active element becomes the selection anchor.

[6]
In extended mode, Shift-Up and Shift-Down move the location cursor (active element) up or down one element and also extend the selection to that element in a fashion similar to dragging with mouse button 1.

[7]
The Left and Right keys scroll the listbox view left and right by the width of the character 0. Control-Left and Control-Right scroll the listbox view left and right by the width of the window. Control-Prior and Control-Next also scroll left and right by the width of the window.

[8]
The Prior and Next keys scroll the listbox view up and down by one page (the height of the window).

[9]
The Home and End keys scroll the listbox horizontally to the left and right edges, respectively.

[10]
Control-Home sets the location cursor to the the first element in the listbox, selects that element, and deselects everything else in the listbox.

[11]
Control-End sets the location cursor to the the last element in the listbox, selects that element, and deselects everything else in the listbox.

[12]
In extended mode, Control-Shift-Home extends the selection to the first element in the listbox and Control-Shift-End extends the selection to the last element.

[13]
In multiple mode, Control-Shift-Home moves the location cursor to the first element in the listbox and Control-Shift-End moves the location cursor to the last element.

[14]
The space and Select keys make a selection at the location cursor (active element) just as if mouse button 1 had been pressed over this element.

[15]
In extended mode, Control-Shift-space and Shift-Select extend the selection to the active element just as if button 1 had been pressed with the Shift key down.

[16]
In extended mode, the Escape key cancels the most recent selection and restores all the elements in the selected range to their previous selection state.

[17]
Control-slash selects everything in the widget, except in single and browse modes, in which case it selects the active element and deselects everything else.

[18]
Control-backslash deselects everything in the widget, except in browse mode where it has no effect.

[19]
The F16 key (labelled Copy on many Sun workstations) or Meta-w copies the selection in the widget to the clipboard, if there is a selection.

The behavior of listboxes can be changed by defining new bindings for individual widgets or by redefining the class bindings.

KEYWORDS

listbox, widget
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tk Tk Built-In Commands - Safe manual page

NAME

loadTk - Load Tk into a safe interpreter.

SYNOPSIS

::safe::loadTk slave ?-use windowId? ?-display displayName?
Safe Tk is based on Safe Tcl, which provides a mechanism that allows restricted and mediated access to auto-loading and packages for safe interpreters. Safe Tk adds the ability to configure the interpreter for safe Tk operations and load Tk into safe interpreters.

DESCRIPTION

The ::safe::loadTk command initializes the required data structures in the named safe interpreter and then loads Tk into it. The command returns the name of the safe interpreter. If -use is specified, the window identified by the specified system dependent identifier windowId is used to contain the ``.'' window of the safe interpreter; it can be any valid id, eventually referencing a window belonging to another application. As a convenience, if the window you plan to use is a Tk Window of the application you can use the window name (eg: .x.y) instead of its window Id ([winfo id .x.y]). When -use is not specified, a new toplevel window is created for the ``.'' window of the safe interpreter. On X11 if you want the embedded window to use another display than the default one, specify it with -display. See the SECURITY ISSUES section below for implementation details.

SECURITY ISSUES

Please read the safe manual page for Tcl to learn about the basic security considerations for Safe Tcl.

::safe::loadTk adds the value of tk_library taken from the master interpreter to the virtual access path of the safe interpreter so that auto-loading will work in the safe interpreter.

Tk initialization is now safe with respect to not trusting the slave's state for startup. ::safe::loadTk registers the slave's name so when the Tk initialization (Tk_SafeInit) is called and in turn calls the master's ::safe::InitTk it will return the desired argv equivalent (-use windowId, correct -display, etc...).

When -use is not used, the new toplevel created is specially decorated so the user is always aware that the user interface presented comes from a potentially unsafe code and can easily delete the corresponding interpreter.

On X11, conflicting -use and -display are likely to generate a fatal X error.

SEE ALSO

safe, interp, library, load, package, source, unknown

KEYWORDS

alias, auto-loading, auto_mkindex, load, master interpreter, safe interpreter, slave interpreter, source
Copyright © 1995-1996 Sun Microsystems, Inc.


Tk Built-In Commands - lower manual page

NAME

lower - Change a window's position in the stacking order

SYNOPSIS

lower window ?belowThis?

DESCRIPTION

If the belowThis argument is omitted then the command lowers window so that it is below all of its siblings in the stacking order (it will be obscured by any siblings that overlap it and will not obscure any siblings). If belowThis is specified then it must be the path name of a window that is either a sibling of window or the descendant of a sibling of window. In this case the lower command will insert window into the stacking order just below belowThis (or the ancestor of belowThis that is a sibling of window); this could end up either raising or lowering window.

SEE ALSO

raise

KEYWORDS

lower, obscure, stacking order
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - menu manual page

NAME
menu - Create and manipulate menu widgets
SYNOPSIS
menu pathName ?options?
STANDARD OPTIONS
-activebackground, activeBackground, Foreground
-activeborderwidth, activeBorderWidth, BorderWidth
-activeforeground, activeForeground, Background
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-font, font, Font
-foreground or -fg, foreground, Foreground
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
WIDGET-SPECIFIC OPTIONS
-postcommand, postCommand, Command
-selectcolor, selectColor, Background
-tearoff, tearOff, TearOff
-tearoffcommand, tearOffCommand, TearOffCommand
-title, title, Title
-type, type, Type
INTRODUCTION
COMMAND ENTRIES
SEPARATOR ENTRIES
CHECKBUTTON ENTRIES
RADIOBUTTON ENTRIES
CASCADE ENTRIES
TEAR-OFF ENTRIES
MENUBARS
SPECIAL MENUS IN MENUBARS
CLONES
WIDGET COMMAND
number
active
end
last
none
@number
pattern
pathName activate index
pathName add type ?option value option value ...?
-activebackground value
-activeforeground value
-accelerator value
-background value
-bitmap value
-columnbreak value
-command value
-font value
-foreground value
-hidemargin value
-image value
-indicatoron value
-label value
-menu value
-offvalue value
-onvalue value
-selectcolor value
-selectimage value
-state value
-underline value
-value value
-variable value
pathName cget option
pathName clone newPathname ?cloneType?
pathName configure ?option? ?value option value ...?
pathName delete index1 ?index2?
pathName entrycget index option
pathName entryconfigure index ?options?
pathName index index
pathName insert index type ?option value option value ...?
pathName invoke index
pathName post x y
pathName postcascade index
pathName type index
.VS
pathName yposition index
MENU CONFIGURATIONS
Pulldown Menus in Menubar
Pulldown Menus in Menu Buttons
Popup Menus
Option Menus
Torn-off Menus
DEFAULT BINDINGS
BUGS
KEYWORDS

NAME

menu - Create and manipulate menu widgets

SYNOPSIS

menu pathName ?options?

STANDARD OPTIONS

-activebackground, activeBackground, Foreground
-activeborderwidth, activeBorderWidth, BorderWidth
-activeforeground, activeForeground, Background
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-font, font, Font
-foreground or -fg, foreground, Foreground
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -postcommand
Database Name: postCommand
Database Class: Command
If this option is specified then it provides a Tcl command to execute each time the menu is posted. The command is invoked by the post widget command before posting the menu. Note that in 8.0 on Macintosh and Windows, all commands in a menu systems are executed before any are posted. This is due to the limitations in the individual platforms' menu managers.

Command-Line Name: -selectcolor
Database Name: selectColor
Database Class: Background
For menu entries that are check buttons or radio buttons, this option specifies the color to display in the indicator when the check button or radio button is selected.

Command-Line Name: -tearoff
Database Name: tearOff
Database Class: TearOff
This option must have a proper boolean value, which specifies whether or not the menu should include a tear-off entry at the top. If so, it will exist as entry 0 of the menu and the other entries will number starting at 1. The default menu bindings arrange for the menu to be torn off when the tear-off entry is invoked.

Command-Line Name: -tearoffcommand
Database Name: tearOffCommand
Database Class: TearOffCommand
If this option has a non-empty value, then it specifies a Tcl command to invoke whenever the menu is torn off. The actual command will consist of the value of this option, followed by a space, followed by the name of the menu window, followed by a space, followed by the name of the name of the torn off menu window. For example, if the option's is ``a b'' and menu .x.y is torn off to create a new menu .x.tearoff1, then the command ``a b .x.y .x.tearoff1'' will be invoked.

Command-Line Name: -title
Database Name: title
Database Class: Title
The string will be used to title the window created when this menu is torn off. If the title is NULL, then the window will have the title of the menubutton or the text of the cascade item from which this menu was invoked.

Command-Line Name: -type
Database Name: type
Database Class: Type
This option can be one of menubar, tearoff, or normal, and is set when the menu is created. While the string returned by the configuration database will change if this option is changed, this does not affect the menu widget's behavior. This is used by the cloning mechanism and is not normally set outside of the Tk library.

INTRODUCTION

The menu command creates a new top-level window (given by the pathName argument) and makes it into a menu widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the menu such as its colors and font. The menu command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A menu is a widget that displays a collection of one-line entries arranged in one or more columns. There exist several different types of entries, each with different properties. Entries of different types may be combined in a single menu. Menu entries are not the same as entry widgets. In fact, menu entries are not even distinct widgets; the entire menu is one widget.

Menu entries are displayed with up to three separate fields. The main field is a label in the form of a text string, a bitmap, or an image, controlled by the -label, -bitmap, and -image options for the entry. If the -accelerator option is specified for an entry then a second textual field is displayed to the right of the label. The accelerator typically describes a keystroke sequence that may be typed in the application to cause the same result as invoking the menu entry. The third field is an indicator. The indicator is present only for checkbutton or radiobutton entries. It indicates whether the entry is selected or not, and is displayed to the left of the entry's string.

In normal use, an entry becomes active (displays itself differently) whenever the mouse pointer is over the entry. If a mouse button is released over the entry then the entry is invoked. The effect of invocation is different for each type of entry; these effects are described below in the sections on individual entries.

Entries may be disabled, which causes their labels and accelerators to be displayed with dimmer colors. The default menu bindings will not allow a disabled entry to be activated or invoked. Disabled entries may be re-enabled, at which point it becomes possible to activate and invoke them again.

Whenever a menu's active entry is changed, a <<MenuSelect>> virtual event is send to the menu. The active item can then be queried from the menu, and an action can be taken, such as setting context-sensitive help text for the entry.

COMMAND ENTRIES

The most common kind of menu entry is a command entry, which behaves much like a button widget. When a command entry is invoked, a Tcl command is executed. The Tcl command is specified with the -command option.

SEPARATOR ENTRIES

A separator is an entry that is displayed as a horizontal dividing line. A separator may not be activated or invoked, and it has no behavior other than its display appearance.

CHECKBUTTON ENTRIES

A checkbutton menu entry behaves much like a checkbutton widget. When it is invoked it toggles back and forth between the selected and deselected states. When the entry is selected, a particular value is stored in a particular global variable (as determined by the -onvalue and -variable options for the entry); when the entry is deselected another value (determined by the -offvalue option) is stored in the global variable. An indicator box is displayed to the left of the label in a checkbutton entry. If the entry is selected then the indicator's center is displayed in the color given by the -selectcolor option for the entry; otherwise the indicator's center is displayed in the background color for the menu. If a -command option is specified for a checkbutton entry, then its value is evaluated as a Tcl command each time the entry is invoked; this happens after toggling the entry's selected state.

RADIOBUTTON ENTRIES

A radiobutton menu entry behaves much like a radiobutton widget. Radiobutton entries are organized in groups of which only one entry may be selected at a time. Whenever a particular entry becomes selected it stores a particular value into a particular global variable (as determined by the -value and -variable options for the entry). This action causes any previously-selected entry in the same group to deselect itself. Once an entry has become selected, any change to the entry's associated variable will cause the entry to deselect itself. Grouping of radiobutton entries is determined by their associated variables: if two entries have the same associated variable then they are in the same group. An indicator diamond is displayed to the left of the label in each radiobutton entry. If the entry is selected then the indicator's center is displayed in the color given by the -selectcolor option for the entry; otherwise the indicator's center is displayed in the background color for the menu. If a -command option is specified for a radiobutton entry, then its value is evaluated as a Tcl command each time the entry is invoked; this happens after selecting the entry.

CASCADE ENTRIES

A cascade entry is one with an associated menu (determined by the -menu option). Cascade entries allow the construction of cascading menus. The postcascade widget command can be used to post and unpost the associated menu just next to of the cascade entry. The associated menu must be a child of the menu containing the cascade entry (this is needed in order for menu traversal to work correctly).

A cascade entry posts its associated menu by invoking a Tcl command of the form

menu post x y
where menu is the path name of the associated menu, and x and y are the root-window coordinates of the upper-right corner of the cascade entry. On Unix, the lower-level menu is unposted by executing a Tcl command with the form
menu unpost
where menu is the name of the associated menu. On other platforms, the platform's native code takes care of unposting the menu.

If a -command option is specified for a cascade entry then it is evaluated as a Tcl command whenever the entry is invoked. This is not supported on Windows.

TEAR-OFF ENTRIES

A tear-off entry appears at the top of the menu if enabled with the tearOff option. It is not like other menu entries in that it cannot be created with the add widget command and cannot be deleted with the delete widget command. When a tear-off entry is created it appears as a dashed line at the top of the menu. Under the default bindings, invoking the tear-off entry causes a torn-off copy to be made of the menu and all of its submenus.

MENUBARS

Any menu can be set as a menubar for a toplevel window (see toplevel command for syntax). On the Macintosh, whenever the toplevel is in front, this menu's cascade items will appear in the menubar across the top of the main monitor. On Windows and Unix, this menu's items will be displayed in a menubar accross the top of the window. These menus will behave according to the interface guidelines of their platforms. For every menu set as a menubar, a clone menu is made. See the CLONES section for more information.

As noted, menubars may behave differently on different platforms. One example of this concerns the handling of checkbuttons and radiobuttons within the menu. While it is permitted to put these menu elements on menubars, they may not be drawn with indicators on some platforms, due to system restrictions.

SPECIAL MENUS IN MENUBARS

Certain menus in a menubar will be treated specially. On the Macintosh, access to the special Apple and Help menus is provided. On Windows, access to the Windows System menu in each window is provided. On X Windows, a special right-justified help menu is provided. In all cases, these menus must be created with the command name of the menubar menu concatenated with the special name. So for a menubar named .menubar, on the Macintosh, the special menus would be .menubar.apple and .menubar.help; on Windows, the special menu would be .menubar.system; on X Windows, the help menu would be .menubar.help.

When Tk sees an Apple menu on the Macintosh, that menu's contents make up the first items of the Apple menu on the screen whenever the window containing the menubar is in front. The menu is the first one that the user sees and has a title which is an Apple logo. After all of the Tk-defined items, the menu will have a separator, followed by all of the items in the user's Apple Menu Items folder. Since the System uses a different menu definition procedure for the Apple menu than Tk uses for its menus, and the system APIs do not fully support everything Tk tries to do, the menu item will only have its text displayed. No font attributes, images, bitmaps, or colors will be displayed. In addition, a menu with a tearoff item will have the tearoff item displayed as "(TearOff)".

When Tk see a Help menu on the Macintosh, the menu's contents are appended to the standard help menu on the right of the user's menubar whenever the user's menubar is in front. The first items in the menu are provided by Apple. Similar to the Apple Menu, cusomization in this menu is limited to what the system provides.

When Tk sees a System menu on Windows, its items are appended to the system menu that the menubar is attached to. This menu has an icon representing a spacebar, and can be invoked with the mouse or by typing Alt+Spacebar. Due to limitations in the Windows API, any font changes, colors, images, bitmaps, or tearoff images will not appear in the system menu.

When Tk see a Help menu on X Windows, the menu is moved to be last in the menubar and is right justified.

CLONES

When a menu is set as a menubar for a toplevel window, or when a menu is torn off, a clone of the menu is made. This clone is a menu widget in its own right, but it is a child of the original. Changes in the configuration of the original are reflected in the clone. Additionally, any cascades that are pointed to are also cloned so that menu traversal will work right. Clones are destroyed when either the tearoff or menubar goes away, or when the original menu is destroyed.

WIDGET COMMAND

The menu command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command.

Many of the widget commands for a menu take as one argument an indicator of which entry of the menu to operate on. These indicators are called indexes and may be specified in any of the following forms:

number
Specifies the entry numerically, where 0 corresponds to the top-most entry of the menu, 1 to the entry below it, and so on.

active
Indicates the entry that is currently active. If no entry is active then this form is equivalent to none. This form may not be abbreviated.

end
Indicates the bottommost entry in the menu. If there are no entries in the menu then this form is equivalent to none. This form may not be abbreviated.

last
Same as end.

none
Indicates ``no entry at all''; this is used most commonly with the activate option to deactivate all the entries in the menu. In most cases the specification of none causes nothing to happen in the widget command. This form may not be abbreviated.

@number
In this form, number is treated as a y-coordinate in the menu's window; the entry closest to that y-coordinate is used. For example, ``@0'' indicates the top-most entry in the window.

pattern
If the index doesn't satisfy one of the above forms then this form is used. Pattern is pattern-matched against the label of each entry in the menu, in order from the top down, until a matching entry is found. The rules of Tcl_StringMatch are used.

The following widget commands are possible for menu widgets:

pathName activate index
Change the state of the entry indicated by index to active and redisplay it using its active colors. Any previously-active entry is deactivated. If index is specified as none, or if the specified entry is disabled, then the menu ends up with no active entry. Returns an empty string.

pathName add type ?option value option value ...?
Add a new entry to the bottom of the menu. The new entry's type is given by type and must be one of cascade, checkbutton, command, radiobutton, or separator, or a unique abbreviation of one of the above. If additional arguments are present, they specify any of the following options:

-activebackground value
Specifies a background color to use for displaying this entry when it is active. If this option is specified as an empty string (the default), then the activeBackground option for the overall menu is used. If the tk_strictMotif variable has been set to request strict Motif compliance, then this option is ignored and the -background option is used in its place. This option is not available for separator or tear-off entries.

-activeforeground value
Specifies a foreground color to use for displaying this entry when it is active. If this option is specified as an empty string (the default), then the activeForeground option for the overall menu is used. This option is not available for separator or tear-off entries.

-accelerator value
Specifies a string to display at the right side of the menu entry. Normally describes an accelerator keystroke sequence that may be typed to invoke the same function as the menu entry. This option is not available for separator or tear-off entries.

-background value
Specifies a background color to use for displaying this entry when it is in the normal state (neither active nor disabled). If this option is specified as an empty string (the default), then the background option for the overall menu is used. This option is not available for separator or tear-off entries.

-bitmap value
Specifies a bitmap to display in the menu instead of a textual label, in any of the forms accepted by Tk_GetBitmap. This option overrides the -label option but may be reset to an empty string to enable a textual label to be displayed. If a -image option has been specified, it overrides -bitmap. This option is not available for separator or tear-off entries.

-columnbreak value
When this option is zero, the appears below the previous entry. When this option is one, the menu appears at the top of a new column in the menu.

-command value
Specifies a Tcl command to execute when the menu entry is invoked. Not available for separator or tear-off entries.

-font value
Specifies the font to use when drawing the label or accelerator string in this entry. If this option is specified as an empty string (the default) then the font option for the overall menu is used. This option is not available for separator or tear-off entries.

-foreground value
Specifies a foreground color to use for displaying this entry when it is in the normal state (neither active nor disabled). If this option is specified as an empty string (the default), then the foreground option for the overall menu is used. This option is not available for separator or tear-off entries.

-hidemargin value
Specifies whether the standard margins should be drawn for this menu entry. This is useful when creating palette with images in them, i.e., color palettes, pattern palettes, etc. 1 indicates that the margin for the entry is hidden; 0 means that the margin is used.

-image value
Specifies an image to display in the menu instead of a text string or bitmap The image must have been created by some previous invocation of image create. This option overrides the -label and -bitmap options but may be reset to an empty string to enable a textual or bitmap label to be displayed. This option is not available for separator or tear-off entries.

-indicatoron value
Available only for checkbutton and radiobutton entries. Value is a boolean that determines whether or not the indicator should be displayed.

-label value
Specifies a string to display as an identifying label in the menu entry. Not available for separator or tear-off entries.

-menu value
Available only for cascade entries. Specifies the path name of the submenu associated with this entry. The submenu must be a child of the menu.

-offvalue value
Available only for checkbutton entries. Specifies the value to store in the entry's associated variable when the entry is deselected.

-onvalue value
Available only for checkbutton entries. Specifies the value to store in the entry's associated variable when the entry is selected.

-selectcolor value
Available only for checkbutton and radiobutton entries. Specifies the color to display in the indicator when the entry is selected. If the value is an empty string (the default) then the selectColor option for the menu determines the indicator color.

-selectimage value
Available only for checkbutton and radiobutton entries. Specifies an image to display in the entry (in place of the -image option) when it is selected. Value is the name of an image, which must have been created by some previous invocation of image create. This option is ignored unless the -image option has been specified.

-state value
Specifies one of three states for the entry: normal, active, or disabled. In normal state the entry is displayed using the foreground option for the menu and the background option from the entry or the menu. The active state is typically used when the pointer is over the entry. In active state the entry is displayed using the activeForeground option for the menu along with the activebackground option from the entry. Disabled state means that the entry should be insensitive: the default bindings will refuse to activate or invoke the entry. In this state the entry is displayed according to the disabledForeground option for the menu and the background option from the entry. This option is not available for separator entries.

-underline value
Specifies the integer index of a character to underline in the entry. This option is also queried by the default bindings and used to implement keyboard traversal. 0 corresponds to the first character of the text displayed in the entry, 1 to the next character, and so on. If a bitmap or image is displayed in the entry then this option is ignored. This option is not available for separator or tear-off entries.

-value value
Available only for radiobutton entries. Specifies the value to store in the entry's associated variable when the entry is selected. If an empty string is specified, then the -label option for the entry as the value to store in the variable.

-variable value
Available only for checkbutton and radiobutton entries. Specifies the name of a global value to set when the entry is selected. For checkbutton entries the variable is also set when the entry is deselected. For radiobutton entries, changing the variable causes the currently-selected entry to deselect itself.

The add widget command returns an empty string.

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the menu command.

pathName clone newPathname ?cloneType?
Makes a clone of the current menu named newPathName. This clone is a menu in its own right, but any changes to the clone are propogated to the original menu and vice versa. cloneType can be normal, menubar, or tearoff. Should not normally be called outside of the Tk library. See the CLONES section for more information.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the menu command.

pathName delete index1 ?index2?
Delete all of the menu entries between index1 and index2 inclusive. If index2 is omitted then it defaults to index1. Attempts to delete a tear-off menu entry are ignored (instead, you should change the tearOff option to remove the tear-off entry).

pathName entrycget index option
Returns the current value of a configuration option for the entry given by index. Option may have any of the values accepted by the add widget command.

pathName entryconfigure index ?options?
This command is similar to the configure command, except that it applies to the options for an individual entry, whereas configure applies to the options for the menu as a whole. Options may have any of the values accepted by the add widget command. If options are specified, options are modified as indicated in the command and the command returns an empty string. If no options are specified, returns a list describing the current options for entry index (see Tk_ConfigureInfo for information on the format of this list).

pathName index index
Returns the numerical index corresponding to index, or none if index was specified as none.

pathName insert index type ?option value option value ...?
Same as the add widget command except that it inserts the new entry just before the entry given by index, instead of appending to the end of the menu. The type, option, and value arguments have the same interpretation as for the add widget command. It is not possible to insert new menu entries before the tear-off entry, if the menu has one.

pathName invoke index
Invoke the action of the menu entry. See the sections on the individual entries above for details on what happens. If the menu entry is disabled then nothing happens. If the entry has a command associated with it then the result of that command is returned as the result of the invoke widget command. Otherwise the result is an empty string. Note: invoking a menu entry does not automatically unpost the menu; the default bindings normally take care of this before invoking the invoke widget command.

pathName post x y
Arrange for the menu to be displayed on the screen at the root-window coordinates given by x and y. These coordinates are adjusted if necessary to guarantee that the entire menu is visible on the screen. This command normally returns an empty string. If the postCommand option has been specified, then its value is executed as a Tcl script before posting the menu and the result of that script is returned as the result of the post widget command. If an error returns while executing the command, then the error is returned without posting the menu.

pathName postcascade index
Posts the submenu associated with the cascade entry given by index, and unposts any previously posted submenu. If index doesn't correspond to a cascade entry, or if pathName isn't posted, the command has no effect except to unpost any currently posted submenu.

pathName type index
Returns the type of the menu entry given by index. This is the type argument passed to the add widget command when the entry was created, such as command or separator, or tearoff for a tear-off entry.

.VS
pathName unpost Unmap the window so that it is no longer displayed. If a lower-level cascaded menu is posted, unpost that menu. Returns an empty string. This subcommand does not work on Windows and the Macintosh, as those platforms have their own way of unposting menus.

pathName yposition index
Returns a decimal string giving the y-coordinate within the menu window of the topmost pixel in the entry specified by index.

MENU CONFIGURATIONS

The default bindings support four different ways of using menus:

Pulldown Menus in Menubar
This is the most command case. You create a menu widget that will become the menu bar. You then add cascade entries to this menu, specifying the pull down menus you wish to use in your menu bar. You then create all of the pulldowns. Once you have done this, specify the menu using the -menu option of the toplevel's widget command. See the toplevel manual entry for details.

Pulldown Menus in Menu Buttons
This is the compatable way to do menu bars. You create one menubutton widget for each top-level menu, and typically you arrange a series of menubuttons in a row in a menubar window. You also create the top-level menus and any cascaded submenus, and tie them together with -menu options in menubuttons and cascade menu entries. The top-level menu must be a child of the menubutton, and each submenu must be a child of the menu that refers to it. Once you have done this, the default bindings will allow users to traverse and invoke the tree of menus via its menubutton; see the menubutton manual entry for details.

Popup Menus
Popup menus typically post in response to a mouse button press or keystroke. You create the popup menus and any cascaded submenus, then you call the tk_popup procedure at the appropriate time to post the top-level menu.

Option Menus
An option menu consists of a menubutton with an associated menu that allows you to select one of several values. The current value is displayed in the menubutton and is also stored in a global variable. Use the tk_optionMenu procedure to create option menubuttons and their menus.

Torn-off Menus
You create a torn-off menu by invoking the tear-off entry at the top of an existing menu. The default bindings will create a new menu that is a copy of the original menu and leave it permanently posted as a top-level window. The torn-off menu behaves just the same as the original menu.

DEFAULT BINDINGS

Tk automatically creates class bindings for menus that give them the following default behavior:

[1]
When the mouse enters a menu, the entry underneath the mouse cursor activates; as the mouse moves around the menu, the active entry changes to track the mouse.

[2]
When the mouse leaves a menu all of the entries in the menu deactivate, except in the special case where the mouse moves from a menu to a cascaded submenu.

[3]
When a button is released over a menu, the active entry (if any) is invoked. The menu also unposts unless it is a torn-off menu.

[4]
The Space and Return keys invoke the active entry and unpost the menu.

[5]
If any of the entries in a menu have letters underlined with with -underline option, then pressing one of the underlined letters (or its upper-case or lower-case equivalent) invokes that entry and unposts the menu.

[6]
The Escape key aborts a menu selection in progress without invoking any entry. It also unposts the menu unless it is a torn-off menu.

[7]
The Up and Down keys activate the next higher or lower entry in the menu. When one end of the menu is reached, the active entry wraps around to the other end.

[8]
The Left key moves to the next menu to the left. If the current menu is a cascaded submenu, then the submenu is unposted and the current menu entry becomes the cascade entry in the parent. If the current menu is a top-level menu posted from a menubutton, then the current menubutton is unposted and the next menubutton to the left is posted. Otherwise the key has no effect. The left-right order of menubuttons is determined by their stacking order: Tk assumes that the lowest menubutton (which by default is the first one created) is on the left.

[9]
The Right key moves to the next menu to the right. If the current entry is a cascade entry, then the submenu is posted and the current menu entry becomes the first entry in the submenu. Otherwise, if the current menu was posted from a menubutton, then the current menubutton is unposted and the next menubutton to the right is posted.

Disabled menu entries are non-responsive: they don't activate and they ignore mouse button presses and releases.

The behavior of menus can be changed by defining new bindings for individual widgets or by redefining the class bindings.

BUGS

At present it isn't possible to use the option database to specify values for the options to individual entries.

KEYWORDS

menu, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tk Built-In Commands - menubutton manual page

NAME
menubutton - Create and manipulate menubutton widgets
SYNOPSIS
menubutton pathName ?options?
STANDARD OPTIONS
-activebackground, activeBackground, Foreground
-activeforeground, activeForeground, Background
-anchor, anchor, Anchor
-background or -bg, background, Background
-bitmap, bitmap, Bitmap
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-image, image, Image
-justify, justify, Justify
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-underline, underline, Underline
-wraplength, wrapLength, WrapLength
WIDGET-SPECIFIC OPTIONS
-direction, direction, Height
-height, height, Height
-indicatoron, indicatorOn, IndicatorOn
-menu, menu, MenuName
-state, state, State
-width, width, Width
INTRODUCTION
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
DEFAULT BINDINGS
KEYWORDS

NAME

menubutton - Create and manipulate menubutton widgets

SYNOPSIS

menubutton pathName ?options?

STANDARD OPTIONS

-activebackground, activeBackground, Foreground
-activeforeground, activeForeground, Background
-anchor, anchor, Anchor
-background or -bg, background, Background
-bitmap, bitmap, Bitmap
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-image, image, Image
-justify, justify, Justify
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-underline, underline, Underline
-wraplength, wrapLength, WrapLength

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -direction
Database Name: direction
Database Class: Height
Specifies where the menu is going to be popup up. above tries to pop the menu above the menubutton. below tries to pop the menu below the menubutton. left tries to pop the menu to the left of the menubutton. right tries to pop the menu to the right of the menu button. flush pops the menu directly over the menubutton.

Command-Line Name: -height
Database Name: height
Database Class: Height
Specifies a desired height for the menubutton. If an image or bitmap is being displayed in the menubutton then the value is in screen units (i.e. any of the forms acceptable to Tk_GetPixels); for text it is in lines of text. If this option isn't specified, the menubutton's desired height is computed from the size of the image or bitmap or text being displayed in it.

Command-Line Name: -indicatoron
Database Name: indicatorOn
Database Class: IndicatorOn
The value must be a proper boolean value. If it is true then a small indicator rectangle will be displayed on the right side of the menubutton and the default menu bindings will treat this as an option menubutton. If false then no indicator will be displayed.

Command-Line Name: -menu
Database Name: menu
Database Class: MenuName
Specifies the path name of the menu associated with this menubutton. The menu must be a child of the menubutton.

Command-Line Name: -state
Database Name: state
Database Class: State
Specifies one of three states for the menubutton: normal, active, or disabled. In normal state the menubutton is displayed using the foreground and background options. The active state is typically used when the pointer is over the menubutton. In active state the menubutton is displayed using the activeForeground and activeBackground options. Disabled state means that the menubutton should be insensitive: the default bindings will refuse to activate the widget and will ignore mouse button presses. In this state the disabledForeground and background options determine how the button is displayed.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies a desired width for the menubutton. If an image or bitmap is being displayed in the menubutton then the value is in screen units (i.e. any of the forms acceptable to Tk_GetPixels); for text it is in characters. If this option isn't specified, the menubutton's desired width is computed from the size of the image or bitmap or text being displayed in it.

INTRODUCTION

The menubutton command creates a new window (given by the pathName argument) and makes it into a menubutton widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the menubutton such as its colors, font, text, and initial relief. The menubutton command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A menubutton is a widget that displays a textual string, bitmap, or image and is associated with a menu widget. If text is displayed, it must all be in a single font, but it can occupy multiple lines on the screen (if it contains newlines or if wrapping occurs because of the wrapLength option) and one of the characters may optionally be underlined using the underline option. In normal usage, pressing mouse button 1 over the menubutton causes the associated menu to be posted just underneath the menubutton. If the mouse is moved over the menu before releasing the mouse button, the button release causes the underlying menu entry to be invoked. When the button is released, the menu is unposted.

Menubuttons are typically organized into groups called menu bars that allow scanning: if the mouse button is pressed over one menubutton (causing it to post its menu) and the mouse is moved over another menubutton in the same menu bar without releasing the mouse button, then the menu of the first menubutton is unposted and the menu of the new menubutton is posted instead.

There are several interactions between menubuttons and menus; see the menu manual entry for information on various menu configurations, such as pulldown menus and option menus.

WIDGET COMMAND

The menubutton command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for menubutton widgets:

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the menubutton command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the menubutton command.

DEFAULT BINDINGS

Tk automatically creates class bindings for menubuttons that give them the following default behavior:

[1]
A menubutton activates whenever the mouse passes over it and deactivates whenever the mouse leaves it.

[2]
Pressing mouse button 1 over a menubutton posts the menubutton: its relief changes to raised and its associated menu is posted under the menubutton. If the mouse is dragged down into the menu with the button still down, and if the mouse button is then released over an entry in the menu, the menubutton is unposted and the menu entry is invoked.

[3]
If button 1 is pressed over a menubutton and then released over that menubutton, the menubutton stays posted: you can still move the mouse over the menu and click button 1 on an entry to invoke it. Once a menu entry has been invoked, the menubutton unposts itself.

[4]
If button 1 is pressed over a menubutton and then dragged over some other menubutton, the original menubutton unposts itself and the new menubutton posts.

[5]
If button 1 is pressed over a menubutton and released outside any menubutton or menu, the menubutton unposts without invoking any menu entry.

[6]
When a menubutton is posted, its associated menu claims the input focus to allow keyboard traversal of the menu and its submenus. See the menu manual entry for details on these bindings.

[7]
If the underline option has been specified for a menubutton then keyboard traversal may be used to post the menubutton: Alt+x, where x is the underlined character (or its lower-case or upper-case equivalent), may be typed in any window under the menubutton's toplevel to post the menubutton.

[8]
The F10 key may be typed in any window to post the first menubutton under its toplevel window that isn't disabled.

[9]
If a menubutton has the input focus, the space and return keys post the menubutton.

If the menubutton's state is disabled then none of the above actions occur: the menubutton is completely non-responsive.

The behavior of menubuttons can be changed by defining new bindings for individual widgets or by redefining the class bindings.

KEYWORDS

menubutton, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tk Built-In Commands - message manual page

NAME
message - Create and manipulate message widgets
SYNOPSIS
message pathName ?options?
STANDARD OPTIONS
-anchor, anchor, Anchor
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-width
WIDGET-SPECIFIC OPTIONS
-aspect, aspect, Aspect
-justify, justify, Justify
-width, width, Width
DESCRIPTION
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
DEFAULT BINDINGS
BUGS
KEYWORDS

NAME

message - Create and manipulate message widgets

SYNOPSIS

message pathName ?options?

STANDARD OPTIONS

-anchor, anchor, Anchor
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-width

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -aspect
Database Name: aspect
Database Class: Aspect
Specifies a non-negative integer value indicating desired aspect ratio for the text. The aspect ratio is specified as 100*width/height. 100 means the text should be as wide as it is tall, 200 means the text should be twice as wide as it is tall, 50 means the text should be twice as tall as it is wide, and so on. Used to choose line length for text if width option isn't specified. Defaults to 150.

Command-Line Name: -justify
Database Name: justify
Database Class: Justify
Specifies how to justify lines of text. Must be one of left, center, or right. Defaults to left. This option works together with the anchor, aspect, padX, padY, and width options to provide a variety of arrangements of the text within the window. The aspect and width options determine the amount of screen space needed to display the text. The anchor, padX, and padY options determine where this rectangular area is displayed within the widget's window, and the justify option determines how each line is displayed within that rectangular region. For example, suppose anchor is e and justify is left, and that the message window is much larger than needed for the text. The the text will displayed so that the left edges of all the lines line up and the right edge of the longest line is padX from the right side of the window; the entire text block will be centered in the vertical span of the window.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies the length of lines in the window. The value may have any of the forms acceptable to Tk_GetPixels. If this option has a value greater than zero then the aspect option is ignored and the width option determines the line length. If this option has a value less than or equal to zero, then the aspect option determines the line length.

DESCRIPTION

The message command creates a new window (given by the pathName argument) and makes it into a message widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the message such as its colors, font, text, and initial relief. The message command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A message is a widget that displays a textual string. A message widget has three special features. First, it breaks up its string into lines in order to produce a given aspect ratio for the window. The line breaks are chosen at word boundaries wherever possible (if not even a single word would fit on a line, then the word will be split across lines). Newline characters in the string will force line breaks; they can be used, for example, to leave blank lines in the display.

The second feature of a message widget is justification. The text may be displayed left-justified (each line starts at the left side of the window), centered on a line-by-line basis, or right-justified (each line ends at the right side of the window).

The third feature of a message widget is that it handles control characters and non-printing characters specially. Tab characters are replaced with enough blank space to line up on the next 8-character boundary. Newlines cause line breaks. Other control characters (ASCII code less than 0x20) and characters not defined in the font are displayed as a four-character sequence \x hh where hh is the two-digit hexadecimal number corresponding to the character. In the unusual case where the font doesn't contain all of the characters in ``0123456789abcdef\x'' then control characters and undefined characters are not displayed at all.

WIDGET COMMAND

The message command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for message widgets:

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the message command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the message command.

DEFAULT BINDINGS

When a new message is created, it has no default event bindings: messages are intended for output purposes only.

BUGS

Tabs don't work very well with text that is centered or right-justified. The most common result is that the line is justified wrong.

KEYWORDS

message, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tk_messageBox manual page

NAME
tk_messageBox - pops up a message window and waits for user response.
SYNOPSIS
tk_messageBox ?option value ...?
DESCRIPTION
-default name
-icon iconImage
-message string
-parent window
-title titleString
-type predefinedType
abortretryignore
ok
okcancel
retrycancel
yesno
yesnocancel
EXAMPLE
KEYWORDS

NAME

tk_messageBox - pops up a message window and waits for user response.

SYNOPSIS

tk_messageBox ?option value ...?

DESCRIPTION

This procedure creates and displays a message window with an application-specified message, an icon and a set of buttons. Each of the buttons in the message window is identified by a unique symbolic name (see the -type options). After the message window is popped up, tk_messageBox waits for the user to select one of the buttons. Then it returns the symbolic name of the selected button. The following option-value pairs are supported:

-default name
Name gives the symbolic name of the default button for this message window ('ok', 'cancel', and so on). See -type for a list of the symbolic names. If this option is not specified, the first button in the dialog will be made the default.

-icon iconImage
Specifies an icon to display. IconImage must be one of the following: error, info, question or warning. If this option is not specified, then the info icon will be displayed.

-message string
Specifies the message to display in this message box.

-parent window
Makes window the logical parent of the message box. The message box is displayed on top of its parent window.

-title titleString
Specifies a string to display as the title of the message box. The default value is an empty string.

-type predefinedType
Arranges for a predefined set of buttons to be displayed. The following values are possible for predefinedType:

abortretryignore
Displays three buttons whose symbolic names are abort, retry and ignore.

ok
Displays one button whose symbolic name is ok.

okcancel
Displays two buttons whose symbolic names are ok and cancel.

retrycancel
Displays two buttons whose symbolic names are retry and cancel.

yesno
Displays two buttons whose symbolic names are yes and no.

yesnocancel
Displays three buttons whose symbolic names are yes, no and cancel.

EXAMPLE

set answer [tk_messageBox -message "Really quit?" -type yesno -icon question]
switch -- $answer {
    yes exit
    no {tk_messageBox -message "I know you like this application!" -type ok}
}

KEYWORDS

message box
Copyright © 1996 Sun Microsystems, Inc.


Built-In Commands - option manual page

NAME
option - Add/retrieve window options to/from the option database
SYNOPSIS
option add pattern value ?priority?
option clear
option get window name class
option readfile fileName ?priority?
DESCRIPTION
widgetDefault
startupFile
userDefault
interactive
KEYWORDS

NAME

option - Add/retrieve window options to/from the option database

SYNOPSIS

option add pattern value ?priority?
option clear
option get window name class
option readfile fileName ?priority?

DESCRIPTION

The option command allows you to add entries to the Tk option database or to retrieve options from the database. The add form of the command adds a new option to the database. Pattern contains the option being specified, and consists of names and/or classes separated by asterisks or dots, in the usual X format. Value contains a text string to associate with pattern; this is the value that will be returned in calls to Tk_GetOption or by invocations of the option get command. If priority is specified, it indicates the priority level for this option (see below for legal values); it defaults to interactive. This command always returns an empty string.

The option clear command clears the option database. Default options (from the RESOURCE_MANAGER property or the .Xdefaults file) will be reloaded automatically the next time an option is added to the database or removed from it. This command always returns an empty string.

The option get command returns the value of the option specified for window under name and class. If several entries in the option database match window, name, and class, then the command returns whichever was created with highest priority level. If there are several matching entries at the same priority level, then it returns whichever entry was most recently entered into the option database. If there are no matching entries, then the empty string is returned.

The readfile form of the command reads fileName, which should have the standard format for an X resource database such as .Xdefaults, and adds all the options specified in that file to the option database. If priority is specified, it indicates the priority level at which to enter the options; priority defaults to interactive.

The priority arguments to the option command are normally specified symbolically using one of the following values:

widgetDefault
Level 20. Used for default values hard-coded into widgets.

startupFile
Level 40. Used for options specified in application-specific startup files.

userDefault
Level 60. Used for options specified in user-specific defaults files, such as .Xdefaults, resource databases loaded into the X server, or user-specific startup files.

interactive
Level 80. Used for options specified interactively after the application starts running. If priority isn't specified, it defaults to this level.

Any of the above keywords may be abbreviated. In addition, priorities may be specified numerically using integers between 0 and 100, inclusive. The numeric form is probably a bad idea except for new priority levels other than the ones given above.

KEYWORDS

database, option, priority, retrieve
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tk_optionMenu manual page

NAME

tk_optionMenu - Create an option menubutton and its menu

SYNOPSIS

tk_optionMenu w varName value ?value value ...?

DESCRIPTION

This procedure creates an option menubutton whose name is w, plus an associated menu. Together they allow the user to select one of the values given by the value arguments. The current value will be stored in the global variable whose name is given by varName and it will also be displayed as the label in the option menubutton. The user can click on the menubutton to display a menu containing all of the values and thereby select a new value. Once a new value is selected, it will be stored in the variable and appear in the option menubutton. The current value can also be changed by setting the variable.

The return value from tk_optionMenu is the name of the menu associated with w, so that the caller can change its configuration options or manipulate it in other ways.

KEYWORDS

option menu
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - options manual page

NAME
options - Standard options supported by widgets
DESCRIPTION
-activebackground, activeBackground, Foreground
-activeborderwidth, activeBorderWidth, BorderWidth
-activeforeground, activeForeground, Background
-anchor, anchor, Anchor
-background or -bg, background, Background
-bitmap, bitmap, Bitmap
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-exportselection, exportSelection, ExportSelection
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-image, image, Image
-insertbackground, insertBackground, Foreground
-insertborderwidth, insertBorderWidth, BorderWidth
-insertofftime, insertOffTime, OffTime
-insertontime, insertOnTime, OnTime
-insertwidth, insertWidth, InsertWidth
-jump, jump, Jump
-justify, justify, Justify
-orient, orient, Orient
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-repeatdelay, repeatDelay, RepeatDelay
-repeatinterval, repeatInterval, RepeatInterval
-selectbackground, selectBackground, Foreground
-selectborderwidth, selectBorderWidth, BorderWidth
-selectforeground, selectForeground, Background
-setgrid, setGrid, SetGrid
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-troughcolor, troughColor, Background
-underline, underline, Underline
-wraplength, wrapLength, WrapLength
-xscrollcommand, xScrollCommand, ScrollCommand
-yscrollcommand, yScrollCommand, ScrollCommand
SEE ALSO
KEYWORDS

NAME

options - Standard options supported by widgets

DESCRIPTION

This manual entry describes the common configuration options supported by widgets in the Tk toolkit. Every widget does not necessarily support every option (see the manual entries for individual widgets for a list of the standard options supported by that widget), but if a widget does support an option with one of the names listed below, then the option has exactly the effect described below.

In the descriptions below, ``Command-Line Name'' refers to the switch used in class commands and configure widget commands to set this value. For example, if an option's command-line switch is -foreground and there exists a widget .a.b.c, then the command

.a.b.c  configure  -foreground black
may be used to specify the value black for the option in the the widget .a.b.c. Command-line switches may be abbreviated, as long as the abbreviation is unambiguous. ``Database Name'' refers to the option's name in the option database (e.g. in .Xdefaults files). ``Database Class'' refers to the option's class value in the option database.
Command-Line Name: -activebackground
Database Name: activeBackground
Database Class: Foreground
Specifies background color to use when drawing active elements. An element (a widget or portion of a widget) is active if the mouse cursor is positioned over the element and pressing a mouse button will cause some action to occur. If strict Motif compliance has been requested by setting the tk_strictMotif variable, this option will normally be ignored; the normal background color will be used instead. For some elements on Windows and Macintosh systems, the active color will only be used while mouse button 1 is pressed over the element.

Command-Line Name: -activeborderwidth
Database Name: activeBorderWidth
Database Class: BorderWidth
Specifies a non-negative value indicating the width of the 3-D border drawn around active elements. See above for definition of active elements. The value may have any of the forms acceptable to Tk_GetPixels. This option is typically only available in widgets displaying more than one element at a time (e.g. menus but not buttons).

Command-Line Name: -activeforeground
Database Name: activeForeground
Database Class: Background
Specifies foreground color to use when drawing active elements. See above for definition of active elements.

Command-Line Name: -anchor
Database Name: anchor
Database Class: Anchor
Specifies how the information in a widget (e.g. text or a bitmap) is to be displayed in the widget. Must be one of the values n, ne, e, se, s, sw, w, nw, or center. For example, nw means display the information such that its top-left corner is at the top-left corner of the widget.

Command-Line Name: -background or -bg
Database Name: background
Database Class: Background
Specifies the normal background color to use when displaying the widget.

Command-Line Name: -bitmap
Database Name: bitmap
Database Class: Bitmap
Specifies a bitmap to display in the widget, in any of the forms acceptable to Tk_GetBitmap. The exact way in which the bitmap is displayed may be affected by other options such as anchor or justify. Typically, if this option is specified then it overrides other options that specify a textual value to display in the widget; the bitmap option may be reset to an empty string to re-enable a text display. In widgets that support both bitmap and image options, image will usually override bitmap.

Command-Line Name: -borderwidth or -bd
Database Name: borderWidth
Database Class: BorderWidth
Specifies a non-negative value indicating the width of the 3-D border to draw around the outside of the widget (if such a border is being drawn; the relief option typically determines this). The value may also be used when drawing 3-D effects in the interior of the widget. The value may have any of the forms acceptable to Tk_GetPixels.

Command-Line Name: -cursor
Database Name: cursor
Database Class: Cursor
Specifies the mouse cursor to be used for the widget. The value may have any of the forms acceptable to Tk_GetCursor.

Command-Line Name: -disabledforeground
Database Name: disabledForeground
Database Class: DisabledForeground
Specifies foreground color to use when drawing a disabled element. If the option is specified as an empty string (which is typically the case on monochrome displays), disabled elements are drawn with the normal foreground color but they are dimmed by drawing them with a stippled fill pattern.

Command-Line Name: -exportselection
Database Name: exportSelection
Database Class: ExportSelection
Specifies whether or not a selection in the widget should also be the X selection. The value may have any of the forms accepted by Tcl_GetBoolean, such as true, false, 0, 1, yes, or no. If the selection is exported, then selecting in the widget deselects the current X selection, selecting outside the widget deselects any widget selection, and the widget will respond to selection retrieval requests when it has a selection. The default is usually for widgets to export selections.

Command-Line Name: -font
Database Name: font
Database Class: Font
Specifies the font to use when drawing text inside the widget. The value may have any of the forms accepted by Tk_GetFont.

Command-Line Name: -foreground or -fg
Database Name: foreground
Database Class: Foreground
Specifies the normal foreground color to use when displaying the widget.

Command-Line Name: -highlightbackground
Database Name: highlightBackground
Database Class: HighlightBackground
Specifies the color to display in the traversal highlight region when the widget does not have the input focus.

Command-Line Name: -highlightcolor
Database Name: highlightColor
Database Class: HighlightColor
Specifies the color to use for the traversal highlight rectangle that is drawn around the widget when it has the input focus.

Command-Line Name: -highlightthickness
Database Name: highlightThickness
Database Class: HighlightThickness
Specifies a non-negative value indicating the width of the highlight rectangle to draw around the outside of the widget when it has the input focus. The value may have any of the forms acceptable to Tk_GetPixels. If the value is zero, no focus highlight is drawn around the widget.

Command-Line Name: -image
Database Name: image
Database Class: Image
Specifies an image to display in the widget, which must have been created with the image create command. Typically, if the image option is specified then it overrides other options that specify a bitmap or textual value to display in the widget; the image option may be reset to an empty string to re-enable a bitmap or text display.

Command-Line Name: -insertbackground
Database Name: insertBackground
Database Class: Foreground
Specifies the color to use as background in the area covered by the insertion cursor. This color will normally override either the normal background for the widget (or the selection background if the insertion cursor happens to fall in the selection).

Command-Line Name: -insertborderwidth
Database Name: insertBorderWidth
Database Class: BorderWidth
Specifies a non-negative value indicating the width of the 3-D border to draw around the insertion cursor. The value may have any of the forms acceptable to Tk_GetPixels.

Command-Line Name: -insertofftime
Database Name: insertOffTime
Database Class: OffTime
Specifies a non-negative integer value indicating the number of milliseconds the insertion cursor should remain ``off'' in each blink cycle. If this option is zero then the cursor doesn't blink: it is on all the time.

Command-Line Name: -insertontime
Database Name: insertOnTime
Database Class: OnTime
Specifies a non-negative integer value indicating the number of milliseconds the insertion cursor should remain ``on'' in each blink cycle.

Command-Line Name: -insertwidth
Database Name: insertWidth
Database Class: InsertWidth
Specifies a value indicating the total width of the insertion cursor. The value may have any of the forms acceptable to Tk_GetPixels. If a border has been specified for the insertion cursor (using the insertBorderWidth option), the border will be drawn inside the width specified by the insertWidth option.

Command-Line Name: -jump
Database Name: jump
Database Class: Jump
For widgets with a slider that can be dragged to adjust a value, such as scrollbars, this option determines when notifications are made about changes in the value. The option's value must be a boolean of the form accepted by Tcl_GetBoolean. If the value is false, updates are made continuously as the slider is dragged. If the value is true, updates are delayed until the mouse button is released to end the drag; at that point a single notification is made (the value ``jumps'' rather than changing smoothly).

Command-Line Name: -justify
Database Name: justify
Database Class: Justify
When there are multiple lines of text displayed in a widget, this option determines how the lines line up with each other. Must be one of left, center, or right. Left means that the lines' left edges all line up, center means that the lines' centers are aligned, and right means that the lines' right edges line up.

Command-Line Name: -orient
Database Name: orient
Database Class: Orient
For widgets that can lay themselves out with either a horizontal or vertical orientation, such as scrollbars, this option specifies which orientation should be used. Must be either horizontal or vertical or an abbreviation of one of these.

Command-Line Name: -padx
Database Name: padX
Database Class: Pad
Specifies a non-negative value indicating how much extra space to request for the widget in the X-direction. The value may have any of the forms acceptable to Tk_GetPixels. When computing how large a window it needs, the widget will add this amount to the width it would normally need (as determined by the width of the things displayed in the widget); if the geometry manager can satisfy this request, the widget will end up with extra internal space to the left and/or right of what it displays inside. Most widgets only use this option for padding text: if they are displaying a bitmap or image, then they usually ignore padding options.

Command-Line Name: -pady
Database Name: padY
Database Class: Pad
Specifies a non-negative value indicating how much extra space to request for the widget in the Y-direction. The value may have any of the forms acceptable to Tk_GetPixels. When computing how large a window it needs, the widget will add this amount to the height it would normally need (as determined by the height of the things displayed in the widget); if the geometry manager can satisfy this request, the widget will end up with extra internal space above and/or below what it displays inside. Most widgets only use this option for padding text: if they are displaying a bitmap or image, then they usually ignore padding options.

Command-Line Name: -relief
Database Name: relief
Database Class: Relief
Specifies the 3-D effect desired for the widget. Acceptable values are raised, sunken, flat, ridge, solid, and groove. The value indicates how the interior of the widget should appear relative to its exterior; for example, raised means the interior of the widget should appear to protrude from the screen, relative to the exterior of the widget.

Command-Line Name: -repeatdelay
Database Name: repeatDelay
Database Class: RepeatDelay
Specifies the number of milliseconds a button or key must be held down before it begins to auto-repeat. Used, for example, on the up- and down-arrows in scrollbars.

Command-Line Name: -repeatinterval
Database Name: repeatInterval
Database Class: RepeatInterval
Used in conjunction with repeatDelay: once auto-repeat begins, this option determines the number of milliseconds between auto-repeats.

Command-Line Name: -selectbackground
Database Name: selectBackground
Database Class: Foreground
Specifies the background color to use when displaying selected items.

Command-Line Name: -selectborderwidth
Database Name: selectBorderWidth
Database Class: BorderWidth
Specifies a non-negative value indicating the width of the 3-D border to draw around selected items. The value may have any of the forms acceptable to Tk_GetPixels.

Command-Line Name: -selectforeground
Database Name: selectForeground
Database Class: Background
Specifies the foreground color to use when displaying selected items.

Command-Line Name: -setgrid
Database Name: setGrid
Database Class: SetGrid
Specifies a boolean value that determines whether this widget controls the resizing grid for its top-level window. This option is typically used in text widgets, where the information in the widget has a natural size (the size of a character) and it makes sense for the window's dimensions to be integral numbers of these units. These natural window sizes form a grid. If the setGrid option is set to true then the widget will communicate with the window manager so that when the user interactively resizes the top-level window that contains the widget, the dimensions of the window will be displayed to the user in grid units and the window size will be constrained to integral numbers of grid units. See the section GRIDDED GEOMETRY MANAGEMENT in the wm manual entry for more details.

Command-Line Name: -takefocus
Database Name: takeFocus
Database Class: TakeFocus
Determines whether the window accepts the focus during keyboard traversal (e.g., Tab and Shift-Tab). Before setting the focus to a window, the traversal scripts consult the value of the takeFocus option. A value of 0 means that the window should be skipped entirely during keyboard traversal. 1 means that the window should receive the input focus as long as it is viewable (it and all of its ancestors are mapped). An empty value for the option means that the traversal scripts make the decision about whether or not to focus on the window: the current algorithm is to skip the window if it is disabled, if it has no key bindings, or if it is not viewable. If the value has any other form, then the traversal scripts take the value, append the name of the window to it (with a separator space), and evaluate the resulting string as a Tcl script. The script must return 0, 1, or an empty string: a 0 or 1 value specifies whether the window will receive the input focus, and an empty string results in the default decision described above. Note: this interpretation of the option is defined entirely by the Tcl scripts that implement traversal: the widget implementations ignore the option entirely, so you can change its meaning if you redefine the keyboard traversal scripts.

Command-Line Name: -text
Database Name: text
Database Class: Text
Specifies a string to be displayed inside the widget. The way in which the string is displayed depends on the particular widget and may be determined by other options, such as anchor or justify.

Command-Line Name: -textvariable
Database Name: textVariable
Database Class: Variable
Specifies the name of a variable. The value of the variable is a text string to be displayed inside the widget; if the variable value changes then the widget will automatically update itself to reflect the new value. The way in which the string is displayed in the widget depends on the particular widget and may be determined by other options, such as anchor or justify.

Command-Line Name: -troughcolor
Database Name: troughColor
Database Class: Background
Specifies the color to use for the rectangular trough areas in widgets such as scrollbars and scales. This option is ignored for scrollbars on Windows (native widget doesn't recognize this option).

Command-Line Name: -underline
Database Name: underline
Database Class: Underline
Specifies the integer index of a character to underline in the widget. This option is used by the default bindings to implement keyboard traversal for menu buttons and menu entries. 0 corresponds to the first character of the text displayed in the widget, 1 to the next character, and so on.

Command-Line Name: -wraplength
Database Name: wrapLength
Database Class: WrapLength
For widgets that can perform word-wrapping, this option specifies the maximum line length. Lines that would exceed this length are wrapped onto the next line, so that no line is longer than the specified length. The value may be specified in any of the standard forms for screen distances. If this value is less than or equal to 0 then no wrapping is done: lines will break only at newline characters in the text.

Command-Line Name: -xscrollcommand
Database Name: xScrollCommand
Database Class: ScrollCommand
Specifies the prefix for a command used to communicate with horizontal scrollbars. When the view in the widget's window changes (or whenever anything else occurs that could change the display in a scrollbar, such as a change in the total size of the widget's contents), the widget will generate a Tcl command by concatenating the scroll command and two numbers. Each of the numbers is a fraction between 0 and 1, which indicates a position in the document. 0 indicates the beginning of the document, 1 indicates the end, .333 indicates a position one third the way through the document, and so on. The first fraction indicates the first information in the document that is visible in the window, and the second fraction indicates the information just after the last portion that is visible. The command is then passed to the Tcl interpreter for execution. Typically the xScrollCommand option consists of the path name of a scrollbar widget followed by ``set'', e.g. ``.x.scrollbar set'': this will cause the scrollbar to be updated whenever the view in the window changes. If this option is not specified, then no command will be executed.

Command-Line Name: -yscrollcommand
Database Name: yScrollCommand
Database Class: ScrollCommand
Specifies the prefix for a command used to communicate with vertical scrollbars. This option is treated in the same way as the xScrollCommand option, except that it is used for vertical scrollbars and is provided by widgets that support vertical scrolling. See the description of xScrollCommand for details on how this option is used.

SEE ALSO

colors, cursors, font

KEYWORDS

class, name, standard option, switch
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - pack manual page

NAME
pack - Geometry manager that packs around edges of cavity
SYNOPSIS
pack option arg ?arg ...?
DESCRIPTION
pack slave ?slave ...? ?options?
pack configure slave ?slave ...? ?options?
-after other
-anchor anchor
-before other
-expand boolean
-fill style
none
x
y
both
-in other
-ipadx amount
-ipady amount
-padx amount
-pady amount
-side side
pack forget slave ?slave ...?
pack info slave
pack propagate master ?boolean?
pack slaves master
THE PACKER ALGORITHM
EXPANSION
GEOMETRY PROPAGATION
RESTRICTIONS ON MASTER WINDOWS
PACKING ORDER
KEYWORDS

NAME

pack - Geometry manager that packs around edges of cavity

SYNOPSIS

pack option arg ?arg ...?

DESCRIPTION

The pack command is used to communicate with the packer, a geometry manager that arranges the children of a parent by packing them in order around the edges of the parent. The pack command can have any of several forms, depending on the option argument:

pack slave ?slave ...? ?options?
If the first argument to pack is a window name (any value starting with ``.''), then the command is processed in the same way as pack configure.

pack configure slave ?slave ...? ?options?
The arguments consist of the names of one or more slave windows followed by pairs of arguments that specify how to manage the slaves. See ``THE PACKER ALGORITHM'' below for details on how the options are used by the packer. The following options are supported:

-after other
Other must the name of another window. Use its master as the master for the slaves, and insert the slaves just after other in the packing order.

-anchor anchor
Anchor must be a valid anchor position such as n or sw; it specifies where to position each slave in its parcel. Defaults to center.

-before other
Other must the name of another window. Use its master as the master for the slaves, and insert the slaves just before other in the packing order.

-expand boolean
Specifies whether the slaves should be expanded to consume extra space in their master. Boolean may have any proper boolean value, such as 1 or no. Defaults to 0.

-fill style
If a slave's parcel is larger than its requested dimensions, this option may be used to stretch the slave. Style must have one of the following values:

none
Give the slave its requested dimensions plus any internal padding requested with -ipadx or -ipady. This is the default.

x
Stretch the slave horizontally to fill the entire width of its parcel (except leave external padding as specified by -padx).

y
Stretch the slave vertically to fill the entire height of its parcel (except leave external padding as specified by -pady).

both
Stretch the slave both horizontally and vertically.

-in other
Insert the slave(s) at the end of the packing order for the master window given by other.

-ipadx amount
Amount specifies how much horizontal internal padding to leave on each side of the slave(s). Amount must be a valid screen distance, such as 2 or .5c. It defaults to 0.

-ipady amount
Amount specifies how much vertical internal padding to leave on each side of the slave(s). Amount defaults to 0.

-padx amount
Amount specifies how much horizontal external padding to leave on each side of the slave(s). Amount defaults to 0.

-pady amount
Amount specifies how much vertical external padding to leave on each side of the slave(s). Amount defaults to 0.

-side side
Specifies which side of the master the slave(s) will be packed against. Must be left, right, top, or bottom. Defaults to top.

If no -in, -after or -before option is specified then each of the slaves will be inserted at the end of the packing list for its parent unless it is already managed by the packer (in which case it will be left where it is). If one of these options is specified then all the slaves will be inserted at the specified point. If any of the slaves are already managed by the geometry manager then any unspecified options for them retain their previous values rather than receiving default values.

pack forget slave ?slave ...?
Removes each of the slaves from the packing order for its master and unmaps their windows. The slaves will no longer be managed by the packer.

pack info slave
Returns a list whose elements are the current configuration state of the slave given by slave in the same option-value form that might be specified to pack configure. The first two elements of the list are ``-in master'' where master is the slave's master.

pack propagate master ?boolean?
If boolean has a true boolean value such as 1 or on then propagation is enabled for master, which must be a window name (see ``GEOMETRY PROPAGATION'' below). If boolean has a false boolean value then propagation is disabled for master. In either of these cases an empty string is returned. If boolean is omitted then the command returns 0 or 1 to indicate whether propagation is currently enabled for master. Propagation is enabled by default.

pack slaves master
Returns a list of all of the slaves in the packing order for master. The order of the slaves in the list is the same as their order in the packing order. If master has no slaves then an empty string is returned.

THE PACKER ALGORITHM

For each master the packer maintains an ordered list of slaves called the packing list. The -in, -after, and -before configuration options are used to specify the master for each slave and the slave's position in the packing list. If none of these options is given for a slave then the slave is added to the end of the packing list for its parent.

The packer arranges the slaves for a master by scanning the packing list in order. At the time it processes each slave, a rectangular area within the master is still unallocated. This area is called the cavity; for the first slave it is the entire area of the master.

For each slave the packer carries out the following steps:

[1]
The packer allocates a rectangular parcel for the slave along the side of the cavity given by the slave's -side option. If the side is top or bottom then the width of the parcel is the width of the cavity and its height is the requested height of the slave plus the -ipady and -pady options. For the left or right side the height of the parcel is the height of the cavity and the width is the requested width of the slave plus the -ipadx and -padx options. The parcel may be enlarged further because of the -expand option (see ``EXPANSION'' below)

[2]
The packer chooses the dimensions of the slave. The width will normally be the slave's requested width plus twice its -ipadx option and the height will normally be the slave's requested height plus twice its -ipady option. However, if the -fill option is x or both then the width of the slave is expanded to fill the width of the parcel, minus twice the -padx option. If the -fill option is y or both then the height of the slave is expanded to fill the width of the parcel, minus twice the -pady option.

[3]
The packer positions the slave over its parcel. If the slave is smaller than the parcel then the -anchor option determines where in the parcel the slave will be placed. If -padx or -pady is non-zero, then the given amount of external padding will always be left between the slave and the edges of the parcel.

Once a given slave has been packed, the area of its parcel is subtracted from the cavity, leaving a smaller rectangular cavity for the next slave. If a slave doesn't use all of its parcel, the unused space in the parcel will not be used by subsequent slaves. If the cavity should become too small to meet the needs of a slave then the slave will be given whatever space is left in the cavity. If the cavity shrinks to zero size, then all remaining slaves on the packing list will be unmapped from the screen until the master window becomes large enough to hold them again.

EXPANSION

If a master window is so large that there will be extra space left over after all of its slaves have been packed, then the extra space is distributed uniformly among all of the slaves for which the -expand option is set. Extra horizontal space is distributed among the expandable slaves whose -side is left or right, and extra vertical space is distributed among the expandable slaves whose -side is top or bottom.

GEOMETRY PROPAGATION

The packer normally computes how large a master must be to just exactly meet the needs of its slaves, and it sets the requested width and height of the master to these dimensions. This causes geometry information to propagate up through a window hierarchy to a top-level window so that the entire sub-tree sizes itself to fit the needs of the leaf windows. However, the pack propagate command may be used to turn off propagation for one or more masters. If propagation is disabled then the packer will not set the requested width and height of the packer. This may be useful if, for example, you wish for a master window to have a fixed size that you specify.

RESTRICTIONS ON MASTER WINDOWS

The master for each slave must either be the slave's parent (the default) or a descendant of the slave's parent. This restriction is necessary to guarantee that the slave can be placed over any part of its master that is visible without danger of the slave being clipped by its parent.

PACKING ORDER

If the master for a slave is not its parent then you must make sure that the slave is higher in the stacking order than the master. Otherwise the master will obscure the slave and it will appear as if the slave hasn't been packed correctly. The easiest way to make sure the slave is higher than the master is to create the master window first: the most recently created window will be highest in the stacking order. Or, you can use the raise and lower commands to change the stacking order of either the master or the slave.

KEYWORDS

geometry manager, location, packer, parcel, propagation, size
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tk_setPalette manual page

NAME

tk_setPalette, tk_bisque - Modify the Tk color palette

SYNOPSIS

tk_setPalette background
tk_setPalette name value ?name value ...?
tk_bisque

DESCRIPTION

The tk_setPalette procedure changes the color scheme for Tk. It does this by modifying the colors of existing widgets and by changing the option database so that future widgets will use the new color scheme. If tk_setPalette is invoked with a single argument, the argument is the name of a color to use as the normal background color; tk_setPalette will compute a complete color palette from this background color. Alternatively, the arguments to tk_setPalette may consist of any number of name-value pairs, where the first argument of the pair is the name of an option in the Tk option database and the second argument is the new value to use for that option. The following database names are currently supported:
activeBackground	foreground	selectColor
activeForeground	highlightBackground	selectBackground
background	highlightColor	selectForeground
disabledForeground	insertBackground	troughColor
tk_setPalette tries to compute reasonable defaults for any options that you don't specify. You can specify options other than the above ones and Tk will change those options on widgets as well. This feature may be useful if you are using custom widgets with additional color options.

Once it has computed the new value to use for each of the color options, tk_setPalette scans the widget hierarchy to modify the options of all existing widgets. For each widget, it checks to see if any of the above options is defined for the widget. If so, and if the option's current value is the default, then the value is changed; if the option has a value other than the default, tk_setPalette will not change it. The default for an option is the one provided by the widget ([lindex [$w configure $option] 3]) unless tk_setPalette has been run previously, in which case it is the value specified in the previous invocation of tk_setPalette.

After modifying all the widgets in the application, tk_setPalette adds options to the option database to change the defaults for widgets created in the future. The new options are added at priority widgetDefault, so they will be overridden by options from the .Xdefaults file or options specified on the command-line that creates a widget.

The procedure tk_bisque is provided for backward compatibility: it restores the application's colors to the light brown (``bisque'') color scheme used in Tk 3.6 and earlier versions.

KEYWORDS

bisque, color, palette
Copyright © 1995-1996 Sun Microsystems, Inc.


Tk Built-In Commands - photo manual page

NAME
photo - Full-color images
SYNOPSIS
image create photo ?name? ?options?
DESCRIPTION
CREATING PHOTOS
-data string
-format format-name
-file name
-gamma value
-height number
-palette palette-spec
-width number
IMAGE COMMAND
imageName blank
imageName cget option
imageName configure ?option? ?value option value ...?
imageName copy sourceImage ?option value(s) ...?
-from x1 y1 x2 y2
-to x1 y1 x2 y2
-shrink
-zoom x y
-subsample x y
imageName data ?option value(s) ...?
-background color
-format format-name
-from x1 y1 x2 y2
-grayscale
imageName get x y
imageName put data ?option value(s) ...?
-format format-name
-from x1 y1 x2 y2
-shrink
-to x y
imageName read filename ?option value(s) ...?
-format format-name
-from x1 y1 x2 y2
-shrink
-to x y
imageName redither
imageName write filename ?option value(s) ...?
-background color
-format format-name
-from x1 y1 x2 y2
-grayscale
IMAGE FORMATS
COLOR ALLOCATION
CREDITS
KEYWORDS

NAME

photo - Full-color images

SYNOPSIS

image create photo ?name? ?options?

DESCRIPTION

A photo is an image whose pixels can display any color or be transparent. A photo image is stored internally in full color (32 bits per pixel), and is displayed using dithering if necessary. Image data for a photo image can be obtained from a file or a string, or it can be supplied from C code through a procedural interface. At present, only GIF and PPM/PGM formats are supported, but an interface exists to allow additional image file formats to be added easily. A photo image is transparent in regions where no image data has been supplied.

CREATING PHOTOS

Like all images, photos are created using the image create command. Photos support the following options:

-data string
Specifies the contents of the image as a string. The string can contain base64 encoded data or binary data. The format of the string must be one of those for which there is an image file format handler that will accept string data. If both the -data and -file options are specified, the -file option takes precedence.

-format format-name
Specifies the name of the file format for the data specified with the -data or -file option.

-file name
name gives the name of a file that is to be read to supply data for the photo image. The file format must be one of those for which there is an image file format handler that can read data.

-gamma value
Specifies that the colors allocated for displaying this image in a window should be corrected for a non-linear display with the specified gamma exponent value. (The intensity produced by most CRT displays is a power function of the input value, to a good approximation; gamma is the exponent and is typically around 2). The value specified must be greater than zero. The default value is one (no correction). In general, values greater than one will make the image lighter, and values less than one will make it darker.

-height number
Specifies the height of the image, in pixels. This option is useful primarily in situations where the user wishes to build up the contents of the image piece by piece. A value of zero (the default) allows the image to expand or shrink vertically to fit the data stored in it.

-palette palette-spec
Specifies the resolution of the color cube to be allocated for displaying this image, and thus the number of colors used from the colormaps of the windows where it is displayed. The palette-spec string may be either a single decimal number, specifying the number of shades of gray to use, or three decimal numbers separated by slashes (/), specifying the number of shades of red, green and blue to use, respectively. If the first form (a single number) is used, the image will be displayed in monochrome (i.e., grayscale).

-width number
Specifies the width of the image, in pixels. This option is useful primarily in situations where the user wishes to build up the contents of the image piece by piece. A value of zero (the default) allows the image to expand or shrink horizontally to fit the data stored in it.

IMAGE COMMAND

When a photo image is created, Tk also creates a new command whose name is the same as the image. This command may be used to invoke various operations on the image. It has the following general form:
imageName option ?arg arg ...?
Option and the args determine the exact behavior of the command.

Those options that write data to the image generally expand the size of the image, if necessary, to accommodate the data written to the image, unless the user has specified non-zero values for the -width and/or -height configuration options, in which case the width and/or height, respectively, of the image will not be changed.

The following commands are possible for photo images:

imageName blank
Blank the image; that is, set the entire image to have no data, so it will be displayed as transparent, and the background of whatever window it is displayed in will show through.

imageName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the image create photo command.

imageName configure ?option? ?value option value ...?
Query or modify the configuration options for the image. If no option is specified, returns a list describing all of the available options for imageName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the image create photo command.

imageName copy sourceImage ?option value(s) ...?
Copies a region from the image called sourceImage (which must be a photo image) to the image called imageName, possibly with pixel zooming and/or subsampling. If no options are specified, this command copies the whole of sourceImage into imageName, starting at coordinates (0,0) in imageName. The following options may be specified:

-from x1 y1 x2 y2
Specifies a rectangular sub-region of the source image to be copied. (x1,y1) and (x2,y2) specify diagonally opposite corners of the rectangle. If x2 and y2 are not specified, the default value is the bottom-right corner of the source image. The pixels copied will include the left and top edges of the specified rectangle but not the bottom or right edges. If the -from option is not given, the default is the whole source image.

-to x1 y1 x2 y2
Specifies a rectangular sub-region of the destination image to be affected. (x1,y1) and (x2,y2) specify diagonally opposite corners of the rectangle. If x2 and y2 are not specified, the default value is (x1,y1) plus the size of the source region (after subsampling and zooming, if specified). If x2 and y2 are specified, the source region will be replicated if necessary to fill the destination region in a tiled fashion.

-shrink
Specifies that the size of the destination image should be reduced, if necessary, so that the region being copied into is at the bottom-right corner of the image. This option will not affect the width or height of the image if the user has specified a non-zero value for the -width or -height configuration option, respectively.

-zoom x y
Specifies that the source region should be magnified by a factor of x in the X direction and y in the Y direction. If y is not given, the default value is the same as x. With this option, each pixel in the source image will be expanded into a block of x x y pixels in the destination image, all the same color. x and y must be greater than 0.

-subsample x y
Specifies that the source image should be reduced in size by using only every xth pixel in the X direction and yth pixel in the Y direction. Negative values will cause the image to be flipped about the Y or X axes, respectively. If y is not given, the default value is the same as x.

imageName data ?option value(s) ...?
Returns image data in the form of a string. The following options may be specified:

-background color
If the color is specified, the data will not contain any transparency information. In all transparent pixels the color will be replaced by the specified color.

-format format-name
Specifies the name of the image file format handler to be used. Specifically, this subcommand searches for the first handler whose name matches a initial substring of format-name and which has the capability to read this image data. If this option is not given, this subcommand uses the first handler that has the capability to read the image data.

-from x1 y1 x2 y2
Specifies a rectangular region of imageName to be returned. If only x1 and y1 are specified, the region extends from (x1,y1) to the bottom-right corner of imageName. If all four coordinates are given, they specify diagonally opposite corners of the rectangular region, including x1,y1 and excluding x2,y2. The default, if this option is not given, is the whole image.

-grayscale
If this options is specified, the data will not contain color information. All pixel data will be transformed into grayscale.

imageName get x y
Returns the color of the pixel at coordinates (x,y) in the image as a list of three integers between 0 and 255, representing the red, green and blue components respectively.

imageName put data ?option value(s) ...?
Sets pixels in imageName to the data specified in data. This command first searches the list of image file format handlers for a handler that can interpret the data in data, and then reads the image in filename into imageName (the destination image). The following options may be specified:

-format format-name
Specifies the format of the image data in data. Specifically, only image file format handlers whose names begin with format-name will be used while searching for an image data format handler to read the data.

-from x1 y1 x2 y2
Specifies a rectangular sub-region of the image file data to be returned. If only x1 and y1 are specified, the region extends from (x1,y1) to the bottom-right corner of the image in the image file. If all four coordinates are specified, they specify diagonally opposite corners or the region. The default, if this option is not specified, is the whole of the image.

-shrink
If this option, the size of imageName will be reduced, if necessary, so that the region into which the image file data are read is at the bottom-right corner of the imageName. This option will not affect the width or height of the image if the user has specified a non-zero value for the -width or -height configuration option, respectively.

-to x y
Specifies the coordinates of the top-left corner of the region of imageName into which data from filename are to be read. The default is (0,0).

imageName read filename ?option value(s) ...?
Reads image data from the file named filename into the image. This command first searches the list of image file format handlers for a handler that can interpret the data in filename, and then reads the image in filename into imageName (the destination image). The following options may be specified:

-format format-name
Specifies the format of the image data in filename. Specifically, only image file format handlers whose names begin with format-name will be used while searching for an image data format handler to read the data.

-from x1 y1 x2 y2
Specifies a rectangular sub-region of the image file data to be copied to the destination image. If only x1 and y1 are specified, the region extends from (x1,y1) to the bottom-right corner of the image in the image file. If all four coordinates are specified, they specify diagonally opposite corners or the region. The default, if this option is not specified, is the whole of the image in the image file.

-shrink
If this option, the size of imageName will be reduced, if necessary, so that the region into which the image file data are read is at the bottom-right corner of the imageName. This option will not affect the width or height of the image if the user has specified a non-zero value for the -width or -height configuration option, respectively.

-to x y
Specifies the coordinates of the top-left corner of the region of imageName into which data from filename are to be read. The default is (0,0).

imageName redither
The dithering algorithm used in displaying photo images propagates quantization errors from one pixel to its neighbors. If the image data for imageName is supplied in pieces, the dithered image may not be exactly correct. Normally the difference is not noticeable, but if it is a problem, this command can be used to recalculate the dithered image in each window where the image is displayed.

imageName write filename ?option value(s) ...?
Writes image data from imageName to a file named filename. The following options may be specified:

-background color
If the color is specified, the data will not contain any transparency information. In all transparent pixels the color will be replaced by the specified color.

-format format-name
Specifies the name of the image file format handler to be used to write the data to the file. Specifically, this subcommand searches for the first handler whose name matches a initial substring of format-name and which has the capability to write an image file. If this option is not given, this subcommand uses the first handler that has the capability to write an image file.

-from x1 y1 x2 y2
Specifies a rectangular region of imageName to be written to the image file. If only x1 and y1 are specified, the region extends from (x1,y1) to the bottom-right corner of imageName. If all four coordinates are given, they specify diagonally opposite corners of the rectangular region. The default, if this option is not given, is the whole image.

-grayscale
If this options is specified, the data will not contain color information. All pixel data will be transformed into grayscale.

IMAGE FORMATS

The photo image code is structured to allow handlers for additional image file formats to be added easily. The photo image code maintains a list of these handlers. Handlers are added to the list by registering them with a call to Tk_CreatePhotoImageFormat. The standard Tk distribution comes with handlers for PPM/PGM and GIF formats, which are automatically registered on initialization.

When reading an image file or processing string data specified with the -data configuration option, the photo image code invokes each handler in turn until one is found that claims to be able to read the data in the file or string. Usually this will find the correct handler, but if it doesn't, the user may give a format name with the -format option to specify which handler to use. In fact the photo image code will try those handlers whose names begin with the string specified for the -format option (the comparison is case-insensitive). For example, if the user specifies -format gif, then a handler named GIF87 or GIF89 may be invoked, but a handler named JPEG may not (assuming that such handlers had been registered).

When writing image data to a file, the processing of the -format option is slightly different: the string value given for the -format option must begin with the complete name of the requested handler, and may contain additional information following that, which the handler can use, for example, to specify which variant to use of the formats supported by the handler.

COLOR ALLOCATION

When a photo image is displayed in a window, the photo image code allocates colors to use to display the image and dithers the image, if necessary, to display a reasonable approximation to the image using the colors that are available. The colors are allocated as a color cube, that is, the number of colors allocated is the product of the number of shades of red, green and blue.

Normally, the number of colors allocated is chosen based on the depth of the window. For example, in an 8-bit PseudoColor window, the photo image code will attempt to allocate seven shades of red, seven shades of green and four shades of blue, for a total of 198 colors. In a 1-bit StaticGray (monochrome) window, it will allocate two colors, black and white. In a 24-bit DirectColor or TrueColor window, it will allocate 256 shades each of red, green and blue. Fortunately, because of the way that pixel values can be combined in DirectColor and TrueColor windows, this only requires 256 colors to be allocated. If not all of the colors can be allocated, the photo image code reduces the number of shades of each primary color and tries again.

The user can exercise some control over the number of colors that a photo image uses with the -palette configuration option. If this option is used, it specifies the maximum number of shades of each primary color to try to allocate. It can also be used to force the image to be displayed in shades of gray, even on a color display, by giving a single number rather than three numbers separated by slashes.

CREDITS

The photo image type was designed and implemented by Paul Mackerras, based on his earlier photo widget and some suggestions from John Ousterhout.

KEYWORDS

photo, image, color
Copyright © 1994 The Australian National University
Copyright © 1994-1997 Sun Microsystems, Inc.


Built-In Commands - place manual page

NAME
place - Geometry manager for fixed or rubber-sheet placement
SYNOPSIS
place window option value ?option value ...?
place configure window option value ?option value ...?
place forget window
place info window
place slaves window
DESCRIPTION
-in master
-x location
-relx location
-y location
-rely location
-anchor where
-width size
-relwidth size
-height size
-relheight size
-bordermode mode
FINE POINTS
KEYWORDS

NAME

place - Geometry manager for fixed or rubber-sheet placement

SYNOPSIS

place window option value ?option value ...?
place configure window option value ?option value ...?
place forget window
place info window
place slaves window

DESCRIPTION

The placer is a geometry manager for Tk. It provides simple fixed placement of windows, where you specify the exact size and location of one window, called the slave, within another window, called the master. The placer also provides rubber-sheet placement, where you specify the size and location of the slave in terms of the dimensions of the master, so that the slave changes size and location in response to changes in the size of the master. Lastly, the placer allows you to mix these styles of placement so that, for example, the slave has a fixed width and height but is centered inside the master.

If the first argument to the place command is a window path name or configure then the command arranges for the placer to manage the geometry of a slave whose path name is window. The remaining arguments consist of one or more option-value pairs that specify the way in which window's geometry is managed. If the placer is already managing window, then the option-value pairs modify the configuration for window. In this form the place command returns an empty string as result. The following option-value pairs are supported:

-in master
Master specifes the path name of the window relative to which window is to be placed. Master must either be window's parent or a descendant of window's parent. In addition, master and window must both be descendants of the same top-level window. These restrictions are necessary to guarantee that window is visible whenever master is visible. If this option isn't specified then the master defaults to window's parent.

-x location
Location specifies the x-coordinate within the master window of the anchor point for window. The location is specified in screen units (i.e. any of the forms accepted by Tk_GetPixels) and need not lie within the bounds of the master window.

-relx location
Location specifies the x-coordinate within the master window of the anchor point for window. In this case the location is specified in a relative fashion as a floating-point number: 0.0 corresponds to the left edge of the master and 1.0 corresponds to the right edge of the master. Location need not be in the range 0.0-1.0. If both -x and -relx are specified for a slave then their values are summed. For example, -relx 0.5 -x -2 positions the left edge of the slave 2 pixels to the left of the center of its master.

-y location
Location specifies the y-coordinate within the master window of the anchor point for window. The location is specified in screen units (i.e. any of the forms accepted by Tk_GetPixels) and need not lie within the bounds of the master window.

-rely location
Location specifies the y-coordinate within the master window of the anchor point for window. In this case the value is specified in a relative fashion as a floating-point number: 0.0 corresponds to the top edge of the master and 1.0 corresponds to the bottom edge of the master. Location need not be in the range 0.0-1.0. If both -y and -rely are specified for a slave then their values are summed. For example, -rely 0.5 -x 3 positions the top edge of the slave 3 pixels below the center of its master.

-anchor where
Where specifies which point of window is to be positioned at the (x,y) location selected by the -x, -y, -relx, and -rely options. The anchor point is in terms of the outer area of window including its border, if any. Thus if where is se then the lower-right corner of window's border will appear at the given (x,y) location in the master. The anchor position defaults to nw.

-width size
Size specifies the width for window in screen units (i.e. any of the forms accepted by Tk_GetPixels). The width will be the outer width of window including its border, if any. If size is an empty string, or if no -width or -relwidth option is specified, then the width requested internally by the window will be used.

-relwidth size
Size specifies the width for window. In this case the width is specified as a floating-point number relative to the width of the master: 0.5 means window will be half as wide as the master, 1.0 means window will have the same width as the master, and so on. If both -width and -relwidth are specified for a slave, their values are summed. For example, -relwidth 1.0 -width 5 makes the slave 5 pixels wider than the master.

-height size
Size specifies the height for window in screen units (i.e. any of the forms accepted by Tk_GetPixels). The height will be the outer dimension of window including its border, if any. If size is an empty string, or if no -height or -relheight option is specified, then the height requested internally by the window will be used.

-relheight size
Size specifies the height for window. In this case the height is specified as a floating-point number relative to the height of the master: 0.5 means window will be half as high as the master, 1.0 means window will have the same height as the master, and so on. If both -height and -relheight are specified for a slave, their values are summed. For example, -relheight 1.0 -height -2 makes the slave 2 pixels shorter than the master.

-bordermode mode
Mode determines the degree to which borders within the master are used in determining the placement of the slave. The default and most common value is inside. In this case the placer considers the area of the master to be the innermost area of the master, inside any border: an option of -x 0 corresponds to an x-coordinate just inside the border and an option of -relwidth 1.0 means window will fill the area inside the master's border. If mode is outside then the placer considers the area of the master to include its border; this mode is typically used when placing window outside its master, as with the options -x 0 -y 0 -anchor ne. Lastly, mode may be specified as ignore, in which case borders are ignored: the area of the master is considered to be its official X area, which includes any internal border but no external border. A bordermode of ignore is probably not very useful.

If the same value is specified separately with two different options, such as -x and -relx, then the most recent option is used and the older one is ignored.

The place slaves command returns a list of all the slave windows for which window is the master. If there are no slaves for window then an empty string is returned.

The place forget command causes the placer to stop managing the geometry of window. As a side effect of this command window will be unmapped so that it doesn't appear on the screen. If window isn't currently managed by the placer then the command has no effect. Place forget returns an empty string as result.

The place info command returns a list giving the current configuration of window. The list consists of option-value pairs in exactly the same form as might be specified to the place configure command. If the configuration of a window has been retrieved with place info, that configuration can be restored later by first using place forget to erase any existing information for the window and then invoking place configure with the saved information.

FINE POINTS

It is not necessary for the master window to be the parent of the slave window. This feature is useful in at least two situations. First, for complex window layouts it means you can create a hierarchy of subwindows whose only purpose is to assist in the layout of the parent. The ``real children'' of the parent (i.e. the windows that are significant for the application's user interface) can be children of the parent yet be placed inside the windows of the geometry-management hierarchy. This means that the path names of the ``real children'' don't reflect the geometry-management hierarchy and users can specify options for the real children without being aware of the structure of the geometry-management hierarchy.

A second reason for having a master different than the slave's parent is to tie two siblings together. For example, the placer can be used to force a window always to be positioned centered just below one of its siblings by specifying the configuration

-in sibling -relx 0.5 -rely 1.0 -anchor n -bordermode outside
Whenever the sibling is repositioned in the future, the slave will be repositioned as well.

Unlike many other geometry managers (such as the packer) the placer does not make any attempt to manipulate the geometry of the master windows or the parents of slave windows (i.e. it doesn't set their requested sizes). To control the sizes of these windows, make them windows like frames and canvases that provide configuration options for this purpose.

KEYWORDS

geometry manager, height, location, master, place, rubber sheet, slave, width
Copyright © 1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tk_popup manual page

NAME

tk_popup - Post a popup menu

SYNOPSIS

tk_popup menu x y ?entry?

DESCRIPTION

This procedure posts a menu at a given position on the screen and configures Tk so that the menu and its cascaded children can be traversed with the mouse or the keyboard. Menu is the name of a menu widget and x and y are the root coordinates at which to display the menu. If entry is omitted or an empty string, the menu's upper left corner is positioned at the given point. Otherwise entry gives the index of an entry in menu and the menu will be positioned so that the entry is positioned over the given point.

KEYWORDS

menu, popup
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - radiobutton manual page

NAME
radiobutton - Create and manipulate radiobutton widgets
SYNOPSIS
radiobutton pathName ?options?
STANDARD OPTIONS
-activebackground, activeBackground, Foreground
-activeforeground, activeForeground, Background
-anchor, anchor, Anchor
-background or -bg, background, Background
-bitmap, bitmap, Bitmap
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-image, image, Image
-justify, justify, Justify
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-underline, underline, Underline
-wraplength, wrapLength, WrapLength
WIDGET-SPECIFIC OPTIONS
-command, command, Command
-height, height, Height
-indicatoron, indicatorOn, IndicatorOn
-selectcolor, selectColor, Background
-selectimage, selectImage, SelectImage
-state, state, State
-value, value, Value
-variable, variable, Variable
-width, width, Width
DESCRIPTION
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName deselect
pathName flash
pathName invoke
pathName select
BINDINGS
KEYWORDS

NAME

radiobutton - Create and manipulate radiobutton widgets

SYNOPSIS

radiobutton pathName ?options?

STANDARD OPTIONS

-activebackground, activeBackground, Foreground
-activeforeground, activeForeground, Background
-anchor, anchor, Anchor
-background or -bg, background, Background
-bitmap, bitmap, Bitmap
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-disabledforeground, disabledForeground, DisabledForeground
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-image, image, Image
-justify, justify, Justify
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
-text, text, Text
-textvariable, textVariable, Variable
-underline, underline, Underline
-wraplength, wrapLength, WrapLength

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -command
Database Name: command
Database Class: Command
Specifies a Tcl command to associate with the button. This command is typically invoked when mouse button 1 is released over the button window. The button's global variable (-variable option) will be updated before the command is invoked.

Command-Line Name: -height
Database Name: height
Database Class: Height
Specifies a desired height for the button. If an image or bitmap is being displayed in the button then the value is in screen units (i.e. any of the forms acceptable to Tk_GetPixels); for text it is in lines of text. If this option isn't specified, the button's desired height is computed from the size of the image or bitmap or text being displayed in it.

Command-Line Name: -indicatoron
Database Name: indicatorOn
Database Class: IndicatorOn
Specifies whether or not the indicator should be drawn. Must be a proper boolean value. If false, the relief option is ignored and the widget's relief is always sunken if the widget is selected and raised otherwise.

Command-Line Name: -selectcolor
Database Name: selectColor
Database Class: Background
Specifies a background color to use when the button is selected. If indicatorOn is true then the color applies to the indicator. Under Windows, this color is used as the background for the indicator regardless of the select state. If indicatorOn is false, this color is used as the background for the entire widget, in place of background or activeBackground, whenever the widget is selected. If specified as an empty string then no special color is used for displaying when the widget is selected.

Command-Line Name: -selectimage
Database Name: selectImage
Database Class: SelectImage
Specifies an image to display (in place of the image option) when the radiobutton is selected. This option is ignored unless the image option has been specified.

Command-Line Name: -state
Database Name: state
Database Class: State
Specifies one of three states for the radiobutton: normal, active, or disabled. In normal state the radiobutton is displayed using the foreground and background options. The active state is typically used when the pointer is over the radiobutton. In active state the radiobutton is displayed using the activeForeground and activeBackground options. Disabled state means that the radiobutton should be insensitive: the default bindings will refuse to activate the widget and will ignore mouse button presses. In this state the disabledForeground and background options determine how the radiobutton is displayed.

Command-Line Name: -value
Database Name: value
Database Class: Value
Specifies value to store in the button's associated variable whenever this button is selected.

Command-Line Name: -variable
Database Name: variable
Database Class: Variable
Specifies name of global variable to set whenever this button is selected. Changes in this variable also cause the button to select or deselect itself. Defaults to the value selectedButton.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies a desired width for the button. If an image or bitmap is being displayed in the button, the value is in screen units (i.e. any of the forms acceptable to Tk_GetPixels); for text it is in characters. If this option isn't specified, the button's desired width is computed from the size of the image or bitmap or text being displayed in it.

DESCRIPTION

The radiobutton command creates a new window (given by the pathName argument) and makes it into a radiobutton widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the radiobutton such as its colors, font, text, and initial relief. The radiobutton command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A radiobutton is a widget that displays a textual string, bitmap or image and a diamond or circle called an indicator. If text is displayed, it must all be in a single font, but it can occupy multiple lines on the screen (if it contains newlines or if wrapping occurs because of the wrapLength option) and one of the characters may optionally be underlined using the underline option. A radiobutton has all of the behavior of a simple button: it can display itself in either of three different ways, according to the state option; it can be made to appear raised, sunken, or flat; it can be made to flash; and it invokes a Tcl command whenever mouse button 1 is clicked over the check button.

In addition, radiobuttons can be selected. If a radiobutton is selected, the indicator is normally drawn with a selected appearance, and a Tcl variable associated with the radiobutton is set to a particular value (normally 1). Under Unix, the indicator is drawn with a sunken relief and a special color. Under Windows, the indicator is drawn with a round mark inside. If the radiobutton is not selected, then the indicator is drawn with a deselected appearance, and the associated variable is set to a different value (typically 0). Under Unix, the indicator is drawn with a raised relief and no special color. Under Windows, the indicator is drawn without a round mark inside. Typically, several radiobuttons share a single variable and the value of the variable indicates which radiobutton is to be selected. When a radiobutton is selected it sets the value of the variable to indicate that fact; each radiobutton also monitors the value of the variable and automatically selects and deselects itself when the variable's value changes. By default the variable selectedButton is used; its contents give the name of the button that is selected, or the empty string if no button associated with that variable is selected. The name of the variable for a radiobutton, plus the variable to be stored into it, may be modified with options on the command line or in the option database. Configuration options may also be used to modify the way the indicator is displayed (or whether it is displayed at all). By default a radiobutton is configured to select itself on button clicks.

WIDGET COMMAND

The radiobutton command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for radiobutton widgets:

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the radiobutton command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the radiobutton command.

pathName deselect
Deselects the radiobutton and sets the associated variable to an empty string. If this radiobutton was not currently selected, the command has no effect.

pathName flash
Flashes the radiobutton. This is accomplished by redisplaying the radiobutton several times, alternating between active and normal colors. At the end of the flash the radiobutton is left in the same normal/active state as when the command was invoked. This command is ignored if the radiobutton's state is disabled.

pathName invoke
Does just what would have happened if the user invoked the radiobutton with the mouse: selects the button and invokes its associated Tcl command, if there is one. The return value is the return value from the Tcl command, or an empty string if there is no command associated with the radiobutton. This command is ignored if the radiobutton's state is disabled.

pathName select
Selects the radiobutton and sets the associated variable to the value corresponding to this widget.

BINDINGS

Tk automatically creates class bindings for radiobuttons that give them the following default behavior:

[1]
On Unix systems, a radiobutton activates whenever the mouse passes over it and deactivates whenever the mouse leaves the radiobutton. On Mac and Windows systems, when mouse button 1 is pressed over a radiobutton, the button activates whenever the mouse pointer is inside the button, and deactivates whenever the mouse pointer leaves the button.

[2]
When mouse button 1 is pressed over a radiobutton it is invoked (it becomes selected and the command associated with the button is invoked, if there is one).

[3]
When a radiobutton has the input focus, the space key causes the radiobutton to be invoked.

If the radiobutton's state is disabled then none of the above actions occur: the radiobutton is completely non-responsive.

The behavior of radiobuttons can be changed by defining new bindings for individual widgets or by redefining the class bindings.

KEYWORDS

radiobutton, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - raise manual page

NAME

raise - Change a window's position in the stacking order

SYNOPSIS

raise window ?aboveThis?

DESCRIPTION

If the aboveThis argument is omitted then the command raises window so that it is above all of its siblings in the stacking order (it will not be obscured by any siblings and will obscure any siblings that overlap it). If aboveThis is specified then it must be the path name of a window that is either a sibling of window or the descendant of a sibling of window. In this case the raise command will insert window into the stacking order just above aboveThis (or the ancestor of aboveThis that is a sibling of window); this could end up either raising or lowering window.

SEE ALSO

lower

KEYWORDS

obscure, raise, stacking order
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - scale manual page

NAME
scale - Create and manipulate scale widgets
SYNOPSIS
scale pathName ?options?
STANDARD OPTIONS
-activebackground, activeBackground, Foreground
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-orient, orient, Orient
-relief, relief, Relief
-repeatdelay, repeatDelay, RepeatDelay
-repeatinterval, repeatInterval, RepeatInterval
-takefocus, takeFocus, TakeFocus
-troughcolor, troughColor, Background
WIDGET-SPECIFIC OPTIONS
-bigincrement, bigIncrement, BigIncrement
-command, command, Command
-digits, digits, Digits
-from, from, From
-label, label, Label
-length, length, Length
-resolution, resolution, Resolution
-showvalue, showValue, ShowValue
-sliderlength, sliderLength, SliderLength
-sliderrelief, sliderRelief, SliderRelief
-state, state, State
-tickinterval, tickInterval, TickInterval
-to, to, To
-variable, variable, Variable
-width, width, Width
DESCRIPTION
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
pathName coords ?value?
pathName get ?x y?
pathName identify x y
pathName set value
BINDINGS
KEYWORDS

NAME

scale - Create and manipulate scale widgets

SYNOPSIS

scale pathName ?options?

STANDARD OPTIONS

-activebackground, activeBackground, Foreground
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-orient, orient, Orient
-relief, relief, Relief
-repeatdelay, repeatDelay, RepeatDelay
-repeatinterval, repeatInterval, RepeatInterval
-takefocus, takeFocus, TakeFocus
-troughcolor, troughColor, Background

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -bigincrement
Database Name: bigIncrement
Database Class: BigIncrement
Some interactions with the scale cause its value to change by ``large'' increments; this option specifies the size of the large increments. If specified as 0, the large increments default to 1/10 the range of the scale.

Command-Line Name: -command
Database Name: command
Database Class: Command
Specifies the prefix of a Tcl command to invoke whenever the scale's value is changed via a widget command. The actual command consists of this option followed by a space and a real number indicating the new value of the scale.

Command-Line Name: -digits
Database Name: digits
Database Class: Digits
An integer specifying how many significant digits should be retained when converting the value of the scale to a string. If the number is less than or equal to zero, then the scale picks the smallest value that guarantees that every possible slider position prints as a different string.

Command-Line Name: -from
Database Name: from
Database Class: From
A real value corresponding to the left or top end of the scale.

Command-Line Name: -label
Database Name: label
Database Class: Label
A string to display as a label for the scale. For vertical scales the label is displayed just to the right of the top end of the scale. For horizontal scales the label is displayed just above the left end of the scale. If the option is specified as an empty string, no label is displayed.

Command-Line Name: -length
Database Name: length
Database Class: Length
Specifies the desired long dimension of the scale in screen units (i.e. any of the forms acceptable to Tk_GetPixels). For vertical scales this is the scale's height; for horizontal scales it is the scale's width.

Command-Line Name: -resolution
Database Name: resolution
Database Class: Resolution
A real value specifying the resolution for the scale. If this value is greater than zero then the scale's value will always be rounded to an even multiple of this value, as will tick marks and the endpoints of the scale. If the value is less than zero then no rounding occurs. Defaults to 1 (i.e., the value will be integral).

Command-Line Name: -showvalue
Database Name: showValue
Database Class: ShowValue
Specifies a boolean value indicating whether or not the current value of the scale is to be displayed.

Command-Line Name: -sliderlength
Database Name: sliderLength
Database Class: SliderLength
Specfies the size of the slider, measured in screen units along the slider's long dimension. The value may be specified in any of the forms acceptable to Tk_GetPixels.

Command-Line Name: -sliderrelief
Database Name: sliderRelief
Database Class: SliderRelief
Specifies the relief to use when drawing the slider, such as raised or sunken.

Command-Line Name: -state
Database Name: state
Database Class: State
Specifies one of three states for the scale: normal, active, or disabled. If the scale is disabled then the value may not be changed and the scale won't activate. If the scale is active, the slider is displayed using the color specified by the activeBackground option.

Command-Line Name: -tickinterval
Database Name: tickInterval
Database Class: TickInterval
Must be a real value. Determines the spacing between numerical tick marks displayed below or to the left of the slider. If 0, no tick marks will be displayed.

Command-Line Name: -to
Database Name: to
Database Class: To
Specifies a real value corresponding to the right or bottom end of the scale. This value may be either less than or greater than the from option.

Command-Line Name: -variable
Database Name: variable
Database Class: Variable
Specifies the name of a global variable to link to the scale. Whenever the value of the variable changes, the scale will update to reflect this value. Whenever the scale is manipulated interactively, the variable will be modified to reflect the scale's new value.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies the desired narrow dimension of the trough in screen units (i.e. any of the forms acceptable to Tk_GetPixels). For vertical scales this is the trough's width; for horizontal scales this is the trough's height.

DESCRIPTION

The scale command creates a new window (given by the pathName argument) and makes it into a scale widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the scale such as its colors, orientation, and relief. The scale command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A scale is a widget that displays a rectangular trough and a small slider. The trough corresponds to a range of real values (determined by the from, to, and resolution options), and the position of the slider selects a particular real value. The slider's position (and hence the scale's value) may be adjusted with the mouse or keyboard as described in the BINDINGS section below. Whenever the scale's value is changed, a Tcl command is invoked (using the command option) to notify other interested widgets of the change. In addition, the value of the scale can be linked to a Tcl variable (using the variable option), so that changes in either are reflected in the other.

Three annotations may be displayed in a scale widget: a label appearing at the top right of the widget (top left for horizontal scales), a number displayed just to the left of the slider (just above the slider for horizontal scales), and a collection of numerical tick marks just to the left of the current value (just below the trough for horizontal scales). Each of these three annotations may be enabled or disabled using the configuration options.

WIDGET COMMAND

The scale command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for scale widgets:

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the scale command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the scale command.

pathName coords ?value?
Returns a list whose elements are the x and y coordinates of the point along the centerline of the trough that corresponds to value. If value is omitted then the scale's current value is used.

pathName get ?x y?
If x and y are omitted, returns the current value of the scale. If x and y are specified, they give pixel coordinates within the widget; the command returns the scale value corresponding to the given pixel. Only one of x or y is used: for horizontal scales y is ignored, and for vertical scales x is ignored.

pathName identify x y
Returns a string indicating what part of the scale lies under the coordinates given by x and y. A return value of slider means that the point is over the slider; trough1 means that the point is over the portion of the slider above or to the left of the slider; and trough2 means that the point is over the portion of the slider below or to the right of the slider. If the point isn't over one of these elements, an empty string is returned.

pathName set value
This command is invoked to change the current value of the scale, and hence the position at which the slider is displayed. Value gives the new value for the scale. The command has no effect if the scale is disabled.

BINDINGS

Tk automatically creates class bindings for scales that give them the following default behavior. Where the behavior is different for vertical and horizontal scales, the horizontal behavior is described in parentheses.

[1]
If button 1 is pressed in the trough, the scale's value will be incremented or decremented by the value of the resolution option so that the slider moves in the direction of the cursor. If the button is held down, the action auto-repeats.

[2]
If button 1 is pressed over the slider, the slider can be dragged with the mouse.

[3]
If button 1 is pressed in the trough with the Control key down, the slider moves all the way to the end of its range, in the direction towards the mouse cursor.

[4]
If button 2 is pressed, the scale's value is set to the mouse position. If the mouse is dragged with button 2 down, the scale's value changes with the drag.

[5]
The Up and Left keys move the slider up (left) by the value of the resolution option.

[6]
The Down and Right keys move the slider down (right) by the value of the resolution option.

[7]
Control-Up and Control-Left move the slider up (left) by the value of the bigIncrement option.

[8]
Control-Down and Control-Right move the slider down (right) by the value of the bigIncrement option.

[9]
Home moves the slider to the top (left) end of its range.

[10]
End moves the slider to the bottom (right) end of its range.

If the scale is disabled using the state option then none of the above bindings have any effect.

The behavior of scales can be changed by defining new bindings for individual widgets or by redefining the class bindings.

KEYWORDS

scale, slider, trough, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - scrollbar manual page

NAME
scrollbar - Create and manipulate scrollbar widgets
SYNOPSIS
scrollbar pathName ?options?
STANDARD OPTIONS
-activebackground, activeBackground, Foreground
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-jump, jump, Jump
-orient, orient, Orient
-relief, relief, Relief
-repeatdelay, repeatDelay, RepeatDelay
-repeatinterval, repeatInterval, RepeatInterval
-takefocus, takeFocus, TakeFocus
-troughcolor, troughColor, Background
WIDGET-SPECIFIC OPTIONS
-activerelief, activeRelief, ActiveRelief
-command, command, Command
-elementborderwidth, elementBorderWidth, BorderWidth
-width, width, Width
DESCRIPTION
ELEMENTS
arrow1
trough1
slider
trough2
arrow2
WIDGET COMMAND
pathName activate ?element?
pathName cget option
pathName configure ?option? ?value option value ...?
pathName delta deltaX deltaY
pathName fraction x y
pathName get
pathName identify x y
pathName set first last
SCROLLING COMMANDS
prefix moveto fraction
prefix scroll number units
prefix scroll number pages
OLD COMMAND SYNTAX
pathName set totalUnits windowUnits firstUnit lastUnit
prefix unit
BINDINGS
KEYWORDS

NAME

scrollbar - Create and manipulate scrollbar widgets

SYNOPSIS

scrollbar pathName ?options?

STANDARD OPTIONS

-activebackground, activeBackground, Foreground
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-jump, jump, Jump
-orient, orient, Orient
-relief, relief, Relief
-repeatdelay, repeatDelay, RepeatDelay
-repeatinterval, repeatInterval, RepeatInterval
-takefocus, takeFocus, TakeFocus
-troughcolor, troughColor, Background

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -activerelief
Database Name: activeRelief
Database Class: ActiveRelief
Specifies the relief to use when displaying the element that is active, if any. Elements other than the active element are always displayed with a raised relief.

Command-Line Name: -command
Database Name: command
Database Class: Command
Specifies the prefix of a Tcl command to invoke to change the view in the widget associated with the scrollbar. When a user requests a view change by manipulating the scrollbar, a Tcl command is invoked. The actual command consists of this option followed by additional information as described later. This option almost always has a value such as .t xview or .t yview, consisting of the name of a widget and either xview (if the scrollbar is for horizontal scrolling) or yview (for vertical scrolling). All scrollable widgets have xview and yview commands that take exactly the additional arguments appended by the scrollbar as described in SCROLLING COMMANDS below.

Command-Line Name: -elementborderwidth
Database Name: elementBorderWidth
Database Class: BorderWidth
Specifies the width of borders drawn around the internal elements of the scrollbar (the two arrows and the slider). The value may have any of the forms acceptable to Tk_GetPixels. If this value is less than zero, the value of the borderWidth option is used in its place.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies the desired narrow dimension of the scrollbar window, not including 3-D border, if any. For vertical scrollbars this will be the width and for horizontal scrollbars this will be the height. The value may have any of the forms acceptable to Tk_GetPixels.

DESCRIPTION

The scrollbar command creates a new window (given by the pathName argument) and makes it into a scrollbar widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the scrollbar such as its colors, orientation, and relief. The scrollbar command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

A scrollbar is a widget that displays two arrows, one at each end of the scrollbar, and a slider in the middle portion of the scrollbar. It provides information about what is visible in an associated window that displays an document of some sort (such as a file being edited or a drawing). The position and size of the slider indicate which portion of the document is visible in the associated window. For example, if the slider in a vertical scrollbar covers the top third of the area between the two arrows, it means that the associated window displays the top third of its document.

Scrollbars can be used to adjust the view in the associated window by clicking or dragging with the mouse. See the BINDINGS section below for details.

ELEMENTS

A scrollbar displays five elements, which are referred to in the widget commands for the scrollbar:

arrow1
The top or left arrow in the scrollbar.

trough1
The region between the slider and arrow1.

slider
The rectangle that indicates what is visible in the associated widget.

trough2
The region between the slider and arrow2.

arrow2
The bottom or right arrow in the scrollbar.

WIDGET COMMAND

The scrollbar command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
Option and the args determine the exact behavior of the command. The following commands are possible for scrollbar widgets:

pathName activate ?element?
Marks the element indicated by element as active, which causes it to be displayed as specified by the activeBackground and activeRelief options. The only element values understood by this command are arrow1, slider, or arrow2. If any other value is specified then no element of the scrollbar will be active. If element is not specified, the command returns the name of the element that is currently active, or an empty string if no element is active.

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the scrollbar command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the scrollbar command.

pathName delta deltaX deltaY
Returns a real number indicating the fractional change in the scrollbar setting that corresponds to a given change in slider position. For example, if the scrollbar is horizontal, the result indicates how much the scrollbar setting must change to move the slider deltaX pixels to the right (deltaY is ignored in this case). If the scrollbar is vertical, the result indicates how much the scrollbar setting must change to move the slider deltaY pixels down. The arguments and the result may be zero or negative.

pathName fraction x y
Returns a real number between 0 and 1 indicating where the point given by x and y lies in the trough area of the scrollbar. The value 0 corresponds to the top or left of the trough, the value 1 corresponds to the bottom or right, 0.5 corresponds to the middle, and so on. X and y must be pixel coordinates relative to the scrollbar widget. If x and y refer to a point outside the trough, the closest point in the trough is used.

pathName get
Returns the scrollbar settings in the form of a list whose elements are the arguments to the most recent set widget command.

pathName identify x y
Returns the name of the element under the point given by x and y (such as arrow1), or an empty string if the point does not lie in any element of the scrollbar. X and y must be pixel coordinates relative to the scrollbar widget.

pathName set first last
This command is invoked by the scrollbar's associated widget to tell the scrollbar about the current view in the widget. The command takes two arguments, each of which is a real fraction between 0 and 1. The fractions describe the range of the document that is visible in the associated widget. For example, if first is 0.2 and last is 0.4, it means that the first part of the document visible in the window is 20% of the way through the document, and the last visible part is 40% of the way through.

SCROLLING COMMANDS

When the user interacts with the scrollbar, for example by dragging the slider, the scrollbar notifies the associated widget that it must change its view. The scrollbar makes the notification by evaluating a Tcl command generated from the scrollbar's -command option. The command may take any of the following forms. In each case, prefix is the contents of the -command option, which usually has a form like .t yview

prefix moveto fraction
Fraction is a real number between 0 and 1. The widget should adjust its view so that the point given by fraction appears at the beginning of the widget. If fraction is 0 it refers to the beginning of the document. 1.0 refers to the end of the document, 0.333 refers to a point one-third of the way through the document, and so on.

prefix scroll number units
The widget should adjust its view by number units. The units are defined in whatever way makes sense for the widget, such as characters or lines in a text widget. Number is either 1, which means one unit should scroll off the top or left of the window, or -1, which means that one unit should scroll off the bottom or right of the window.

prefix scroll number pages
The widget should adjust its view by number pages. It is up to the widget to define the meaning of a page; typically it is slightly less than what fits in the window, so that there is a slight overlap between the old and new views. Number is either 1, which means the next page should become visible, or -1, which means that the previous page should become visible.

OLD COMMAND SYNTAX

In versions of Tk before 4.0, the set and get widget commands used a different form. This form is still supported for backward compatibility, but it is deprecated. In the old command syntax, the set widget command has the following form:

pathName set totalUnits windowUnits firstUnit lastUnit
In this form the arguments are all integers. TotalUnits gives the total size of the object being displayed in the associated widget. The meaning of one unit depends on the associated widget; for example, in a text editor widget units might correspond to lines of text. WindowUnits indicates the total number of units that can fit in the associated window at one time. FirstUnit and lastUnit give the indices of the first and last units currently visible in the associated window (zero corresponds to the first unit of the object).

Under the old syntax the get widget command returns a list of four integers, consisting of the totalUnits, windowUnits, firstUnit, and lastUnit values from the last set widget command.

The commands generated by scrollbars also have a different form when the old syntax is being used:

prefix unit
Unit is an integer that indicates what should appear at the top or left of the associated widget's window. It has the same meaning as the firstUnit and lastUnit arguments to the set widget command.

The most recent set widget command determines whether or not to use the old syntax. If it is given two real arguments then the new syntax will be used in the future, and if it is given four integer arguments then the old syntax will be used.

BINDINGS

Tk automatically creates class bindings for scrollbars that give them the following default behavior. If the behavior is different for vertical and horizontal scrollbars, the horizontal behavior is described in parentheses.

[1]
Pressing button 1 over arrow1 causes the view in the associated widget to shift up (left) by one unit so that the document appears to move down (right) one unit. If the button is held down, the action auto-repeats.

[2]
Pressing button 1 over trough1 causes the view in the associated widget to shift up (left) by one screenful so that the document appears to move down (right) one screenful. If the button is held down, the action auto-repeats.

[3]
Pressing button 1 over the slider and dragging causes the view to drag with the slider. If the jump option is true, then the view doesn't drag along with the slider; it changes only when the mouse button is released.

[4]
Pressing button 1 over trough2 causes the view in the associated widget to shift down (right) by one screenful so that the document appears to move up (left) one screenful. If the button is held down, the action auto-repeats.

[5]
Pressing button 1 over arrow2 causes the view in the associated widget to shift down (right) by one unit so that the document appears to move up (left) one unit. If the button is held down, the action auto-repeats.

[6]
If button 2 is pressed over the trough or the slider, it sets the view to correspond to the mouse position; dragging the mouse with button 2 down causes the view to drag with the mouse. If button 2 is pressed over one of the arrows, it causes the same behavior as pressing button 1.

[7]
If button 1 is pressed with the Control key down, then if the mouse is over arrow1 or trough1 the view changes to the very top (left) of the document; if the mouse is over arrow2 or trough2 the view changes to the very bottom (right) of the document; if the mouse is anywhere else then the button press has no effect.

[8]
In vertical scrollbars the Up and Down keys have the same behavior as mouse clicks over arrow1 and arrow2, respectively. In horizontal scrollbars these keys have no effect.

[9]
In vertical scrollbars Control-Up and Control-Down have the same behavior as mouse clicks over trough1 and trough2, respectively. In horizontal scrollbars these keys have no effect.

[10]
In horizontal scrollbars the Up and Down keys have the same behavior as mouse clicks over arrow1 and arrow2, respectively. In vertical scrollbars these keys have no effect.

[11]
In horizontal scrollbars Control-Up and Control-Down have the same behavior as mouse clicks over trough1 and trough2, respectively. In vertical scrollbars these keys have no effect.

[12]
The Prior and Next keys have the same behavior as mouse clicks over trough1 and trough2, respectively.

[13]
The Home key adjusts the view to the top (left edge) of the document.

[14]
The End key adjusts the view to the bottom (right edge) of the document.

KEYWORDS

scrollbar, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - selection manual page

NAME
selection - Manipulate the X selection
SYNOPSIS
selection option ?arg arg ...?
DESCRIPTION
selection clear ?-displayof window? ?-selection selection?
selection get ?-displayof window? ?-selection selection? ?-type type?
selection handle ?-selection selection? ?-type type? ?-format format? window command
selection own ?-displayof window? ?-selection selection?
selection own ?-command command? ?-selection selection? window
KEYWORDS

NAME

selection - Manipulate the X selection

SYNOPSIS

selection option ?arg arg ...?

DESCRIPTION

This command provides a Tcl interface to the X selection mechanism and implements the full selection functionality described in the X Inter-Client Communication Conventions Manual (ICCCM).

The first argument to selection determines the format of the rest of the arguments and the behavior of the command. The following forms are currently supported:

selection clear ?-displayof window? ?-selection selection?
If selection exists anywhere on window's display, clear it so that no window owns the selection anymore. Selection specifies the X selection that should be cleared, and should be an atom name such as PRIMARY or CLIPBOARD; see the Inter-Client Communication Conventions Manual for complete details. Selection defaults to PRIMARY and window defaults to ``.''. Returns an empty string.

selection get ?-displayof window? ?-selection selection? ?-type type?
Retrieves the value of selection from window's display and returns it as a result. Selection defaults to PRIMARY and window defaults to ``.''. Type specifies the form in which the selection is to be returned (the desired ``target'' for conversion, in ICCCM terminology), and should be an atom name such as STRING or FILE_NAME; see the Inter-Client Communication Conventions Manual for complete details. Type defaults to STRING. The selection owner may choose to return the selection in any of several different representation formats, such as STRING, ATOM, INTEGER, etc. (this format is different than the selection type; see the ICCCM for all the confusing details). If the selection is returned in a non-string format, such as INTEGER or ATOM, the selection command converts it to string format as a collection of fields separated by spaces: atoms are converted to their textual names, and anything else is converted to hexadecimal integers.

selection handle ?-selection selection? ?-type type? ?-format format? window command
Creates a handler for selection requests, such that command will be executed whenever selection is owned by window and someone attempts to retrieve it in the form given by type (e.g. type is specified in the selection get command). Selection defaults to PRIMARY, type defaults to STRING, and format defaults to STRING. If command is an empty string then any existing handler for window, type, and selection is removed.

When selection is requested, window is the selection owner, and type is the requested type, command will be executed as a Tcl command with two additional numbers appended to it (with space separators). The two additional numbers are offset and maxChars: offset specifies a starting character position in the selection and maxChars gives the maximum number of characters to retrieve. The command should return a value consisting of at most maxChars of the selection, starting at position offset. For very large selections (larger than maxChars) the selection will be retrieved using several invocations of command with increasing offset values. If command returns a string whose length is less than maxChars, the return value is assumed to include all of the remainder of the selection; if the length of command's result is equal to maxChars then command will be invoked again, until it eventually returns a result shorter than maxChars. The value of maxChars will always be relatively large (thousands of characters).

If command returns an error then the selection retrieval is rejected just as if the selection didn't exist at all.

The format argument specifies the representation that should be used to transmit the selection to the requester (the second column of Table 2 of the ICCCM), and defaults to STRING. If format is STRING, the selection is transmitted as 8-bit ASCII characters (i.e. just in the form returned by command). If format is ATOM, then the return value from command is divided into fields separated by white space; each field is converted to its atom value, and the 32-bit atom value is transmitted instead of the atom name. For any other format, the return value from command is divided into fields separated by white space and each field is converted to a 32-bit integer; an array of integers is transmitted to the selection requester.

The format argument is needed only for compatibility with selection requesters that don't use Tk. If Tk is being used to retrieve the selection then the value is converted back to a string at the requesting end, so format is irrelevant.

selection own ?-displayof window? ?-selection selection?

selection own ?-command command? ?-selection selection? window
The first form of selection own returns the path name of the window in this application that owns selection on the display containing window, or an empty string if no window in this application owns the selection. Selection defaults to PRIMARY and window defaults to ``.''.

The second form of selection own causes window to become the new owner of selection on window's display, returning an empty string as result. The existing owner, if any, is notified that it has lost the selection. If command is specified, it is a Tcl script to execute when some other window claims ownership of the selection away from window. Selection defaults to PRIMARY.

KEYWORDS

clear, format, handler, ICCCM, own, selection, target, type
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - send manual page

NAME
send - Execute a command in a different application
SYNOPSIS
send ?options? app cmd ?arg arg ...?
DESCRIPTION
-async
-displayof pathName
- -
APPLICATION NAMES
DISABLING SENDS
SECURITY
KEYWORDS

NAME

send - Execute a command in a different application

SYNOPSIS

send ?options? app cmd ?arg arg ...?

DESCRIPTION

This command arranges for cmd (and args) to be executed in the application named by app. It returns the result or error from that command execution. App may be the name of any application whose main window is on the display containing the sender's main window; it need not be within the same process. If no arg arguments are present, then the command to be executed is contained entirely within the cmd argument. If one or more args are present, they are concatenated to form the command to be executed, just as for the eval command.

If the initial arguments of the command begin with ``-'' they are treated as options. The following options are currently defined:

-async
Requests asynchronous invocation. In this case the send command will complete immediately without waiting for cmd to complete in the target application; no result will be available and errors in the sent command will be ignored. If the target application is in the same process as the sending application then the -async option is ignored.

-displayof pathName
Specifies that the target application's main window is on the display of the window given by pathName, instead of the display containing the application's main window.

- -
Serves no purpose except to terminate the list of options. This option is needed only if app could contain a leading ``-'' character.

APPLICATION NAMES

The name of an application is set initially from the name of the program or script that created the application. You can query and change the name of an application with the tk appname command.

DISABLING SENDS

If the send command is removed from an application (e.g. with the command rename send {}) then the application will not respond to incoming send requests anymore, nor will it be able to issue outgoing requests. Communication can be reenabled by invoking the tk appname command.

SECURITY

The send command is potentially a serious security loophole. On Unix, any application that can connect to your X server can send scripts to your applications. These incoming scripts can use Tcl to read and write your files and invoke subprocesses under your name. Host-based access control such as that provided by xhost is particularly insecure, since it allows anyone with an account on particular hosts to connect to your server, and if disabled it allows anyone anywhere to connect to your server. In order to provide at least a small amount of security, Tk checks the access control being used by the server and rejects incoming sends unless (a) xhost-style access control is enabled (i.e. only certain hosts can establish connections) and (b) the list of enabled hosts is empty. This means that applications cannot connect to your server unless they use some other form of authorization such as that provide by xauth. Under Windows, send is currently disabled. Most of the functionality is provided by the dde command instead.

KEYWORDS

application, dde, name, remote execution, security, send
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - text manual page

NAME
text - Create and manipulate text widgets
SYNOPSIS
text pathName ?options?
STANDARD OPTIONS
-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-exportselection, exportSelection, ExportSelection
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-insertbackground, insertBackground, Foreground
-insertborderwidth, insertBorderWidth, BorderWidth
-insertofftime, insertOffTime, OffTime
-insertontime, insertOnTime, OnTime
-insertwidth, insertWidth, InsertWidth
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-selectbackground, selectBackground, Foreground
-selectborderwidth, selectBorderWidth, BorderWidth
-selectforeground, selectForeground, Background
-setgrid, setGrid, SetGrid
-takefocus, takeFocus, TakeFocus
-xscrollcommand, xScrollCommand, ScrollCommand
-yscrollcommand, yScrollCommand, ScrollCommand
WIDGET-SPECIFIC OPTIONS
-height, height, Height
-spacing1, spacing1, Spacing1
-spacing2, spacing2, Spacing2
-spacing3, spacing3, Spacing3
-state, state, State
-tabs, tabs, Tabs
-width, width, Width
-wrap, wrap, Wrap
DESCRIPTION
INDICES
line.char
@x,y
end
mark
tag.first
tag.last
pathName
.VS
+ count chars
- count chars
+ count lines
- count lines
linestart
lineend
wordstart
wordend
TAGS
-background color
-bgstipple bitmap
-borderwidth pixels
-elide boolean
-fgstipple bitmap
-font fontName
-foreground color
-justify justify
-lmargin1 pixels
-lmargin2 pixels
-offset pixels
-overstrike boolean
-relief relief
-rmargin pixels
-spacing1 pixels
-spacing2 pixels
-spacing3 pixels
-tabs tabList
-underline boolean
-wrap mode
MARKS
EMBEDDED WINDOWS
-align where
-create script
-padx pixels
-pady pixels
-stretch boolean
-window pathName
EMBEDDED IMAGES
-align where
-image image
-name ImageName
-padx pixels
-pady pixels
THE SELECTION
THE INSERTION CURSOR
WIDGET COMMAND
pathName bbox index
pathName cget option
pathName compare index1 op index2
pathName configure ?option? ?value option value ...?
pathName debug ?boolean?
pathName delete index1 ?index2?
pathName dlineinfo index
pathName dump ?switches? index1 ?index2?
-all
-command command
-image
-mark
-tag
-text
-window
pathName get index1 ?index2?
pathName image option ?arg arg ...?
pathName image cget index option
pathName image configure index ?option value ...?
pathName image create index ?option value ...?
pathName image names
pathName index index
pathName insert index chars ?tagList chars tagList ...?
pathName mark option ?arg arg ...?
pathName mark gravity markName ?direction?
pathName mark names
pathName mark next index
pathName mark previous index
pathName mark set markName index
pathName mark unset markName ?markName markName ...?
pathName scan option args
pathName scan mark x y
pathName scan dragto x y
pathName search ?switches? pattern index ?stopIndex?
-forwards
-backwards
-exact
-regexp
-nocase
-count varName
-elide
- -
pathName see index
pathName tag option ?arg arg ...?
pathName tag add tagName index1 ?index2 index1 index2 ...?
pathName tag bind tagName ?sequence? ?script?
pathName tag cget tagName option
pathName tag configure tagName ?option? ?value? ?option value ...?
pathName tag delete tagName ?tagName ...?
pathName tag lower tagName ?belowThis?
pathName tag names ?index?
pathName tag nextrange tagName index1 ?index2?
pathName tag prevrange tagName index1 ?index2?
pathName tag raise tagName ?aboveThis?
pathName tag ranges tagName
pathName tag remove tagName index1 ?index2 index1 index2 ...?
pathName window option ?arg arg ...?
pathName window cget index option
pathName window configure index ?option value ...?
pathName window create index ?option value ...?
pathName window names
pathName xview option args
pathName xview
pathName xview moveto fraction
pathName xview scroll number what
pathName yview ?args?
pathName yview
pathName yview moveto fraction
pathName yview scroll number what
pathName yview ?-pickplace? index
pathName yview number
BINDINGS
PERFORMANCE ISSUES
KEYWORDS

NAME

text - Create and manipulate text widgets

SYNOPSIS

text pathName ?options?

STANDARD OPTIONS

-background or -bg, background, Background
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-exportselection, exportSelection, ExportSelection
-font, font, Font
-foreground or -fg, foreground, Foreground
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-insertbackground, insertBackground, Foreground
-insertborderwidth, insertBorderWidth, BorderWidth
-insertofftime, insertOffTime, OffTime
-insertontime, insertOnTime, OnTime
-insertwidth, insertWidth, InsertWidth
-padx, padX, Pad
-pady, padY, Pad
-relief, relief, Relief
-selectbackground, selectBackground, Foreground
-selectborderwidth, selectBorderWidth, BorderWidth
-selectforeground, selectForeground, Background
-setgrid, setGrid, SetGrid
-takefocus, takeFocus, TakeFocus
-xscrollcommand, xScrollCommand, ScrollCommand
-yscrollcommand, yScrollCommand, ScrollCommand

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -height
Database Name: height
Database Class: Height
Specifies the desired height for the window, in units of characters in the font given by the -font option. Must be at least one.

Command-Line Name: -spacing1
Database Name: spacing1
Database Class: Spacing1
Requests additional space above each text line in the widget, using any of the standard forms for screen distances. If a line wraps, this option only applies to the first line on the display. This option may be overriden with -spacing1 options in tags.

Command-Line Name: -spacing2
Database Name: spacing2
Database Class: Spacing2
For lines that wrap (so that they cover more than one line on the display) this option specifies additional space to provide between the display lines that represent a single line of text. The value may have any of the standard forms for screen distances. This option may be overriden with -spacing2 options in tags.

Command-Line Name: -spacing3
Database Name: spacing3
Database Class: Spacing3
Requests additional space below each text line in the widget, using any of the standard forms for screen distances. If a line wraps, this option only applies to the last line on the display. This option may be overriden with -spacing3 options in tags.

Command-Line Name: -state
Database Name: state
Database Class: State
Specifies one of two states for the text: normal or disabled. If the text is disabled then characters may not be inserted or deleted and no insertion cursor will be displayed, even if the input focus is in the widget.

Command-Line Name: -tabs
Database Name: tabs
Database Class: Tabs
Specifies a set of tab stops for the window. The option's value consists of a list of screen distances giving the positions of the tab stops. Each position may optionally be followed in the next list element by one of the keywords left, right, center, or numeric, which specifies how to justify text relative to the tab stop. Left is the default; it causes the text following the tab character to be positioned with its left edge at the tab position. Right means that the right edge of the text following the tab character is positioned at the tab position, and center means that the text is centered at the tab position. Numeric means that the decimal point in the text is positioned at the tab position; if there is no decimal point then the least significant digit of the number is positioned just to the left of the tab position; if there is no number in the text then the text is right-justified at the tab position. For example, -tabs {2c left 4c 6c center} creates three tab stops at two-centimeter intervals; the first two use left justification and the third uses center justification. If the list of tab stops does not have enough elements to cover all of the tabs in a text line, then Tk extrapolates new tab stops using the spacing and alignment from the last tab stop in the list. The value of the tabs option may be overridden by -tabs options in tags. If no -tabs option is specified, or if it is specified as an empty list, then Tk uses default tabs spaced every eight (average size) characters.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies the desired width for the window in units of characters in the font given by the -font option. If the font doesn't have a uniform width then the width of the character ``0'' is used in translating from character units to screen units.

Command-Line Name: -wrap
Database Name: wrap
Database Class: Wrap
Specifies how to handle lines in the text that are too long to be displayed in a single line of the text's window. The value must be none or char or word. A wrap mode of none means that each line of text appears as exactly one line on the screen; extra characters that don't fit on the screen are not displayed. In the other modes each line of text will be broken up into several screen lines if necessary to keep all the characters visible. In char mode a screen line break may occur after any character; in word mode a line break will only be made at word boundaries.

DESCRIPTION

The text command creates a new window (given by the pathName argument) and makes it into a text widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the text such as its default background color and relief. The text command returns the path name of the new window.

A text widget displays one or more lines of text and allows that text to be edited. Text widgets support four different kinds of annotations on the text, called tags, marks, embedded windows or embedded images. Tags allow different portions of the text to be displayed with different fonts and colors. In addition, Tcl commands can be associated with tags so that scripts are invoked when particular actions such as keystrokes and mouse button presses occur in particular ranges of the text. See TAGS below for more details.

The second form of annotation consists of marks, which are floating markers in the text. Marks are used to keep track of various interesting positions in the text as it is edited. See MARKS below for more details.

The third form of annotation allows arbitrary windows to be embedded in a text widget. See EMBEDDED WINDOWS below for more details.

The fourth form of annotation allows Tk images to be embedded in a text widget. See EMBEDDED IMAGES below for more details.

INDICES

Many of the widget commands for texts take one or more indices as arguments. An index is a string used to indicate a particular place within a text, such as a place to insert characters or one endpoint of a range of characters to delete. Indices have the syntax
base modifier modifier modifier ...
Where base gives a starting point and the modifiers adjust the index from the starting point (e.g. move forward or backward one character). Every index must contain a base, but the modifiers are optional.

The base for an index must have one of the following forms:

line.char
Indicates char'th character on line line. Lines are numbered from 1 for consistency with other UNIX programs that use this numbering scheme. Within a line, characters are numbered from 0. If char is end then it refers to the newline character that ends the line.

@x,y
Indicates the character that covers the pixel whose x and y coordinates within the text's window are x and y.

end
Indicates the end of the text (the character just after the last newline).

mark
Indicates the character just after the mark whose name is mark.

tag.first
Indicates the first character in the text that has been tagged with tag. This form generates an error if no characters are currently tagged with tag.

tag.last
Indicates the character just after the last one in the text that has been tagged with tag. This form generates an error if no characters are currently tagged with tag.

pathName
Indicates the position of the embedded window whose name is pathName. This form generates an error if there is no embedded window by the given name.

.VS
imageName Indicates the position of the embedded image whose name is imageName. This form generates an error if there is no embedded image by the given name.

If the base could match more than one of the above forms, such as a mark and imageName both having the same value, then the form earlier in the above list takes precedence. If modifiers follow the base index, each one of them must have one of the forms listed below. Keywords such as chars and wordend may be abbreviated as long as the abbreviation is unambiguous.

+ count chars
Adjust the index forward by count characters, moving to later lines in the text if necessary. If there are fewer than count characters in the text after the current index, then set the index to the last character in the text. Spaces on either side of count are optional.

- count chars
Adjust the index backward by count characters, moving to earlier lines in the text if necessary. If there are fewer than count characters in the text before the current index, then set the index to the first character in the text. Spaces on either side of count are optional.

+ count lines
Adjust the index forward by count lines, retaining the same character position within the line. If there are fewer than count lines after the line containing the current index, then set the index to refer to the same character position on the last line of the text. Then, if the line is not long enough to contain a character at the indicated character position, adjust the character position to refer to the last character of the line (the newline). Spaces on either side of count are optional.

- count lines
Adjust the index backward by count lines, retaining the same character position within the line. If there are fewer than count lines before the line containing the current index, then set the index to refer to the same character position on the first line of the text. Then, if the line is not long enough to contain a character at the indicated character position, adjust the character position to refer to the last character of the line (the newline). Spaces on either side of count are optional.

linestart
Adjust the index to refer to the first character on the line.

lineend
Adjust the index to refer to the last character on the line (the newline).

wordstart
Adjust the index to refer to the first character of the word containing the current index. A word consists of any number of adjacent characters that are letters, digits, or underscores, or a single character that is not one of these.

wordend
Adjust the index to refer to the character just after the last one of the word containing the current index. If the current index refers to the last character of the text then it is not modified.

If more than one modifier is present then they are applied in left-to-right order. For example, the index ``end - 1 chars'' refers to the next-to-last character in the text and ``insert wordstart - 1 c'' refers to the character just before the first one in the word containing the insertion cursor.

TAGS

The first form of annotation in text widgets is a tag. A tag is a textual string that is associated with some of the characters in a text. Tags may contain arbitrary characters, but it is probably best to avoid using the the characters `` '' (space), +, or -: these characters have special meaning in indices, so tags containing them can't be used as indices. There may be any number of tags associated with characters in a text. Each tag may refer to a single character, a range of characters, or several ranges of characters. An individual character may have any number of tags associated with it.

A priority order is defined among tags, and this order is used in implementing some of the tag-related functions described below. When a tag is defined (by associating it with characters or setting its display options or binding commands to it), it is given a priority higher than any existing tag. The priority order of tags may be redefined using the ``pathName tag raise'' and ``pathName tag lower'' widget commands.

Tags serve three purposes in text widgets. First, they control the way information is displayed on the screen. By default, characters are displayed as determined by the background, font, and foreground options for the text widget. However, display options may be associated with individual tags using the ``pathName tag configure'' widget command. If a character has been tagged, then the display options associated with the tag override the default display style. The following options are currently supported for tags:

-background color
Color specifies the background color to use for characters associated with the tag. It may have any of the forms accepted by Tk_GetColor.

-bgstipple bitmap
Bitmap specifies a bitmap that is used as a stipple pattern for the background. It may have any of the forms accepted by Tk_GetBitmap. If bitmap hasn't been specified, or if it is specified as an empty string, then a solid fill will be used for the background.

-borderwidth pixels
Pixels specifies the width of a 3-D border to draw around the background. It may have any of the forms accepted by Tk_GetPixels. This option is used in conjunction with the -relief option to give a 3-D appearance to the background for characters; it is ignored unless the -background option has been set for the tag.

-elide boolean
Elide specifies whether the data should be elided. Elided data is not displayed and takes no space on screen, but further on behaves just as normal data.

-fgstipple bitmap
Bitmap specifies a bitmap that is used as a stipple pattern when drawing text and other foreground information such as underlines. It may have any of the forms accepted by Tk_GetBitmap. If bitmap hasn't been specified, or if it is specified as an empty string, then a solid fill will be used.

-font fontName
FontName is the name of a font to use for drawing characters. It may have any of the forms accepted by Tk_GetFont.

-foreground color
Color specifies the color to use when drawing text and other foreground information such as underlines. It may have any of the forms accepted by Tk_GetColor.

-justify justify
If the first character of a display line has a tag for which this option has been specified, then justify determines how to justify the line. It must be one of left, right, or center. If a line wraps, then the justification for each line on the display is determined by the first character of that display line.

-lmargin1 pixels
If the first character of a text line has a tag for which this option has been specified, then pixels specifies how much the line should be indented from the left edge of the window. Pixels may have any of the standard forms for screen distances. If a line of text wraps, this option only applies to the first line on the display; the -lmargin2 option controls the indentation for subsequent lines.

-lmargin2 pixels
If the first character of a display line has a tag for which this option has been specified, and if the display line is not the first for its text line (i.e., the text line has wrapped), then pixels specifies how much the line should be indented from the left edge of the window. Pixels may have any of the standard forms for screen distances. This option is only used when wrapping is enabled, and it only applies to the second and later display lines for a text line.

-offset pixels
Pixels specifies an amount by which the text's baseline should be offset vertically from the baseline of the overall line, in pixels. For example, a positive offset can be used for superscripts and a negative offset can be used for subscripts. Pixels may have any of the standard forms for screen distances.

-overstrike boolean
Specifies whether or not to draw a horizontal rule through the middle of characters. Boolean may have any of the forms accepted by Tk_GetBoolean.

-relief relief
Relief specifies the 3-D relief to use for drawing backgrounds, in any of the forms accepted by Tk_GetRelief. This option is used in conjunction with the -borderwidth option to give a 3-D appearance to the background for characters; it is ignored unless the -background option has been set for the tag.

-rmargin pixels
If the first character of a display line has a tag for which this option has been specified, then pixels specifies how wide a margin to leave between the end of the line and the right edge of the window. Pixels may have any of the standard forms for screen distances. This option is only used when wrapping is enabled. If a text line wraps, the right margin for each line on the display is determined by the first character of that display line.

-spacing1 pixels
Pixels specifies how much additional space should be left above each text line, using any of the standard forms for screen distances. If a line wraps, this option only applies to the first line on the display.

-spacing2 pixels
For lines that wrap, this option specifies how much additional space to leave between the display lines for a single text line. Pixels may have any of the standard forms for screen distances.

-spacing3 pixels
Pixels specifies how much additional space should be left below each text line, using any of the standard forms for screen distances. If a line wraps, this option only applies to the last line on the display.

-tabs tabList
TabList specifies a set of tab stops in the same form as for the -tabs option for the text widget. This option only applies to a display line if it applies to the first character on that display line. If this option is specified as an empty string, it cancels the option, leaving it unspecified for the tag (the default). If the option is specified as a non-empty string that is an empty list, such as -tags { }, then it requests default 8-character tabs as described for the tags widget option.

-underline boolean
Boolean specifies whether or not to draw an underline underneath characters. It may have any of the forms accepted by Tk_GetBoolean.

-wrap mode
Mode specifies how to handle lines that are wider than the text's window. It has the same legal values as the -wrap option for the text widget: none, char, or word. If this tag option is specified, it overrides the -wrap option for the text widget.

If a character has several tags associated with it, and if their display options conflict, then the options of the highest priority tag are used. If a particular display option hasn't been specified for a particular tag, or if it is specified as an empty string, then that option will never be used; the next-highest-priority tag's option will used instead. If no tag specifies a particular display option, then the default style for the widget will be used.

The second purpose for tags is event bindings. You can associate bindings with a tag in much the same way you can associate bindings with a widget class: whenever particular X events occur on characters with the given tag, a given Tcl command will be executed. Tag bindings can be used to give behaviors to ranges of characters; among other things, this allows hypertext-like features to be implemented. For details, see the description of the tag bind widget command below.

The third use for tags is in managing the selection. See THE SELECTION below.

MARKS

The second form of annotation in text widgets is a mark. Marks are used for remembering particular places in a text. They are something like tags, in that they have names and they refer to places in the file, but a mark isn't associated with particular characters. Instead, a mark is associated with the gap between two characters. Only a single position may be associated with a mark at any given time. If the characters around a mark are deleted the mark will still remain; it will just have new neighbor characters. In contrast, if the characters containing a tag are deleted then the tag will no longer have an association with characters in the file. Marks may be manipulated with the ``pathName mark'' widget command, and their current locations may be determined by using the mark name as an index in widget commands.

Each mark also has a gravity, which is either left or right. The gravity for a mark specifies what happens to the mark when text is inserted at the point of the mark. If a mark has left gravity, then the mark is treated as if it were attached to the character on its left, so the mark will remain to the left of any text inserted at the mark position. If the mark has right gravity, new text inserted at the mark position will appear to the left of the mark (so that the mark remains rightmost). The gravity for a mark defaults to right.

The name space for marks is different from that for tags: the same name may be used for both a mark and a tag, but they will refer to different things.

Two marks have special significance. First, the mark insert is associated with the insertion cursor, as described under THE INSERTION CURSOR below. Second, the mark current is associated with the character closest to the mouse and is adjusted automatically to track the mouse position and any changes to the text in the widget (one exception: current is not updated in response to mouse motions if a mouse button is down; the update will be deferred until all mouse buttons have been released). Neither of these special marks may be deleted.

EMBEDDED WINDOWS

The third form of annotation in text widgets is an embedded window. Each embedded window annotation causes a window to be displayed at a particular point in the text. There may be any number of embedded windows in a text widget, and any widget may be used as an embedded window (subject to the usual rules for geometry management, which require the text window to be the parent of the embedded window or a descendant of its parent). The embedded window's position on the screen will be updated as the text is modified or scrolled, and it will be mapped and unmapped as it moves into and out of the visible area of the text widget. Each embedded window occupies one character's worth of index space in the text widget, and it may be referred to either by the name of its embedded window or by its position in the widget's index space. If the range of text containing the embedded window is deleted then the window is destroyed.

When an embedded window is added to a text widget with the window create widget command, several configuration options may be associated with it. These options may be modified later with the window configure widget command. The following options are currently supported:

-align where
If the window is not as tall as the line in which it is displayed, this option determines where the window is displayed in the line. Where must have one of the values top (align the top of the window with the top of the line), center (center the window within the range of the line), bottom (align the bottom of the window with the bottom of the line's area), or baseline (align the bottom of the window with the baseline of the line).

-create script
Specifies a Tcl script that may be evaluated to create the window for the annotation. If no -window option has been specified for the annotation this script will be evaluated when the annotation is about to be displayed on the screen. Script must create a window for the annotation and return the name of that window as its result. If the annotation's window should ever be deleted, script will be evaluated again the next time the annotation is displayed.

-padx pixels
Pixels specifies the amount of extra space to leave on each side of the embedded window. It may have any of the usual forms defined for a screen distance.

-pady pixels
Pixels specifies the amount of extra space to leave on the top and on the bottom of the embedded window. It may have any of the usual forms defined for a screen distance.

-stretch boolean
If the requested height of the embedded window is less than the height of the line in which it is displayed, this option can be used to specify whether the window should be stretched vertically to fill its line. If the -pady option has been specified as well, then the requested padding will be retained even if the window is stretched.

-window pathName
Specifies the name of a window to display in the annotation.

EMBEDDED IMAGES

The final form of annotation in text widgets is an embedded image. Each embedded image annotation causes an image to be displayed at a particular point in the text. There may be any number of embedded images in a text widget, and a particular image may be embedded in multiple places in the same text widget. The embedded image's position on the screen will be updated as the text is modified or scrolled. Each embedded image occupies one character's worth of index space in the text widget, and it may be referred to either by its position in the widget's index space, or the name it is assigned when the image is inserted into the text widget widh image create. If the range of text containing the embedded image is deleted then that copy of the image is removed from the screen.

When an embedded image is added to a text widget with the image create widget command, a name unique to this instance of the image is returned. This name may then be used to refer to this image instance. The name is taken to be the value of the -name option (described below). If the -name option is not provided, the -image name is used instead. If the imageName is already in use in the text widget, then #nn is added to the end of the imageName, where nn is an arbitrary integer. This insures the imageName is unique. Once this name is assigned to this instance of the image, it does not change, even though the -image or -name values can be changed with image configure.

When an embedded image is added to a text widget with the image create widget command, several configuration options may be associated with it. These options may be modified later with the image configure widget command. The following options are currently supported:

-align where
If the image is not as tall as the line in which it is displayed, this option determines where the image is displayed in the line. Where must have one of the values top (align the top of the image with the top of the line), center (center the image within the range of the line), bottom (align the bottom of the image with the bottom of the line's area), or baseline (align the bottom of the image with the baseline of the line).

-image image
Specifies the name of the Tk image to display in the annotation. If image is not a valid Tk image, then an error is returned.

-name ImageName
Specifies the name by which this image instance may be referenced in the text widget. If ImageName is not supplied, then the name of the Tk image is used instead. If the imageName is already in use, #nn is appended to the end of the name as described above.

-padx pixels
Pixels specifies the amount of extra space to leave on each side of the embedded image. It may have any of the usual forms defined for a screen distance.

-pady pixels
Pixels specifies the amount of extra space to leave on the top and on the bottom of the embedded image. It may have any of the usual forms defined for a screen distance.

THE SELECTION

Selection support is implemented via tags. If the exportSelection option for the text widget is true then the sel tag will be associated with the selection:

[1]
Whenever characters are tagged with sel the text widget will claim ownership of the selection.

[2]
Attempts to retrieve the selection will be serviced by the text widget, returning all the characters with the sel tag.

[3]
If the selection is claimed away by another application or by another window within this application, then the sel tag will be removed from all characters in the text.

The sel tag is automatically defined when a text widget is created, and it may not be deleted with the ``pathName tag delete'' widget command. Furthermore, the selectBackground, selectBorderWidth, and selectForeground options for the text widget are tied to the -background, -borderwidth, and -foreground options for the sel tag: changes in either will automatically be reflected in the other.

THE INSERTION CURSOR

The mark named insert has special significance in text widgets. It is defined automatically when a text widget is created and it may not be unset with the ``pathName mark unset'' widget command. The insert mark represents the position of the insertion cursor, and the insertion cursor will automatically be drawn at this point whenever the text widget has the input focus.

WIDGET COMMAND

The text command creates a new Tcl command whose name is the same as the path name of the text's window. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
PathName is the name of the command, which is the same as the text widget's path name. Option and the args determine the exact behavior of the command. The following commands are possible for text widgets:

pathName bbox index
Returns a list of four elements describing the screen area of the character given by index. The first two elements of the list give the x and y coordinates of the upper-left corner of the area occupied by the character, and the last two elements give the width and height of the area. If the character is only partially visible on the screen, then the return value reflects just the visible part. If the character is not visible on the screen then the return value is an empty list.

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the text command.

pathName compare index1 op index2
Compares the indices given by index1 and index2 according to the relational operator given by op, and returns 1 if the relationship is satisfied and 0 if it isn't. Op must be one of the operators <, <=, ==, >=, >, or !=. If op is == then 1 is returned if the two indices refer to the same character, if op is < then 1 is returned if index1 refers to an earlier character in the text than index2, and so on.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the text command.

pathName debug ?boolean?
If boolean is specified, then it must have one of the true or false values accepted by Tcl_GetBoolean. If the value is a true one then internal consistency checks will be turned on in the B-tree code associated with text widgets. If boolean has a false value then the debugging checks will be turned off. In either case the command returns an empty string. If boolean is not specified then the command returns on or off to indicate whether or not debugging is turned on. There is a single debugging switch shared by all text widgets: turning debugging on or off in any widget turns it on or off for all widgets. For widgets with large amounts of text, the consistency checks may cause a noticeable slow-down.

pathName delete index1 ?index2?
Delete a range of characters from the text. If both index1 and index2 are specified, then delete all the characters starting with the one given by index1 and stopping just before index2 (i.e. the character at index2 is not deleted). If index2 doesn't specify a position later in the text than index1 then no characters are deleted. If index2 isn't specified then the single character at index1 is deleted. It is not allowable to delete characters in a way that would leave the text without a newline as the last character. The command returns an empty string.

pathName dlineinfo index
Returns a list with five elements describing the area occupied by the display line containing index. The first two elements of the list give the x and y coordinates of the upper-left corner of the area occupied by the line, the third and fourth elements give the width and height of the area, and the fifth element gives the position of the baseline for the line, measured down from the top of the area. All of this information is measured in pixels. If the current wrap mode is none and the line extends beyond the boundaries of the window, the area returned reflects the entire area of the line, including the portions that are out of the window. If the line is shorter than the full width of the window then the area returned reflects just the portion of the line that is occupied by characters and embedded windows. If the display line containing index is not visible on the screen then the return value is an empty list.

pathName dump ?switches? index1 ?index2?
Return the contents of the text widget from index1 up to, but not including index2, including the text and information about marks, tags, and embedded windows. If index2 is not specified, then it defaults to one character past index1. The information is returned in the following format:

key1 value1 index1 key2 value2 index2 ...

The possible key values are text, mark, tagon, tagoff, and window. The corresponding value is the text, mark name, tag name, or window name. The index information is the index of the start of the text, the mark, the tag transition, or the window. One or more of the following switches (or abbreviations thereof) may be specified to control the dump:

-all
Return information about all elements: text, marks, tags, images and windows. This is the default.

-command command
Instead of returning the information as the result of the dump operation, invoke the command on each element of the text widget within the range. The command has three arguments appended to it before it is evaluated: the key, value, and index.

-image
Include information about images in the dump results.

-mark
Include information about marks in the dump results.

-tag
Include information about tag transitions in the dump results. Tag information is returned as tagon and tagoff elements that indicate the begin and end of each range of each tag, respectively.

-text
Include information about text in the dump results. The value is the text up to the next element or the end of range indicated by index2. A text element does not span newlines. A multi-line block of text that contains no marks or tag transitions will still be dumped as a set of text seqments that each end with a newline. The newline is part of the value.

-window
Include information about embedded windows in the dump results. The value of a window is its Tk pathname, unless the window has not been created yet. (It must have a create script.) In this case an empty string is returned, and you must query the window by its index position to get more information.

pathName get index1 ?index2?
Return a range of characters from the text. The return value will be all the characters in the text starting with the one whose index is index1 and ending just before the one whose index is index2 (the character at index2 will not be returned). If index2 is omitted then the single character at index1 is returned. If there are no characters in the specified range (e.g. index1 is past the end of the file or index2 is less than or equal to index1) then an empty string is returned. If the specified range contains embedded windows, no information about them is included in the returned string.

pathName image option ?arg arg ...?
This command is used to manipulate embedded images. The behavior of the command depends on the option argument that follows the tag argument. The following forms of the command are currently supported:

pathName image cget index option
Returns the value of a configuration option for an embedded image. Index identifies the embedded image, and option specifies a particular configuration option, which must be one of the ones listed in the section EMBEDDED IMAGES.

pathName image configure index ?option value ...?
Query or modify the configuration options for an embedded image. If no option is specified, returns a list describing all of the available options for the embedded image at index (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. See EMBEDDED IMAGES for information on the options that are supported.

pathName image create index ?option value ...?
This command creates a new image annotation, which will appear in the text at the position given by index. Any number of option-value pairs may be specified to configure the annotation. Returns a unique identifier that may be used as an index to refer to this image. See EMBEDDED IMAGES for information on the options that are supported, and a description of the identifier returned.

pathName image names
Returns a list whose elements are the names of all image instances currently embedded in window.

pathName index index
Returns the position corresponding to index in the form line.char where line is the line number and char is the character number. Index may have any of the forms described under INDICES above.

pathName insert index chars ?tagList chars tagList ...?
Inserts all of the chars arguments just before the character at index. If index refers to the end of the text (the character after the last newline) then the new text is inserted just before the last newline instead. If there is a single chars argument and no tagList, then the new text will receive any tags that are present on both the character before and the character after the insertion point; if a tag is present on only one of these characters then it will not be applied to the new text. If tagList is specified then it consists of a list of tag names; the new characters will receive all of the tags in this list and no others, regardless of the tags present around the insertion point. If multiple chars-tagList argument pairs are present, they produce the same effect as if a separate insert widget command had been issued for each pair, in order. The last tagList argument may be omitted.

pathName mark option ?arg arg ...?
This command is used to manipulate marks. The exact behavior of the command depends on the option argument that follows the mark argument. The following forms of the command are currently supported:

pathName mark gravity markName ?direction?
If direction is not specified, returns left or right to indicate which of its adjacent characters markName is attached to. If direction is specified, it must be left or right; the gravity of markName is set to the given value.

pathName mark names
Returns a list whose elements are the names of all the marks that are currently set.

pathName mark next index
Returns the name of the next mark at or after index. If index is specified in numerical form, then the search for the next mark begins at that index. If index is the name of a mark, then the search for the next mark begins immediately after that mark. This can still return a mark at the same position if there are multiple marks at the same index. These semantics mean that the mark next operation can be used to step through all the marks in a text widget in the same order as the mark information returned by the dump operation. If a mark has been set to the special end index, then it appears to be after end with respect to the mark next operation. An empty string is returned if there are no marks after index.

pathName mark previous index
Returns the name of the mark at or before index. If index is specified in numerical form, then the search for the previous mark begins with the character just before that index. If index is the name of a mark, then the search for the next mark begins immediately before that mark. This can still return a mark at the same position if there are multiple marks at the same index. These semantics mean that the mark previous operation can be used to step through all the marks in a text widget in the reverse order as the mark information returned by the dump operation. An empty string is returned if there are no marks before index.

pathName mark set markName index
Sets the mark named markName to a position just before the character at index. If markName already exists, it is moved from its old position; if it doesn't exist, a new mark is created. This command returns an empty string.

pathName mark unset markName ?markName markName ...?
Remove the mark corresponding to each of the markName arguments. The removed marks will not be usable in indices and will not be returned by future calls to ``pathName mark names''. This command returns an empty string.

pathName scan option args
This command is used to implement scanning on texts. It has two forms, depending on option:

pathName scan mark x y
Records x and y and the current view in the text window, for use in conjunction with later scan dragto commands. Typically this command is associated with a mouse button press in the widget. It returns an empty string.

pathName scan dragto x y
This command computes the difference between its x and y arguments and the x and y arguments to the last scan mark command for the widget. It then adjusts the view by 10 times the difference in coordinates. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the text at high speed through the window. The return value is an empty string.

pathName search ?switches? pattern index ?stopIndex?
Searches the text in pathName starting at index for a range of characters that matches pattern. If a match is found, the index of the first character in the match is returned as result; otherwise an empty string is returned. One or more of the following switches (or abbreviations thereof) may be specified to control the search:

-forwards
The search will proceed forward through the text, finding the first matching range starting at or after the position given by index. This is the default.

-backwards
The search will proceed backward through the text, finding the matching range closest to index whose first character is before index.

-exact
Use exact matching: the characters in the matching range must be identical to those in pattern. This is the default.

-regexp
Treat pattern as a regular expression and match it against the text using the rules for regular expressions (see the regexp command for details).

-nocase
Ignore case differences between the pattern and the text.

-count varName
The argument following -count gives the name of a variable; if a match is found, the number of index positions between beginning and end of the matching range will be stored in the variable. If there are no embedded images or windows in the matching range, this is equivalent to the number of characters matched. In either case, the range matchIdx to matchIdx + $count chars will return the entire matched text.

-elide
Find elidden (hidden) text as well. By default only displayed text is searched.

- -
This switch has no effect except to terminate the list of switches: the next argument will be treated as pattern even if it starts with -.

The matching range must be entirely within a single line of text. For regular expression matching the newlines are removed from the ends of the lines before matching: use the $ feature in regular expressions to match the end of a line. For exact matching the newlines are retained. If stopIndex is specified, the search stops at that index: for forward searches, no match at or after stopIndex will be considered; for backward searches, no match earlier in the text than stopIndex will be considered. If stopIndex is omitted, the entire text will be searched: when the beginning or end of the text is reached, the search continues at the other end until the starting location is reached again; if stopIndex is specified, no wrap-around will occur.

pathName see index
Adjusts the view in the window so that the character given by index is completely visible. If index is already visible then the command does nothing. If index is a short distance out of view, the command adjusts the view just enough to make index visible at the edge of the window. If index is far out of view, then the command centers index in the window.

pathName tag option ?arg arg ...?
This command is used to manipulate tags. The exact behavior of the command depends on the option argument that follows the tag argument. The following forms of the command are currently supported:

pathName tag add tagName index1 ?index2 index1 index2 ...?
Associate the tag tagName with all of the characters starting with index1 and ending just before index2 (the character at index2 isn't tagged). A single command may contain any number of index1-index2 pairs. If the last index2 is omitted then the single character at index1 is tagged. If there are no characters in the specified range (e.g. index1 is past the end of the file or index2 is less than or equal to index1) then the command has no effect.

pathName tag bind tagName ?sequence? ?script?
This command associates script with the tag given by tagName. Whenever the event sequence given by sequence occurs for a character that has been tagged with tagName, the script will be invoked. This widget command is similar to the bind command except that it operates on characters in a text rather than entire widgets. See the bind manual entry for complete details on the syntax of sequence and the substitutions performed on script before invoking it. If all arguments are specified then a new binding is created, replacing any existing binding for the same sequence and tagName (if the first character of script is ``+'' then script augments an existing binding rather than replacing it). In this case the return value is an empty string. If script is omitted then the command returns the script associated with tagName and sequence (an error occurs if there is no such binding). If both script and sequence are omitted then the command returns a list of all the sequences for which bindings have been defined for tagName.

The only events for which bindings may be specified are those related to the mouse and keyboard (such as Enter, Leave, ButtonPress, Motion, and KeyPress) or virtual events. Event bindings for a text widget use the current mark described under MARKS above. An Enter event triggers for a tag when the tag first becomes present on the current character, and a Leave event triggers for a tag when it ceases to be present on the current character. Enter and Leave events can happen either because the current mark moved or because the character at that position changed. Note that these events are different than Enter and Leave events for windows. Mouse and keyboard events are directed to the current character. If a virtual event is used in a binding, that binding can trigger only if the virtual event is defined by an underlying mouse-related or keyboard-related event.

It is possible for the current character to have multiple tags, and for each of them to have a binding for a particular event sequence. When this occurs, one binding is invoked for each tag, in order from lowest-priority to highest priority. If there are multiple matching bindings for a single tag, then the most specific binding is chosen (see the manual entry for the bind command for details). continue and break commands within binding scripts are processed in the same way as for bindings created with the bind command.

If bindings are created for the widget as a whole using the bind command, then those bindings will supplement the tag bindings. The tag bindings will be invoked first, followed by bindings for the window as a whole.

pathName tag cget tagName option
This command returns the current value of the option named option associated with the tag given by tagName. Option may have any of the values accepted by the tag configure widget command.

pathName tag configure tagName ?option? ?value? ?option value ...?
This command is similar to the configure widget command except that it modifies options associated with the tag given by tagName instead of modifying options for the overall text widget. If no option is specified, the command returns a list describing all of the available options for tagName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s) in tagName; in this case the command returns an empty string. See TAGS above for details on the options available for tags.

pathName tag delete tagName ?tagName ...?
Deletes all tag information for each of the tagName arguments. The command removes the tags from all characters in the file and also deletes any other information associated with the tags, such as bindings and display information. The command returns an empty string.

pathName tag lower tagName ?belowThis?
Changes the priority of tag tagName so that it is just lower in priority than the tag whose name is belowThis. If belowThis is omitted, then tagName's priority is changed to make it lowest priority of all tags.

pathName tag names ?index?
Returns a list whose elements are the names of all the tags that are active at the character position given by index. If index is omitted, then the return value will describe all of the tags that exist for the text (this includes all tags that have been named in a ``pathName tag'' widget command but haven't been deleted by a ``pathName tag delete'' widget command, even if no characters are currently marked with the tag). The list will be sorted in order from lowest priority to highest priority.

pathName tag nextrange tagName index1 ?index2?
This command searches the text for a range of characters tagged with tagName where the first character of the range is no earlier than the character at index1 and no later than the character just before index2 (a range starting at index2 will not be considered). If several matching ranges exist, the first one is chosen. The command's return value is a list containing two elements, which are the index of the first character of the range and the index of the character just after the last one in the range. If no matching range is found then the return value is an empty string. If index2 is not given then it defaults to the end of the text.

pathName tag prevrange tagName index1 ?index2?
This command searches the text for a range of characters tagged with tagName where the first character of the range is before the character at index1 and no earlier than the character at index2 (a range starting at index2 will be considered). If several matching ranges exist, the one closest to index1 is chosen. The command's return value is a list containing two elements, which are the index of the first character of the range and the index of the character just after the last one in the range. If no matching range is found then the return value is an empty string. If index2 is not given then it defaults to the beginning of the text.

pathName tag raise tagName ?aboveThis?
Changes the priority of tag tagName so that it is just higher in priority than the tag whose name is aboveThis. If aboveThis is omitted, then tagName's priority is changed to make it highest priority of all tags.

pathName tag ranges tagName
Returns a list describing all of the ranges of text that have been tagged with tagName. The first two elements of the list describe the first tagged range in the text, the next two elements describe the second range, and so on. The first element of each pair contains the index of the first character of the range, and the second element of the pair contains the index of the character just after the last one in the range. If there are no characters tagged with tag then an empty string is returned.

pathName tag remove tagName index1 ?index2 index1 index2 ...?
Remove the tag tagName from all of the characters starting at index1 and ending just before index2 (the character at index2 isn't affected). A single command may contain any number of index1-index2 pairs. If the last index2 is omitted then the single character at index1 is tagged. If there are no characters in the specified range (e.g. index1 is past the end of the file or index2 is less than or equal to index1) then the command has no effect. This command returns an empty string.

pathName window option ?arg arg ...?
This command is used to manipulate embedded windows. The behavior of the command depends on the option argument that follows the tag argument. The following forms of the command are currently supported:

pathName window cget index option
Returns the value of a configuration option for an embedded window. Index identifies the embedded window, and option specifies a particular configuration option, which must be one of the ones listed in the section EMBEDDED WINDOWS.

pathName window configure index ?option value ...?
Query or modify the configuration options for an embedded window. If no option is specified, returns a list describing all of the available options for the embedded window at index (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. See EMBEDDED WINDOWS for information on the options that are supported.

pathName window create index ?option value ...?
This command creates a new window annotation, which will appear in the text at the position given by index. Any number of option-value pairs may be specified to configure the annotation. See EMBEDDED WINDOWS for information on the options that are supported. Returns an empty string.

pathName window names
Returns a list whose elements are the names of all windows currently embedded in window.

pathName xview option args
This command is used to query and change the horizontal position of the text in the widget's window. It can take any of the following forms:

pathName xview
Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the portion of the document's horizontal span that is visible in the window. For example, if the first element is .2 and the second element is .6, 20% of the text is off-screen to the left, the middle 40% is visible in the window, and 40% of the text is off-screen to the right. The fractions refer only to the lines that are actually visible in the window: if the lines in the window are all very short, so that they are entirely visible, the returned fractions will be 0 and 1, even if there are other lines in the text that are much wider than the window. These are the same values passed to scrollbars via the -xscrollcommand option.

pathName xview moveto fraction
Adjusts the view in the window so that fraction of the horizontal span of the text is off-screen to the left. Fraction is a fraction between 0 and 1.

pathName xview scroll number what
This command shifts the view in the window left or right according to number and what. Number must be an integer. What must be either units or pages or an abbreviation of one of these. If what is units, the view adjusts left or right by number average-width characters on the display; if it is pages then the view adjusts by number screenfuls. If number is negative then characters farther to the left become visible; if it is positive then characters farther to the right become visible.

pathName yview ?args?
This command is used to query and change the vertical position of the text in the widget's window. It can take any of the following forms:

pathName yview
Returns a list containing two elements, both of which are real fractions between 0 and 1. The first element gives the position of the first character in the top line in the window, relative to the text as a whole (0.5 means it is halfway through the text, for example). The second element gives the position of the character just after the last one in the bottom line of the window, relative to the text as a whole. These are the same values passed to scrollbars via the -yscrollcommand option.

pathName yview moveto fraction
Adjusts the view in the window so that the character given by fraction appears on the top line of the window. Fraction is a fraction between 0 and 1; 0 indicates the first character in the text, 0.33 indicates the character one-third the way through the text, and so on.

pathName yview scroll number what
This command adjust the view in the window up or down according to number and what. Number must be an integer. What must be either units or pages. If what is units, the view adjusts up or down by number lines on the display; if it is pages then the view adjusts by number screenfuls. If number is negative then earlier positions in the text become visible; if it is positive then later positions in the text become visible.

pathName yview ?-pickplace? index
Changes the view in the widget's window to make index visible. If the -pickplace option isn't specified then index will appear at the top of the window. If -pickplace is specified then the widget chooses where index appears in the window:

[1]
If index is already visible somewhere in the window then the command does nothing.

[2]
If index is only a few lines off-screen above the window then it will be positioned at the top of the window.

[3]
If index is only a few lines off-screen below the window then it will be positioned at the bottom of the window.

[4]
Otherwise, index will be centered in the window.

The -pickplace option has been obsoleted by the see widget command (see handles both x- and y-motion to make a location visible, whereas -pickplace only handles motion in y).

pathName yview number
This command makes the first character on the line after the one given by number visible at the top of the window. Number must be an integer. This command used to be used for scrolling, but now it is obsolete.

BINDINGS

Tk automatically creates class bindings for texts that give them the following default behavior. In the descriptions below, ``word'' is dependent on the value of the tcl_wordchars variable. See tclvars(n).

[1]
Clicking mouse button 1 positions the insertion cursor just before the character underneath the mouse cursor, sets the input focus to this widget, and clears any selection in the widget. Dragging with mouse button 1 strokes out a selection between the insertion cursor and the character under the mouse.

[2]
Double-clicking with mouse button 1 selects the word under the mouse and positions the insertion cursor at the beginning of the word. Dragging after a double click will stroke out a selection consisting of whole words.

[3]
Triple-clicking with mouse button 1 selects the line under the mouse and positions the insertion cursor at the beginning of the line. Dragging after a triple click will stroke out a selection consisting of whole lines.

[4]
The ends of the selection can be adjusted by dragging with mouse button 1 while the Shift key is down; this will adjust the end of the selection that was nearest to the mouse cursor when button 1 was pressed. If the button is double-clicked before dragging then the selection will be adjusted in units of whole words; if it is triple-clicked then the selection will be adjusted in units of whole lines.

[5]
Clicking mouse button 1 with the Control key down will reposition the insertion cursor without affecting the selection.

[6]
If any normal printing characters are typed, they are inserted at the point of the insertion cursor.

[7]
The view in the widget can be adjusted by dragging with mouse button 2. If mouse button 2 is clicked without moving the mouse, the selection is copied into the text at the position of the mouse cursor. The Insert key also inserts the selection, but at the position of the insertion cursor.

[8]
If the mouse is dragged out of the widget while button 1 is pressed, the entry will automatically scroll to make more text visible (if there is more text off-screen on the side where the mouse left the window).

[9]
The Left and Right keys move the insertion cursor one character to the left or right; they also clear any selection in the text. If Left or Right is typed with the Shift key down, then the insertion cursor moves and the selection is extended to include the new character. Control-Left and Control-Right move the insertion cursor by words, and Control-Shift-Left and Control-Shift-Right move the insertion cursor by words and also extend the selection. Control-b and Control-f behave the same as Left and Right, respectively. Meta-b and Meta-f behave the same as Control-Left and Control-Right, respectively.

[10]
The Up and Down keys move the insertion cursor one line up or down and clear any selection in the text. If Up or Right is typed with the Shift key down, then the insertion cursor moves and the selection is extended to include the new character. Control-Up and Control-Down move the insertion cursor by paragraphs (groups of lines separated by blank lines), and Control-Shift-Up and Control-Shift-Down move the insertion cursor by paragraphs and also extend the selection. Control-p and Control-n behave the same as Up and Down, respectively.

[11]
The Next and Prior keys move the insertion cursor forward or backwards by one screenful and clear any selection in the text. If the Shift key is held down while Next or Prior is typed, then the selection is extended to include the new character. Control-v moves the view down one screenful without moving the insertion cursor or adjusting the selection.

[12]
Control-Next and Control-Prior scroll the view right or left by one page without moving the insertion cursor or affecting the selection.

[13]
Home and Control-a move the insertion cursor to the beginning of its line and clear any selection in the widget. Shift-Home moves the insertion cursor to the beginning of the line and also extends the selection to that point.

[14]
End and Control-e move the insertion cursor to the end of the line and clear any selection in the widget. Shift-End moves the cursor to the end of the line and extends the selection to that point.

[15]
Control-Home and Meta-< move the insertion cursor to the beginning of the text and clear any selection in the widget. Control-Shift-Home moves the insertion cursor to the beginning of the text and also extends the selection to that point.

[16]
Control-End and Meta-> move the insertion cursor to the end of the text and clear any selection in the widget. Control-Shift-End moves the cursor to the end of the text and extends the selection to that point.

[17]
The Select key and Control-Space set the selection anchor to the position of the insertion cursor. They don't affect the current selection. Shift-Select and Control-Shift-Space adjust the selection to the current position of the insertion cursor, selecting from the anchor to the insertion cursor if there was not any selection previously.

[18]
Control-/ selects the entire contents of the widget.

[19]
Control-\ clears any selection in the widget.

[20]
The F16 key (labelled Copy on many Sun workstations) or Meta-w copies the selection in the widget to the clipboard, if there is a selection.

[21]
The F20 key (labelled Cut on many Sun workstations) or Control-w copies the selection in the widget to the clipboard and deletes the selection. If there is no selection in the widget then these keys have no effect.

[22]
The F18 key (labelled Paste on many Sun workstations) or Control-y inserts the contents of the clipboard at the position of the insertion cursor.

[23]
The Delete key deletes the selection, if there is one in the widget. If there is no selection, it deletes the character to the right of the insertion cursor.

[24]
Backspace and Control-h delete the selection, if there is one in the widget. If there is no selection, they delete the character to the left of the insertion cursor.

[25]
Control-d deletes the character to the right of the insertion cursor.

[26]
Meta-d deletes the word to the right of the insertion cursor.

[27]
Control-k deletes from the insertion cursor to the end of its line; if the insertion cursor is already at the end of a line, then Control-k deletes the newline character.

[28]
Control-o opens a new line by inserting a newline character in front of the insertion cursor without moving the insertion cursor.

[29]
Meta-backspace and Meta-Delete delete the word to the left of the insertion cursor.

[30]
Control-x deletes whatever is selected in the text widget.

[31]
Control-t reverses the order of the two characters to the right of the insertion cursor.

If the widget is disabled using the -state option, then its view can still be adjusted and text can still be selected, but no insertion cursor will be displayed and no text modifications will take place.

The behavior of texts can be changed by defining new bindings for individual widgets or by redefining the class bindings.

PERFORMANCE ISSUES

Text widgets should run efficiently under a variety of conditions. The text widget uses about 2-3 bytes of main memory for each byte of text, so texts containing a megabyte or more should be practical on most workstations. Text is represented internally with a modified B-tree structure that makes operations relatively efficient even with large texts. Tags are included in the B-tree structure in a way that allows tags to span large ranges or have many disjoint smaller ranges without loss of efficiency. Marks are also implemented in a way that allows large numbers of marks. In most cases it is fine to have large numbers of unique tags, or a tag that has many distinct ranges.

One performance problem can arise if you have hundreds or thousands of different tags that all have the following characteristics: the first and last ranges of each tag are near the beginning and end of the text, respectively, or a single tag range covers most of the text widget. The cost of adding and deleting tags like this is proportional to the number of other tags with the same properties. In contrast, there is no problem with having thousands of distinct tags if their overall ranges are localized and spread uniformly throughout the text.

Very long text lines can be expensive, especially if they have many marks and tags within them.

The display line with the insert cursor is redrawn each time the cursor blinks, which causes a steady stream of graphics traffic. Set the insertOffTime attribute to 0 avoid this.

KEYWORDS

text, widget
Copyright © 1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tk manual page

NAME

tk - Manipulate Tk internal state

SYNOPSIS

tk option ?arg arg ...?

DESCRIPTION

The tk command provides access to miscellaneous elements of Tk's internal state. Most of the information manipulated by this command pertains to the application as a whole, or to a screen or display, rather than to a particular window. The command can take any of a number of different forms depending on the option argument. The legal forms are:

tk appname ?newName?
If newName isn't specified, this command returns the name of the application (the name that may be used in send commands to communicate with the application). If newName is specified, then the name of the application is changed to newName. If the given name is already in use, then a suffix of the form `` #2'' or `` #3'' is appended in order to make the name unique. The command's result is the name actually chosen. newName should not start with a capital letter. This will interfere with option processing, since names starting with capitals are assumed to be classes; as a result, Tk may not be able to find some options for the application. If sends have been disabled by deleting the send command, this command will reenable them and recreate the send command.

tk scaling ?-displayof window? ?number?
Sets and queries the current scaling factor used by Tk to convert between physical units (for example, points, inches, or millimeters) and pixels. The number argument is a floating point number that specifies the number of pixels per point on window's display. If the window argument is omitted, it defaults to the main window. If the number argument is omitted, the current value of the scaling factor is returned.

A ``point'' is a unit of measurement equal to 1/72 inch. A scaling factor of 1.0 corresponds to 1 pixel per point, which is equivalent to a standard 72 dpi monitor. A scaling factor of 1.25 would mean 1.25 pixels per point, which is the setting for a 90 dpi monitor; setting the scaling factor to 1.25 on a 72 dpi monitor would cause everything in the application to be displayed 1.25 times as large as normal. The initial value for the scaling factor is set when the application starts, based on properties of the installed monitor, but it can be changed at any time. Measurements made after the scaling factor is changed will use the new scaling factor, but it is undefined whether existing widgets will resize themselves dynamically to accomodate the new scaling factor.

tk useinputmethods ?-displayof window? ?boolean?
Sets and queries the state of whether Tk should use XIM (X Input Methods) for filtering events. The resulting state is returned. XIM is used in some locales (ie: Japanese, Korean), to handle special input devices. This feature is only significant on X. If XIM support is not available, this will always return 0. If the window argument is omitted, it defaults to the main window. If the boolean argument is omitted, the current state is returned. This is turned on by default for the main display.

KEYWORDS

application name, send
Copyright © 1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tkerror manual page

NAME

tkerror - Command invoked to process background errors

SYNOPSIS

tkerror message

DESCRIPTION

Note: as of Tk 4.1 the tkerror command has been renamed to bgerror because the event loop (which is what usually invokes it) is now part of Tcl. For backward compatibility the bgerror provided by the current Tk version still tries to call tkerror if there is one (or an auto loadable one), so old script defining that error handler should still work, but you should anyhow modify your scripts to use bgerror instead of tkerror because that support for the old name might vanish in the near future. If that call fails, bgerror posts a dialog showing the error and offering to see the stack trace to the user. If you want your own error management you should directly override bgerror instead of tkerror. Documentation for bgerror is available as part of Tcl's documentation.

KEYWORDS

background error, reporting
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - tkvars manual page

NAME

tkvars - Variables used or set by Tk

DESCRIPTION

The following Tcl variables are either set or used by Tk at various times in its execution:

tk_library
This variable holds the file name for a directory containing a library of Tcl scripts related to Tk. These scripts include an initialization file that is normally processed whenever a Tk application starts up, plus other files containing procedures that implement default behaviors for widgets. The initial value of tcl_library is set when Tk is added to an interpreter; this is done by searching several different directories until one is found that contains an appropriate Tk startup script. If the TK_LIBRARY environment variable exists, then the directory it names is checked first. If TK_LIBRARY isn't set or doesn't refer to an appropriate directory, then Tk checks several other directories based on a compiled-in default location, the location of the Tcl library directory, the location of the binary containing the application, and the current working directory. The variable can be modified by an application to switch to a different library.

tk_patchLevel
Contains a decimal integer giving the current patch level for Tk. The patch level is incremented for each new release or patch, and it uniquely identifies an official version of Tk.

tkPriv
This variable is an array containing several pieces of information that are private to Tk. The elements of tkPriv are used by Tk library procedures and default bindings. They should not be accessed by any code outside Tk.

tk_strictMotif
This variable is set to zero by default. If an application sets it to one, then Tk attempts to adhere as closely as possible to Motif look-and-feel standards. For example, active elements such as buttons and scrollbar sliders will not change color when the pointer passes over them.

tk_version
Tk sets this variable in the interpreter for each application. The variable holds the current version number of the Tk library in the form major.minor. Major and minor are integers. The major version number increases in any Tk release that includes changes that are not backward compatible (i.e. whenever existing Tk applications and scripts may have to change to work with the new release). The minor version number increases with each new release of Tk, except that it resets to zero whenever the major version number changes.

KEYWORDS

variables, version
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Built-In Commands - tkwait manual page

NAME

tkwait - Wait for variable to change or window to be destroyed

SYNOPSIS

tkwait variable name
tkwait visibility name
tkwait window name

DESCRIPTION

The tkwait command waits for one of several things to happen, then it returns without taking any other actions. The return value is always an empty string. If the first argument is variable (or any abbreviation of it) then the second argument is the name of a global variable and the command waits for that variable to be modified. If the first argument is visibility (or any abbreviation of it) then the second argument is the name of a window and the tkwait command waits for a change in its visibility state (as indicated by the arrival of a VisibilityNotify event). This form is typically used to wait for a newly-created window to appear on the screen before taking some action. If the first argument is window (or any abbreviation of it) then the second argument is the name of a window and the tkwait command waits for that window to be destroyed. This form is typically used to wait for a user to finish interacting with a dialog box before using the result of that interaction.

While the tkwait command is waiting it processes events in the normal fashion, so the application will continue to respond to user interactions. If an event handler invokes tkwait again, the nested call to tkwait must complete before the outer call can complete.

KEYWORDS

variable, visibility, wait, window
Copyright © 1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - toplevel manual page

NAME
toplevel - Create and manipulate toplevel widgets
SYNOPSIS
toplevel pathName ?options?
STANDARD OPTIONS
-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus
WIDGET-SPECIFIC OPTIONS
-background, background, Background
-class, class, Class
-colormap, colormap, Colormap
-container, container, Container
-height, height, Height
-menu, menu, Menu
-screen, ,
-use, use, Use
-visual, visual, Visual
-width, width, Width
DESCRIPTION
WIDGET COMMAND
pathName cget option
pathName configure ?option? ?value option value ...?
BINDINGS
KEYWORDS

NAME

toplevel - Create and manipulate toplevel widgets

SYNOPSIS

toplevel pathName ?options?

STANDARD OPTIONS

-borderwidth or -bd, borderWidth, BorderWidth
-cursor, cursor, Cursor
-highlightbackground, highlightBackground, HighlightBackground
-highlightcolor, highlightColor, HighlightColor
-highlightthickness, highlightThickness, HighlightThickness
-relief, relief, Relief
-takefocus, takeFocus, TakeFocus

WIDGET-SPECIFIC OPTIONS

Command-Line Name: -background
Database Name: background
Database Class: Background
This option is the same as the standard background option except that its value may also be specified as an empty string. In this case, the widget will display no background or border, and no colors will be consumed from its colormap for its background and border.

Command-Line Name: -class
Database Name: class
Database Class: Class
Specifies a class for the window. This class will be used when querying the option database for the window's other options, and it will also be used later for other purposes such as bindings. The class option may not be changed with the configure widget command.

Command-Line Name: -colormap
Database Name: colormap
Database Class: Colormap
Specifies a colormap to use for the window. The value may be either new, in which case a new colormap is created for the window and its children, or the name of another window (which must be on the same screen and have the same visual as pathName), in which case the new window will use the colormap from the specified window. If the colormap option is not specified, the new window uses the default colormap of its screen. This option may not be changed with the configure widget command.

Command-Line Name: -container
Database Name: container
Database Class: Container
The value must be a boolean. If true, it means that this window will be used as a container in which some other application will be embedded (for example, a Tk toplevel can be embedded using the -use option). The window will support the appropriate window manager protocols for things like geometry requests. The window should not have any children of its own in this application. This option may not be changed with the configure widget command.

Command-Line Name: -height
Database Name: height
Database Class: Height
Specifies the desired height for the window in any of the forms acceptable to Tk_GetPixels. If this option is less than or equal to zero then the window will not request any size at all.

Command-Line Name: -menu
Database Name: menu
Database Class: Menu
Specifies a menu widget to be used as a menubar. On the Macintosh, the menubar will be displayed accross the top of the main monitor. On Microsoft Windows and all UNIX platforms, the menu will appear accross the toplevel window as part of the window dressing maintained by the window manager.

Command-Line Name: -screen
Database Name:
Database Class:
Specifies the screen on which to place the new window. Any valid screen name may be used, even one associated with a different display. Defaults to the same screen as its parent. This option is special in that it may not be specified via the option database, and it may not be modified with the configure widget command.

Command-Line Name: -use
Database Name: use
Database Class: Use
This option is used for embedding. If the value isn't an empty string, it must be the the window identifier of a container window, specified as a hexadecimal string like the ones returned by the winfo id command. The toplevel widget will be created as a child of the given container instead of the root window for the screen. If the container window is in a Tk application, it must be a frame or toplevel widget for which the -container option was specified. This option may not be changed with the configure widget command.

Command-Line Name: -visual
Database Name: visual
Database Class: Visual
Specifies visual information for the new window in any of the forms accepted by Tk_GetVisual. If this option is not specified, the new window will use the default visual for its screen. The visual option may not be modified with the configure widget command.

Command-Line Name: -width
Database Name: width
Database Class: Width
Specifies the desired width for the window in any of the forms acceptable to Tk_GetPixels. If this option is less than or equal to zero then the window will not request any size at all.

DESCRIPTION

The toplevel command creates a new toplevel widget (given by the pathName argument). Additional options, described above, may be specified on the command line or in the option database to configure aspects of the toplevel such as its background color and relief. The toplevel command returns the path name of the new window.

A toplevel is similar to a frame except that it is created as a top-level window: its X parent is the root window of a screen rather than the logical parent from its path name. The primary purpose of a toplevel is to serve as a container for dialog boxes and other collections of widgets. The only visible features of a toplevel are its background color and an optional 3-D border to make the toplevel appear raised or sunken.

WIDGET COMMAND

The toplevel command creates a new Tcl command whose name is the same as the path name of the toplevel's window. This command may be used to invoke various operations on the widget. It has the following general form:
pathName option ?arg arg ...?
PathName is the name of the command, which is the same as the toplevel widget's path name. Option and the args determine the exact behavior of the command. The following commands are possible for toplevel widgets:

pathName cget option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the toplevel command.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option may have any of the values accepted by the toplevel command.

BINDINGS

When a new toplevel is created, it has no default event bindings: toplevels are not intended to be interactive.

KEYWORDS

toplevel, widget
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Built-In Commands - winfo manual page

NAME
winfo - Return window-related information
SYNOPSIS
winfo option ?arg arg ...?
DESCRIPTION
winfo atom ?-displayof window? name
winfo atomname ?-displayof window? id
winfo cells window
winfo children window
winfo class window
winfo colormapfull window
winfo containing ?-displayof window? rootX rootY
winfo depth window
winfo exists window
winfo fpixels window number
winfo geometry window
winfo height window
winfo id window
winfo interps ?-displayof window?
winfo ismapped window
winfo manager window
winfo name window
winfo parent window
winfo pathname ?-displayof window? id
winfo pixels window number
winfo pointerx window
winfo pointerxy window
winfo pointery window
winfo reqheight window
winfo reqwidth window
winfo rgb window color
winfo rootx window
winfo rooty window
winfo screen window
winfo screencells window
winfo screendepth window
winfo screenheight window
winfo screenmmheight window
winfo screenmmwidth window
winfo screenvisual window
winfo screenwidth window
winfo server window
winfo toplevel window
winfo viewable window
winfo visual window
winfo visualid window
winfo visualsavailable window ?includeids?
winfo vrootheight window
winfo vrootwidth window
winfo vrootx window
winfo vrooty window
winfo width window
winfo x window
winfo y window
KEYWORDS

NAME

winfo - Return window-related information

SYNOPSIS

winfo option ?arg arg ...?

DESCRIPTION

The winfo command is used to retrieve information about windows managed by Tk. It can take any of a number of different forms, depending on the option argument. The legal forms are:

winfo atom ?-displayof window? name
Returns a decimal string giving the integer identifier for the atom whose name is name. If no atom exists with the name name then a new one is created. If the -displayof option is given then the atom is looked up on the display of window; otherwise it is looked up on the display of the application's main window.

winfo atomname ?-displayof window? id
Returns the textual name for the atom whose integer identifier is id. If the -displayof option is given then the identifier is looked up on the display of window; otherwise it is looked up on the display of the application's main window. This command is the inverse of the winfo atom command. It generates an error if no such atom exists.

winfo cells window
Returns a decimal string giving the number of cells in the color map for window.

winfo children window
Returns a list containing the path names of all the children of window. The list is in stacking order, with the lowest window first. Top-level windows are returned as children of their logical parents.

winfo class window
Returns the class name for window.

winfo colormapfull window
Returns 1 if the colormap for window is known to be full, 0 otherwise. The colormap for a window is ``known'' to be full if the last attempt to allocate a new color on that window failed and this application hasn't freed any colors in the colormap since the failed allocation.

winfo containing ?-displayof window? rootX rootY
Returns the path name for the window containing the point given by rootX and rootY. RootX and rootY are specified in screen units (i.e. any form acceptable to Tk_GetPixels) in the coordinate system of the root window (if a virtual-root window manager is in use then the coordinate system of the virtual root window is used). If the -displayof option is given then the coordinates refer to the screen containing window; otherwise they refer to the screen of the application's main window. If no window in this application contains the point then an empty string is returned. In selecting the containing window, children are given higher priority than parents and among siblings the highest one in the stacking order is chosen.

winfo depth window
Returns a decimal string giving the depth of window (number of bits per pixel).

winfo exists window
Returns 1 if there exists a window named window, 0 if no such window exists.

winfo fpixels window number
Returns a floating-point value giving the number of pixels in window corresponding to the distance given by number. Number may be specified in any of the forms acceptable to Tk_GetScreenMM, such as ``2.0c'' or ``1i''. The return value may be fractional; for an integer value, use winfo pixels.

winfo geometry window
Returns the geometry for window, in the form width x height+x+y. All dimensions are in pixels.

winfo height window
Returns a decimal string giving window's height in pixels. When a window is first created its height will be 1 pixel; the height will eventually be changed by a geometry manager to fulfill the window's needs. If you need the true height immediately after creating a widget, invoke update to force the geometry manager to arrange it, or use winfo reqheight to get the window's requested height instead of its actual height.

winfo id window
Returns a hexadecimal string giving a low-level platform-specific identifier for window. On Unix platforms, this is the X window identifier. Under Windows, this is the Windows HWND. On the Macintosh the value has no meaning outside Tk.

winfo interps ?-displayof window?
Returns a list whose members are the names of all Tcl interpreters (e.g. all Tk-based applications) currently registered for a particular display. If the -displayof option is given then the return value refers to the display of window; otherwise it refers to the display of the application's main window.

winfo ismapped window
Returns 1 if window is currently mapped, 0 otherwise.

winfo manager window
Returns the name of the geometry manager currently responsible for window, or an empty string if window isn't managed by any geometry manager. The name is usually the name of the Tcl command for the geometry manager, such as pack or place. If the geometry manager is a widget, such as canvases or text, the name is the widget's class command, such as canvas.

winfo name window
Returns window's name (i.e. its name within its parent, as opposed to its full path name). The command winfo name . will return the name of the application.

winfo parent window
Returns the path name of window's parent, or an empty string if window is the main window of the application.

winfo pathname ?-displayof window? id
Returns the path name of the window whose X identifier is id. Id must be a decimal, hexadecimal, or octal integer and must correspond to a window in the invoking application. If the -displayof option is given then the identifier is looked up on the display of window; otherwise it is looked up on the display of the application's main window.

winfo pixels window number
Returns the number of pixels in window corresponding to the distance given by number. Number may be specified in any of the forms acceptable to Tk_GetPixels, such as ``2.0c'' or ``1i''. The result is rounded to the nearest integer value; for a fractional result, use winfo fpixels.

winfo pointerx window
If the mouse pointer is on the same screen as window, returns the pointer's x coordinate, measured in pixels in the screen's root window. If a virtual root window is in use on the screen, the position is measured in the virtual root. If the mouse pointer isn't on the same screen as window then -1 is returned.

winfo pointerxy window
If the mouse pointer is on the same screen as window, returns a list with two elements, which are the pointer's x and y coordinates measured in pixels in the screen's root window. If a virtual root window is in use on the screen, the position is computed in the virtual root. If the mouse pointer isn't on the same screen as window then both of the returned coordinates are -1.

winfo pointery window
If the mouse pointer is on the same screen as window, returns the pointer's y coordinate, measured in pixels in the screen's root window. If a virtual root window is in use on the screen, the position is computed in the virtual root. If the mouse pointer isn't on the same screen as window then -1 is returned.

winfo reqheight window
Returns a decimal string giving window's requested height, in pixels. This is the value used by window's geometry manager to compute its geometry.

winfo reqwidth window
Returns a decimal string giving window's requested width, in pixels. This is the value used by window's geometry manager to compute its geometry.

winfo rgb window color
Returns a list containing three decimal values, which are the red, green, and blue intensities that correspond to color in the window given by window. Color may be specified in any of the forms acceptable for a color option.

winfo rootx window
Returns a decimal string giving the x-coordinate, in the root window of the screen, of the upper-left corner of window's border (or window if it has no border).

winfo rooty window
Returns a decimal string giving the y-coordinate, in the root window of the screen, of the upper-left corner of window's border (or window if it has no border).

winfo screen window
Returns the name of the screen associated with window, in the form displayName.screenIndex.

winfo screencells window
Returns a decimal string giving the number of cells in the default color map for window's screen.

winfo screendepth window
Returns a decimal string giving the depth of the root window of window's screen (number of bits per pixel).

winfo screenheight window
Returns a decimal string giving the height of window's screen, in pixels.

winfo screenmmheight window
Returns a decimal string giving the height of window's screen, in millimeters.

winfo screenmmwidth window
Returns a decimal string giving the width of window's screen, in millimeters.

winfo screenvisual window
Returns one of the following strings to indicate the default visual class for window's screen: directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor.

winfo screenwidth window
Returns a decimal string giving the width of window's screen, in pixels.

winfo server window
Returns a string containing information about the server for window's display. The exact format of this string may vary from platform to platform. For X servers the string has the form ``X major R minor vendor vendorVersion'' where major and minor are the version and revision numbers provided by the server (e.g., X11R5), vendor is the name of the vendor for the server, and vendorRelease is an integer release number provided by the server.

winfo toplevel window
Returns the path name of the top-level window containing window.

winfo viewable window
Returns 1 if window and all of its ancestors up through the nearest toplevel window are mapped. Returns 0 if any of these windows are not mapped.

winfo visual window
Returns one of the following strings to indicate the visual class for window: directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor.

winfo visualid window
Returns the X identifier for the visual for window.

winfo visualsavailable window ?includeids?
Returns a list whose elements describe the visuals available for window's screen. Each element consists of a visual class followed by an integer depth. The class has the same form as returned by winfo visual. The depth gives the number of bits per pixel in the visual. In addition, if the includeids argument is provided, then the depth is followed by the X identifier for the visual.

winfo vrootheight window
Returns the height of the virtual root window associated with window if there is one; otherwise returns the height of window's screen.

winfo vrootwidth window
Returns the width of the virtual root window associated with window if there is one; otherwise returns the width of window's screen.

winfo vrootx window
Returns the x-offset of the virtual root window associated with window, relative to the root window of its screen. This is normally either zero or negative. Returns 0 if there is no virtual root window for window.

winfo vrooty window
Returns the y-offset of the virtual root window associated with window, relative to the root window of its screen. This is normally either zero or negative. Returns 0 if there is no virtual root window for window.

winfo width window
Returns a decimal string giving window's width in pixels. When a window is first created its width will be 1 pixel; the width will eventually be changed by a geometry manager to fulfill the window's needs. If you need the true width immediately after creating a widget, invoke update to force the geometry manager to arrange it, or use winfo reqwidth to get the window's requested width instead of its actual width.

winfo x window
Returns a decimal string giving the x-coordinate, in window's parent, of the upper-left corner of window's border (or window if it has no border).

winfo y window
Returns a decimal string giving the y-coordinate, in window's parent, of the upper-left corner of window's border (or window if it has no border).

KEYWORDS

atom, children, class, geometry, height, identifier, information, interpreters, mapped, parent, path name, screen, virtual root, width, window
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tk Built-In Commands - wm manual page

NAME
wm - Communicate with window manager
SYNOPSIS
wm option window ?args?
DESCRIPTION
wm aspect window ?minNumer minDenom maxNumer maxDenom?
wm client window ?name?
wm colormapwindows window ?windowList?
wm command window ?value?
wm deiconify window
wm focusmodel window ?active|passive?
wm frame window
wm geometry window ?newGeometry?
wm grid window ?baseWidth baseHeight widthInc heightInc?
wm group window ?pathName?
wm iconbitmap window ?bitmap?
wm iconify window
wm iconmask window ?bitmap?
wm iconname window ?newName?
wm iconposition window ?x y?
wm iconwindow window ?pathName?
wm maxsize window ?width height?
wm minsize window ?width height?
wm overrideredirect window ?boolean?
wm positionfrom window ?who?
wm protocol window ?name? ?command?
wm resizable window ?width height?
wm sizefrom window ?who?
wm state window ?newstate?
wm title window ?string?
wm transient window ?master?
wm withdraw window
GEOMETRY MANAGEMENT
GRIDDED GEOMETRY MANAGEMENT
BUGS
KEYWORDS

NAME

wm - Communicate with window manager

SYNOPSIS

wm option window ?args?

DESCRIPTION

The wm command is used to interact with window managers in order to control such things as the title for a window, its geometry, or the increments in terms of which it may be resized. The wm command can take any of a number of different forms, depending on the option argument. All of the forms expect at least one additional argument, window, which must be the path name of a top-level window.

The legal forms for the wm command are:

wm aspect window ?minNumer minDenom maxNumer maxDenom?
If minNumer, minDenom, maxNumer, and maxDenom are all specified, then they will be passed to the window manager and the window manager should use them to enforce a range of acceptable aspect ratios for window. The aspect ratio of window (width/length) will be constrained to lie between minNumer/minDenom and maxNumer/maxDenom. If minNumer etc. are all specified as empty strings, then any existing aspect ratio restrictions are removed. If minNumer etc. are specified, then the command returns an empty string. Otherwise, it returns a Tcl list containing four elements, which are the current values of minNumer, minDenom, maxNumer, and maxDenom (if no aspect restrictions are in effect, then an empty string is returned).

wm client window ?name?
If name is specified, this command stores name (which should be the name of the host on which the application is executing) in window's WM_CLIENT_MACHINE property for use by the window manager or session manager. The command returns an empty string in this case. If name isn't specified, the command returns the last name set in a wm client command for window. If name is specified as an empty string, the command deletes the WM_CLIENT_MACHINE property from window.

wm colormapwindows window ?windowList?
This command is used to manipulate the WM_COLORMAP_WINDOWS property, which provides information to the window managers about windows that have private colormaps. If windowList isn't specified, the command returns a list whose elements are the names of the windows in the WM_COLORMAP_WINDOWS property. If windowList is specified, it consists of a list of window path names; the command overwrites the WM_COLORMAP_WINDOWS property with the given windows and returns an empty string. The WM_COLORMAP_WINDOWS property should normally contain a list of the internal windows within window whose colormaps differ from their parents. The order of the windows in the property indicates a priority order: the window manager will attempt to install as many colormaps as possible from the head of this list when window gets the colormap focus. If window is not included among the windows in windowList, Tk implicitly adds it at the end of the WM_COLORMAP_WINDOWS property, so that its colormap is lowest in priority. If wm colormapwindows is not invoked, Tk will automatically set the property for each top-level window to all the internal windows whose colormaps differ from their parents, followed by the top-level itself; the order of the internal windows is undefined. See the ICCCM documentation for more information on the WM_COLORMAP_WINDOWS property.

wm command window ?value?
If value is specified, this command stores value in window's WM_COMMAND property for use by the window manager or session manager and returns an empty string. Value must have proper list structure; the elements should contain the words of the command used to invoke the application. If value isn't specified then the command returns the last value set in a wm command command for window. If value is specified as an empty string, the command deletes the WM_COMMAND property from window.

wm deiconify window
Arrange for window to be displayed in normal (non-iconified) form. This is done by mapping the window. If the window has never been mapped then this command will not map the window, but it will ensure that when the window is first mapped it will be displayed in de-iconified form. On Windows, a deiconified window will also be raised and be given the focus (made the active window). Returns an empty string.

wm focusmodel window ?active|passive?
If active or passive is supplied as an optional argument to the command, then it specifies the focus model for window. In this case the command returns an empty string. If no additional argument is supplied, then the command returns the current focus model for window. An active focus model means that window will claim the input focus for itself or its descendants, even at times when the focus is currently in some other application. Passive means that window will never claim the focus for itself: the window manager should give the focus to window at appropriate times. However, once the focus has been given to window or one of its descendants, the application may re-assign the focus among window's descendants. The focus model defaults to passive, and Tk's focus command assumes a passive model of focusing.

wm frame window
If window has been reparented by the window manager into a decorative frame, the command returns the platform specific window identifier for the outermost frame that contains window (the window whose parent is the root or virtual root). If window hasn't been reparented by the window manager then the command returns the platform specific window identifier for window.

wm geometry window ?newGeometry?
If newGeometry is specified, then the geometry of window is changed and an empty string is returned. Otherwise the current geometry for window is returned (this is the most recent geometry specified either by manual resizing or in a wm geometry command). NewGeometry has the form =width x height±x±y, where any of =, width x height, or ±x±y may be omitted. Width and height are positive integers specifying the desired dimensions of window. If window is gridded (see GRIDDED GEOMETRY MANAGEMENT below) then the dimensions are specified in grid units; otherwise they are specified in pixel units. X and y specify the desired location of window on the screen, in pixels. If x is preceded by +, it specifies the number of pixels between the left edge of the screen and the left edge of window's border; if preceded by - then x specifies the number of pixels between the right edge of the screen and the right edge of window's border. If y is preceded by + then it specifies the number of pixels between the top of the screen and the top of window's border; if y is preceded by - then it specifies the number of pixels between the bottom of window's border and the bottom of the screen. If newGeometry is specified as an empty string then any existing user-specified geometry for window is cancelled, and the window will revert to the size requested internally by its widgets.

wm grid window ?baseWidth baseHeight widthInc heightInc?
This command indicates that window is to be managed as a gridded window. It also specifies the relationship between grid units and pixel units. BaseWidth and baseHeight specify the number of grid units corresponding to the pixel dimensions requested internally by window using Tk_GeometryRequest. WidthInc and heightInc specify the number of pixels in each horizontal and vertical grid unit. These four values determine a range of acceptable sizes for window, corresponding to grid-based widths and heights that are non-negative integers. Tk will pass this information to the window manager; during manual resizing, the window manager will restrict the window's size to one of these acceptable sizes. Furthermore, during manual resizing the window manager will display the window's current size in terms of grid units rather than pixels. If baseWidth etc. are all specified as empty strings, then window will no longer be managed as a gridded window. If baseWidth etc. are specified then the return value is an empty string. Otherwise the return value is a Tcl list containing four elements corresponding to the current baseWidth, baseHeight, widthInc, and heightInc; if window is not currently gridded, then an empty string is returned. Note: this command should not be needed very often, since the Tk_SetGrid library procedure and the setGrid option provide easier access to the same functionality.

wm group window ?pathName?
If pathName is specified, it gives the path name for the leader of a group of related windows. The window manager may use this information, for example, to unmap all of the windows in a group when the group's leader is iconified. PathName may be specified as an empty string to remove window from any group association. If pathName is specified then the command returns an empty string; otherwise it returns the path name of window's current group leader, or an empty string if window isn't part of any group.

wm iconbitmap window ?bitmap?
If bitmap is specified, then it names a bitmap in the standard forms accepted by Tk (see the Tk_GetBitmap manual entry for details). This bitmap is passed to the window manager to be displayed in window's icon, and the command returns an empty string. If an empty string is specified for bitmap, then any current icon bitmap is cancelled for window. If bitmap is specified then the command returns an empty string. Otherwise it returns the name of the current icon bitmap associated with window, or an empty string if window has no icon bitmap. On the Windows operating system, an additional flag is supported: wm iconbitmap window ?-default? ?image?. If the -default flag is given, the icon is applied to all toplevel windows (existing and future) to which no other specific icon has yet been applied. In addition to bitmap image types, any file which contains a valid Windows icon is also accepted (usually .ico or .icr files). Tcl will first test if the files contains an icon, and if that fails, test for a bitmap.

wm iconify window
Arrange for window to be iconified. It window hasn't yet been mapped for the first time, this command will arrange for it to appear in the iconified state when it is eventually mapped.

wm iconmask window ?bitmap?
If bitmap is specified, then it names a bitmap in the standard forms accepted by Tk (see the Tk_GetBitmap manual entry for details). This bitmap is passed to the window manager to be used as a mask in conjunction with the iconbitmap option: where the mask has zeroes no icon will be displayed; where it has ones, the bits from the icon bitmap will be displayed. If an empty string is specified for bitmap then any current icon mask is cancelled for window (this is equivalent to specifying a bitmap of all ones). If bitmap is specified then the command returns an empty string. Otherwise it returns the name of the current icon mask associated with window, or an empty string if no mask is in effect.

wm iconname window ?newName?
If newName is specified, then it is passed to the window manager; the window manager should display newName inside the icon associated with window. In this case an empty string is returned as result. If newName isn't specified then the command returns the current icon name for window, or an empty string if no icon name has been specified (in this case the window manager will normally display the window's title, as specified with the wm title command).

wm iconposition window ?x y?
If x and y are specified, they are passed to the window manager as a hint about where to position the icon for window. In this case an empty string is returned. If x and y are specified as empty strings then any existing icon position hint is cancelled. If neither x nor y is specified, then the command returns a Tcl list containing two values, which are the current icon position hints (if no hints are in effect then an empty string is returned).

wm iconwindow window ?pathName?
If pathName is specified, it is the path name for a window to use as icon for window: when window is iconified then pathName will be mapped to serve as icon, and when window is de-iconified then pathName will be unmapped again. If pathName is specified as an empty string then any existing icon window association for window will be cancelled. If the pathName argument is specified then an empty string is returned. Otherwise the command returns the path name of the current icon window for window, or an empty string if there is no icon window currently specified for window. Button press events are disabled for window as long as it is an icon window; this is needed in order to allow window managers to ``own'' those events. Note: not all window managers support the notion of an icon window.

wm maxsize window ?width height?
If width and height are specified, they give the maximum permissible dimensions for window. For gridded windows the dimensions are specified in grid units; otherwise they are specified in pixel units. The window manager will restrict the window's dimensions to be less than or equal to width and height. If width and height are specified, then the command returns an empty string. Otherwise it returns a Tcl list with two elements, which are the maximum width and height currently in effect. The maximum size defaults to the size of the screen. If resizing has been disabled with the wm resizable command, then this command has no effect. See the sections on geometry management below for more information.

wm minsize window ?width height?
If width and height are specified, they give the minimum permissible dimensions for window. For gridded windows the dimensions are specified in grid units; otherwise they are specified in pixel units. The window manager will restrict the window's dimensions to be greater than or equal to width and height. If width and height are specified, then the command returns an empty string. Otherwise it returns a Tcl list with two elements, which are the minimum width and height currently in effect. The minimum size defaults to one pixel in each dimension. If resizing has been disabled with the wm resizable command, then this command has no effect. See the sections on geometry management below for more information.

wm overrideredirect window ?boolean?
If boolean is specified, it must have a proper boolean form and the override-redirect flag for window is set to that value. If boolean is not specified then 1 or 0 is returned to indicate whether or not the override-redirect flag is currently set for window. Setting the override-redirect flag for a window causes it to be ignored by the window manager; among other things, this means that the window will not be reparented from the root window into a decorative frame and the user will not be able to manipulate the window using the normal window manager mechanisms.

wm positionfrom window ?who?
If who is specified, it must be either program or user, or an abbreviation of one of these two. It indicates whether window's current position was requested by the program or by the user. Many window managers ignore program-requested initial positions and ask the user to manually position the window; if user is specified then the window manager should position the window at the given place without asking the user for assistance. If who is specified as an empty string, then the current position source is cancelled. If who is specified, then the command returns an empty string. Otherwise it returns user or program to indicate the source of the window's current position, or an empty string if no source has been specified yet. Most window managers interpret ``no source'' as equivalent to program. Tk will automatically set the position source to user when a wm geometry command is invoked, unless the source has been set explicitly to program.

wm protocol window ?name? ?command?
This command is used to manage window manager protocols such as WM_DELETE_WINDOW. Name is the name of an atom corresponding to a window manager protocol, such as WM_DELETE_WINDOW or WM_SAVE_YOURSELF or WM_TAKE_FOCUS. If both name and command are specified, then command is associated with the protocol specified by name. Name will be added to window's WM_PROTOCOLS property to tell the window manager that the application has a protocol handler for name, and command will be invoked in the future whenever the window manager sends a message to the client for that protocol. In this case the command returns an empty string. If name is specified but command isn't, then the current command for name is returned, or an empty string if there is no handler defined for name. If command is specified as an empty string then the current handler for name is deleted and it is removed from the WM_PROTOCOLS property on window; an empty string is returned. Lastly, if neither name nor command is specified, the command returns a list of all the protocols for which handlers are currently defined for window.

Tk always defines a protocol handler for WM_DELETE_WINDOW, even if you haven't asked for one with wm protocol. If a WM_DELETE_WINDOW message arrives when you haven't defined a handler, then Tk handles the message by destroying the window for which it was received.

wm resizable window ?width height?
This command controls whether or not the user may interactively resize a top-level window. If width and height are specified, they are boolean values that determine whether the width and height of window may be modified by the user. In this case the command returns an empty string. If width and height are omitted then the command returns a list with two 0/1 elements that indicate whether the width and height of window are currently resizable. By default, windows are resizable in both dimensions. If resizing is disabled, then the window's size will be the size from the most recent interactive resize or wm geometry command. If there has been no such operation then the window's natural size will be used.

wm sizefrom window ?who?
If who is specified, it must be either program or user, or an abbreviation of one of these two. It indicates whether window's current size was requested by the program or by the user. Some window managers ignore program-requested sizes and ask the user to manually size the window; if user is specified then the window manager should give the window its specified size without asking the user for assistance. If who is specified as an empty string, then the current size source is cancelled. If who is specified, then the command returns an empty string. Otherwise it returns user or window to indicate the source of the window's current size, or an empty string if no source has been specified yet. Most window managers interpret ``no source'' as equivalent to program.

wm state window ?newstate?
If newstate is specified, the window will be set to the new state, otherwise it returns the current state of window: either normal, iconic, withdrawn, icon, or (Windows only) zoomed. The difference between iconic and icon is that iconic refers to a window that has been iconified (e.g., with the wm iconify command) while icon refers to a window whose only purpose is to serve as the icon for some other window (via the wm iconwindow command). The icon state cannot be set.

wm title window ?string?
If string is specified, then it will be passed to the window manager for use as the title for window (the window manager should display this string in window's title bar). In this case the command returns an empty string. If string isn't specified then the command returns the current title for the window. The title for a window defaults to its name.

wm transient window ?master?
If master is specified, then the window manager is informed that window is a transient window (e.g. pull-down menu) working on behalf of master (where master is the path name for a top-level window). Some window managers will use this information to manage window specially. If master is specified as an empty string then window is marked as not being a transient window any more. If master is specified, then the command returns an empty string. Otherwise the command returns the path name of window's current master, or an empty string if window isn't currently a transient window.

wm withdraw window
Arranges for window to be withdrawn from the screen. This causes the window to be unmapped and forgotten about by the window manager. If the window has never been mapped, then this command causes the window to be mapped in the withdrawn state. Not all window managers appear to know how to handle windows that are mapped in the withdrawn state. Note: it sometimes seems to be necessary to withdraw a window and then re-map it (e.g. with wm deiconify) to get some window managers to pay attention to changes in window attributes such as group.

GEOMETRY MANAGEMENT

By default a top-level window appears on the screen in its natural size, which is the one determined internally by its widgets and geometry managers. If the natural size of a top-level window changes, then the window's size changes to match. A top-level window can be given a size other than its natural size in two ways. First, the user can resize the window manually using the facilities of the window manager, such as resize handles. Second, the application can request a particular size for a top-level window using the wm geometry command. These two cases are handled identically by Tk; in either case, the requested size overrides the natural size. You can return the window to its natural by invoking wm geometry with an empty geometry string.

Normally a top-level window can have any size from one pixel in each dimension up to the size of its screen. However, you can use the wm minsize and wm maxsize commands to limit the range of allowable sizes. The range set by wm minsize and wm maxsize applies to all forms of resizing, including the window's natural size as well as manual resizes and the wm geometry command. You can also use the command wm resizable to completely disable interactive resizing in one or both dimensions.

GRIDDED GEOMETRY MANAGEMENT

Gridded geometry management occurs when one of the widgets of an application supports a range of useful sizes. This occurs, for example, in a text editor where the scrollbars, menus, and other adornments are fixed in size but the edit widget can support any number of lines of text or characters per line. In this case, it is usually desirable to let the user specify the number of lines or characters-per-line, either with the wm geometry command or by interactively resizing the window. In the case of text, and in other interesting cases also, only discrete sizes of the window make sense, such as integral numbers of lines and characters-per-line; arbitrary pixel sizes are not useful.

Gridded geometry management provides support for this kind of application. Tk (and the window manager) assume that there is a grid of some sort within the application and that the application should be resized in terms of grid units rather than pixels. Gridded geometry management is typically invoked by turning on the setGrid option for a widget; it can also be invoked with the wm grid command or by calling Tk_SetGrid. In each of these approaches the particular widget (or sometimes code in the application as a whole) specifies the relationship between integral grid sizes for the window and pixel sizes. To return to non-gridded geometry management, invoke wm grid with empty argument strings.

When gridded geometry management is enabled then all the dimensions specified in wm minsize, wm maxsize, and wm geometry commands are treated as grid units rather than pixel units. Interactive resizing is also carried out in even numbers of grid units rather than pixels.

BUGS

Most existing window managers appear to have bugs that affect the operation of the wm command. For example, some changes won't take effect if the window is already active: the window will have to be withdrawn and de-iconified in order to make the change happen.

On the Windows operating system wm iconbitmap has no effect when passed a bitmap: only icon files currently work properly.

KEYWORDS

aspect ratio, deiconify, focus model, geometry, grid, group, icon, iconify, increments, position, size, title, top-level window, units, window manager
Copyright © 1991-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_Alloc3DBorderFromObj manual page

NAME

Tk_Alloc3DBorderFromObj, Tk_Get3DBorder, Tk_Get3DBorderFromObj, Tk_Draw3DRectangle, Tk_Fill3DRectangle, Tk_Draw3DPolygon, Tk_Fill3DPolygon, Tk_3DVerticalBevel, Tk_3DHorizontalBevel, Tk_SetBackgroundFromBorder, Tk_NameOf3DBorder, Tk_3DBorderColor, Tk_3DBorderGC, Tk_Free3DBorderFromObj, Tk_Free3DBorder - draw borders with three-dimensional appearance

SYNOPSIS

#include <tk.h>
Tk_3DBorder
Tk_Alloc3DBorderFromObj(interp, tkwin, objPtr)
Tk_3DBorder
Tk_Get3DBorder(interp, tkwin, colorName)
Tk_3DBorder
Tk_Get3DBorderFromObj(tkwin, objPtr)
void
Tk_Draw3DRectangle(tkwin, drawable, border, x, y, width, height, borderWidth, relief)
void
Tk_Fill3DRectangle(tkwin, drawable, border, x, y, width, height, borderWidth, relief)
void
Tk_Draw3DPolygon(tkwin, drawable, border, pointPtr, numPoints, polyBorderWidth, leftRelief)
void
Tk_Fill3DPolygon(tkwin, drawable, border, pointPtr, numPoints, polyBorderWidth, leftRelief)
void
Tk_3DVerticalBevel(tkwin, drawable, border, x, y, width, height, leftBevel, relief)
void
Tk_3DHorizontalBevel(tkwin, drawable, border, x, y, width, height, leftIn, rightIn, topBevel, relief)
void
Tk_SetBackgroundFromBorder(tkwin, border)
char *
Tk_NameOf3DBorder(border)
XColor *
Tk_3DBorderColor(border)
GC *
Tk_3DBorderGC(tkwin, border, which)
Tk_Free3DBorderFromObj(tkwin, objPtr)
Tk_Free3DBorder(border)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

Tk_Window tkwin (in)
Token for window (for all procedures except Tk_Get3DBorder, must be the window for which the border was allocated).

Tcl_Obj *objPtr (in)
Pointer to object whose value describes color corresponding to background (flat areas). Illuminated edges will be brighter than this and shadowed edges will be darker than this.

char *colorName (in)
Same as objPtr except value is supplied as a string rather than an object.

Drawable drawable (in)
X token for window or pixmap; indicates where graphics are to be drawn. Must either be the X window for tkwin or a pixmap with the same screen and depth as tkwin.

Tk_3DBorder border (in)
Token for border previously allocated in call to Tk_Get3DBorder.

int x (in)
X-coordinate of upper-left corner of rectangle describing border or bevel, in pixels.

int y (in)
Y-coordinate of upper-left corner of rectangle describing border or bevel, in pixels.

int width (in)
Width of rectangle describing border or bevel, in pixels.

int height (in)
Height of rectangle describing border or bevel, in pixels.

int borderWidth (in)
Width of border in pixels. Positive means border is inside rectangle given by x, y, width, height, negative means border is outside rectangle.

int relief (in)
Indicates 3-D position of interior of object relative to exterior; should be TK_RELIEF_RAISED, TK_RELIEF_SUNKEN, TK_RELIEF_GROOVE, TK_RELIEF_SOLID, or TK_RELIEF_RIDGE (may also be TK_RELIEF_FLAT for Tk_Fill3DRectangle).

XPoint *pointPtr (in)
Pointer to array of points describing the set of vertices in a polygon. The polygon need not be closed (it will be closed automatically if it isn't).

int numPoints (in)
Number of points at *pointPtr.

int polyBorderWidth (in)
Width of border in pixels. If positive, border is drawn to left of trajectory given by pointPtr; if negative, border is drawn to right of trajectory. If leftRelief is TK_RELIEF_GROOVE or TK_RELIEF_RIDGE then the border is centered on the trajectory.

int leftRelief (in)
Height of left side of polygon's path relative to right. TK_RELIEF_RAISED means left side should appear higher and TK_RELIEF_SUNKEN means right side should appear higher; TK_RELIEF_GROOVE and TK_RELIEF_RIDGE mean the obvious things. For Tk_Fill3DPolygon, TK_RELIEF_FLAT may also be specified to indicate no difference in height.

int leftBevel (in)
Non-zero means this bevel forms the left side of the object; zero means it forms the right side.

int leftIn (in)
Non-zero means that the left edge of the horizontal bevel angles in, so that the bottom of the edge is farther to the right than the top. Zero means the edge angles out, so that the bottom is farther to the left than the top.

int rightIn (in)
Non-zero means that the right edge of the horizontal bevel angles in, so that the bottom of the edge is farther to the left than the top. Zero means the edge angles out, so that the bottom is farther to the right than the top.

int topBevel (in)
Non-zero means this bevel forms the top side of the object; zero means it forms the bottom side.

int which (in)
Specifies which of the border's graphics contexts is desired. Must be TK_3D_FLAT_GC, TK_3D_LIGHT_GC, or TK_3D_DARK_GC.

DESCRIPTION

These procedures provide facilities for drawing window borders in a way that produces a three-dimensional appearance. Tk_Alloc3DBorderFromObj allocates colors and Pixmaps needed to draw a border in the window given by the tkwin argument. The value of objPtr is a standard Tk color name that determines the border colors. The color indicated by objPtr will not actually be used in the border; it indicates the background color for the window (i.e. a color for flat surfaces). The illuminated portions of the border will appear brighter than indicated by objPtr, and the shadowed portions of the border will appear darker than objPtr.

Tk_Alloc3DBorderFromObj returns a token that may be used in later calls to Tk_Draw3DRectangle. If an error occurs in allocating information for the border (e.g. a bogus color name was given) then NULL is returned and an error message is left in interp->result. If it returns successfully, Tk_Alloc3DBorderFromObj caches information about the return value in objPtr, which speeds up future calls to Tk_Alloc3DBorderFromObj with the same objPtr and tkwin.

Tk_Get3DBorder is identical to Tk_Alloc3DBorderFromObj except that the color is specified with a string instead of an object. This prevents Tk_Get3DBorder from caching the return value, so Tk_Get3DBorder is less efficient than Tk_Alloc3DBorderFromObj.

Tk_Get3DBorderFromObj returns the token for an existing border, given the window and color name used to create the border. Tk_Get3DBorderFromObj doesn't actually create the border; it must already have been created with a previous call to Tk_Alloc3DBorderFromObj or Tk_Get3DBorder. The return value is cached in objPtr, which speeds up future calls to Tk_Get3DBorderFromObj with the same objPtr and tkwin.

Once a border structure has been created, Tk_Draw3DRectangle may be invoked to draw the border. The tkwin argument specifies the window for which the border was allocated, and drawable specifies a window or pixmap in which the border is to be drawn. Drawable need not refer to the same window as tkwin, but it must refer to a compatible pixmap or window: one associated with the same screen and with the same depth as tkwin. The x, y, width, and height arguments define the bounding box of the border region within drawable (usually x and y are zero and width and height are the dimensions of the window), and borderWidth specifies the number of pixels actually occupied by the border. The relief argument indicates which of several three-dimensional effects is desired: TK_RELIEF_RAISED means that the interior of the rectangle should appear raised relative to the exterior of the rectangle, and TK_RELIEF_SUNKEN means that the interior should appear depressed. TK_RELIEF_GROOVE and TK_RELIEF_RIDGE mean that there should appear to be a groove or ridge around the exterior of the rectangle.

Tk_Fill3DRectangle is somewhat like Tk_Draw3DRectangle except that it first fills the rectangular area with the background color (one corresponding to the color used to create border). Then it calls Tk_Draw3DRectangle to draw a border just inside the outer edge of the rectangular area. The argument relief indicates the desired effect (TK_RELIEF_FLAT means no border should be drawn; all that happens is to fill the rectangle with the background color).

The procedure Tk_Draw3DPolygon may be used to draw more complex shapes with a three-dimensional appearance. The pointPtr and numPoints arguments define a trajectory, polyBorderWidth indicates how wide the border should be (and on which side of the trajectory to draw it), and leftRelief indicates which side of the trajectory should appear raised. Tk_Draw3DPolygon draws a border around the given trajectory using the colors from border to produce a three-dimensional appearance. If the trajectory is non-self-intersecting, the appearance will be a raised or sunken polygon shape. The trajectory may be self-intersecting, although it's not clear how useful this is.

Tk_Fill3DPolygon is to Tk_Draw3DPolygon what Tk_Fill3DRectangle is to Tk_Draw3DRectangle: it fills the polygonal area with the background color from border, then calls Tk_Draw3DPolygon to draw a border around the area (unless leftRelief is TK_RELIEF_FLAT; in this case no border is drawn).

The procedures Tk_3DVerticalBevel and Tk_3DHorizontalBevel provide lower-level drawing primitives that are used by procedures such as Tk_Draw3DRectangle. These procedures are also useful in their own right for drawing rectilinear border shapes. Tk_3DVerticalBevel draws a vertical beveled edge, such as the left or right side of a rectangle, and Tk_3DHorizontalBevel draws a horizontal beveled edge, such as the top or bottom of a rectangle. Each procedure takes x, y, width, and height arguments that describe the rectangular area of the beveled edge (e.g., width is the border width for Tk_3DVerticalBevel). The leftBorder and topBorder arguments indicate the position of the border relative to the ``inside'' of the object, and relief indicates the relief of the inside of the object relative to the outside. Tk_3DVerticalBevel just draws a rectangular region. Tk_3DHorizontalBevel draws a trapezoidal region to generate mitered corners; it should be called after Tk_3DVerticalBevel (otherwise Tk_3DVerticalBevel will overwrite the mitering in the corner). The leftIn and rightIn arguments to Tk_3DHorizontalBevel describe the mitering at the corners; a value of 1 means that the bottom edge of the trapezoid will be shorter than the top, 0 means it will be longer. For example, to draw a rectangular border the top bevel should be drawn with 1 for both leftIn and rightIn, and the bottom bevel should be drawn with 0 for both arguments.

The procedure Tk_SetBackgroundFromBorder will modify the background pixel and/or pixmap of tkwin to produce a result compatible with border. For color displays, the resulting background will just be the color specified when border was created; for monochrome displays, the resulting background will be a light stipple pattern, in order to distinguish the background from the illuminated portion of the border.

Given a token for a border, the procedure Tk_NameOf3DBorder will return the color name that was used to create the border.

The procedure Tk_3DBorderColor returns the XColor structure that will be used for flat surfaces drawn for its border argument by procedures like Tk_Fill3DRectangle. The return value corresponds to the color name that was used to create the border. The XColor, and its associated pixel value, will remain allocated as long as border exists.

The procedure Tk_3DBorderGC returns one of the X graphics contexts that are used to draw the border. The argument which selects which one of the three possible GC's: TK_3D_FLAT_GC returns the context used for flat surfaces, TK_3D_LIGHT_GC returns the context for light shadows, and TK_3D_DARK_GC returns the context for dark shadows.

When a border is no longer needed, Tk_Free3DBorderFromObj or Tk_Free3DBorder should be called to release the resources associated with it. For Tk_Free3DBorderFromObj the border to release is specified with the window and color name used to create the border; for Tk_Free3DBorder the border to release is specified with the Tk_3DBorder token for the border. There should be exactly one call to Tk_Free3DBorderFromObj or Tk_Free3DBorder for each call to Tk_Alloc3DBorderFromObj or Tk_Get3DBorder.

KEYWORDS

3D, background, border, color, depressed, illumination, object, polygon, raised, shadow, three-dimensional effect
Copyright © 1990-1993 The Regents of the University of California.
Copyright © 1994-1998 Sun Microsystems, Inc.


Library Procedures - Tk_AddOption manual page

NAME
Tk_AddOption - Add an option to the option database
SYNOPSIS
ARGUMENTS
DESCRIPTION
20
40
60
80
KEYWORDS

NAME

Tk_AddOption - Add an option to the option database

SYNOPSIS

#include <tk.h>
void
Tk_AddOption(tkwin, name, value, priority)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

char *name (in)
Multi-element name of option.

char *value (in)
Value of option.

int priority (in)
Overall priority level to use for option.

DESCRIPTION

This procedure is invoked to add an option to the database associated with tkwin's main window. Name contains the option being specified and consists of names and/or classes separated by asterisks or dots, in the usual X format. Value contains the text string to associate with name; this value will be returned in calls to Tk_GetOption. Priority specifies the priority of the value; when options are queried using Tk_GetOption, the value with the highest priority is returned. Priority must be between 0 and TK_MAX_PRIO. Some common priority values are:

20
Used for default values hard-coded into widgets.

40
Used for options specified in application-specific startup files.

60
Used for options specified in user-specific defaults files, such as .Xdefaults, resource databases loaded into the X server, or user-specific startup files.

80
Used for options specified interactively after the application starts running.

KEYWORDS

class, name, option, add
Copyright © 1998-2000 by Scriptics Corporation.


Tk Library Procedures - Tk_CreateBindingTable manual page

NAME

Tk_CreateBindingTable, Tk_DeleteBindingTable, Tk_CreateBinding, Tk_DeleteBinding, Tk_GetBinding, Tk_GetAllBindings, Tk_DeleteAllBindings, Tk_BindEvent - invoke scripts in response to X events

SYNOPSIS

#include <tk.h>
Tk_BindingTable
Tk_CreateBindingTable(interp)
Tk_DeleteBindingTable(bindingTable)
unsigned long
Tk_CreateBinding(interp, bindingTable, object, eventString, script, append)
int
Tk_DeleteBinding(interp, bindingTable, object, eventString)
char *
Tk_GetBinding(interp, bindingTable, object, eventString)
Tk_GetAllBindings(interp, bindingTable, object)
Tk_DeleteAllBindings(bindingTable, object)
Tk_BindEvent(bindingTable, eventPtr, tkwin, numObjects, objectPtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use when invoking bindings in binding table. Also used for returning results and errors from binding procedures.

Tk_BindingTable bindingTable (in)
Token for binding table; must have been returned by some previous call to Tk_CreateBindingTable.

ClientData object (in)
Identifies object with which binding is associated.

char *eventString (in)
String describing event sequence.

char *script (in)
Tcl script to invoke when binding triggers.

int append (in)
Non-zero means append script to existing script for binding, if any; zero means replace existing script with new one.

XEvent *eventPtr (in)
X event to match against bindings in bindingTable.

Tk_Window tkwin (in)
Identifier for any window on the display where the event occurred. Used to find display-related information such as key maps.

int numObjects (in)
Number of object identifiers pointed to by objectPtr.

ClientData *objectPtr (in)
Points to an array of object identifiers: bindings will be considered for each of these objects in order from first to last.

DESCRIPTION

These procedures provide a general-purpose mechanism for creating and invoking bindings. Bindings are organized in terms of binding tables. A binding table consists of a collection of bindings plus a history of recent events. Within a binding table, bindings are associated with objects. The meaning of an object is defined by clients of the binding package. For example, Tk keeps uses one binding table to hold all of the bindings created by the bind command. For this table, objects are pointers to strings such as window names, class names, or other binding tags such as all. Tk also keeps a separate binding table for each canvas widget, which manages bindings created by the canvas's bind widget command; within this table, an object is either a pointer to the internal structure for a canvas item or a Tk_Uid identifying a tag.

The procedure Tk_CreateBindingTable creates a new binding table and associates interp with it (when bindings in the table are invoked, the scripts will be evaluated in interp). Tk_CreateBindingTable returns a token for the table, which must be used in calls to other procedures such as Tk_CreateBinding or Tk_BindEvent.

Tk_DeleteBindingTable frees all of the state associated with a binding table. Once it returns the caller should not use the bindingTable token again.

Tk_CreateBinding adds a new binding to an existing table. The object argument identifies the object with which the binding is to be associated, and it may be any one-word value. Typically it is a pointer to a string or data structure. The eventString argument identifies the event or sequence of events for the binding; see the documentation for the bind command for a description of its format. script is the Tcl script to be evaluated when the binding triggers. append indicates what to do if there already exists a binding for object and eventString: if append is zero then script replaces the old script; if append is non-zero then the new script is appended to the old one. Tk_CreateBinding returns an X event mask for all the events associated with the bindings. This information may be useful to invoke XSelectInput to select relevant events, or to disallow the use of certain events in bindings. If an error occurred while creating the binding (e.g., eventString refers to a non-existent event), then 0 is returned and an error message is left in interp->result.

Tk_DeleteBinding removes from bindingTable the binding given by object and eventString, if such a binding exists. Tk_DeleteBinding always returns TCL_OK. In some cases it may reset interp->result to the default empty value.

Tk_GetBinding returns a pointer to the script associated with eventString and object in bindingTable. If no such binding exists then NULL is returned and an error message is left in interp->result.

Tk_GetAllBindings returns in interp->result a list of all the event strings for which there are bindings in bindingTable associated with object. If there are no bindings for object then an empty string is returned in interp->result.

Tk_DeleteAllBindings deletes all of the bindings in bindingTable that are associated with object.

Tk_BindEvent is called to process an event. It makes a copy of the event in an internal history list associated with the binding table, then it checks for bindings that match the event. Tk_BindEvent processes each of the objects pointed to by objectPtr in turn. For each object, it finds all the bindings that match the current event history, selects the most specific binding using the priority mechanism described in the documentation for bind, and invokes the script for that binding. If there are no matching bindings for a particular object, then the object is skipped. Tk_BindEvent continues through all of the objects, handling exceptions such as errors, break, and continue as described in the documentation for bind.

KEYWORDS

binding, event, object, script
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_CanvasPs manual page

NAME

Tk_CanvasPsY, Tk_CanvasPsBitmap, Tk_CanvasPsColor, Tk_CanvasPsFont, Tk_CanvasPsPath, Tk_CanvasPsStipple - utility procedures for generating Postscript for canvases

SYNOPSIS

#include <tk.h>
double
Tk_CanvasPsY(canvas, canvasY)
int
Tk_CanvasPsBitmap(interp, canvas, bitmap, x, y, width, height)
int
Tk_CanvasPsColor(interp, canvas, colorPtr)
int
Tk_CanvasPsFont(interp, canvas, tkFont)
Tk_CanvasPsPath(interp, canvas, coordPtr, numPoints)
int
Tk_CanvasPsStipple(interp, canvas, bitmap)

ARGUMENTS

Tk_Canvas canvas (in)
A token that identifies a canvas widget for which Postscript is being generated.

double canvasY (in)
Y-coordinate in the space of the canvas.

Tcl_Interp *interp (in/out)
A Tcl interpreter; Postscript is appended to its result, or the result may be replaced with an error message.

Pixmap bitmap (in)
Bitmap to use for generating Postscript.

int x (in)
X-coordinate within bitmap of left edge of region to output.

int y (in)
Y-coordinate within bitmap of top edge of region to output.

int width (in)
Width of region of bitmap to output, in pixels.

int height (in)
Height of region of bitmap to output, in pixels.

XColor *colorPtr (in)
Information about color value to set in Postscript.

Tk_Font tkFont (in)
Font for which Postscript is to be generated.

double *coordPtr (in)
Pointer to an array of coordinates for one or more points specified in canvas coordinates. The order of values in coordPtr is x1, y1, x2, y2, x3, y3, and so on.

int numPoints (in)
Number of points at coordPtr.

DESCRIPTION

These procedures are called by canvas type managers to carry out common functions related to generating Postscript. Most of the procedures take a canvas argument, which refers to a canvas widget for which Postscript is being generated.

Tk_CanvasPsY takes as argument a y-coordinate in the space of a canvas and returns the value that should be used for that point in the Postscript currently being generated for canvas. Y coordinates require transformation because Postscript uses an origin at the lower-left corner whereas X uses an origin at the upper-left corner. Canvas x coordinates can be used directly in Postscript without transformation.

Tk_CanvasPsBitmap generates Postscript to describe a region of a bitmap. The Postscript is generated in proper image data format for Postscript, i.e., as data between angle brackets, one bit per pixel. The Postscript is appended to interp->result and TCL_OK is returned unless an error occurs, in which case TCL_ERROR is returned and interp->result is overwritten with an error message.

Tk_CanvasPsColor generates Postscript to set the current color to correspond to its colorPtr argument, taking into account any color map specified in the postscript command. It appends the Postscript to interp->result and returns TCL_OK unless an error occurs, in which case TCL_ERROR is returned and interp->result is overwritten with an error message.

Tk_CanvasPsFont generates Postscript that sets the current font to match tkFont as closely as possible. Tk_CanvasPsFont takes into account any font map specified in the postscript command, and it does the best it can at mapping X fonts to Postscript fonts. It appends the Postscript to interp->result and returns TCL_OK unless an error occurs, in which case TCL_ERROR is returned and interp->result is overwritten with an error message.

Tk_CanvasPsPath generates Postscript to set the current path to the set of points given by coordPtr and numPoints. It appends the resulting Postscript to interp->result.

Tk_CanvasPsStipple generates Postscript that will fill the current path in stippled fashion. It uses bitmap as the stipple pattern and the current Postscript color; ones in the stipple bitmap are drawn in the current color, and zeroes are not drawn at all. The Postscript is appended to interp->result and TCL_OK is returned, unless an error occurs, in which case TCL_ERROR is returned and interp->result is overwritten with an error message.

KEYWORDS

bitmap, canvas, color, font, path, Postscript, stipple
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_CanvasTkwin manual page

NAME

Tk_CanvasTkwin, Tk_CanvasGetCoord, Tk_CanvasDrawableCoords, Tk_CanvasSetStippleOrigin, Tk_CanvasWindowCoords, Tk_CanvasEventuallyRedraw, Tk_CanvasTagsOption - utility procedures for canvas type managers

SYNOPSIS

#include <tk.h>
Tk_Window
Tk_CanvasTkwin(canvas)
int
Tk_CanvasGetCoord(interp, canvas, string, doublePtr)
Tk_CanvasDrawableCoords(canvas, x, y, drawableXPtr, drawableYPtr)
Tk_CanvasSetStippleOrigin(canvas, gc)
Tk_CanvasWindowCoords(canvas, x, y, screenXPtr, screenYPtr)
Tk_CanvasEventuallyRedraw(canvas, x1, y1, x2, y2)
Tk_OptionParseProc *Tk_CanvasTagsParseProc;
Tk_OptionPrintProc *Tk_CanvasTagsPrintProc;

ARGUMENTS

Tk_Canvas canvas (in)
A token that identifies a canvas widget.

Tcl_Interp *interp (in/out)
Interpreter to use for error reporting.

char *string (in)
Textual description of a canvas coordinate.

double *doublePtr (out)
Points to place to store a converted coordinate.

double x (in)
An x coordinate in the space of the canvas.

double y (in)
A y coordinate in the space of the canvas.

short *drawableXPtr (out)
Pointer to a location in which to store an x coordinate in the space of the drawable currently being used to redisplay the canvas.

short *drawableYPtr (out)
Pointer to a location in which to store a y coordinate in the space of the drawable currently being used to redisplay the canvas.

GC gc (out)
Graphics context to modify.

short *screenXPtr (out)
Points to a location in which to store the screen coordinate in the canvas window that corresponds to x.

short *screenYPtr (out)
Points to a location in which to store the screen coordinate in the canvas window that corresponds to y.

int x1 (in)
Left edge of the region that needs redisplay. Only pixels at or to the right of this coordinate need to be redisplayed.

int y1 (in)
Top edge of the region that needs redisplay. Only pixels at or below this coordinate need to be redisplayed.

int x2 (in)
Right edge of the region that needs redisplay. Only pixels to the left of this coordinate need to be redisplayed.

int y2 (in)
Bottom edge of the region that needs redisplay. Only pixels above this coordinate need to be redisplayed.

DESCRIPTION

These procedures are called by canvas type managers to perform various utility functions.

Tk_CanvasTkwin returns the Tk_Window associated with a particular canvas.

Tk_CanvasGetCoord translates a string specification of a coordinate (such as 2p or 1.6c) into a double-precision canvas coordinate. If string is a valid coordinate description then Tk_CanvasGetCoord stores the corresponding canvas coordinate at *doublePtr and returns TCL_OK. Otherwise it stores an error message in interp->result and returns TCL_ERROR.

Tk_CanvasDrawableCoords is called by type managers during redisplay to compute where to draw things. Given x and y coordinates in the space of the canvas, Tk_CanvasDrawableCoords computes the corresponding pixel in the drawable that is currently being used for redisplay; it returns those coordinates in *drawableXPtr and *drawableYPtr. This procedure should not be invoked except during redisplay.

Tk_CanvasSetStippleOrigin is also used during redisplay. It sets the stipple origin in gc so that stipples drawn with gc in the current offscreen pixmap will line up with stipples drawn with origin (0,0) in the canvas's actual window. Tk_CanvasSetStippleOrigin is needed in order to guarantee that stipple patterns line up properly when the canvas is redisplayed in small pieces. Redisplays are carried out in double-buffered fashion where a piece of the canvas is redrawn in an offscreen pixmap and then copied back onto the screen. In this approach the stipple origins in graphics contexts need to be adjusted during each redisplay to compensate for the position of the off-screen pixmap relative to the window. If an item is being drawn with stipples, its type manager typically calls Tk_CanvasSetStippleOrigin just before using gc to draw something; after it is finished drawing, the type manager calls XSetTSOrigin to restore the origin in gc back to (0,0) (the restore is needed because graphics contexts are shared, so they cannot be modified permanently).

Tk_CanvasWindowCoords is similar to Tk_CanvasDrawableCoords except that it returns coordinates in the canvas's window on the screen, instead of coordinates in an off-screen pixmap.

Tk_CanvasEventuallyRedraw may be invoked by a type manager to inform Tk that a portion of a canvas needs to be redrawn. The x1, y1, x2, and y2 arguments specify the region that needs to be redrawn, in canvas coordinates. Type managers rarely need to invoke Tk_CanvasEventuallyRedraw, since Tk can normally figure out when an item has changed and make the redisplay request on its behalf (this happens, for example whenever Tk calls a configureProc or scaleProc). The only time that a type manager needs to call Tk_CanvasEventuallyRedraw is if an item has changed on its own without being invoked through one of the procedures in its Tk_ItemType; this could happen, for example, in an image item if the image is modified using image commands.

Tk_CanvasTagsParseProc and Tk_CanvasTagsPrintProc are procedures that handle the -tags option for canvas items. The code of a canvas type manager won't call these procedures directly, but will use their addresses to create a Tk_CustomOption structure for the -tags option. The code typically looks like this:

static Tk_CustomOption tagsOption = {Tk_CanvasTagsParseProc,
    Tk_CanvasTagsPrintProc, (ClientData) NULL
};

static Tk_ConfigSpec configSpecs[] = {
    ...
    {TK_CONFIG_CUSTOM, "-tags", (char *) NULL, (char *) NULL,
        (char *) NULL, 0, TK_CONFIG_NULL_OK, &tagsOption},
    ...
};

KEYWORDS

canvas, focus, item type, redisplay, selection, type manager
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_CanvasTextInfo manual page

NAME

Tk_CanvasTextInfo - additional information for managing text items in canvases

SYNOPSIS

#include <tk.h>
Tk_CanvasTextInfo *
Tk_CanvasGetTextInfo(canvas)

ARGUMENTS

Tk_Canvas canvas (in)
A token that identifies a particular canvas widget.

DESCRIPTION

Textual canvas items are somewhat more complicated to manage than other items, due to things like the selection and the input focus. Tk_CanvasGetTextInfo may be invoked by a type manager to obtain additional information needed for items that display text. The return value from Tk_CanvasGetTextInfo is a pointer to a structure that is shared between Tk and all the items that display text. The structure has the following form:
typedef struct Tk_CanvasTextInfo {
    Tk_3DBorder selBorder;
    int selBorderWidth;
    XColor *selFgColorPtr;
    Tk_Item *selItemPtr;
    int selectFirst;
    int selectLast;
    Tk_Item *anchorItemPtr;
    int selectAnchor;
    Tk_3DBorder insertBorder;
    int insertWidth;
    int insertBorderWidth;
    Tk_Item *focusItemPtr;
    int gotFocus;
    int cursorOn;
} Tk_CanvasTextInfo;
The selBorder field identifies a Tk_3DBorder that should be used for drawing the background under selected text. selBorderWidth gives the width of the raised border around selected text, in pixels. selFgColorPtr points to an XColor that describes the foreground color to be used when drawing selected text. selItemPtr points to the item that is currently selected, or NULL if there is no item selected or if the canvas doesn't have the selection. selectFirst and selectLast give the indices of the first and last selected characters in selItemPtr, as returned by the indexProc for that item. anchorItemPtr points to the item that currently has the selection anchor; this is not necessarily the same as selItemPtr. selectAnchor is an index that identifies the anchor position within anchorItemPtr. insertBorder contains a Tk_3DBorder to use when drawing the insertion cursor; insertWidth gives the total width of the insertion cursor in pixels, and insertBorderWidth gives the width of the raised border around the insertion cursor. focusItemPtr identifies the item that currently has the input focus, or NULL if there is no such item. gotFocus is 1 if the canvas widget has the input focus and 0 otherwise. cursorOn is 1 if the insertion cursor should be drawn in focusItemPtr and 0 if it should not be drawn; this field is toggled on and off by Tk to make the cursor blink.

The structure returned by Tk_CanvasGetTextInfo is shared between Tk and the type managers; typically the type manager calls Tk_CanvasGetTextInfo once when an item is created and then saves the pointer in the item's record. Tk will update information in the Tk_CanvasTextInfo; for example, a configure widget command might change the selBorder field, or a select widget command might change the selectFirst field, or Tk might change cursorOn in order to make the insertion cursor flash on and off during successive redisplays.

Type managers should treat all of the fields of the Tk_CanvasTextInfo structure as read-only, except for selItemPtr, selectFirst, selectLast, and selectAnchor. Type managers may change selectFirst, selectLast, and selectAnchor to adjust for insertions and deletions in the item (but only if the item is the current owner of the selection or anchor, as determined by selItemPtr or anchorItemPtr). If all of the selected text in the item is deleted, the item should set selItemPtr to NULL to indicate that there is no longer a selection.

KEYWORDS

canvas, focus, insertion cursor, selection, selection anchor, text
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_ClipboardClear manual page

NAME

Tk_ClipboardClear, Tk_ClipboardAppend - Manage the clipboard

SYNOPSIS

#include <tk.h>
int
Tk_ClipboardClear(interp, tkwin)
int
Tk_ClipboardAppend(interp, tkwin, target, format, buffer)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for reporting errors.

Tk_Window tkwin (in)
Window that determines which display's clipboard to manipulate.

Atom target (in)
Conversion type for this clipboard item; has same meaning as target argument to Tk_CreateSelHandler.

Atom format (in)
Representation to use when data is retrieved; has same meaning as format argument to Tk_CreateSelHandler.

char *buffer (in)
Null terminated string containing the data to be appended to the clipboard.

DESCRIPTION

These two procedures manage the clipboard for Tk. The clipboard is typically managed by calling Tk_ClipboardClear once, then calling Tk_ClipboardAppend to add data for any number of targets.

Tk_ClipboardClear claims the CLIPBOARD selection and frees any data items previously stored on the clipboard in this application. It normally returns TCL_OK, but if an error occurs it returns TCL_ERROR and leaves an error message in interp->result. Tk_ClipboardClear must be called before a sequence of Tk_ClipboardAppend calls can be issued.

Tk_ClipboardAppend appends a buffer of data to the clipboard. The first buffer for a given target determines the format for that target. Any successive appends for that target must have the same format or an error will be returned. Tk_ClipboardAppend returns TCL_OK if the buffer is successfully copied onto the clipboard. If the clipboard is not currently owned by the application, either because Tk_ClipboardClear has not been called or because ownership of the clipboard has changed since the last call to Tk_ClipboardClear, Tk_ClipboardAppend returns TCL_ERROR and leaves an error message in interp->result.

In order to guarantee atomicity, no event handling should occur between Tk_ClipboardClear and the following Tk_ClipboardAppend calls (otherwise someone could retrieve a partially completed clipboard or claim ownership away from this application).

Tk_ClipboardClear may invoke callbacks, including arbitrary Tcl scripts, as a result of losing the CLIPBOARD selection, so any calling function should take care to be reentrant at the point Tk_ClipboardClear is invoked.

KEYWORDS

append, clipboard, clear, format, type
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_ClearSelection manual page

NAME

Tk_ClearSelection - Deselect a selection

SYNOPSIS

#include <tk.h>
Tk_ClearSelection(tkwin, selection)

ARGUMENTS

Tk_Window tkwin (in)
The selection will be cleared from the display containing this window.

Atom selection (in)
The name of selection to be cleared.

DESCRIPTION

Tk_ClearSelection cancels the selection specified by the atom selection for the display containing tkwin. The selection need not be in tkwin itself or even in tkwin's application. If there is a window anywhere on tkwin's display that owns selection, the window will be notified and the selection will be cleared. If there is no owner for selection on the display, then the procedure has no effect.

KEYWORDS

clear, selection
Copyright © 1992-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_ConfigureWidget manual page

NAME
Tk_ConfigureWidget, Tk_Offset, Tk_ConfigureInfo, Tk_ConfigureValue, Tk_FreeOptions - process configuration options for widgets
SYNOPSIS
ARGUMENTS
DESCRIPTION
TK_CONFIG_ACTIVE_CURSOR
TK_CONFIG_ANCHOR
TK_CONFIG_BITMAP
TK_CONFIG_BOOLEAN
TK_CONFIG_BORDER
TK_CONFIG_CAP_STYLE
TK_CONFIG_COLOR
TK_CONFIG_CURSOR
TK_CONFIG_CUSTOM
TK_CONFIG_DOUBLE
TK_CONFIG_END
TK_CONFIG_FONT
TK_CONFIG_INT
TK_CONFIG_JOIN_STYLE
TK_CONFIG_JUSTIFY
TK_CONFIG_MM
TK_CONFIG_PIXELS
TK_CONFIG_RELIEF
TK_CONFIG_STRING
TK_CONFIG_SYNONYM
TK_CONFIG_UID
TK_CONFIG_WINDOW
GROUPED ENTRIES
FLAGS
TK_CONFIG_COLOR_ONLY
TK_CONFIG_MONO_ONLY
TK_CONFIG_NULL_OK
TK_CONFIG_DONT_SET_DEFAULT
TK_CONFIG_OPTION_SPECIFIED
TK_OFFSET
TK_CONFIGUREINFO
TK_CONFIGUREVALUE
TK_FREEOPTIONS
CUSTOM OPTION TYPES
EXAMPLES
SEE ALSO
KEYWORDS

NAME

Tk_ConfigureWidget, Tk_Offset, Tk_ConfigureInfo, Tk_ConfigureValue, Tk_FreeOptions - process configuration options for widgets

SYNOPSIS

#include <tk.h>
int
Tk_ConfigureWidget(interp, tkwin, specs, argc, argv, widgRec, flags)
int
Tk_Offset(type, field)
int
Tk_ConfigureInfo(interp, tkwin, specs, widgRec, argvName, flags)
int
Tk_ConfigureValue(interp, tkwin, specs, widgRec, argvName, flags)
Tk_FreeOptions(specs, widgRec, display, flags)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for returning error messages.

Tk_Window tkwin (in)
Window used to represent widget (needed to set up X resources).

Tk_ConfigSpec *specs (in)
Pointer to table specifying legal configuration options for this widget.

int argc (in)
Number of arguments in argv.

char **argv (in)
Command-line options for configuring widget.

char *widgRec (in/out)
Points to widget record structure. Fields in this structure get modified by Tk_ConfigureWidget to hold configuration information.

int flags (in)
If non-zero, then it specifies an OR-ed combination of flags that control the processing of configuration information. TK_CONFIG_ARGV_ONLY causes the option database and defaults to be ignored, and flag bits TK_CONFIG_USER_BIT and higher are used to selectively disable entries in specs.

type name type (in)
The name of the type of a widget record.

field name field (in)
The name of a field in records of type type.

char *argvName (in)
The name used on Tcl command lines to refer to a particular option (e.g. when creating a widget or invoking the configure widget command). If non-NULL, then information is returned only for this option. If NULL, then information is returned for all available options.

Display *display (in)
Display containing widget whose record is being freed; needed in order to free up resources.

DESCRIPTION

Note: Tk_ConfigureWidget should be replaced with the new Tcl_Obj based API Tk_SetOptions. The old interface is retained for backward compatibility.

Tk_ConfigureWidget is called to configure various aspects of a widget, such as colors, fonts, border width, etc. It is intended as a convenience procedure to reduce the amount of code that must be written in individual widget managers to handle configuration information. It is typically invoked when widgets are created, and again when the configure command is invoked for a widget. Although intended primarily for widgets, Tk_ConfigureWidget can be used in other situations where argc-argv information is to be used to fill in a record structure, such as configuring graphical elements for a canvas widget or entries of a menu.

Tk_ConfigureWidget processes a table specifying the configuration options that are supported (specs) and a collection of command-line arguments (argc and argv) to fill in fields of a record (widgRec). It uses the option database and defaults specified in specs to fill in fields of widgRec that are not specified in argv. Tk_ConfigureWidget normally returns the value TCL_OK; in this case it does not modify interp. If an error occurs then TCL_ERROR is returned and Tk_ConfigureWidget will leave an error message in interp->result in the standard Tcl fashion. In the event of an error return, some of the fields of widgRec could already have been set, if configuration information for them was successfully processed before the error occurred. The other fields will be set to reasonable initial values so that Tk_FreeOptions can be called for cleanup.

The specs array specifies the kinds of configuration options expected by the widget. Each of its entries specifies one configuration option and has the following structure:

typedef struct {
    int type;
    char *argvName;
    char *dbName;
    char *dbClass;
    char *defValue;
    int offset;
    int specFlags;
    Tk_CustomOption *customPtr;
} Tk_ConfigSpec;
The type field indicates what type of configuration option this is (e.g. TK_CONFIG_COLOR for a color value, or TK_CONFIG_INT for an integer value). The type field indicates how to use the value of the option (more on this below). The argvName field is a string such as ``-font'' or ``-bg'', which is compared with the values in argv (if argvName is NULL it means this is a grouped entry; see GROUPED ENTRIES below). The dbName and dbClass fields are used to look up a value for this option in the option database. The defValue field specifies a default value for this configuration option if no value is specified in either argv or the option database. Offset indicates where in widgRec to store information about this option, and specFlags contains additional information to control the processing of this configuration option (see FLAGS below). The last field, customPtr, is only used if type is TK_CONFIG_CUSTOM; see CUSTOM OPTION TYPES below.

Tk_ConfigureWidget first processes argv to see which (if any) configuration options are specified there. Argv must contain an even number of fields; the first of each pair of fields must match the argvName of some entry in specs (unique abbreviations are acceptable), and the second field of the pair contains the value for that configuration option. If there are entries in spec for which there were no matching entries in argv, Tk_ConfigureWidget uses the dbName and dbClass fields of the specs entry to probe the option database; if a value is found, then it is used as the value for the option. Finally, if no entry is found in the option database, the defValue field of the specs entry is used as the value for the configuration option. If the defValue is NULL, or if the TK_CONFIG_DONT_SET_DEFAULT bit is set in flags, then there is no default value and this specs entry will be ignored if no value is specified in argv or the option database.

Once a string value has been determined for a configuration option, Tk_ConfigureWidget translates the string value into a more useful form, such as a color if type is TK_CONFIG_COLOR or an integer if type is TK_CONFIG_INT. This value is then stored in the record pointed to by widgRec. This record is assumed to contain information relevant to the manager of the widget; its exact type is unknown to Tk_ConfigureWidget. The offset field of each specs entry indicates where in widgRec to store the information about this configuration option. You should use the Tk_Offset macro to generate offset values (see below for a description of Tk_Offset). The location indicated by widgRec and offset will be referred to as the ``target'' in the descriptions below.

The type field of each entry in specs determines what to do with the string value of that configuration option. The legal values for type, and the corresponding actions, are:

TK_CONFIG_ACTIVE_CURSOR
The value must be an ASCII string identifying a cursor in a form suitable for passing to Tk_GetCursor. The value is converted to a Tk_Cursor by calling Tk_GetCursor and the result is stored in the target. In addition, the resulting cursor is made the active cursor for tkwin by calling XDefineCursor. If TK_CONFIG_NULL_OK is specified in specFlags then the value may be an empty string, in which case the target and tkwin's active cursor will be set to None. If the previous value of the target wasn't None, then it is freed by passing it to Tk_FreeCursor.

TK_CONFIG_ANCHOR
The value must be an ASCII string identifying an anchor point in one of the ways accepted by Tk_GetAnchor. The string is converted to a Tk_Anchor by calling Tk_GetAnchor and the result is stored in the target.

TK_CONFIG_BITMAP
The value must be an ASCII string identifying a bitmap in a form suitable for passing to Tk_GetBitmap. The value is converted to a Pixmap by calling Tk_GetBitmap and the result is stored in the target. If TK_CONFIG_NULL_OK is specified in specFlags then the value may be an empty string, in which case the target is set to None. If the previous value of the target wasn't None, then it is freed by passing it to Tk_FreeBitmap.

TK_CONFIG_BOOLEAN
The value must be an ASCII string specifying a boolean value. Any of the values ``true'', ``yes'', ``on'', or ``1'', or an abbreviation of one of these values, means true; any of the values ``false'', ``no'', ``off'', or ``0'', or an abbreviation of one of these values, means false. The target is expected to be an integer; for true values it will be set to 1 and for false values it will be set to 0.

TK_CONFIG_BORDER
The value must be an ASCII string identifying a border color in a form suitable for passing to Tk_Get3DBorder. The value is converted to a (Tk_3DBorder *) by calling Tk_Get3DBorder and the result is stored in the target. If TK_CONFIG_NULL_OK is specified in specFlags then the value may be an empty string, in which case the target will be set to NULL. If the previous value of the target wasn't NULL, then it is freed by passing it to Tk_Free3DBorder.

TK_CONFIG_CAP_STYLE
The value must be an ASCII string identifying a cap style in one of the ways accepted by Tk_GetCapStyle. The string is converted to an integer value corresponding to the cap style by calling Tk_GetCapStyle and the result is stored in the target.

TK_CONFIG_COLOR
The value must be an ASCII string identifying a color in a form suitable for passing to Tk_GetColor. The value is converted to an (XColor *) by calling Tk_GetColor and the result is stored in the target. If TK_CONFIG_NULL_OK is specified in specFlags then the value may be an empty string, in which case the target will be set to None. If the previous value of the target wasn't NULL, then it is freed by passing it to Tk_FreeColor.

TK_CONFIG_CURSOR
This option is identical to TK_CONFIG_ACTIVE_CURSOR except that the new cursor is not made the active one for tkwin.

TK_CONFIG_CUSTOM
This option allows applications to define new option types. The customPtr field of the entry points to a structure defining the new option type. See the section CUSTOM OPTION TYPES below for details.

TK_CONFIG_DOUBLE
The value must be an ASCII floating-point number in the format accepted by strtol. The string is converted to a double value, and the value is stored in the target.

TK_CONFIG_END
Marks the end of the table. The last entry in specs must have this type; all of its other fields are ignored and it will never match any arguments.

TK_CONFIG_FONT
The value must be an ASCII string identifying a font in a form suitable for passing to Tk_GetFont. The value is converted to a Tk_Font by calling Tk_GetFont and the result is stored in the target. If TK_CONFIG_NULL_OK is specified in specFlags then the value may be an empty string, in which case the target will be set to NULL. If the previous value of the target wasn't NULL, then it is freed by passing it to Tk_FreeFont.

TK_CONFIG_INT
The value must be an ASCII integer string in the format accepted by strtol (e.g. ``0'' and ``0x'' prefixes may be used to specify octal or hexadecimal numbers, respectively). The string is converted to an integer value and the integer is stored in the target.

TK_CONFIG_JOIN_STYLE
The value must be an ASCII string identifying a join style in one of the ways accepted by Tk_GetJoinStyle. The string is converted to an integer value corresponding to the join style by calling Tk_GetJoinStyle and the result is stored in the target.

TK_CONFIG_JUSTIFY
The value must be an ASCII string identifying a justification method in one of the ways accepted by Tk_GetJustify. The string is converted to a Tk_Justify by calling Tk_GetJustify and the result is stored in the target.

TK_CONFIG_MM
The value must specify a screen distance in one of the forms acceptable to Tk_GetScreenMM. The string is converted to double-precision floating-point distance in millimeters and the value is stored in the target.

TK_CONFIG_PIXELS
The value must specify screen units in one of the forms acceptable to Tk_GetPixels. The string is converted to an integer distance in pixels and the value is stored in the target.

TK_CONFIG_RELIEF
The value must be an ASCII string identifying a relief in a form suitable for passing to Tk_GetRelief. The value is converted to an integer relief value by calling Tk_GetRelief and the result is stored in the target.

TK_CONFIG_STRING
A copy of the value is made by allocating memory space with malloc and copying the value into the dynamically-allocated space. A pointer to the new string is stored in the target. If TK_CONFIG_NULL_OK is specified in specFlags then the value may be an empty string, in which case the target will be set to NULL. If the previous value of the target wasn't NULL, then it is freed by passing it to free.

TK_CONFIG_SYNONYM
This type value identifies special entries in specs that are synonyms for other entries. If an argv value matches the argvName of a TK_CONFIG_SYNONYM entry, the entry isn't used directly. Instead, Tk_ConfigureWidget searches specs for another entry whose argvName is the same as the dbName field in the TK_CONFIG_SYNONYM entry; this new entry is used just as if its argvName had matched the argv value. The synonym mechanism allows multiple argv values to be used for a single configuration option, such as ``-background'' and ``-bg''.

TK_CONFIG_UID
The value is translated to a Tk_Uid (by passing it to Tk_GetUid). The resulting value is stored in the target. If TK_CONFIG_NULL_OK is specified in specFlags and the value is an empty string then the target will be set to NULL.

TK_CONFIG_WINDOW
The value must be a window path name. It is translated to a Tk_Window token and the token is stored in the target.

GROUPED ENTRIES

In some cases it is useful to generate multiple resources from a single configuration value. For example, a color name might be used both to generate the background color for a widget (using TK_CONFIG_COLOR) and to generate a 3-D border to draw around the widget (using TK_CONFIG_BORDER). In cases like this it is possible to specify that several consecutive entries in specs are to be treated as a group. The first entry is used to determine a value (using its argvName, dbName, dbClass, and defValue fields). The value will be processed several times (one for each entry in the group), generating multiple different resources and modifying multiple targets within widgRec. Each of the entries after the first must have a NULL value in its argvName field; this indicates that the entry is to be grouped with the entry that precedes it. Only the type and offset fields are used from these follow-on entries.

FLAGS

The flags argument passed to Tk_ConfigureWidget is used in conjunction with the specFlags fields in the entries of specs to provide additional control over the processing of configuration options. These values are used in three different ways as described below.

First, if the flags argument to Tk_ConfigureWidget has the TK_CONFIG_ARGV_ONLY bit set (i.e., flags | TK_CONFIG_ARGV_ONLY != 0), then the option database and defValue fields are not used. In this case, if an entry in specs doesn't match a field in argv then nothing happens: the corresponding target isn't modified. This feature is useful when the goal is to modify certain configuration options while leaving others in their current state, such as when a configure widget command is being processed.

Second, the specFlags field of an entry in specs may be used to control the processing of that entry. Each specFlags field may consists of an OR-ed combination of the following values:

TK_CONFIG_COLOR_ONLY
If this bit is set then the entry will only be considered if the display for tkwin has more than one bit plane. If the display is monochromatic then this specs entry will be ignored.

TK_CONFIG_MONO_ONLY
If this bit is set then the entry will only be considered if the display for tkwin has exactly one bit plane. If the display is not monochromatic then this specs entry will be ignored.

TK_CONFIG_NULL_OK
This bit is only relevant for some types of entries (see the descriptions of the various entry types above). If this bit is set, it indicates that an empty string value for the field is acceptable and if it occurs then the target should be set to NULL or None, depending on the type of the target. This flag is typically used to allow a feature to be turned off entirely, e.g. set a cursor value to None so that a window simply inherits its parent's cursor. If this bit isn't set then empty strings are processed as strings, which generally results in an error.

TK_CONFIG_DONT_SET_DEFAULT
If this bit is one, it means that the defValue field of the entry should only be used for returning the default value in Tk_ConfigureInfo. In calls to Tk_ConfigureWidget no default will be supplied for entries with this flag set; it is assumed that the caller has already supplied a default value in the target location. This flag provides a performance optimization where it is expensive to process the default string: the client can compute the default once, save the value, and provide it before calling Tk_ConfigureWidget.

TK_CONFIG_OPTION_SPECIFIED
This bit is set and cleared by Tk_ConfigureWidget. Whenever Tk_ConfigureWidget returns, this bit will be set in all the entries where a value was specified in argv. It will be zero in all other entries. This bit provides a way for clients to determine which values actually changed in a call to Tk_ConfigureWidget.

The TK_CONFIG_MONO_ONLY and TK_CONFIG_COLOR_ONLY flags are typically used to specify different default values for monochrome and color displays. This is done by creating two entries in specs that are identical except for their defValue and specFlags fields. One entry should have the value TK_CONFIG_MONO_ONLY in its specFlags and the default value for monochrome displays in its defValue; the other entry entry should have the value TK_CONFIG_COLOR_ONLY in its specFlags and the appropriate defValue for color displays.

Third, it is possible to use flags and specFlags together to selectively disable some entries. This feature is not needed very often. It is useful in cases where several similar kinds of widgets are implemented in one place. It allows a single specs table to be created with all the configuration options for all the widget types. When processing a particular widget type, only entries relevant to that type will be used. This effect is achieved by setting the high-order bits (those in positions equal to or greater than TK_CONFIG_USER_BIT) in specFlags values or in flags. In order for a particular entry in specs to be used, its high-order bits must match exactly the high-order bits of the flags value passed to Tk_ConfigureWidget. If a specs table is being used for N different widget types, then N of the high-order bits will be used. Each specs entry will have one of more of those bits set in its specFlags field to indicate the widget types for which this entry is valid. When calling Tk_ConfigureWidget, flags will have a single one of these bits set to select the entries for the desired widget type. For a working example of this feature, see the code in tkButton.c.

TK_OFFSET

The Tk_Offset macro is provided as a safe way of generating the offset values for entries in Tk_ConfigSpec structures. It takes two arguments: the name of a type of record, and the name of a field in that record. It returns the byte offset of the named field in records of the given type.

TK_CONFIGUREINFO

The Tk_ConfigureInfo procedure may be used to obtain information about one or all of the options for a given widget. Given a token for a window (tkwin), a table describing the configuration options for a class of widgets (specs), a pointer to a widget record containing the current information for a widget (widgRec), and a NULL argvName argument, Tk_ConfigureInfo generates a string describing all of the configuration options for the window. The string is placed in interp->result. Under normal circumstances it returns TCL_OK; if an error occurs then it returns TCL_ERROR and interp->result contains an error message.

If argvName is NULL, then the value left in interp->result by Tk_ConfigureInfo consists of a list of one or more entries, each of which describes one configuration option (i.e. one entry in specs). Each entry in the list will contain either two or five values. If the corresponding entry in specs has type TK_CONFIG_SYNONYM, then the list will contain two values: the argvName for the entry and the dbName (synonym name). Otherwise the list will contain five values: argvName, dbName, dbClass, defValue, and current value. The current value is computed from the appropriate field of widgRec by calling procedures like Tk_NameOfColor.

If the argvName argument to Tk_ConfigureInfo is non-NULL, then it indicates a single option, and information is returned only for that option. The string placed in interp->result will be a list containing two or five values as described above; this will be identical to the corresponding sublist that would have been returned if argvName had been NULL.

The flags argument to Tk_ConfigureInfo is used to restrict the specs entries to consider, just as for Tk_ConfigureWidget.

TK_CONFIGUREVALUE

Tk_ConfigureValue takes arguments similar to Tk_ConfigureInfo; instead of returning a list of values, it just returns the current value of the option given by argvName (argvName must not be NULL). The value is returned in interp->result and TCL_OK is normally returned as the procedure's result. If an error occurs in Tk_ConfigureValue (e.g., argvName is not a valid option name), TCL_ERROR is returned and an error message is left in interp->result. This procedure is typically called to implement cget widget commands.

TK_FREEOPTIONS

The Tk_FreeOptions procedure may be invoked during widget cleanup to release all of the resources associated with configuration options. It scans through specs and for each entry corresponding to a resource that must be explicitly freed (e.g. those with type TK_CONFIG_COLOR), it frees the resource in the widget record. If the field in the widget record doesn't refer to a resource (e.g. it contains a null pointer) then no resource is freed for that entry. After freeing a resource, Tk_FreeOptions sets the corresponding field of the widget record to null.

CUSTOM OPTION TYPES

Applications can extend the built-in configuration types with additional configuration types by writing procedures to parse and print options of the a type and creating a structure pointing to those procedures:
typedef struct Tk_CustomOption {
    Tk_OptionParseProc *parseProc;
    Tk_OptionPrintProc *printProc;
    ClientData clientData;
} Tk_CustomOption;

typedef int Tk_OptionParseProc(
    ClientData clientData,
    Tcl_Interp *interp,
    Tk_Window tkwin,
    char *value,
    char *widgRec,
    int offset);

typedef char *Tk_OptionPrintProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc **freeProcPtr);
The Tk_CustomOption structure contains three fields, which are pointers to the two procedures and a clientData value to be passed to those procedures when they are invoked. The clientData value typically points to a structure containing information that is needed by the procedures when they are parsing and printing options.

The parseProc procedure is invoked by Tk_ConfigureWidget to parse a string and store the resulting value in the widget record. The clientData argument is a copy of the clientData field in the Tk_CustomOption structure. The interp argument points to a Tcl interpreter used for error reporting. Tkwin is a copy of the tkwin argument to Tk_ConfigureWidget. The value argument is a string describing the value for the option; it could have been specified explicitly in the call to Tk_ConfigureWidget or it could come from the option database or a default. Value will never be a null pointer but it may point to an empty string. RecordPtr is the same as the widgRec argument to Tk_ConfigureWidget; it points to the start of the widget record to modify. The last argument, offset, gives the offset in bytes from the start of the widget record to the location where the option value is to be placed. The procedure should translate the string to whatever form is appropriate for the option and store the value in the widget record. It should normally return TCL_OK, but if an error occurs in translating the string to a value then it should return TCL_ERROR and store an error message in interp->result.

The printProc procedure is called by Tk_ConfigureInfo to produce a string value describing an existing option. Its clientData, tkwin, widgRec, and offset arguments all have the same meaning as for Tk_OptionParseProc procedures. The printProc procedure should examine the option whose value is stored at offset in widgRec, produce a string describing that option, and return a pointer to the string. If the string is stored in dynamically-allocated memory, then the procedure must set *freeProcPtr to the address of a procedure to call to free the string's memory; Tk_ConfigureInfo will call this procedure when it is finished with the string. If the result string is stored in static memory then printProc need not do anything with the freeProcPtr argument.

Once parseProc and printProc have been defined and a Tk_CustomOption structure has been created for them, options of this new type may be manipulated with Tk_ConfigSpec entries whose type fields are TK_CONFIG_CUSTOM and whose customPtr fields point to the Tk_CustomOption structure.

EXAMPLES

Although the explanation of Tk_ConfigureWidget is fairly complicated, its actual use is pretty straightforward. The easiest way to get started is to copy the code from an existing widget. The library implementation of frames (tkFrame.c) has a simple configuration table, and the library implementation of buttons (tkButton.c) has a much more complex table that uses many of the fancy specFlags mechanisms.

SEE ALSO

Tk_SetOptions

KEYWORDS

anchor, bitmap, boolean, border, cap style, color, configuration options, cursor, custom, double, font, integer, join style, justify, millimeters, pixels, relief, synonym, uid
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_ConfigureWindow manual page

NAME

Tk_ConfigureWindow, Tk_MoveWindow, Tk_ResizeWindow, Tk_MoveResizeWindow, Tk_SetWindowBorderWidth, Tk_ChangeWindowAttributes, Tk_SetWindowBackground, Tk_SetWindowBackgroundPixmap, Tk_SetWindowBorder, Tk_SetWindowBorderPixmap, Tk_SetWindowColormap, Tk_DefineCursor, Tk_UndefineCursor - change window configuration or attributes

SYNOPSIS

#include <tk.h>
Tk_ConfigureWindow(tkwin, valueMask, valuePtr)
Tk_MoveWindow(tkwin, x, y)
Tk_ResizeWindow(tkwin, width, height)
Tk_MoveResizeWindow(tkwin, x, y, width, height)
Tk_SetWindowBorderWidth(tkwin, borderWidth)
Tk_ChangeWindowAttributes(tkwin, valueMask, attsPtr)
Tk_SetWindowBackground(tkwin, pixel)
Tk_SetWindowBackgroundPixmap(tkwin, pixmap)
Tk_SetWindowBorder(tkwin, pixel)
Tk_SetWindowBorderPixmap(tkwin, pixmap)
Tk_SetWindowColormap(tkwin, colormap)
Tk_DefineCursor(tkwin, cursor)
Tk_UndefineCursor(tkwin)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

unsigned int valueMask (in)
OR-ed mask of values like CWX or CWBorderPixel, indicating which fields of *valuePtr or *attsPtr to use.

XWindowChanges *valuePtr (in)
Points to a structure containing new values for the configuration parameters selected by valueMask. Fields not selected by valueMask are ignored.

int x (in)
New x-coordinate for tkwin's top left pixel (including border, if any) within tkwin's parent.

int y (in)
New y-coordinate for tkwin's top left pixel (including border, if any) within tkwin's parent.

int width (in)
New width for tkwin (interior, not including border).

int height (in)
New height for tkwin (interior, not including border).

int borderWidth (in)
New width for tkwin's border.

XSetWindowAttributes *attsPtr (in)
Points to a structure containing new values for the attributes given by the valueMask argument. Attributes not selected by valueMask are ignored.

unsigned long pixel (in)
New background or border color for window.

Pixmap pixmap (in)
New pixmap to use for background or border of tkwin. WARNING: cannot necessarily be deleted immediately, as for Xlib calls. See note below.

Colormap colormap (in)
New colormap to use for tkwin.

Tk_Cursor cursor (in)
New cursor to use for tkwin. If None is specified, then tkwin will not have its own cursor; it will use the cursor of its parent.

DESCRIPTION

These procedures are analogous to the X library procedures with similar names, such as XConfigureWindow. Each one of the above procedures calls the corresponding X procedure and also saves the configuration information in Tk's local structure for the window. This allows the information to be retrieved quickly by the application (using macros such as Tk_X and Tk_Height) without having to contact the X server. In addition, if no X window has actually been created for tkwin yet, these procedures do not issue X operations or cause event handlers to be invoked; they save the information in Tk's local structure for the window; when the window is created later, the saved information will be used to configure the window.

See the X library documentation for details on what these procedures do and how they use their arguments.

In the procedures Tk_ConfigureWindow, Tk_MoveWindow, Tk_ResizeWindow, Tk_MoveResizeWindow, and Tk_SetWindowBorderWidth, if tkwin is an internal window then event handlers interested in configure events are invoked immediately, before the procedure returns. If tkwin is a top-level window then the event handlers will be invoked later, after X has seen the request and returned an event for it.

Applications using Tk should never call procedures like XConfigureWindow directly; they should always use the corresponding Tk procedures.

The size and location of a window should only be modified by the appropriate geometry manager for that window and never by a window itself (but see Tk_MoveToplevelWindow for moving a top-level window).

You may not use Tk_ConfigureWindow to change the stacking order of a window (valueMask may not contain the CWSibling or CWStackMode bits). To change the stacking order, use the procedure Tk_RestackWindow.

The procedure Tk_SetWindowColormap will automatically add tkwin to the TK_COLORMAP_WINDOWS property of its nearest top-level ancestor if the new colormap is different from that of tkwin's parent and tkwin isn't already in the TK_COLORMAP_WINDOWS property.

BUGS

Tk_SetWindowBackgroundPixmap and Tk_SetWindowBorderPixmap differ slightly from their Xlib counterparts in that the pixmap argument may not necessarily be deleted immediately after calling one of these procedures. This is because tkwin's window may not exist yet at the time of the call, in which case pixmap is merely saved and used later when tkwin's window is actually created. If you wish to delete pixmap, then call Tk_MakeWindowExist first to be sure that tkwin's window exists and pixmap has been passed to the X server.

A similar problem occurs for the cursor argument passed to Tk_DefineCursor. The solution is the same as for pixmaps above: call Tk_MakeWindowExist before freeing the cursor.

SEE ALSO

Tk_MoveToplevelWindow, Tk_RestackWindow

KEYWORDS

attributes, border, color, configure, height, pixel, pixmap, width, window, x, y
Copyright © 1990-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_CoordsToWindow manual page

NAME

Tk_CoordsToWindow - Find window containing a point

SYNOPSIS

#include <tk.h>
Tk_Window
Tk_CoordsToWindow(rootX, rootY, tkwin)

ARGUMENTS

int rootX (in)
X-coordinate (in root window coordinates).

int rootY (in)
Y-coordinate (in root window coordinates).

Tk_Window tkwin (in)
Token for window that identifies application.

DESCRIPTION

Tk_CoordsToWindow locates the window that contains a given point. The point is specified in root coordinates with rootX and rootY (if a virtual-root window manager is in use then rootX and rootY are in the coordinate system of the virtual root window). The return value from the procedure is a token for the window that contains the given point. If the point is not in any window, or if the containing window is not in the same application as tkwin, then NULL is returned.

The containing window is decided using the same rules that determine which window contains the mouse cursor: if a parent and a child both contain the point then the child gets preference, and if two siblings both contain the point then the highest one in the stacking order (i.e. the one that's visible on the screen) gets preference.

KEYWORDS

containing, coordinates, root window
Copyright © 1990-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_CreateErrorHandler manual page

NAME

Tk_CreateErrorHandler, Tk_DeleteErrorHandler - handle X protocol errors

SYNOPSIS

#include <tk.h>
Tk_ErrorHandler
Tk_CreateErrorHandler(display, error, request, minor, proc, clientData)
Tk_DeleteErrorHandler(handler)

ARGUMENTS

Display *display (in)
Display whose errors are to be handled.

int error (in)
Match only error events with this value in the error_code field. If -1, then match any error_code value.

int request (in)
Match only error events with this value in the request_code field. If -1, then match any request_code value.

int minor (in)
Match only error events with this value in the minor_code field. If -1, then match any minor_code value.

Tk_ErrorProc *proc (in)
Procedure to invoke whenever an error event is received for display and matches error, request, and minor. NULL means ignore any matching errors.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

Tk_ErrorHandler handler (in)
Token for error handler to delete (return value from a previous call to Tk_CreateErrorHandler).

DESCRIPTION

Tk_CreateErrorHandler arranges for a particular procedure (proc) to be called whenever certain protocol errors occur on a particular display (display). Protocol errors occur when the X protocol is used incorrectly, such as attempting to map a window that doesn't exist. See the Xlib documentation for XSetErrorHandler for more information on the kinds of errors that can occur. For proc to be invoked to handle a particular error, five things must occur:

[1]
The error must pertain to display.

[2]
Either the error argument to Tk_CreateErrorHandler must have been -1, or the error argument must match the error_code field from the error event.

[3]
Either the request argument to Tk_CreateErrorHandler must have been -1, or the request argument must match the request_code field from the error event.

[4]
Either the minor argument to Tk_CreateErrorHandler must have been -1, or the minor argument must match the minor_code field from the error event.

[5]
The protocol request to which the error pertains must have been made when the handler was active (see below for more information).

Proc should have arguments and result that match the following type:

typedef int Tk_ErrorProc(
    ClientData clientData,
    XErrorEvent *errEventPtr);
The clientData parameter to proc is a copy of the clientData argument given to Tcl_CreateErrorHandler when the callback was created. Typically, clientData points to a data structure containing application-specific information that is needed to deal with the error. ErrEventPtr is a pointer to the X error event. The procedure proc should return an integer value. If it returns 0 it means that proc handled the error completely and there is no need to take any other action for the error. If it returns non-zero it means proc was unable to handle the error.

If a value of NULL is specified for proc, all matching errors will be ignored: this will produce the same result as if a procedure had been specified that always returns 0.

If more than more than one handler matches a particular error, then they are invoked in turn. The handlers will be invoked in reverse order of creation: most recently declared handler first. If any handler returns 0, then subsequent (older) handlers will not be invoked. If no handler returns 0, then Tk invokes X'es default error handler, which prints an error message and aborts the program. If you wish to have a default handler that deals with errors that no other handler can deal with, then declare it first.

The X documentation states that ``the error handler should not call any functions (directly or indirectly) on the display that will generate protocol requests or that will look for input events.'' This restriction applies to handlers declared by Tk_CreateErrorHandler; disobey it at your own risk.

Tk_DeleteErrorHandler may be called to delete a previously-created error handler. The handler argument identifies the error handler, and should be a value returned by a previous call to Tk_CreateEventHandler.

A particular error handler applies to errors resulting from protocol requests generated between the call to Tk_CreateErrorHandler and the call to Tk_DeleteErrorHandler. However, the actual callback to proc may not occur until after the Tk_DeleteErrorHandler call, due to buffering in the client and server. If an error event pertains to a protocol request made just before calling Tk_DeleteErrorHandler, then the error event may not have been processed before the Tk_DeleteErrorHandler call. When this situation arises, Tk will save information about the handler and invoke the handler's proc later when the error event finally arrives. If an application wishes to delete an error handler and know for certain that all relevant errors have been processed, it should first call Tk_DeleteErrorHandler and then call XSync; this will flush out any buffered requests and errors, but will result in a performance penalty because it requires communication to and from the X server. After the XSync call Tk is guaranteed not to call any error handlers deleted before the XSync call.

For the Tk error handling mechanism to work properly, it is essential that application code never calls XSetErrorHandler directly; applications should use only Tk_CreateErrorHandler.

KEYWORDS

callback, error, event, handler
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_CreateGenericHandler manual page

NAME

Tk_CreateGenericHandler, Tk_DeleteGenericHandler - associate procedure callback with all X events

SYNOPSIS

#include <tk.h>
Tk_CreateGenericHandler(proc, clientData)
Tk_DeleteGenericHandler(proc, clientData)

ARGUMENTS

Tk_GenericProc *proc (in)
Procedure to invoke whenever any X event occurs on any display.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

Tk_CreateGenericHandler arranges for proc to be invoked in the future whenever any X event occurs. This mechanism is not intended for dispatching X events on windows managed by Tk (you should use Tk_CreateEventHandler for this purpose). Tk_CreateGenericHandler is intended for other purposes, such as tracing X events, monitoring events on windows not owned by Tk, accessing X-related libraries that were not originally designed for use with Tk, and so on.

The callback to proc will be made by Tk_HandleEvent; this mechanism only works in programs that dispatch events through Tk_HandleEvent (or through other Tk procedures that call Tk_HandleEvent, such as Tk_DoOneEvent or Tk_MainLoop).

Proc should have arguments and result that match the type Tk_GenericProc:

typedef int Tk_GenericProc(
    ClientData clientData,
    XEvent *eventPtr);
The clientData parameter to proc is a copy of the clientData argument given to Tk_CreateGenericHandler when the callback was created. Typically, clientData points to a data structure containing application-specific information about how to handle events. EventPtr is a pointer to the X event.

Whenever an X event is processed by Tk_HandleEvent, proc is called. The return value from proc is normally 0. A non-zero return value indicates that the event is not to be handled further; that is, proc has done all processing that is to be allowed for the event.

If there are multiple generic event handlers, each one is called for each event, in the order in which they were established.

Tk_DeleteGenericHandler may be called to delete a previously-created generic event handler: it deletes each handler it finds that matches the proc and clientData arguments. If no such handler exists, then Tk_DeleteGenericHandler returns without doing anything. Although Tk supports it, it's probably a bad idea to have more than one callback with the same proc and clientData arguments.

Establishing a generic event handler does nothing to ensure that the process will actually receive the X events that the handler wants to process. For example, it is the caller's responsibility to invoke XSelectInput to select the desired events, if that is necessary.

KEYWORDS

bind, callback, event, handler
Copyright © 1992-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_CreateImageType manual page

NAME
Tk_CreateImageType, Tk_GetImageMasterData, Tk_InitImageArgs - define new kind of image
SYNOPSIS
ARGUMENTS
DESCRIPTION
NAME
PORTABILITY
CREATEPROC
GETPROC
DISPLAYPROC
FREEPROC
DELETEPROC
TK_GETIMAGEMASTERDATA
TK_INITIMAGEARGS
SEE ALSO
KEYWORDS

NAME

Tk_CreateImageType, Tk_GetImageMasterData, Tk_InitImageArgs - define new kind of image

SYNOPSIS

#include <tk.h>
Tk_CreateImageType(typePtr)
ClientData
Tk_GetImageMasterData(interp, name, typePtrPtr)
Tk_InitImageArgs(interp, argc, argvPtr)

ARGUMENTS

Tk_ImageType *typePtr (in)
Structure that defines the new type of image. Must be static: a pointer to this structure is retained by the image code.

Tcl_Interp *interp (in)
Interpreter in which image was created.

char *name (in)
Name of existing image.

Tk_ImageType **typePtrPtr (out)
Points to word in which to store a pointer to type information for the given image, if it exists.

int argc (in)
Number of arguments

char ***argvPtr (in/out)
Pointer to argument list

DESCRIPTION

Tk_CreateImageType is invoked to define a new kind of image. An image type corresponds to a particular value of the type argument for the image create command. There may exist any number of different image types, and new types may be defined dynamically by calling Tk_CreateImageType. For example, there might be one type for 2-color bitmaps, another for multi-color images, another for dithered images, another for video, and so on.

The code that implements a new image type is called an image manager. It consists of a collection of procedures plus three different kinds of data structures. The first data structure is a Tk_ImageType structure, which contains the name of the image type and pointers to five procedures provided by the image manager to deal with images of this type:

typedef struct Tk_ImageType {
    char *name;
    Tk_ImageCreateProc *createProc;
    Tk_ImageGetProc *getProc;
    Tk_ImageDisplayProc *displayProc;
    Tk_ImageFreeProc *freeProc;
    Tk_ImageDeleteProc *deleteProc;
} Tk_ImageType;
The fields of this structure will be described in later subsections of this entry.

The second major data structure manipulated by an image manager is called an image master; it contains overall information about a particular image, such as the values of the configuration options specified in an image create command. There will usually be one of these structures for each invocation of the image create command.

The third data structure related to images is an image instance. There will usually be one of these structures for each usage of an image in a particular widget. It is possible for a single image to appear simultaneously in multiple widgets, or even multiple times in the same widget. Furthermore, different instances may be on different screens or displays. The image instance data structure describes things that may vary from instance to instance, such as colors and graphics contexts for redisplay. There is usually one instance structure for each -image option specified for a widget or canvas item.

The following subsections describe the fields of a Tk_ImageType in more detail.

NAME

typePtr->name provides a name for the image type. Once Tk_CreateImageType returns, this name may be used in image create commands to create images of the new type. If there already existed an image type by this name then the new image type replaces the old one.

PORTABILITY

In Tk 8.2 and earlier, the createProc below had a different signature. If you want to compile an image type using the old interface which should still run on all Tcl/Tk versions, compile it with the flag -DUSE_OLD_IMAGE. Further on, if you are using Stubs, you need to call the function Tk_InitImageArgs(interp, argc, &argv) first in your createProc. See below for a description of this function.

CREATEPROC

typePtr->createProc provides the address of a procedure for Tk to call whenever image create is invoked to create an image of the new type. typePtr->createProc must match the following prototype:
typedef int Tk_ImageCreateProc(
    Tcl_Interp *interp,
    char *name,
    int objc,
    Tcl_Obj *CONST objv[],
    Tk_ImageType *typePtr,
    Tk_ImageMaster master,
    ClientData *masterDataPtr);
The interp argument is the interpreter in which the image command was invoked, and name is the name for the new image, which was either specified explicitly in the image command or generated automatically by the image command. The objc and objv arguments describe all the configuration options for the new image (everything after the name argument to image). The master argument is a token that refers to Tk's information about this image; the image manager must return this token to Tk when invoking the Tk_ImageChanged procedure. Typically createProc will parse objc and objv and create an image master data structure for the new image. createProc may store an arbitrary one-word value at *masterDataPtr, which will be passed back to the image manager when other callbacks are invoked. Typically the value is a pointer to the master data structure for the image.

If createProc encounters an error, it should leave an error message in interp->result and return TCL_ERROR; otherwise it should return TCL_OK.

createProc should call Tk_ImageChanged in order to set the size of the image and request an initial redisplay.

GETPROC

typePtr->getProc is invoked by Tk whenever a widget calls Tk_GetImage to use a particular image. This procedure must match the following prototype:
typedef ClientData Tk_ImageGetProc(
    Tk_Window tkwin,
    ClientData masterData);
The tkwin argument identifies the window in which the image will be used and masterData is the value returned by createProc when the image master was created. getProc will usually create a data structure for the new instance, including such things as the resources needed to display the image in the given window. getProc returns a one-word token for the instance, which is typically the address of the instance data structure. Tk will pass this value back to the image manager when invoking its displayProc and freeProc procedures.

DISPLAYPROC

typePtr->displayProc is invoked by Tk whenever an image needs to be displayed (i.e., whenever a widget calls Tk_RedrawImage). displayProc must match the following prototype:
typedef void Tk_ImageDisplayProc(
    ClientData instanceData,
    Display *display,
    Drawable drawable,
    int imageX,
    int imageY,
    int width,
    int height,
    int drawableX,
    int drawableY);
The instanceData will be the same as the value returned by getProc when the instance was created. display and drawable indicate where to display the image; drawable may be a pixmap rather than the window specified to getProc (this is usually the case, since most widgets double-buffer their redisplay to get smoother visual effects). imageX, imageY, width, and height identify the region of the image that must be redisplayed. This region will always be within the size of the image as specified in the most recent call to Tk_ImageChanged. drawableX and drawableY indicate where in drawable the image should be displayed; displayProc should display the given region of the image so that point (imageX, imageY) in the image appears at (drawableX, drawableY) in drawable.

FREEPROC

typePtr->freeProc contains the address of a procedure that Tk will invoke when an image instance is released (i.e., when Tk_FreeImage is invoked). This can happen, for example, when a widget is deleted or a image item in a canvas is deleted, or when the image displayed in a widget or canvas item is changed. freeProc must match the following prototype:
typedef void Tk_ImageFreeProc(
    ClientData instanceData,
    Display *display);
The instanceData will be the same as the value returned by getProc when the instance was created, and display is the display containing the window for the instance. freeProc should release any resources associated with the image instance, since the instance will never be used again.

DELETEPROC

typePtr->deleteProc is a procedure that Tk invokes when an image is being deleted (i.e. when the image delete command is invoked). Before invoking deleteProc Tk will invoke freeProc for each of the image's instances. deleteProc must match the following prototype:
typedef void Tk_ImageDeleteProc(
    ClientData masterData);
The masterData argument will be the same as the value stored in *masterDataPtr by createProc when the image was created. deleteProc should release any resources associated with the image.

TK_GETIMAGEMASTERDATA

The procedure Tk_GetImageMasterData may be invoked to retrieve information about an image. For example, an image manager can use this procedure to locate its image master data for an image. If there exists an image named name in the interpreter given by interp, then *typePtrPtr is filled in with type information for the image (the typePtr value passed to Tk_CreateImageType when the image type was registered) and the return value is the ClientData value returned by the createProc when the image was created (this is typically a pointer to the image master data structure). If no such image exists then NULL is returned and NULL is stored at *typePtrPtr.

TK_INITIMAGEARGS

The function Tk_InitImageArgs converts the arguments of the createProc from objects to strings when necessary. When not using stubs, not using the old interface, or running under an older (pre-8.3) Tk version, this function has no effect. This function makes porting older image handlers to the new interface a lot easier: After running this function, the arguments are guaranteed to be in string format, no matter how Tk deliverd them.

SEE ALSO

Tk_ImageChanged, Tk_GetImage, Tk_FreeImage, Tk_RedrawImage, Tk_SizeOfImage

KEYWORDS

image manager, image type, instance, master
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tk Library Procedures - Tk_CreateItemType manual page

NAME
Tk_CreateItemType, Tk_GetItemTypes - define new kind of canvas item
SYNOPSIS
ARGUMENTS
INTRODUCTION
DATA STRUCTURES
NAME
ITEMSIZE
CREATEPROC
CONFIGSPECS
CONFIGPROC
COORDPROC
DELETEPROC
DISPLAYPROC AND ALWAYSREDRAW
POINTPROC
AREAPROC
POSTSCRIPTPROC
SCALEPROC
TRANSLATEPROC
INDEXPROC
ICURSORPROC
SELECTIONPROC
INSERTPROC
DCHARSPROC
SEE ALSO
KEYWORDS

NAME

Tk_CreateItemType, Tk_GetItemTypes - define new kind of canvas item

SYNOPSIS

#include <tk.h>
Tk_CreateItemType(typePtr)
Tk_ItemType *
Tk_GetItemTypes()

ARGUMENTS

Tk_ItemType *typePtr (in)
Structure that defines the new type of canvas item.

INTRODUCTION

Tk_CreateItemType is invoked to define a new kind of canvas item described by the typePtr argument. An item type corresponds to a particular value of the type argument to the create widget command for canvases, and the code that implements a canvas item type is called a type manager. Tk defines several built-in item types, such as rectangle and text and image, but Tk_CreateItemType allows additional item types to be defined. Once Tk_CreateItemType returns, the new item type may be used in new or existing canvas widgets just like the built-in item types.

Tk_GetItemTypes returns a pointer to the first in the list of all item types currently defined for canvases. The entries in the list are linked together through their nextPtr fields, with the end of the list marked by a NULL nextPtr.

You may find it easier to understand the rest of this manual entry by looking at the code for an existing canvas item type such as bitmap (file tkCanvBmap.c) or text (tkCanvText.c). The easiest way to create a new type manager is to copy the code for an existing type and modify it for the new type.

Tk provides a number of utility procedures for the use of canvas type managers, such as Tk_CanvasCoords and Tk_CanvasPsColor; these are described in separate manual entries.

DATA STRUCTURES

A type manager consists of a collection of procedures that provide a standard set of operations on items of that type. The type manager deals with three kinds of data structures. The first data structure is a Tk_ItemType; it contains information such as the name of the type and pointers to the standard procedures implemented by the type manager:
typedef struct Tk_ItemType {
    char *name;
    int itemSize;
    Tk_ItemCreateProc *createProc;
    Tk_ConfigSpec *configSpecs;
    Tk_ItemConfigureProc *configProc;
    Tk_ItemCoordProc *coordProc;
    Tk_ItemDeleteProc *deleteProc;
    Tk_ItemDisplayProc *displayProc;
    int alwaysRedraw;
    Tk_ItemPointProc *pointProc;
    Tk_ItemAreaProc *areaProc;
    Tk_ItemPostscriptProc *postscriptProc;
    Tk_ItemScaleProc *scaleProc;
    Tk_ItemTranslateProc *translateProc;
    Tk_ItemIndexProc *indexProc;
    Tk_ItemCursorProc *icursorProc;
    Tk_ItemSelectionProc *selectionProc;
    Tk_ItemInsertProc *insertProc;
    Tk_ItemDCharsProc *dCharsProc;
    Tk_ItemType *nextPtr;
} Tk_ItemType;

The fields of a Tk_ItemType structure are described in more detail later in this manual entry. When Tk_CreateItemType is called, its typePtr argument must point to a structure with all of the fields initialized except nextPtr, which Tk sets to link all the types together into a list. The structure must be in permanent memory (either statically allocated or dynamically allocated but never freed); Tk retains a pointer to this structure.

The second data structure manipulated by a type manager is an item record. For each item in a canvas there exists one item record. All of the items of a given type generally have item records with the same structure, but different types usually have different formats for their item records. The first part of each item record is a header with a standard structure defined by Tk via the type Tk_Item; the rest of the item record is defined by the type manager. A type manager must define its item records with a Tk_Item as the first field. For example, the item record for bitmap items is defined as follows:

typedef struct BitmapItem {
    Tk_Item header;
    double x, y;
    Tk_Anchor anchor;
    Pixmap bitmap;
    XColor *fgColor;
    XColor *bgColor;
    GC gc;
} BitmapItem;
The header substructure contains information used by Tk to manage the item, such as its identifier, its tags, its type, and its bounding box. The fields starting with x belong to the type manager: Tk will never read or write them. The type manager should not need to read or write any of the fields in the header except for four fields whose names are x1, y1, x2, and y2. These fields give a bounding box for the items using integer canvas coordinates: the item should not cover any pixels with x-coordinate lower than x1 or y-coordinate lower than y1, nor should it cover any pixels with x-coordinate greater than or equal to x2 or y-coordinate greater than or equal to y2. It is up to the type manager to keep the bounding box up to date as the item is moved and reconfigured.

Whenever Tk calls a procedure in a type manager it passes in a pointer to an item record. The argument is always passed as a pointer to a Tk_Item; the type manager will typically cast this into a pointer to its own specific type, such as BitmapItem.

The third data structure used by type managers has type Tk_Canvas; it serves as an opaque handle for the canvas widget as a whole. Type managers need not know anything about the contents of this structure. A Tk_Canvas handle is typically passed in to the procedures of a type manager, and the type manager can pass the handle back to library procedures such as Tk_CanvasTkwin to fetch information about the canvas.

NAME

This section and the ones that follow describe each of the fields in a Tk_ItemType structure in detail. The name field provides a string name for the item type. Once Tk_CreateImageType returns, this name may be used in create widget commands to create items of the new type. If there already existed an item type by this name then the new item type replaces the old one.

ITEMSIZE

typePtr->itemSize gives the size in bytes of item records of this type, including the Tk_Item header. Tk uses this size to allocate memory space for items of the type. All of the item records for a given type must have the same size. If variable length fields are needed for an item (such as a list of points for a polygon), the type manager can allocate a separate object of variable length and keep a pointer to it in the item record.

CREATEPROC

typePtr->createProc points to a procedure for Tk to call whenever a new item of this type is created. typePtr->createProc must match the following prototype:
typedef int Tk_ItemCreateProc(
    Tcl_Interp *interp,
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    int objc,
    Tcl_Obj* CONST objv);
The interp argument is the interpreter in which the canvas's create widget command was invoked, and canvas is a handle for the canvas widget. itemPtr is a pointer to a newly-allocated item of size typePtr->itemSize. Tk has already initialized the item's header (the first sizeof(Tk_ItemType) bytes). The objc and objv arguments describe all of the arguments to the create command after the type argument. For example, in the widget command
    .c create rectangle 10 20 50 50 -fill black
objc will be 6 and objv[0] will contain the integer object 10.

createProc should use objc and objv to initialize the type-specific parts of the item record and set an initial value for the bounding box in the item's header. It should return a standard Tcl completion code and leave an error message in interp->result if an error occurs. If an error occurs Tk will free the item record, so createProc must be sure to leave the item record in a clean state if it returns an error (e.g., it must free any additional memory that it allocated for the item).

CONFIGSPECS

Each type manager must provide a standard table describing its configuration options, in a form suitable for use with Tk_ConfigureWidget. This table will normally be used by typePtr->createProc and typePtr->configProc, but Tk also uses it directly to retrieve option information in the itemcget and itemconfigure widget commands. typePtr->configSpecs must point to the configuration table for this type. Note: Tk provides a custom option type tk_CanvasTagsOption for implementing the -tags option; see an existing type manager for an example of how to use it in configSpecs.

CONFIGPROC

typePtr->configProc is called by Tk whenever the itemconfigure widget command is invoked to change the configuration options for a canvas item. This procedure must match the following prototype:
typedef int Tk_ItemConfigureProc(
    Tcl_Interp *interp,
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    int objc,
    Tcl_Obj* CONST objv,
    int flags);
The interp objument identifies the interpreter in which the widget command was invoked, canvas is a handle for the canvas widget, and itemPtr is a pointer to the item being configured. objc and objv contain the configuration options. For example, if the following command is invoked:
    .c itemconfigure 2 -fill red -outline black
objc is 4 and objv contains the string objects -fill through black. objc will always be an even value. The flags argument contains flags to pass to Tk_ConfigureWidget; currently this value is always TK_CONFIG_ARGV_ONLY when Tk invokes typePtr->configProc, but the type manager's createProc procedure will usually invoke configProc with different flag values.

typePtr->configProc returns a standard Tcl completion code and leaves an error message in interp->result if an error occurs. It must update the item's bounding box to reflect the new configuration options.

COORDPROC

typePtr->coordProc is invoked by Tk to implement the coords widget command for an item. It must match the following prototype:
typedef int Tk_ItemCoordProc(
    Tcl_Interp *interp,
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    int objc,
    Tcl_Obj* CONST objv);
The arguments interp, canvas, and itemPtr all have the standard meanings, and objc and objv describe the coordinate arguments. For example, if the following widget command is invoked:
    .c coords 2 30 90
objc will be 2 and objv will contain the integer objects 30 and 90.

The coordProc procedure should process the new coordinates, update the item appropriately (e.g., it must reset the bounding box in the item's header), and return a standard Tcl completion code. If an error occurs, coordProc must leave an error message in interp->result.

DELETEPROC

typePtr->deleteProc is invoked by Tk to delete an item and free any resources allocated to it. It must match the following prototype:
typedef void Tk_ItemDeleteProc(
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    Display *display);
The canvas and itemPtr arguments have the usual interpretations, and display identifies the X display containing the canvas. deleteProc must free up any resources allocated for the item, so that Tk can free the item record. deleteProc should not actually free the item record; this will be done by Tk when deleteProc returns.

DISPLAYPROC AND ALWAYSREDRAW

typePtr->displayProc is invoked by Tk to redraw an item on the screen. It must match the following prototype:
typedef void Tk_ItemDisplayProc(
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    Display *display,
    Drawable dst,
    int x,
    int y,
    int width,
    int height);
The canvas and itemPtr arguments have the usual meaning. display identifies the display containing the canvas, and dst specifies a drawable in which the item should be rendered; typically this is an off-screen pixmap, which Tk will copy into the canvas's window once all relevant items have been drawn. x, y, width, and height specify a rectangular region in canvas coordinates, which is the area to be redrawn; only information that overlaps this area needs to be redrawn. Tk will not call displayProc unless the item's bounding box overlaps the redraw area, but the type manager may wish to use the redraw area to optimize the redisplay of the item.

Because of scrolling and the use of off-screen pixmaps for double-buffered redisplay, the item's coordinates in dst will not necessarily be the same as those in the canvas. displayProc should call Tk_CanvasDrawableCoords to transform coordinates from those of the canvas to those of dst.

Normally an item's displayProc is only invoked if the item overlaps the area being displayed. However, if typePtr->alwaysRedraw has a non-zero value, then displayProc is invoked during every redisplay operation, even if the item doesn't overlap the area of redisplay. alwaysRedraw should normally be set to 0; it is only set to 1 in special cases such as window items that need to be unmapped when they are off-screen.

POINTPROC

typePtr->pointProc is invoked by Tk to find out how close a given point is to a canvas item. Tk uses this procedure for purposes such as locating the item under the mouse or finding the closest item to a given point. The procedure must match the following prototype:
typedef double Tk_ItemPointProc(
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    double *pointPtr);
canvas and itemPtr have the usual meaning. pointPtr points to an array of two numbers giving the x and y coordinates of a point. pointProc must return a real value giving the distance from the point to the item, or 0 if the point lies inside the item.

AREAPROC

typePtr->areaProc is invoked by Tk to find out the relationship between an item and a rectangular area. It must match the following prototype:
typedef int Tk_ItemAreaProc(
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    double *rectPtr);
canvas and itemPtr have the usual meaning. rectPtr points to an array of four real numbers; the first two give the x and y coordinates of the upper left corner of a rectangle, and the second two give the x and y coordinates of the lower right corner. areaProc must return -1 if the item lies entirely outside the given area, 0 if it lies partially inside and partially outside the area, and 1 if it lies entirely inside the area.

POSTSCRIPTPROC

typePtr->postscriptProc is invoked by Tk to generate Postcript for an item during the postscript widget command. If the type manager is not capable of generating Postscript then typePtr->postscriptProc should be NULL. The procedure must match the following prototype:
typedef int Tk_ItemPostscriptProc(
    Tcl_Interp *interp,
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    int prepass);
The interp, canvas, and itemPtr arguments all have standard meanings; prepass will be described below. If postscriptProc completes successfully, it should append Postscript for the item to the information in interp->result (e.g. by calling Tcl_AppendResult, not Tcl_SetResult) and return TCL_OK. If an error occurs, postscriptProc should clear the result and replace its contents with an error message; then it should return TCL_ERROR.

Tk provides a collection of utility procedures to simplify postscriptProc. For example, Tk_CanvasPsColor will generate Postscript to set the current color to a given Tk color and Tk_CanvasPsFont will set up font information. When generating Postscript, the type manager is free to change the graphics state of the Postscript interpreter, since Tk places gsave and grestore commands around the Postscript for the item. The type manager can use canvas x coordinates directly in its Postscript, but it must call Tk_CanvasPsY to convert y coordinates from the space of the canvas (where the origin is at the upper left) to the space of Postscript (where the origin is at the lower left).

In order to generate Postscript that complies with the Adobe Document Structuring Conventions, Tk actually generates Postscript in two passes. It calls each item's postscriptProc in each pass. The only purpose of the first pass is to collect font information (which is done by Tk_CanvasPsFont); the actual Postscript is discarded. Tk sets the prepass argument to postscriptProc to 1 during the first pass; the type manager can use prepass to skip all Postscript generation except for calls to Tk_CanvasPsFont. During the second pass prepass will be 0, so the type manager must generate complete Postscript.

SCALEPROC

typePtr->scaleProc is invoked by Tk to rescale a canvas item during the scale widget command. The procedure must match the following prototype:
typedef void Tk_ItemScaleProc(
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    double originX,
    double originY,
    double scaleX,
    double scaleY);
The canvas and itemPtr arguments have the usual meaning. originX and originY specify an origin relative to which the item is to be scaled, and scaleX and scaleY give the x and y scale factors. The item should adjust its coordinates so that a point in the item that used to have coordinates x and y will have new coordinates x' and y', where
x' = originX  + scaleX*(x-originX)
y' = originY + scaleY*(y-originY)
scaleProc must also update the bounding box in the item's header.

TRANSLATEPROC

typePtr->translateProc is invoked by Tk to translate a canvas item during the move widget command. The procedure must match the following prototype:
typedef void Tk_ItemTranslateProc(
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    double deltaX,
    double deltaY);
The canvas and itemPtr arguments have the usual meaning, and deltaX and deltaY give the amounts that should be added to each x and y coordinate within the item. The type manager should adjust the item's coordinates and update the bounding box in the item's header.

INDEXPROC

typePtr->indexProc is invoked by Tk to translate a string index specification into a numerical index, for example during the index widget command. It is only relevant for item types that support indexable text; typePtr->indexProc may be specified as NULL for non-textual item types. The procedure must match the following prototype:
typedef int Tk_ItemIndexProc(
    Tcl_Interp *interp,
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    char indexString,
    int *indexPtr);
The interp, canvas, and itemPtr arguments all have the usual meaning. indexString contains a textual description of an index, and indexPtr points to an integer value that should be filled in with a numerical index. It is up to the type manager to decide what forms of index are supported (e.g., numbers, insert, sel.first, end, etc.). indexProc should return a Tcl completion code and set interp->result in the event of an error.

ICURSORPROC

typePtr->icursorProc is invoked by Tk during the icursor widget command to set the position of the insertion cursor in a textual item. It is only relevant for item types that support an insertion cursor; typePtr->icursorProc may be specified as NULL for item types that don't support an insertion cursor. The procedure must match the following prototype:
typedef void Tk_ItemCursorProc(
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    int index);
canvas and itemPtr have the usual meanings, and index is an index into the item's text, as returned by a previous call to typePtr->insertProc. The type manager should position the insertion cursor in the item just before the character given by index. Whether or not to actually display the insertion cursor is determined by other information provided by Tk_CanvasGetTextInfo.

SELECTIONPROC

typePtr->selectionProc is invoked by Tk during selection retrievals; it must return part or all of the selected text in the item (if any). It is only relevant for item types that support text; typePtr->selectionProc may be specified as NULL for non-textual item types. The procedure must match the following prototype:
typedef int Tk_ItemSelectionProc(
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    int offset,
    char *buffer,
    int maxBytes);
canvas and itemPtr have the usual meanings. offset is an offset in bytes into the selection where 0 refers to the first byte of the selection; it identifies the first character that is to be returned in this call. buffer points to an area of memory in which to store the requested bytes, and maxBytes specifies the maximum number of bytes to return. selectionProc should extract up to maxBytes characters from the selection and copy them to maxBytes; it should return a count of the number of bytes actually copied, which may be less than maxBytes if there aren't offset+maxBytes bytes in the selection.

INSERTPROC

typePtr->insertProc is invoked by Tk during the insert widget command to insert new text into a canvas item. It is only relevant for item types that support text; typePtr->insertProc may be specified as NULL for non-textual item types. The procedure must match the following prototype:
typedef void Tk_ItemInsertProc(
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    int index,
    char *string);
canvas and itemPtr have the usual meanings. index is an index into the item's text, as returned by a previous call to typePtr->insertProc, and string contains new text to insert just before the character given by index. The type manager should insert the text and recompute the bounding box in the item's header.

DCHARSPROC

typePtr->dCharsProc is invoked by Tk during the dchars widget command to delete a range of text from a canvas item. It is only relevant for item types that support text; typePtr->dCharsProc may be specified as NULL for non-textual item types. The procedure must match the following prototype:
typedef void Tk_ItemDCharsProc(
    Tk_Canvas canvas,
    Tk_Item *itemPtr,
    int first,
    int last);
canvas and itemPtr have the usual meanings. first and last give the indices of the first and last bytes to be deleted, as returned by previous calls to typePtr->indexProc. The type manager should delete the specified characters and update the bounding box in the item's header.

SEE ALSO

Tk_CanvasPsY, Tk_CanvasTextInfo, Tk_CanvasTkwin

KEYWORDS

canvas, focus, item type, selection, type manager
Copyright © 1994-1995 Sun Microsystems, Inc.


Tk Library Procedures - Tk_CreatePhotoImageFormat manual page

NAME
Tk_CreatePhotoImageFormat - define new file format for photo images
SYNOPSIS
ARGUMENTS
DESCRIPTION
PORTABILITY
NAME
FILEMATCHPROC
STRINGMATCHPROC
FILEREADPROC
STRINGREADPROC
FILEWRITEPROC
STRINGWRITEPROC
SEE ALSO
KEYWORDS

NAME

Tk_CreatePhotoImageFormat - define new file format for photo images

SYNOPSIS

#include <tk.h>
#include <tkPhoto.h>
Tk_CreatePhotoImageFormat(formatPtr)

ARGUMENTS

Tk_PhotoImageFormat *formatPtr (in)
Structure that defines the new file format.

DESCRIPTION

Tk_CreatePhotoImageFormat is invoked to define a new file format for image data for use with photo images. The code that implements an image file format is called an image file format handler, or handler for short. The photo image code maintains a list of handlers that can be used to read and write data to or from a file. Some handlers may also support reading image data from a string or converting image data to a string format. The user can specify which handler to use with the -format image configuration option or the -format option to the read and write photo image subcommands.

An image file format handler consists of a collection of procedures plus a Tk_PhotoImageFormat structure, which contains the name of the image file format and pointers to six procedures provided by the handler to deal with files and strings in this format. The Tk_PhotoImageFormat structure contains the following fields:

typedef struct Tk_PhotoImageFormat {
    char *name;
    Tk_ImageFileMatchProc *fileMatchProc;
    Tk_ImageStringMatchProc *stringMatchProc;
    Tk_ImageFileReadProc *fileReadProc;
    Tk_ImageStringReadProc *stringReadProc;
    Tk_ImageFileWriteProc *fileWriteProc;
    Tk_ImageStringWriteProc *stringWriteProc;
} Tk_PhotoImageFormat;

The handler need not provide implementations of all six procedures. For example, the procedures that handle string data would not be provided for a format in which the image data are stored in binary, and could therefore contain null characters. If any procedure is not implemented, the corresponding pointer in the Tk_PhotoImageFormat structure should be set to NULL. The handler must provide the fileMatchProc procedure if it provides the fileReadProc procedure, and the stringMatchProc procedure if it provides the stringReadProc procedure.

PORTABILITY

In Tk 8.2 and earlier, a different interface was used. Tk 8.3 will still support the old format handlers if the format name is in upper case. If you still want to compile old format handlers with Tk8.3, use the flag -DUSE_OLD_IMAGE. This will restore all function prototypes to match the pre-8.3 situation.

NAME

formatPtr->name provides a name for the image type. Once Tk_CreatePhotoImageFormat returns, this name may be used in the -format photo image configuration and subcommand option. The manual page for the photo image (photo(n)) describes how image file formats are chosen based on their names and the value given to the -format option. For new format handlers, the name should be in lower case. Pre-8.3 format handlers are assumed to be in upper case.

FILEMATCHPROC

formatPtr->fileMatchProc provides the address of a procedure for Tk to call when it is searching for an image file format handler suitable for reading data in a given file. formatPtr->fileMatchProc must match the following prototype:
typedef int Tk_ImageFileMatchProc(
    Tcl_Channel chan,
    CONST char *fileName,
    Tcl_Obj *format,
    int *widthPtr,
    int *heightPtr,
    Tcl_Interp *interp);
The fileName argument is the name of the file containing the image data, which is open for reading as chan. The format argument contains the value given for the -format option, or NULL if the option was not specified. If the data in the file appears to be in the format supported by this handler, the formatPtr->fileMatchProc procedure should store the width and height of the image in *widthPtr and *heightPtr respectively, and return 1. Otherwise it should return 0.

STRINGMATCHPROC

formatPtr->stringMatchProc provides the address of a procedure for Tk to call when it is searching for an image file format handler for suitable for reading data from a given string. formatPtr->stringMatchProc must match the following prototype:
typedef int Tk_ImageStringMatchProc(
    Tcl_Obj *data,
    Tcl_Obj *format,
    int *widthPtr,
    int *heightPtr,
    Tcl_Interp *interp);
The data argument points to the object containing the image data. The format argument contains the value given for the -format option, or NULL if the option was not specified. If the data in the string appears to be in the format supported by this handler, the formatPtr->stringMatchProc procedure should store the width and height of the image in *widthPtr and *heightPtr respectively, and return 1. Otherwise it should return 0.

FILEREADPROC

formatPtr->fileReadProc provides the address of a procedure for Tk to call to read data from an image file into a photo image. formatPtr->fileReadProc must match the following prototype:
typedef int Tk_ImageFileReadProc(
    Tcl_Interp *interp,
    Tcl_Channel chan,
    CONST char *fileName,
    Tcl_Obj *format,
    PhotoHandle imageHandle,
    int destX, int destY,
    int width, int height,
    int srcX, int srcY);
The interp argument is the interpreter in which the command was invoked to read the image; it should be used for reporting errors. The image data is in the file named fileName, which is open for reading as chan. The format argument contains the value given for the -format option, or NULL if the option was not specified. The image data in the file, or a subimage of it, is to be read into the photo image identified by the handle imageHandle. The subimage of the data in the file is of dimensions width x height and has its top-left corner at coordinates (srcX,srcY). It is to be stored in the photo image with its top-left corner at coordinates (destX,destY) using the Tk_PhotoPutBlock procedure. The return value is a standard Tcl return value.

STRINGREADPROC

formatPtr->stringReadProc provides the address of a procedure for Tk to call to read data from a string into a photo image. formatPtr->stringReadProc must match the following prototype:
typedef int Tk_ImageStringReadProc(
    Tcl_Interp *interp,
    Tcl_Obj *data,
    Tcl_Obj *format,
    PhotoHandle imageHandle,
    int destX, int destY,
    int width, int height,
    int srcX, int srcY);
The interp argument is the interpreter in which the command was invoked to read the image; it should be used for reporting errors. The data argument points to the image data in object form. The format argument contains the value given for the -format option, or NULL if the option was not specified. The image data in the string, or a subimage of it, is to be read into the photo image identified by the handle imageHandle. The subimage of the data in the string is of dimensions width x height and has its top-left corner at coordinates (srcX,srcY). It is to be stored in the photo image with its top-left corner at coordinates (destX,destY) using the Tk_PhotoPutBlock procedure. The return value is a standard Tcl return value.

FILEWRITEPROC

formatPtr->fileWriteProc provides the address of a procedure for Tk to call to write data from a photo image to a file. formatPtr->fileWriteProc must match the following prototype:
typedef int Tk_ImageFileWriteProc(
    Tcl_Interp *interp,
    CONST char *fileName,
    Tcl_Obj *format,
    Tk_PhotoImageBlock *blockPtr);
The interp argument is the interpreter in which the command was invoked to write the image; it should be used for reporting errors. The image data to be written are in memory and are described by the Tk_PhotoImageBlock structure pointed to by blockPtr; see the manual page FindPhoto(3) for details. The fileName argument points to the string giving the name of the file in which to write the image data. The format argument contains the value given for the -format option, or NULL if the option was not specified. The format string can contain extra characters after the name of the format. If appropriate, the formatPtr->fileWriteProc procedure may interpret these characters to specify further details about the image file. The return value is a standard Tcl return value.

STRINGWRITEPROC

formatPtr->stringWriteProc provides the address of a procedure for Tk to call to translate image data from a photo image into a string. formatPtr->stringWriteProc must match the following prototype:
typedef int Tk_ImageStringWriteProc(
    Tcl_Interp *interp,
    Tcl_Obj *format,
    Tk_PhotoImageBlock *blockPtr);
The interp argument is the interpreter in which the command was invoked to convert the image; it should be used for reporting errors. The image data to be converted are in memory and are described by the Tk_PhotoImageBlock structure pointed to by blockPtr; see the manual page FindPhoto(3) for details. The data for the string should be put in the interpreter interp result. The format argument contains the value given for the -format option, or NULL if the option was not specified. The format string can contain extra characters after the name of the format. If appropriate, the formatPtr->stringWriteProc procedure may interpret these characters to specify further details about the image file. The return value is a standard Tcl return value.

SEE ALSO

Tk_FindPhoto, Tk_PhotoPutBlock

KEYWORDS

photo image, image file
Copyright © 1994 The Australian National University
Copyright © 1994-1997 Sun Microsystems, Inc.


Tk Library Procedures - Tk_CreateSelHandler manual page

NAME

Tk_CreateSelHandler, Tk_DeleteSelHandler - arrange to handle requests for a selection

SYNOPSIS

#include <tk.h>
Tk_CreateSelHandler(tkwin, selection, target, proc, clientData, format)
Tk_DeleteSelHandler(tkwin, selection, target)

ARGUMENTS

Tk_Window tkwin (in)
Window for which proc will provide selection information.

Atom selection (in)
The name of the selection for which proc will provide selection information.

Atom target (in)
Form in which proc can provide the selection (e.g. STRING or FILE_NAME). Corresponds to type arguments in selection commands.

Tk_SelectionProc *proc (in)
Procedure to invoke whenever the selection is owned by tkwin and the selection contents are requested in the format given by target.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

Atom format (in)
If the selection requestor isn't in this process, format determines the representation used to transmit the selection to its requestor.

DESCRIPTION

Tk_CreateSelHandler arranges for a particular procedure (proc) to be called whenever selection is owned by tkwin and the selection contents are requested in the form given by target. Target should be one of the entries defined in the left column of Table 2 of the X Inter-Client Communication Conventions Manual (ICCCM) or any other form in which an application is willing to present the selection. The most common form is STRING.

Proc should have arguments and result that match the type Tk_SelectionProc:

typedef int Tk_SelectionProc(
    ClientData clientData,
    int offset,
    char *buffer,
    int maxBytes);
The clientData parameter to proc is a copy of the clientData argument given to Tk_CreateSelHandler. Typically, clientData points to a data structure containing application-specific information that is needed to retrieve the selection. Offset specifies an offset position into the selection, buffer specifies a location at which to copy information about the selection, and maxBytes specifies the amount of space available at buffer. Proc should place a NULL-terminated string at buffer containing maxBytes or fewer characters (not including the terminating NULL), and it should return a count of the number of non-NULL characters stored at buffer. If the selection no longer exists (e.g. it once existed but the user deleted the range of characters containing it), then proc should return -1.

When transferring large selections, Tk will break them up into smaller pieces (typically a few thousand bytes each) for more efficient transmission. It will do this by calling proc one or more times, using successively higher values of offset to retrieve successive portions of the selection. If proc returns a count less than maxBytes it means that the entire remainder of the selection has been returned. If proc's return value is maxBytes it means there may be additional information in the selection, so Tk must make another call to proc to retrieve the next portion.

Proc always returns selection information in the form of a character string. However, the ICCCM allows for information to be transmitted from the selection owner to the selection requestor in any of several formats, such as a string, an array of atoms, an array of integers, etc. The format argument to Tk_CreateSelHandler indicates what format should be used to transmit the selection to its requestor (see the middle column of Table 2 of the ICCCM for examples). If format is not STRING, then Tk will take the value returned by proc and divided it into fields separated by white space. If format is ATOM, then Tk will return the selection as an array of atoms, with each field in proc's result treated as the name of one atom. For any other value of format, Tk will return the selection as an array of 32-bit values where each field of proc's result is treated as a number and translated to a 32-bit value. In any event, the format atom is returned to the selection requestor along with the contents of the selection.

If Tk_CreateSelHandler is called when there already exists a handler for selection and target on tkwin, then the existing handler is replaced with a new one.

Tk_DeleteSelHandler removes the handler given by tkwin, selection, and target, if such a handler exists. If there is no such handler then it has no effect.

KEYWORDS

format, handler, selection, target
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_CreateWindow manual page

NAME

Tk_CreateWindow, Tk_CreateWindowFromPath, Tk_DestroyWindow, Tk_MakeWindowExist - create or delete window

SYNOPSIS

#include <tk.h>
Tk_Window
Tk_CreateWindow(interp, parent, name, topLevScreen)
Tk_Window
Tk_CreateWindowFromPath(interp, tkwin, pathName, topLevScreen)
Tk_DestroyWindow(tkwin)
Tk_MakeWindowExist(tkwin)

ARGUMENTS

Tcl_Interp *interp (out)
Tcl interpreter to use for error reporting. If no error occurs, then *interp isn't modified.

Tk_Window parent (in)
Token for the window that is to serve as the logical parent of the new window.

char *name (in)
Name to use for this window. Must be unique among all children of the same parent.

char *topLevScreen (in)
Has same format as screenName. If NULL, then new window is created as an internal window. If non-NULL, new window is created as a top-level window on screen topLevScreen. If topLevScreen is an empty string (``'') then new window is created as top-level window of parent's screen.

Tk_Window tkwin (in)
Token for window.

char *pathName (in)
Name of new window, specified as path name within application (e.g. .a.b.c).

DESCRIPTION

The procedures Tk_CreateWindow and Tk_CreateWindowFromPath are used to create new windows for use in Tk-based applications. Each of the procedures returns a token that can be used to manipulate the window in other calls to the Tk library. If the window couldn't be created successfully, then NULL is returned and interp->result is modified to hold an error message.

Tk supports two different kinds of windows: internal windows and top-level windows. An internal window is an interior window of a Tk application, such as a scrollbar or menu bar or button. A top-level window is one that is created as a child of a screen's root window, rather than as an interior window, but which is logically part of some existing main window. Examples of top-level windows are pop-up menus and dialog boxes.

New windows may be created by calling Tk_CreateWindow. If the topLevScreen argument is NULL, then the new window will be an internal window. If topLevScreen is non-NULL, then the new window will be a top-level window: topLevScreen indicates the name of a screen and the new window will be created as a child of the root window of topLevScreen. In either case Tk will consider the new window to be the logical child of parent: the new window's path name will reflect this fact, options may be specified for the new window under this assumption, and so on. The only difference is that new X window for a top-level window will not be a child of parent's X window. For example, a pull-down menu's parent would be the button-like window used to invoke it, which would in turn be a child of the menu bar window. A dialog box might have the application's main window as its parent.

Tk_CreateWindowFromPath offers an alternate way of specifying new windows. In Tk_CreateWindowFromPath the new window is specified with a token for any window in the target application (tkwin), plus a path name for the new window. It produces the same effect as Tk_CreateWindow and allows both top-level and internal windows to be created, depending on the value of topLevScreen. In calls to Tk_CreateWindowFromPath, as in calls to Tk_CreateWindow, the parent of the new window must exist at the time of the call, but the new window must not already exist.

The window creation procedures don't actually issue the command to X to create a window. Instead, they create a local data structure associated with the window and defer the creation of the X window. The window will actually be created by the first call to Tk_MapWindow. Deferred window creation allows various aspects of the window (such as its size, background color, etc.) to be modified after its creation without incurring any overhead in the X server. When the window is finally mapped all of the window attributes can be set while creating the window.

The value returned by a window-creation procedure is not the X token for the window (it can't be, since X hasn't been asked to create the window yet). Instead, it is a token for Tk's local data structure for the window. Most of the Tk library procedures take Tk_Window tokens, rather than X identifiers. The actual X window identifier can be retrieved from the local data structure using the Tk_WindowId macro; see the manual entry for Tk_WindowId for details.

Tk_DestroyWindow deletes a window and all the data structures associated with it, including any event handlers created with Tk_CreateEventHandler. In addition, Tk_DestroyWindow will delete any children of tkwin recursively (where children are defined in the Tk sense, consisting of all windows that were created with the given window as parent). If tkwin is an internal window, then event handlers interested in destroy events are invoked immediately. If tkwin is a top-level or main window, then the event handlers will be invoked later, after X has seen the request and returned an event for it.

If a window has been created but hasn't been mapped, so no X window exists, it is possible to force the creation of the X window by calling Tk_MakeWindowExist. This procedure issues the X commands to instantiate the window given by tkwin.

KEYWORDS

create, deferred creation, destroy, display, internal window, screen, top-level window, window
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_DeleteImage manual page

NAME

Tk_DeleteImage - Destroy an image.

SYNOPSIS

#include <tk.h>
Tk_DeleteImage(interp, name)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter for which the image was created.

char *name (in)
Name of the image.

DESCRIPTION

Tk_DeleteImage deletes the image given by interp and name, if there is one. All instances of that image will redisplay as empty regions. If the given image does not exist then the procedure has no effect.

KEYWORDS

delete image, image manager
Copyright © 1995-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_DrawFocusHighlight manual page

NAME

Tk_DrawFocusHighlight - draw the traversal highlight ring for a widget

SYNOPSIS

#include <tk.h>
Tk_DrawFocusHighlight(tkwin, gc, width, drawable)

ARGUMENTS

Tk_Window tkwin (in)
Window for which the highlight is being drawn. Used to retrieve the window's dimensions, among other things.

GC gc (in)
Graphics context to use for drawing the highlight.

int width (in)
Width of the highlight ring, in pixels.

Drawable drawable (in)
Drawable in which to draw the highlight; usually an offscreen pixmap for double buffering.

DESCRIPTION

Tk_DrawFocusHighlight is a utility procedure that draws the traversal highlight ring for a widget. It is typically invoked by widgets during redisplay.

KEYWORDS

focus, traversal highlight
Copyright © 1995-1996 Sun Microsystems, Inc.


Library Procedures - Tk_CreateEventHandler manual page

NAME

Tk_CreateEventHandler, Tk_DeleteEventHandler - associate procedure callback with an X event

SYNOPSIS

#include <tk.h>
Tk_CreateEventHandler(tkwin, mask, proc, clientData)
Tk_DeleteEventHandler(tkwin, mask, proc, clientData)

ARGUMENTS

Tk_Window tkwin (in)
Token for window in which events may occur.

unsigned long mask (in)
Bit-mask of events (such as ButtonPressMask) for which proc should be called.

Tk_EventProc *proc (in)
Procedure to invoke whenever an event in mask occurs in the window given by tkwin.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

Tk_CreateEventHandler arranges for proc to be invoked in the future whenever one of the event types specified by mask occurs in the window specified by tkwin. The callback to proc will be made by Tk_HandleEvent; this mechanism only works in programs that dispatch events through Tk_HandleEvent (or through other Tk procedures that call Tk_HandleEvent, such as Tk_DoOneEvent or Tk_MainLoop).

Proc should have arguments and result that match the type Tk_EventProc:

typedef void Tk_EventProc(
    ClientData clientData,
    XEvent *eventPtr);
The clientData parameter to proc is a copy of the clientData argument given to Tk_CreateEventHandler when the callback was created. Typically, clientData points to a data structure containing application-specific information about the window in which the event occurred. EventPtr is a pointer to the X event, which will be one of the ones specified in the mask argument to Tk_CreateEventHandler.

Tk_DeleteEventHandler may be called to delete a previously-created event handler: it deletes the first handler it finds that is associated with tkwin and matches the mask, proc, and clientData arguments. If no such handler exists, then Tk_HandleEvent returns without doing anything. Although Tk supports it, it's probably a bad idea to have more than one callback with the same mask, proc, and clientData arguments. When a window is deleted all of its handlers will be deleted automatically; in this case there is no need to call Tk_DeleteEventHandler.

If multiple handlers are declared for the same type of X event on the same window, then the handlers will be invoked in the order they were created.

KEYWORDS

bind, callback, event, handler
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_FindPhoto manual page

NAME

Tk_FindPhoto, Tk_PhotoPutBlock, Tk_PhotoPutZoomedBlock, Tk_PhotoGetImage, Tk_PhotoBlank, Tk_PhotoExpand, Tk_PhotoGetSize, Tk_PhotoSetSize - manipulate the image data stored in a photo image.

SYNOPSIS

#include <tk.h>
#include <tkPhoto.h>
Tk_PhotoHandle
Tk_FindPhoto(interp, imageName)
void
Tk_PhotoPutBlock(handle, blockPtr, x, y, width, height)
void
Tk_PhotoPutZoomedBlock(handle, blockPtr, x, y, width, height,
zoomX, zoomY, subsampleX, subsampleY)
int
Tk_PhotoGetImage(handle, blockPtr)
void
Tk_PhotoBlank(handle)
void
Tk_PhotoExpand(handle, width, height)
void
Tk_PhotoGetSize(handle, widthPtr, heightPtr)
void
Tk_PhotoSetSize(handle, width, height)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which image was created.

char *imageName (in)
Name of the photo image.

Tk_PhotoHandle handle (in)
Opaque handle identifying the photo image to be affected.

Tk_PhotoImageBlock *blockPtr (in)
Specifies the address and storage layout of image data.

int x (in)
Specifies the X coordinate where the top-left corner of the block is to be placed within the image.

int y (in)
Specifies the Y coordinate where the top-left corner of the block is to be placed within the image.

int width (in)
Specifies the width of the image area to be affected (for Tk_PhotoPutBlock) or the desired image width (for Tk_PhotoExpand and Tk_PhotoSetSize).

int height (in)
Specifies the height of the image area to be affected (for Tk_PhotoPutBlock) or the desired image height (for Tk_PhotoExpand and Tk_PhotoSetSize).

int *widthPtr (out)
Pointer to location in which to store the image width.

int *heightPtr (out)
Pointer to location in which to store the image height.

int subsampleX (in)
Specifies the subsampling factor in the X direction for input image data.

int subsampleY (in)
Specifies the subsampling factor in the Y direction for input image data.

int zoomX (in)
Specifies the zoom factor to be applied in the X direction to pixels being written to the photo image.

int zoomY (in)
Specifies the zoom factor to be applied in the Y direction to pixels being written to the photo image.

DESCRIPTION

Tk_FindPhoto returns an opaque handle that is used to identify a particular photo image to the other procedures. The parameter is the name of the image, that is, the name specified to the image create photo command, or assigned by that command if no name was specified.

Tk_PhotoPutBlock is used to supply blocks of image data to be displayed. The call affects an area of the image of size width x height pixels, with its top-left corner at coordinates (x,y). All of width, height, x, and y must be non-negative. If part of this area lies outside the current bounds of the image, the image will be expanded to include the area, unless the user has specified an explicit image size with the -width and/or -height widget configuration options (see photo(n)); in that case the area is silently clipped to the image boundaries.

The block parameter is a pointer to a Tk_PhotoImageBlock structure, defined as follows:

typedef struct {
    unsigned char *pixelPtr;
    int width;
    int height;
    int pitch;
    int pixelSize;
    int offset[4];
} Tk_PhotoImageBlock;
The pixelPtr field points to the first pixel, that is, the top-left pixel in the block. The width and height fields specify the dimensions of the block of pixels. The pixelSize field specifies the address difference between two horizontally adjacent pixels. Often it is 3 or 4, but it can have any value. The pitch field specifies the address difference between two vertically adjacent pixels. The offset array contains the offsets from the address of a pixel to the addresses of the bytes containing the red, green, blue and alpha (transparency) components. These are normally 0, 1, 2 and 3, but can have other values, e.g., for images that are stored as separate red, green and blue planes.

The value given for the width and height parameters to Tk_PhotoPutBlock do not have to correspond to the values specified in block. If they are smaller, Tk_PhotoPutBlock extracts a sub-block from the image data supplied. If they are larger, the data given are replicated (in a tiled fashion) to fill the specified area. These rules operate independently in the horizontal and vertical directions.

Tk_PhotoPutZoomedBlock works like Tk_PhotoPutBlock except that the image can be reduced or enlarged for display. The subsampleX and subsampleY parameters allow the size of the image to be reduced by subsampling. Tk_PhotoPutZoomedBlock will use only pixels from the input image whose X coordinates are multiples of subsampleX, and whose Y coordinates are multiples of subsampleY. For example, an image of 512x512 pixels can be reduced to 256x256 by setting subsampleX and subsampleY to 2.

The zoomX and zoomY parameters allow the image to be enlarged by pixel replication. Each pixel of the (possibly subsampled) input image will be written to a block zoomX pixels wide and zoomY pixels high of the displayed image. Subsampling and zooming can be used together for special effects.

Tk_PhotoGetImage can be used to retrieve image data from a photo image. Tk_PhotoGetImage fills in the structure pointed to by the blockPtr parameter with values that describe the address and layout of the image data that the photo image has stored internally. The values are valid until the image is destroyed or its size is changed. Tk_PhotoGetImage returns 1 for compatibility with the corresponding procedure in the old photo widget.

Tk_PhotoBlank blanks the entire area of the photo image. Blank areas of a photo image are transparent.

Tk_PhotoExpand requests that the widget's image be expanded to be at least width x height pixels in size. The width and/or height are unchanged if the user has specified an explicit image width or height with the -width and/or -height configuration options, respectively. If the image data are being supplied in many small blocks, it is more efficient to use Tk_PhotoExpand or Tk_PhotoSetSize at the beginning rather than allowing the image to expand in many small increments as image blocks are supplied.

Tk_PhotoSetSize specifies the size of the image, as if the user had specified the given width and height values to the -width and -height configuration options. A value of zero for width or height does not change the image's width or height, but allows the width or height to be changed by subsequent calls to Tk_PhotoPutBlock, Tk_PhotoPutZoomedBlock or Tk_PhotoExpand.

Tk_PhotoGetSize returns the dimensions of the image in *widthPtr and *heightPtr.

CREDITS

The code for the photo image type was developed by Paul Mackerras, based on his earlier photo widget code.

KEYWORDS

photo, image
Copyright © 1994 The Australian National University
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_FontId manual page

NAME

Tk_FontId, Tk_GetFontMetrics, Tk_PostscriptFontName - accessor functions for fonts

SYNOPSIS

#include <tk.h>
Font
Tk_FontId(tkfont)
void
Tk_GetFontMetrics(tkfont, fmPtr)
int
Tk_PostscriptFontName(tkfont, dsPtr)

ARGUMENTS

Tk_Font tkfont (in)
Opaque font token being queried. Must have been returned by a previous call to Tk_GetFont.

Tk_FontMetrics *fmPtr (out)
Pointer to structure in which the font metrics for tkfont will be stored.

Tcl_DString *dsPtr (out)
Pointer to an initialized Tcl_DString to which the name of the Postscript font that corresponds to tkfont will be appended.

DESCRIPTION

Given a tkfont, Tk_FontId returns the token that should be selected into an XGCValues structure in order to construct a graphics context that can be used to draw text in the specified font.

Tk_GetFontMetrics computes the ascent, descent, and linespace of the tkfont in pixels and stores those values in the structure pointer to by fmPtr. These values can be used in computations such as to space multiple lines of text, to align the baselines of text in different fonts, and to vertically align text in a given region. See the documentation for the font command for definitions of the terms ascent, descent, and linespace, used in font metrics.

Tk_PostscriptFontName maps a tkfont to the corresponding Postcript font name that should be used when printing. The return value is the size in points of the tkfont and the Postscript font name is appended to dsPtr. DsPtr must refer to an initialized Tcl_DString. Given a ``reasonable'' Postscript printer, the following screen font families should print correctly:

Avant Garde, Arial, Bookman, Courier, Courier New, Geneva, Helvetica, Monaco, New Century Schoolbook, New York, Palatino, Symbol, Times, Times New Roman, Zapf Chancery, and Zapf Dingbats.

Any other font families may not print correctly because the computed Postscript font name may be incorrect or not exist on the printer.

DATA STRUCTURES

The Tk_FontMetrics data structure is used by Tk_GetFontMetrics to return information about a font and is defined as follows:
typedef struct Tk_FontMetrics {
    int ascent;
    int descent;
    int linespace;
} Tk_FontMetrics;
The linespace field is the amount in pixels that the tallest letter sticks up above the baseline, plus any extra blank space added by the designer of the font.

The descent is the largest amount in pixels that any letter sticks below the baseline, plus any extra blank space added by the designer of the font.

The linespace is the sum of the ascent and descent. How far apart two lines of text in the same font should be placed so that none of the characters in one line overlap any of the characters in the other line.

KEYWORDS

font
Copyright © 1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_FreeXId manual page

NAME

Tk_FreeXId - make X resource identifier available for reuse

SYNOPSIS

#include <tk.h>
Tk_FreeXId(display, id)

ARGUMENTS

Display *display (in)
Display for which id was allocated.

XID id (in)
Identifier of X resource (window, font, pixmap, cursor, graphics context, or colormap) that is no longer in use.

DESCRIPTION

The default allocator for resource identifiers provided by Xlib is very simple-minded and does not allow resource identifiers to be re-used. If a long-running application reaches the end of the resource id space, it will generate an X protocol error and crash. Tk replaces the default id allocator with its own allocator, which allows identifiers to be reused. In order for this to work, Tk_FreeXId must be called to tell the allocator about resources that have been freed. Tk automatically calls Tk_FreeXId whenever it frees a resource, so if you use procedures like Tk_GetFont, Tk_GetGC, and Tk_GetPixmap then you need not call Tk_FreeXId. However, if you allocate resources directly from Xlib, for example by calling XCreatePixmap, then you should call Tk_FreeXId when you call the corresponding Xlib free procedure, such as XFreePixmap. If you don't call Tk_FreeXId then the resource identifier will be lost, which could cause problems if the application runs long enough to lose all of the available identifiers.

KEYWORDS

resource identifier
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_GeometryRequest manual page

NAME

Tk_GeometryRequest, Tk_SetInternalBorder - specify desired geometry or internal border for a window

SYNOPSIS

#include <tk.h>
Tk_GeometryRequest(tkwin, reqWidth, reqHeight)
Tk_SetInternalBorder(tkwin, width)

ARGUMENTS

Tk_Window tkwin (in)
Window for which geometry is being requested.

int reqWidth (in)
Desired width for tkwin, in pixel units.

int reqHeight (in)
Desired height for tkwin, in pixel units.

int width (in)
Space to leave for internal border for tkwin, in pixel units.

DESCRIPTION

Tk_GeometryRequest is called by widget code to indicate its preference for the dimensions of a particular window. The arguments to Tk_GeometryRequest are made available to the geometry manager for the window, which then decides on the actual geometry for the window. Although geometry managers generally try to satisfy requests made to Tk_GeometryRequest, there is no guarantee that this will always be possible. Widget code should not assume that a geometry request will be satisfied until it receives a ConfigureNotify event indicating that the geometry change has occurred. Widget code should never call procedures like Tk_ResizeWindow directly. Instead, it should invoke Tk_GeometryRequest and leave the final geometry decisions to the geometry manager.

If tkwin is a top-level window, then the geometry information will be passed to the window manager using the standard ICCCM protocol.

Tk_SetInternalBorder is called by widget code to indicate that the widget has an internal border. This means that the widget draws a decorative border inside the window instead of using the standard X borders, which are external to the window's area. For example, internal borders are used to draw 3-D effects. Width specifies the width of the border in pixels. Geometry managers will use this information to avoid placing any children of tkwin overlapping the outermost width pixels of tkwin's area.

The information specified in calls to Tk_GeometryRequest and Tk_SetInternalBorder can be retrieved using the macros Tk_ReqWidth, Tk_ReqHeight, and Tk_InternalBorderWidth. See the Tk_WindowId manual entry for details.

KEYWORDS

geometry, request
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetAnchorFromObj manual page

NAME

Tk_GetAnchorFromObj, Tk_GetAnchor, Tk_NameOfAnchor - translate between strings and anchor positions

SYNOPSIS

#include <tk.h>
int
Tk_GetAnchorFromObj(interp, objPtr, anchorPtr)
int
Tk_GetAnchor(interp, string, anchorPtr)
char *
Tk_NameOfAnchor(anchor)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting, or NULL.

Tcl_Obj *objPtr (in/out)
String value contains name of anchor point: n, ne, e, se, s, sw, w, nw, or center; internal rep will be modified to cache corresponding Tk_Anchor.

char *string (in)
Same as objPtr except description of anchor point is passed as a string.

int *anchorPtr (out)
Pointer to location in which to store anchor position corresponding to objPtr or string.

Tk_Anchor anchor (in)
Anchor position, e.g. TCL_ANCHOR_CENTER.

DESCRIPTION

Tk_GetAnchorFromObj places in *anchorPtr an anchor position (enumerated type Tk_Anchor) corresponding to objPtr's value. The result will be one of TK_ANCHOR_N, TK_ANCHOR_NE, TK_ANCHOR_E, TK_ANCHOR_SE, TK_ANCHOR_S, TK_ANCHOR_SW, TK_ANCHOR_W, TK_ANCHOR_NW, or TK_ANCHOR_CENTER. Anchor positions are typically used for indicating a point on an object that will be used to position the object, e.g. TK_ANCHOR_N means position the top center point of the object at a particular place.

Under normal circumstances the return value is TCL_OK and interp is unused. If string doesn't contain a valid anchor position or an abbreviation of one of these names, TCL_ERROR is returned, *anchorPtr is unmodified, and an error message is stored in interp's result if interp isn't NULL. Tk_GetAnchorFromObj caches information about the return value in objPtr, which speeds up future calls to Tk_GetAnchorFromObj with the same objPtr.

Tk_GetAnchor is identical to Tk_GetAnchorFromObj except that the description of the anchor is specified with a string instead of an object. This prevents Tk_GetAnchor from caching the return value, so Tk_GetAnchor is less efficient than Tk_GetAnchorFromObj.

Tk_NameOfAnchor is the logical inverse of Tk_GetAnchor. Given an anchor position such as TK_ANCHOR_N it returns a statically-allocated string corresponding to anchor. If anchor isn't a legal anchor value, then ``unknown anchor position'' is returned.

KEYWORDS

anchor position
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1998 Sun Microsystems, Inc.


Tk Library Procedures - Tk_AllocBitmapFromObj manual page

NAME
Tk_AllocBitmapFromObj, Tk_GetBitmap, Tk_GetBitmapFromObj, Tk_DefineBitmap, Tk_NameOfBitmap, Tk_SizeOfBitmap, Tk_FreeBitmapFromObj, Tk_FreeBitmap, Tk_GetBitmapFromData - maintain database of single-plane pixmaps
SYNOPSIS
ARGUMENTS
DESCRIPTION
@fileName
name
error
gray75
gray50
gray25
gray12
hourglass
info
questhead
question
warning
document
stationery
edition
application
accessory
folder
pfolder
trash
floppy
ramdisk
cdrom
preferences
querydoc
stop
note
caution
BUGS
KEYWORDS

NAME

Tk_AllocBitmapFromObj, Tk_GetBitmap, Tk_GetBitmapFromObj, Tk_DefineBitmap, Tk_NameOfBitmap, Tk_SizeOfBitmap, Tk_FreeBitmapFromObj, Tk_FreeBitmap, Tk_GetBitmapFromData - maintain database of single-plane pixmaps

SYNOPSIS

#include <tk.h>
Pixmap
Tk_GetBitmapFromObj(interp, tkwin, objPtr)
Pixmap
Tk_GetBitmap(interp, tkwin, info)
Pixmap
Tk_GetBitmapFromObj(tkwin, objPtr)
int
Tk_DefineBitmap(interp, name, source, width, height)
char *
Tk_NameOfBitmap(display, bitmap)
Tk_SizeOfBitmap(display, bitmap, widthPtr, heightPtr)
Tk_FreeBitmapFromObj(tkwin, objPtr)
Tk_FreeBitmap(display, bitmap)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting; if NULL then no error message is left after errors.

Tk_Window tkwin (in)
Token for window in which the bitmap will be used.

Tcl_Obj *objPtr (in/out)
String value describes desired bitmap; internal rep will be modified to cache pointer to corresponding Pixmap.

CONST char *info (in)
Same as objPtr except description of bitmap is passed as a string and resulting Pixmap isn't cached.

CONST char *name (in)
Name for new bitmap to be defined.

char *source (in)
Data for bitmap, in standard bitmap format. Must be stored in static memory whose value will never change.

int width (in)
Width of bitmap.

int height (in)
Height of bitmap.

int *widthPtr (out)
Pointer to word to fill in with bitmap's width.

int *heightPtr (out)
Pointer to word to fill in with bitmap's height.

Display *display (in)
Display for which bitmap was allocated.

Pixmap bitmap (in)
Identifier for a bitmap allocated by Tk_AllocBitmapFromObj or Tk_GetBitmap.

DESCRIPTION

These procedures manage a collection of bitmaps (one-plane pixmaps) being used by an application. The procedures allow bitmaps to be re-used efficiently, thereby avoiding server overhead, and also allow bitmaps to be named with character strings.

Tk_AllocBitmapFromObj returns a Pixmap identifier for a bitmap that matches the description in objPtr and is suitable for use in tkwin. It re-uses an existing bitmap, if possible, and creates a new one otherwise. ObjPtr's value must have one of the following forms:

@fileName
FileName must be the name of a file containing a bitmap description in the standard X11 or X10 format.

name
Name must be the name of a bitmap defined previously with a call to Tk_DefineBitmap. The following names are pre-defined by Tk:

error
The international "don't" symbol: a circle with a diagonal line across it.

gray75
75% gray: a checkerboard pattern where three out of four bits are on.

gray50
50% gray: a checkerboard pattern where every other bit is on.

gray25
25% gray: a checkerboard pattern where one out of every four bits is on.

gray12
12.5% gray: a pattern where one-eighth of the bits are on, consisting of every fourth pixel in every other row.

hourglass
An hourglass symbol.

info
A large letter ``i''.

questhead
The silhouette of a human head, with a question mark in it.

question
A large question-mark.

warning
A large exclamation point.

In addition, the following pre-defined names are available only on the Macintosh platform:

document
A generic document.

stationery
Document stationery.

edition
The edition symbol.

application
Generic application icon.

accessory
A desk accessory.

folder
Generic folder icon.

pfolder
A locked folder.

trash
A trash can.

floppy
A floppy disk.

ramdisk
A floppy disk with chip.

cdrom
A cd disk icon.

preferences
A folder with prefs symbol.

querydoc
A database document icon.

stop
A stop sign.

note
A face with ballon words.

caution
A triangle with an exclamation point.

Under normal conditions, Tk_AllocBitmapFromObj returns an identifier for the requested bitmap. If an error occurs in creating the bitmap, such as when objPtr refers to a non-existent file, then None is returned and an error message is left in interp's result if interp isn't NULL. Tk_AllocBitmapFromObj caches information about the return value in objPtr, which speeds up future calls to procedures such as Tk_AllocBitmapFromObj and Tk_GetBitmapFromObj.

Tk_GetBitmap is identical to Tk_AllocBitmapFromObj except that the description of the bitmap is specified with a string instead of an object. This prevents Tk_GetBitmap from caching the return value, so Tk_GetBitmap is less efficient than Tk_AllocBitmapFromObj.

Tk_GetBitmapFromObj returns the token for an existing bitmap, given the window and description used to create the bitmap. Tk_GetBitmapFromObj doesn't actually create the bitmap; the bitmap must already have been created with a previous call to Tk_AllocBitmapFromObj or Tk_GetBitmap. The return value is cached in objPtr, which speeds up future calls to Tk_GetBitmapFromObj with the same objPtr and tkwin.

Tk_DefineBitmap associates a name with in-memory bitmap data so that the name can be used in later calls to Tk_AllocBitmapFromObj or Tk_GetBitmap. The nameId argument gives a name for the bitmap; it must not previously have been used in a call to Tk_DefineBitmap. The arguments source, width, and height describe the bitmap. Tk_DefineBitmap normally returns TCL_OK; if an error occurs (e.g. a bitmap named nameId has already been defined) then TCL_ERROR is returned and an error message is left in interp->result. Note: Tk_DefineBitmap expects the memory pointed to by source to be static: Tk_DefineBitmap doesn't make a private copy of this memory, but uses the bytes pointed to by source later in calls to Tk_AllocBitmapFromObj or Tk_GetBitmap.

Typically Tk_DefineBitmap is used by #include-ing a bitmap file directly into a C program and then referencing the variables defined by the file. For example, suppose there exists a file stip.bitmap, which was created by the bitmap program and contains a stipple pattern. The following code uses Tk_DefineBitmap to define a new bitmap named foo:

Pixmap bitmap;
#include "stip.bitmap"
Tk_DefineBitmap(interp, "foo", stip_bits,
    stip_width, stip_height);
    ...
bitmap = Tk_GetBitmap(interp, tkwin, "foo");
This code causes the bitmap file to be read at compile-time and incorporates the bitmap information into the program's executable image. The same bitmap file could be read at run-time using Tk_GetBitmap:
Pixmap bitmap;
bitmap = Tk_GetBitmap(interp, tkwin, "@stip.bitmap");
The second form is a bit more flexible (the file could be modified after the program has been compiled, or a different string could be provided to read a different file), but it is a little slower and requires the bitmap file to exist separately from the program.

Tk maintains a database of all the bitmaps that are currently in use. Whenever possible, it will return an existing bitmap rather than creating a new one. When a bitmap is no longer used, Tk will release it automatically. This approach can substantially reduce server overhead, so Tk_AllocBitmapFromObj and Tk_GetBitmap should generally be used in preference to Xlib procedures like XReadBitmapFile.

The bitmaps returned by Tk_AllocBitmapFromObj and Tk_GetBitmap are shared, so callers should never modify them. If a bitmap must be modified dynamically, then it should be created by calling Xlib procedures such as XReadBitmapFile or XCreatePixmap directly.

The procedure Tk_NameOfBitmap is roughly the inverse of Tk_GetBitmap. Given an X Pixmap argument, it returns the textual description that was passed to Tk_GetBitmap when the bitmap was created. Bitmap must have been the return value from a previous call to Tk_AllocBitmapFromObj or Tk_GetBitmap.

Tk_SizeOfBitmap returns the dimensions of its bitmap argument in the words pointed to by the widthPtr and heightPtr arguments. As with Tk_NameOfBitmap, bitmap must have been created by Tk_AllocBitmapFromObj or Tk_GetBitmap.

When a bitmap is no longer needed, Tk_FreeBitmapFromObj or Tk_FreeBitmap should be called to release it. For Tk_FreeBitmapFromObj the bitmap to release is specified with the same information used to create it; for Tk_FreeBitmap the bitmap to release is specified with its Pixmap token. There should be exactly one call to Tk_FreeBitmapFromObj or Tk_FreeBitmap for each call to Tk_AllocBitmapFromObj or Tk_GetBitmap.

BUGS

In determining whether an existing bitmap can be used to satisfy a new request, Tk_AllocBitmapFromObj and Tk_GetBitmap consider only the immediate value of the string description. For example, when a file name is passed to Tk_GetBitmap, Tk_GetBitmap will assume it is safe to re-use an existing bitmap created from the same file name: it will not check to see whether the file itself has changed, or whether the current directory has changed, thereby causing the name to refer to a different file.

KEYWORDS

bitmap, pixmap
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1998 Sun Microsystems, Inc.


Library Procedures - Tk_GetCapStyle manual page

NAME

Tk_GetCapStyle, Tk_NameOfCapStyle - translate between strings and cap styles

SYNOPSIS

#include <tk.h>
int
Tk_GetCapStyle(interp, string, capPtr)
char *
Tk_NameOfCapStyle(cap)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

char *string (in)
String containing name of cap style: one of ```butt'', ``projecting'', or ``round''.

int *capPtr (out)
Pointer to location in which to store X cap style corresponding to string.

int cap (in)
Cap style: one of CapButt, CapProjecting, or CapRound.

DESCRIPTION

Tk_GetCapStyle places in *capPtr the X cap style corresponding to string. This will be one of the values CapButt, CapProjecting, or CapRound. Cap styles are typically used in X graphics contexts to indicate how the end-points of lines should be capped. See the X documentation for information on what each style implies.

Under normal circumstances the return value is TCL_OK and interp is unused. If string doesn't contain a valid cap style or an abbreviation of one of these names, then an error message is stored in interp->result, TCL_ERROR is returned, and *capPtr is unmodified.

Tk_NameOfCapStyle is the logical inverse of Tk_GetCapStyle. Given a cap style such as CapButt it returns a statically-allocated string corresponding to cap. If cap isn't a legal cap style, then ``unknown cap style'' is returned.

KEYWORDS

butt, cap style, projecting, round
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetColormap manual page

NAME

Tk_GetColormap, Tk_FreeColormap - allocate and free colormaps

SYNOPSIS

#include <tk.h>
Colormap
Tk_GetColormap(interp, tkwin, string)
Tk_FreeColormap(display, colormap)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

Tk_Window tkwin (in)
Token for window in which colormap will be used.

char *string (in)
Selects a colormap: either new or the name of a window with the same screen and visual as tkwin.

Display *display (in)
Display for which colormap was allocated.

Colormap colormap (in)
Colormap to free; must have been returned by a previous call to Tk_GetColormap or Tk_GetVisual.

DESCRIPTION

These procedures are used to manage colormaps. Tk_GetColormap returns a colormap suitable for use in tkwin. If its string argument is new then a new colormap is created; otherwise string must be the name of another window with the same screen and visual as tkwin, and the colormap from that window is returned. If string doesn't make sense, or if it refers to a window on a different screen from tkwin or with a different visual than tkwin, then Tk_GetColormap returns None and leaves an error message in interp->result.

Tk_FreeColormap should be called when a colormap returned by Tk_GetColormap is no longer needed. Tk maintains a reference count for each colormap returned by Tk_GetColormap, so there should eventually be one call to Tk_FreeColormap for each call to Tk_GetColormap. When a colormap's reference count becomes zero, Tk releases the X colormap.

Tk_GetVisual and Tk_GetColormap work together, in that a new colormap created by Tk_GetVisual may later be returned by Tk_GetColormap. The reference counting mechanism for colormaps includes both procedures, so callers of Tk_GetVisual must also call Tk_FreeColormap to release the colormap. If Tk_GetColormap is called with a string value of new then the resulting colormap will never be returned by Tk_GetVisual; however, it can be used in other windows by calling Tk_GetColormap with the original window's name as string.

KEYWORDS

colormap
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_AllocColorFromObj manual page

NAME
Tk_AllocColorFromObj, Tk_GetColor, Tk_GetColorFromObj, Tk_GetColorByValue, Tk_NameOfColor, Tk_FreeColorFromObj, Tk_FreeColor - maintain database of colors
SYNOPSIS
ARGUMENTS
DESCRIPTION
colorname
#RGB
#RRGGBB
#RRRGGGBBB
#RRRRGGGGBBBB
KEYWORDS

NAME

Tk_AllocColorFromObj, Tk_GetColor, Tk_GetColorFromObj, Tk_GetColorByValue, Tk_NameOfColor, Tk_FreeColorFromObj, Tk_FreeColor - maintain database of colors

SYNOPSIS

#include <tk.h>
XColor *
Tk_AllocColorFromObj(interp, tkwin, objPtr)
XColor *
Tk_GetColor(interp, tkwin, name)
XColor *
Tk_GetColorFromObj(tkwin, objPtr)
XColor *
Tk_GetColorByValue(tkwin, prefPtr)
char *
Tk_NameOfColor(colorPtr)
GC
Tk_GCForColor(colorPtr, drawable)
Tk_FreeColorFromObj(tkwin, objPtr)
Tk_FreeColor(colorPtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

Tk_Window tkwin (in)
Token for window in which color will be used.

Tcl_Obj *objPtr (in/out)
String value describes desired color; internal rep will be modified to cache pointer to corresponding (XColor *).

char *name (in)
Same as objPtr except description of color is passed as a string and resulting (XColor *) isn't cached.

XColor *prefPtr (in)
Indicates red, green, and blue intensities of desired color.

XColor *colorPtr (in)
Pointer to X color information. Must have been allocated by previous call to Tk_AllocColorFromObj, Tk_GetColor or Tk_GetColorByValue, except when passed to Tk_NameOfColor.

Drawable drawable (in)
Drawable in which the result graphics context will be used. Must have same screen and depth as the window for which the color was allocated.

DESCRIPTION

These procedures manage the colors being used by a Tk application. They allow colors to be shared whenever possible, so that colormap space is preserved, and they pick closest available colors when colormap space is exhausted.

Given a textual description of a color, Tk_AllocColorFromObj locates a pixel value that may be used to render the color in a particular window. The desired color is specified with an object whose string value must have one of the following forms:

colorname
Any of the valid textual names for a color defined in the server's color database file, such as red or PeachPuff.

#RGB

#RRGGBB

#RRRGGGBBB

#RRRRGGGGBBBB
A numeric specification of the red, green, and blue intensities to use to display the color. Each R, G, or B represents a single hexadecimal digit. The four forms permit colors to be specified with 4-bit, 8-bit, 12-bit or 16-bit values. When fewer than 16 bits are provided for each color, they represent the most significant bits of the color. For example, #3a7 is the same as #3000a0007000.

Tk_AllocColorFromObj returns a pointer to an XColor structure; the structure indicates the exact intensities of the allocated color (which may differ slightly from those requested, depending on the limitations of the screen) and a pixel value that may be used to draw with the color in tkwin. If an error occurs in Tk_AllocColorFromObj (such as an unknown color name) then NULL is returned and an error message is stored in interp's result if interp isn't NULL. If the colormap for tkwin is full, Tk_AllocColorFromObj will use the closest existing color in the colormap. Tk_AllocColorFromObj caches information about the return value in objPtr, which speeds up future calls to procedures such as Tk_AllocColorFromObj and Tk_GetColorFromObj.

Tk_GetColor is identical to Tk_AllocColorFromObj except that the description of the color is specified with a string instead of an object. This prevents Tk_GetColor from caching the return value, so Tk_GetColor is less efficient than Tk_AllocColorFromObj.

Tk_GetColorFromObj returns the token for an existing color, given the window and description used to create the color. Tk_GetColorFromObj doesn't actually create the color; the color must already have been created with a previous call to Tk_AllocColorFromObj or Tk_GetColor. The return value is cached in objPtr, which speeds up future calls to Tk_GetColorFromObj with the same objPtr and tkwin.

Tk_GetColorByValue is similar to Tk_GetColor except that the desired color is indicated with the red, green, and blue fields of the structure pointed to by colorPtr.

This package maintains a database of all the colors currently in use. If the same color is requested multiple times from Tk_GetColor or Tk_AllocColorFromObj (e.g. by different windows), or if the same intensities are requested multiple times from Tk_GetColorByValue, then existing pixel values will be re-used. Re-using an existing pixel avoids any interaction with the window server, which makes the allocation much more efficient. These procedures also provide a portable interface that works across all platforms. For this reason, you should generally use Tk_AllocColorFromObj, Tk_GetColor, or Tk_GetColorByValue instead of lower level procedures like XAllocColor.

Since different calls to this package may return the same shared pixel value, callers should never change the color of a pixel returned by the procedures. If you need to change a color value dynamically, you should use XAllocColorCells to allocate the pixel value for the color.

The procedure Tk_NameOfColor is roughly the inverse of Tk_GetColor. If its colorPtr argument was created by Tk_AllocColorFromObj or Tk_GetColor then the return value is the string that was used to create the color. If colorPtr was created by a call to Tk_GetColorByValue, or by any other mechanism, then the return value is a string that could be passed to Tk_GetColor to return the same color. Note: the string returned by Tk_NameOfColor is only guaranteed to persist until the next call to Tk_NameOfColor.

Tk_GCForColor returns a graphics context whose foreground field is the pixel allocated for colorPtr and whose other fields all have default values. This provides an easy way to do basic drawing with a color. The graphics context is cached with the color and will exist only as long as colorPtr exists; it is freed when the last reference to colorPtr is freed by calling Tk_FreeColor.

When a color is no longer needed Tk_FreeColorFromObj or Tk_FreeColor should be called to release it. For Tk_FreeColorFromObj the color to release is specified with the same information used to create it; for Tk_FreeColor the color to release is specified with a pointer to its XColor structure. There should be exactly one call to Tk_FreeColorFromObj or Tk_FreeColor for each call to Tk_AllocColorFromObj, Tk_GetColor, or Tk_GetColorByValue.

KEYWORDS

color, intensity, object, pixel value
Copyright © 1990-1991 The Regents of the University of California.
Copyright © 1994-1998 Sun Microsystems, Inc.


Tk Library Procedures - Tk_AllocCursorFromObj manual page

NAME
Tk_AllocCursorFromObj, Tk_GetCursor, Tk_GetCursorFromObj, Tk_GetCursorFromData, Tk_NameOfCursor, Tk_FreeCursorFromObj, Tk_FreeCursor - maintain database of cursors
SYNOPSIS
ARGUMENTS
DESCRIPTION
name [fgColor [bgColor]]
@sourceName maskName fgColor bgColor
@sourceName fgColor
@sourceName
BUGS
KEYWORDS

NAME

Tk_AllocCursorFromObj, Tk_GetCursor, Tk_GetCursorFromObj, Tk_GetCursorFromData, Tk_NameOfCursor, Tk_FreeCursorFromObj, Tk_FreeCursor - maintain database of cursors

SYNOPSIS

#include <tk.h>
Tk_Cursor
Tk_AllocCursorFromObj(interp, tkwin, objPtr)
Tk_Cursor
Tk_GetCursor(interp, tkwin, name)
Tk_Cursor
Tk_GetCursorFromObj(tkwin, objPtr)
Tk_Cursor
Tk_GetCursorFromData(interp, tkwin, source, mask, width, height, xHot, yHot, fg, bg)
char *
Tk_NameOfCursor(display, cursor)
Tk_FreeCursorFromObj(tkwin, objPtr)
Tk_FreeCursor(display, cursor)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

Tk_Window tkwin (in)
Token for window in which the cursor will be used.

Tcl_Obj *objPtr (in/out)
Description of cursor; see below for possible values. Internal rep will be modified to cache pointer to corresponding Tk_Cursor.

char *name (in)
Same as objPtr except description of cursor is passed as a string and resulting Tk_Cursor isn't cached.

char *source (in)
Data for cursor cursor, in standard cursor format.

char *mask (in)
Data for mask cursor, in standard cursor format.

int width (in)
Width of source and mask.

int height (in)
Height of source and mask.

int xHot (in)
X-location of cursor hot-spot.

int yHot (in)
Y-location of cursor hot-spot.

Tk_Uid fg (in)
Textual description of foreground color for cursor.

Tk_Uid bg (in)
Textual description of background color for cursor.

Display *display (in)
Display for which cursor was allocated.

Tk_Cursor cursor (in)
Opaque Tk identifier for cursor. If passed to Tk_FreeCursor, must have been returned by some previous call to Tk_GetCursor or Tk_GetCursorFromData.

DESCRIPTION

These procedures manage a collection of cursors being used by an application. The procedures allow cursors to be re-used efficiently, thereby avoiding server overhead, and also allow cursors to be named with character strings.

Tk_AllocCursorFromObj takes as argument an object describing a cursor, and returns an opaque Tk identifier for a cursor corresponding to the description. It re-uses an existing cursor if possible and creates a new one otherwise. Tk_AllocCursorFromObj caches information about the return value in objPtr, which speeds up future calls to procedures such as Tk_AllocCursorFromObj and Tk_GetCursorFromObj. If an error occurs in creating the cursor, such as when objPtr refers to a non-existent file, then None is returned and an error message will be stored in interp's result if interp isn't NULL. ObjPtr must contain a standard Tcl list with one of the following forms:

name [fgColor [bgColor]]
Name is the name of a cursor in the standard X cursor cursor, i.e., any of the names defined in cursorcursor.h, without the XC_. Some example values are X_cursor, hand2, or left_ptr. Appendix B of ``The X Window System'' by Scheifler & Gettys has illustrations showing what each of these cursors looks like. If fgColor and bgColor are both specified, they give the foreground and background colors to use for the cursor (any of the forms acceptable to Tk_GetColor may be used). If only fgColor is specified, then there will be no background color: the background will be transparent. If no colors are specified, then the cursor will use black for its foreground color and white for its background color.

The Macintosh version of Tk supports all of the X cursors and will also accept any of the standard Mac cursors including ibeam, crosshair, watch, plus, and arrow. In addition, Tk will load Macintosh cursor resources of the types crsr (color) and CURS (black and white) by the name of the of the resource. The application and all its open dynamic library's resource files will be searched for the named cursor. If there are conflicts color cursors will always be loaded in preference to black and white cursors.

@sourceName maskName fgColor bgColor
In this form, sourceName and maskName are the names of files describing cursors for the cursor's source bits and mask. Each file must be in standard X11 or X10 cursor format. FgColor and bgColor indicate the colors to use for the cursor, in any of the forms acceptable to Tk_GetColor. This form of the command will not work on Macintosh or Windows computers.

@sourceName fgColor
This form is similar to the one above, except that the source is used as mask also. This means that the cursor's background is transparent. This form of the command will not work on Macintosh or Windows computers.

@sourceName
This form only works on Windows, and will load a Windows system cursor (.ani or .cur) from the file specified in sourceName.

Tk_GetCursor is identical to Tk_AllocCursorFromObj except that the description of the cursor is specified with a string instead of an object. This prevents Tk_GetCursor from caching the return value, so Tk_GetCursor is less efficient than Tk_AllocCursorFromObj.

Tk_GetCursorFromObj returns the token for an existing cursor, given the window and description used to create the cursor. Tk_GetCursorFromObj doesn't actually create the cursor; the cursor must already have been created with a previous call to Tk_AllocCursorFromObj or Tk_GetCursor. The return value is cached in objPtr, which speeds up future calls to Tk_GetCursorFromObj with the same objPtr and tkwin.

Tk_GetCursorFromData allows cursors to be created from in-memory descriptions of their source and mask cursors. Source points to standard cursor data for the cursor's source bits, and mask points to standard cursor data describing which pixels of source are to be drawn and which are to be considered transparent. Width and height give the dimensions of the cursor, xHot and yHot indicate the location of the cursor's hot-spot (the point that is reported when an event occurs), and fg and bg describe the cursor's foreground and background colors textually (any of the forms suitable for Tk_GetColor may be used). Typically, the arguments to Tk_GetCursorFromData are created by including a cursor file directly into the source code for a program, as in the following example:

Tk_Cursor cursor;
#include "source.cursor"
#include "mask.cursor"
cursor = Tk_GetCursorFromData(interp, tkwin, source_bits,
    mask_bits, source_width, source_height, source_x_hot,
    source_y_hot, Tk_GetUid("red"), Tk_GetUid("blue"));

Under normal conditions Tk_GetCursorFromData will return an identifier for the requested cursor. If an error occurs in creating the cursor then None is returned and an error message will be stored in interp's result.

Tk_AllocCursorFromObj, Tk_GetCursor, and Tk_GetCursorFromData maintain a database of all the cursors they have created. Whenever possible, a call to Tk_AllocCursorFromObj, Tk_GetCursor, or Tk_GetCursorFromData will return an existing cursor rather than creating a new one. This approach can substantially reduce server overhead, so the Tk procedures should generally be used in preference to Xlib procedures like XCreateFontCursor or XCreatePixmapCursor, which create a new cursor on each call. The Tk procedures are also more portable than the lower-level X procedures.

The procedure Tk_NameOfCursor is roughly the inverse of Tk_GetCursor. If its cursor argument was created by Tk_GetCursor, then the return value is the name argument that was passed to Tk_GetCursor to create the cursor. If cursor was created by a call to Tk_GetCursorFromData, or by any other mechanism, then the return value is a hexadecimal string giving the X identifier for the cursor. Note: the string returned by Tk_NameOfCursor is only guaranteed to persist until the next call to Tk_NameOfCursor. Also, this call is not portable except for cursors returned by Tk_GetCursor.

When a cursor returned by Tk_AllocCursorFromObj, Tk_GetCursor, or Tk_GetCursorFromData is no longer needed, Tk_FreeCursorFromObj or Tk_FreeCursor should be called to release it. For Tk_FreeCursorFromObj the cursor to release is specified with the same information used to create it; for Tk_FreeCursor the cursor to release is specified with its Tk_Cursor token. There should be exactly one call to Tk_FreeCursor for each call to Tk_AllocCursorFromObj, Tk_GetCursor, or Tk_GetCursorFromData.

BUGS

In determining whether an existing cursor can be used to satisfy a new request, Tk_AllocCursorFromObj, Tk_GetCursor, and Tk_GetCursorFromData consider only the immediate values of their arguments. For example, when a file name is passed to Tk_GetCursor, Tk_GetCursor will assume it is safe to re-use an existing cursor created from the same file name: it will not check to see whether the file itself has changed, or whether the current directory has changed, thereby causing the name to refer to a different file. Similarly, Tk_GetCursorFromData assumes that if the same source pointer is used in two different calls, then the pointers refer to the same data; it does not check to see if the actual data values have changed.

KEYWORDS

cursor
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1998 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetDash manual page

NAME

Tk_GetDash - convert from string to valid dash structure.

SYNOPSIS

#include <tk.h>
int
Tk_GetDash(interp, string, dashPtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

CONST char * string (in)
Textual value to be converted.

Tk_Dash *dashPtr (out)
Points to place to store the dash pattern value converted from string.

DESCRIPTION

These procedure parses the string and fills in the result in the Tk_Dash structure. The string can be a list of integers or a character string containing only [.,-_] or spaces. If all goes well, TCL_OK is returned. If string doesn't have the proper syntax then TCL_ERROR is returned, an error message is left in the interpreter's result, and nothing is stored at *dashPtr.

The first possible syntax is a list of integers. Each element represents the number of pixels of a line segment. Only the odd segments are drawn using the "outline" color. The other segments are drawn transparent.

The second possible syntax is a character list containing only
5 possible characters [.,-_ ]. The space can be used
to enlarge the space between other line elements, and can not
occur as the first posibion in the string. Some examples:
    -dash .     = -dash {2 4}
    -dash -     = -dash {6 4}
    -dash -.    = -dash {6 4 2 4}
    -dash -..   = -dash {6 4 2 4 2 4}
    -dash {. }  = -dash {2 8}
    -dash ,     = -dash {4 4}

The main difference of this syntax with the previous is that it it shape-conserving. This means that all values in the dash list will be multiplied by the line width before display. This assures that "." will always be displayed as a dot and "-" always as a dash regardless of the line width.

On systems where only a limited set of dash patterns, the dash pattern will be displayed as the most close dash pattern that is available. For example, on Windows only the first 4 of the above examples are available. The last 2 examples will be displayed identically as the first one.

KEYWORDS

dash, conversion
Copyright © 1989-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_AllocFontFromObj manual page

NAME

Tk_AllocFontFromObj, Tk_GetFont, Tk_GetFontFromObj, Tk_NameOfFont, Tk_FreeFontFromObj, Tk_FreeFont - maintain database of fonts

SYNOPSIS

#include <tk.h>
Tk_Font
Tk_AllocFontFromObj(interp, tkwin, objPtr)
Tk_Font
Tk_GetFont(interp, tkwin, string)
Tk_Font
Tk_GetFontFromObj(tkwin, objPtr)
char *
Tk_NameOfFont(tkfont)
Tk_Font
Tk_FreeFontFromObj(tkwin, objPtr)
void
Tk_FreeFont(tkfont)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting. If NULL, then no error messages are left after errors.

Tk_Window tkwin (in)
Token for window in which font will be used.

Tcl_Obj *objPtr (in/out)
Gives name or description of font. See documentation for the font command for details on acceptable formats. Internal rep will be modified to cache corresponding Tk_Font.

const char *string (in)
Same as objPtr except description of font is passed as a string and resulting Tk_Font isn't cached.

Tk_Font tkfont (in)
Opaque font token.

DESCRIPTION

Tk_AllocFontFromObj finds the font indicated by objPtr and returns a token that represents the font. The return value can be used in subsequent calls to procedures such as Tk_GetFontMetrics, Tk_MeasureChars, and Tk_FreeFont. The Tk_Font token will remain valid until Tk_FreeFontFromObj or Tk_FreeFont is called to release it. ObjPtr can contain either a symbolic name or a font description; see the documentation for the font command for a description of the valid formats. If Tk_AllocFontFromObj is unsuccessful (because, for example, objPtr did not contain a valid font specification) then it returns NULL and leaves an error message in interp's result if interp isn't NULL. Tk_AllocFontFromObj caches information about the return value in objPtr, which speeds up future calls to procedures such as Tk_AllocFontFromObj and Tk_GetFontFromObj.

Tk_GetFont is identical to Tk_AllocFontFromObj except that the description of the font is specified with a string instead of an object. This prevents Tk_GetFont from caching the matching Tk_Font, so Tk_GetFont is less efficient than Tk_AllocFontFromObj.

Tk_GetFontFromObj returns the token for an existing font, given the window and description used to create the font. Tk_GetFontFromObj doesn't actually create the font; the font must already have been created with a previous call to Tk_AllocFontFromObj or Tk_GetFont. The return value is cached in objPtr, which speeds up future calls to Tk_GetFontFromObj with the same objPtr and tkwin.

Tk_AllocFontFromObj and Tk_GetFont maintain a database of all fonts they have allocated. If the same font is requested multiple times (e.g. by different windows or for different purposes), then a single Tk_Font will be shared for all uses. The underlying resources will be freed automatically when no-one is using the font anymore.

The procedure Tk_NameOfFont is roughly the inverse of Tk_GetFont. Given a tkfont that was created by Tk_GetFont (or Tk_AllocFontFromObj), the return value is the string argument that was passed to Tk_GetFont to create the font. The string returned by Tk_NameOfFont is only guaranteed to persist until the tkfont is deleted. The caller must not modify this string.

When a font is no longer needed, Tk_FreeFontFromObj or Tk_FreeFont should be called to release it. For Tk_FreeFontFromObj the font to release is specified with the same information used to create it; for Tk_FreeFont the font to release is specified with its Tk_Font token. There should be exactly one call to Tk_FreeFontFromObj or Tk_FreeFont for each call to Tk_AllocFontFromObj or Tk_GetFont.

SEE ALSO

Tk_FontId

KEYWORDS

font
Copyright © 1990-1992 The Regents of the University of California.
Copyright © 1994-1998 Sun Microsystems, Inc.


Library Procedures - Tk_GetGC manual page

NAME

Tk_GetGC, Tk_FreeGC - maintain database of read-only graphics contexts

SYNOPSIS

#include <tk.h>
GC
Tk_GetGC(tkwin, valueMask, valuePtr)
Tk_FreeGC(display, gc)

ARGUMENTS

Tk_Window tkwin (in)
Token for window in which the graphics context will be used.

unsigned long valueMask (in)
Mask of bits (such as GCForeground or GCStipple) indicating which fields of *valuePtr are valid.

XGCValues *valuePtr (in)
Pointer to structure describing the desired values for the graphics context.

Display *display (in)
Display for which gc was allocated.

GC gc (in)
X identifier for graphics context that is no longer needed. Must have been allocated by Tk_GetGC.

DESCRIPTION

Tk_GetGC and Tk_FreeGC manage a collection of graphics contexts being used by an application. The procedures allow graphics contexts to be shared, thereby avoiding the server overhead that would be incurred if a separate GC were created for each use. Tk_GetGC takes arguments describing the desired graphics context and returns an X identifier for a GC that fits the description. The graphics context that is returned will have default values in all of the fields not specified explicitly by valueMask and valuePtr.

Tk_GetGC maintains a database of all the graphics contexts it has created. Whenever possible, a call to Tk_GetGC will return an existing graphics context rather than creating a new one. This approach can substantially reduce server overhead, so Tk_GetGC should generally be used in preference to the Xlib procedure XCreateGC, which creates a new graphics context on each call.

Since the return values of Tk_GetGC are shared, callers should never modify the graphics contexts returned by Tk_GetGC. If a graphics context must be modified dynamically, then it should be created by calling XCreateGC instead of Tk_GetGC.

When a graphics context is no longer needed, Tk_FreeGC should be called to release it. There should be exactly one call to Tk_FreeGC for each call to Tk_GetGC. When a graphics context is no longer in use anywhere (i.e. it has been freed as many times as it has been gotten) Tk_FreeGC will release it to the X server and delete it from the database.

KEYWORDS

graphics context
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_GetHISTANCE manual page

NAME

Tk_GetHINSTANCE - retrieve the global application instance handle

SYNOPSIS

#include <tk.h>
HINSTANCE
Tk_GetHINSTANCE()

DESCRIPTION

Tk_GetHINSTANCE returns the Windows application instance handle for the Tk application. This function is only available on Windows platforms.

KEYWORDS

identifier, instance
Copyright © 1998-2000 by Scriptics Corporation.


Library Procedures - Tk_GetHWND manual page

NAME

Tk_GetHWND - retrieve the Windows handle for an X window

SYNOPSIS

#include <tkPlatDecls.h>
HWND
Tk_GetHWND(window)

ARGUMENTS

Window window (in)
X token for window.

DESCRIPTION

Tk_GetHWND returns the Windows HWND identifier for X Windows window given by window.

KEYWORDS

identifier, window
Copyright © 1998-2000 by Scriptics Corporation.


Tk Library Procedures - Tk_GetImage manual page

NAME

Tk_GetImage, Tk_RedrawImage, Tk_SizeOfImage, Tk_FreeImage - use an image in a widget

SYNOPSIS

#include <tk.h>
Tk_Image
Tk_GetImage(interp, tkwin, name, changeProc, clientData)
Tk_RedrawImage(image, imageX, imageY, width, height, drawable, drawableX, drawableY)
Tk_SizeOfImage(image, widthPtr, heightPtr)
Tk_FreeImage(image)

ARGUMENTS

Tcl_Interp *interp (in)
Place to leave error message.

Tk_Window tkwin (in)
Window in which image will be used.

char *name (in)
Name of image.

Tk_ImageChangedProc *changeProc (in)
Procedure for Tk to invoke whenever image content or size changes.

ClientData clientData (in)
One-word value for Tk to pass to changeProc.

Tk_Image image (in)
Token for image instance; must have been returned by a previous call to Tk_GetImage.

int imageX (in)
X-coordinate of upper-left corner of region of image to redisplay (measured in pixels from the image's upper-left corner).

int imageY (in)
Y-coordinate of upper-left corner of region of image to redisplay (measured in pixels from the image's upper-left corner).

int width ((in))
Width of region of image to redisplay.

int height ((in))
Height of region of image to redisplay.

Drawable drawable (in)
Where to display image. Must either be window specified to Tk_GetImage or a pixmap compatible with that window.

int drawableX (in)
Where to display image in drawable: this is the x-coordinate in drawable where x-coordinate imageX of the image should be displayed.

int drawableY (in)
Where to display image in drawable: this is the y-coordinate in drawable where y-coordinate imageY of the image should be displayed.

int widthPtr (out)
Store width of image (in pixels) here.

int heightPtr (out)
Store height of image (in pixels) here.

DESCRIPTION

These procedures are invoked by widgets that wish to display images. Tk_GetImage is invoked by a widget when it first decides to display an image. name gives the name of the desired image and tkwin identifies the window where the image will be displayed. Tk_GetImage looks up the image in the table of existing images and returns a token for a new instance of the image. If the image doesn't exist then Tk_GetImage returns NULL and leaves an error message in interp->result.

When a widget wishes to actually display an image it must call Tk_RedrawImage, identifying the image (image), a region within the image to redisplay (imageX, imageY, width, and height), and a place to display the image (drawable, drawableX, and drawableY). Tk will then invoke the appropriate image manager, which will display the requested portion of the image before returning.

A widget can find out the dimensions of an image by calling Tk_SizeOfImage: the width and height will be stored in the locations given by widthPtr and heightPtr, respectively.

When a widget is finished with an image (e.g., the widget is being deleted or it is going to use a different image instead of the current one), it must call Tk_FreeImage to release the image instance. The widget should never again use the image token after passing it to Tk_FreeImage. There must be exactly one call to Tk_FreeImage for each call to Tk_GetImage.

If the contents or size of an image changes, then any widgets using the image will need to find out about the changes so that they can redisplay themselves. The changeProc and clientData arguments to Tk_GetImage are used for this purpose. changeProc will be called by Tk whenever a change occurs in the image; it must match the following prototype:

typedef void Tk_ImageChangedProc(
    ClientData clientData,
    int x,
    int y,
    int width,
    int height,
    int imageWidth,
    int imageHeight);
The clientData argument to changeProc is the same as the clientData argument to Tk_GetImage. It is usually a pointer to the widget record for the widget or some other data structure managed by the widget. The arguments x, y, width, and height identify a region within the image that must be redisplayed; they are specified in pixels measured from the upper-left corner of the image. The arguments imageWidth and imageHeight give the image's (new) size.

SEE ALSO

Tk_CreateImageType

KEYWORDS

images, redisplay
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_GetJoinStyle manual page

NAME

Tk_GetJoinStyle, Tk_NameOfJoinStyle - translate between strings and join styles

SYNOPSIS

#include <tk.h>
int
Tk_GetJoinStyle(interp, string, joinPtr)
char *
Tk_NameOfJoinStyle(join)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

char *string (in)
String containing name of join style: one of ``bevel'', ``miter'', or ``round''.

int *joinPtr (out)
Pointer to location in which to store X join style corresponding to string.

int join (in)
Join style: one of JoinBevel, JoinMiter, JoinRound.

DESCRIPTION

Tk_GetJoinStyle places in *joinPtr the X join style corresponding to string, which will be one of JoinBevel, JoinMiter, or JoinRound. Join styles are typically used in X graphics contexts to indicate how adjacent line segments should be joined together. See the X documentation for information on what each style implies.

Under normal circumstances the return value is TCL_OK and interp is unused. If string doesn't contain a valid join style or an abbreviation of one of these names, then an error message is stored in interp->result, TCL_ERROR is returned, and *joinPtr is unmodified.

Tk_NameOfJoinStyle is the logical inverse of Tk_GetJoinStyle. Given a join style such as JoinBevel it returns a statically-allocated string corresponding to join. If join isn't a legal join style, then ``unknown join style'' is returned.

KEYWORDS

bevel, join style, miter, round
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetJustifyFromObj manual page

NAME
Tk_GetJustifyFromObj, Tk_GetJustify, Tk_NameOfJustify - translate between strings and justification styles
SYNOPSIS
ARGUMENTS
DESCRIPTION
TK_JUSTIFY_LEFT
TK_JUSTIFY_RIGHT
TK_JUSTIFY_CENTER
KEYWORDS

NAME

Tk_GetJustifyFromObj, Tk_GetJustify, Tk_NameOfJustify - translate between strings and justification styles

SYNOPSIS

#include <tk.h>
int
Tk_GetJustifyFromObj(interp, objPtr, justifyPtr)
int
Tk_GetJustify(interp, string, justifyPtr)
char *
Tk_NameOfJustify(justify)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting, or NULL.

Tcl_Obj *objPtr (in/out)
String value contains name of justification style (left, right, or center). The internal rep will be modified to cache corresponding justify value.

char *string (in)
Same as objPtr except description of justification style is passed as a string.

int *justifyPtr (out)
Pointer to location in which to store justify value corresponding to objPtr or string.

Tk_Justify justify (in)
Justification style (one of the values listed below).

DESCRIPTION

Tk_GetJustifyFromObj places in *justifyPtr the justify value corresponding to objPtr's value. This value will be one of the following:

TK_JUSTIFY_LEFT
Means that the text on each line should start at the left edge of the line; as a result, the right edges of lines may be ragged.

TK_JUSTIFY_RIGHT
Means that the text on each line should end at the right edge of the line; as a result, the left edges of lines may be ragged.

TK_JUSTIFY_CENTER
Means that the text on each line should be centered; as a result, both the left and right edges of lines may be ragged.

Under normal circumstances the return value is TCL_OK and interp is unused. If objPtr doesn't contain a valid justification style or an abbreviation of one of these names, TCL_ERROR is returned, *justifyPtr is unmodified, and an error message is stored in interp's result if interp isn't NULL. Tk_GetJustifyFromObj caches information about the return value in objPtr, which speeds up future calls to Tk_GetJustifyFromObj with the same objPtr.

Tk_GetJustify is identical to Tk_GetJustifyFromObj except that the description of the justification is specified with a string instead of an object. This prevents Tk_GetJustify from caching the return value, so Tk_GetJustify is less efficient than Tk_GetJustifyFromObj.

Tk_NameOfJustify is the logical inverse of Tk_GetJustify. Given a justify value it returns a statically-allocated string corresponding to justify. If justify isn't a legal justify value, then ``unknown justification style'' is returned.

KEYWORDS

center, fill, justification, string
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1998 Sun Microsystems, Inc.


Library Procedures - Tk_GetOption manual page

NAME

Tk_GetOption - retrieve an option from the option database

SYNOPSIS

#include <tk.h>
Tk_Uid
Tk_GetOption(tkwin, name, class)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

char *name (in)
Name of desired option.

char *class (in)
Class of desired option. Null means there is no class for this option; do lookup based on name only.

DESCRIPTION

This procedure is invoked to retrieve an option from the database associated with tkwin's main window. If there is an option for tkwin that matches the given name or class, then it is returned in the form of a Tk_Uid. If multiple options match name and class, then the highest-priority one is returned. If no option matches, then NULL is returned.

Tk_GetOption caches options related to tkwin so that successive calls for the same tkwin will execute much more quickly than successive calls for different windows.

KEYWORDS

class, name, option, retrieve
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetPixelsFromObj manual page

NAME
Tk_GetPixelsFromObj, Tk_GetPixels, Tk_GetMMFromObj, Tk_GetScreenMM - translate between strings and screen units
SYNOPSIS
ARGUMENTS
DESCRIPTION
<none>
c
i
m
p
KEYWORDS

NAME

Tk_GetPixelsFromObj, Tk_GetPixels, Tk_GetMMFromObj, Tk_GetScreenMM - translate between strings and screen units

SYNOPSIS

#include <tk.h>
int
Tk_GetPixelsFromObj(interp, tkwin, objPtr, intPtr)
int
Tk_GetPixels(interp, tkwin, string, intPtr)
int
Tk_GetMMFromObj(interp, tkwin, objPtr, doublePtr)
int
Tk_GetScreenMM(interp, tkwin, string, doublePtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

Tk_Window tkwin (in)
Window whose screen geometry determines the conversion between absolute units and pixels.

Tcl_Obj *objPtr (in/out)
String value specifies a distance on the screen; internal rep will be modified to cache converted distance.

char *string (in)
Same as objPtr except specification of distance is passed as a string.

int *intPtr (out)
Pointer to location in which to store converted distance in pixels.

double *doublePtr (out)
Pointer to location in which to store converted distance in millimeters.

DESCRIPTION

These procedures take as argument a specification of distance on the screen (objPtr or string) and compute the corresponding distance either in integer pixels or floating-point millimeters. In either case, objPtr or string specifies a screen distance as a floating-point number followed by one of the following characters that indicates units:

<none>
The number specifies a distance in pixels.

c
The number specifies a distance in centimeters on the screen.

i
The number specifies a distance in inches on the screen.

m
The number specifies a distance in millimeters on the screen.

p
The number specifies a distance in printer's points (1/72 inch) on the screen.

Tk_GetPixelsFromObj converts the value of objPtr to the nearest even number of pixels and stores that value at *intPtr. It returns TCL_OK under normal circumstances. If an error occurs (e.g. objPtr contains a number followed by a character that isn't one of the ones above) then TCL_ERROR is returned and an error message is left in interp's result if interp isn't NULL. Tk_GetPixelsFromObj caches information about the return value in objPtr, which speeds up future calls to Tk_GetPixelsFromObj with the same objPtr.

Tk_GetPixels is identical to Tk_GetPixelsFromObj except that the screen distance is specified with a string instead of an object. This prevents Tk_GetPixels from caching the return value, so Tk_GetAnchor is less efficient than Tk_GetPixelsFromObj.

Tk_GetMMFromObj and Tk_GetScreenMM are similar to Tk_GetPixelsFromObj and Tk_GetPixels (respectively) except that they convert the screen distance to millimeters and store a double-precision floating-point result at *doublePtr.

KEYWORDS

centimeters, convert, inches, millimeters, pixels, points, screen units
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1998 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetPixmap manual page

NAME

Tk_GetPixmap, Tk_FreePixmap - allocate and free pixmaps

SYNOPSIS

#include <tk.h>
Pixmap
Tk_GetPixmap(display, d, width, height, depth)
Tk_FreePixmap(display, pixmap)

ARGUMENTS

Display *display (in)
X display for the pixmap.

Drawable d (in)
Pixmap or window where the new pixmap will be used for drawing.

int width (in)
Width of pixmap.

int height (in)
Height of pixmap.

int depth (in)
Number of bits per pixel in pixmap.

Pixmap pixmap (in)
Pixmap to destroy.

DESCRIPTION

These procedures are identical to the Xlib procedures XCreatePixmap and XFreePixmap, except that they have extra code to manage X resource identifiers so that identifiers for deleted pixmaps can be reused in the future. It is important for Tk applications to use these procedures rather than XCreatePixmap and XFreePixmap; otherwise long-running applications may run out of resource identifiers.

Tk_GetPixmap creates a pixmap suitable for drawing in d, with dimensions given by width, height, and depth, and returns its identifier. Tk_FreePixmap destroys the pixmap given by pixmap and makes its resource identifier available for reuse.

KEYWORDS

pixmap, resource identifier
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetReliefFromObj manual page

NAME

Tk_GetReliefFromObj, Tk_GetRelief, Tk_NameOfRelief - translate between strings and relief values

SYNOPSIS

#include <tk.h>
int
Tk_GetReliefFromObj(interp, objPtr, reliefPtr)
int
Tk_GetRelief(interp, name, reliefPtr)
char *
Tk_NameOfRelief(relief)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

Tcl_Obj *objPtr (in/out)
String value contains name of relief (one of flat, groove, raised, ridge, solid, or sunken); internal rep will be modified to cache corresponding relief value.

char *string (in)
Same as objPtr except description of relief is passed as a string.

int *reliefPtr (out)
Pointer to location in which to store relief value corresponding to objPtr or name.

int relief (in)
Relief value (one of TK_RELIEF_FLAT, TK_RELIEF_RAISED, TK_RELIEF_SUNKEN, TK_RELIEF_GROOVE, TK_RELIEF_SOLID, or TK_RELIEF_RIDGE).

DESCRIPTION

Tk_GetReliefFromObj places in *reliefPtr the relief value corresponding to the value of objPtr. This value will be one of TK_RELIEF_FLAT, TK_RELIEF_RAISED, TK_RELIEF_SUNKEN, TK_RELIEF_GROOVE, TK_RELIEF_SOLID, or TK_RELIEF_RIDGE. Under normal circumstances the return value is TCL_OK and interp is unused. If objPtr doesn't contain one of the valid relief names or an abbreviation of one of them, then TCL_ERROR is returned, *reliefPtr is unmodified, and an error message is stored in interp's result if interp isn't NULL. Tk_GetReliefFromObj caches information about the return value in objPtr, which speeds up future calls to Tk_GetReliefFromObj with the same objPtr.

Tk_GetRelief is identical to Tk_GetReliefFromObj except that the description of the relief is specified with a string instead of an object. This prevents Tk_GetRelief from caching the return value, so Tk_GetRelief is less efficient than Tk_GetReliefFromObj.

Tk_NameOfRelief is the logical inverse of Tk_GetRelief. Given a relief value it returns the corresponding string (flat, raised, sunken, groove, solid, or ridge). If relief isn't a legal relief value, then ``unknown relief'' is returned.

KEYWORDS

name, relief, string
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1998 Sun Microsystems, Inc.


Library Procedures - Tk_GetRootCoords manual page

NAME

Tk_GetRootCoords - Compute root-window coordinates of window

SYNOPSIS

#include <tk.h>
Tk_GetRootCoords(tkwin, xPtr, yPtr)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

int *xPtr (out)
Pointer to location in which to store root-window x-coordinate corresponding to left edge of tkwin's border.

int *yPtr (out)
Pointer to location in which to store root-window y-coordinate corresponding to top edge of tkwin's border.

DESCRIPTION

This procedure scans through the structural information maintained by Tk to compute the root-window coordinates corresponding to the upper-left corner of tkwin's border. If tkwin has no border, then Tk_GetRootCoords returns the root-window coordinates corresponding to location (0,0) in tkwin. Tk_GetRootCoords is relatively efficient, since it doesn't have to communicate with the X server.

KEYWORDS

coordinates, root window
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetScrollInfo manual page

NAME

Tk_GetScrollInfo, Tk_GetScrollInfoObj - parse arguments for scrolling commands

SYNOPSIS

#include <tk.h>
int
Tk_GetScrollInfo(interp, argc, argv, dblPtr, intPtr)
int
Tk_GetScrollInfoObj(interp, objc, objv, dblPtr, intPtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

int argc (in)
Number of strings in argv array.

char *argv[] (in)
Argument strings. These represent the entire widget command, of which the first word is typically the widget name and the second word is typically xview or yview.

int objc (in)
Number of Tcl_Obj's in objv array.

Tcl_Obj *CONST objv[] (in)
Argument objects. These represent the entire widget command, of which the first word is typically the widget name and the second word is typically xview or yview.

double *dblPtr (out)
Filled in with fraction from moveto option, if any.

int *intPtr (out)
Filled in with line or page count from scroll option, if any. The value may be negative.

DESCRIPTION

Tk_GetScrollInfo parses the arguments expected by widget scrolling commands such as xview and yview. It receives the entire list of words that make up a widget command and parses the words starting with argv[2]. The words starting with argv[2] must have one of the following forms:
moveto fraction
scroll number units
scroll number pages

Any of the moveto, scroll, units, and pages keywords may be abbreviated. If argv has the moveto form, TK_SCROLL_MOVETO is returned as result and *dblPtr is filled in with the fraction argument to the command, which must be a proper real value. If argv has the scroll form, TK_SCROLL_UNITS or TK_SCROLL_PAGES is returned and *intPtr is filled in with the number value, which must be a proper integer. If an error occurs in parsing the arguments, TK_SCROLL_ERROR is returned and an error message is left in interp->result.

Tk_GetScrollInfoObj is identical in function to Tk_GetScrollInfo. However, Tk_GetScrollInfoObj accepts Tcl_Obj style arguments, making it more appropriate for use with new development.

KEYWORDS

parse, scrollbar, scrolling command, xview, yview
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetSelection manual page

NAME

Tk_GetSelection - retrieve the contents of a selection

SYNOPSIS

#include <tk.h>
int
Tk_GetSelection(interp, tkwin, selection, target, proc, clientData)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for reporting errors.

Tk_Window tkwin (in)
Window on whose behalf to retrieve the selection (determines display from which to retrieve).

Atom selection (in)
The name of the selection to be retrieved.

Atom target (in)
Form in which to retrieve selection.

Tk_GetSelProc *proc (in)
Procedure to invoke to process pieces of the selection as they are retrieved.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

Tk_GetSelection retrieves the selection specified by the atom selection in the format specified by target. The selection may actually be retrieved in several pieces; as each piece is retrieved, proc is called to process the piece. Proc should have arguments and result that match the type Tk_GetSelProc:
typedef int Tk_GetSelProc(
    ClientData clientData,
    Tcl_Interp *interp,
    char *portion);
The clientData and interp parameters to proc will be copies of the corresponding arguments to Tk_GetSelection. Portion will be a pointer to a string containing part or all of the selection. For large selections, proc will be called several times with successive portions of the selection. The X Inter-Client Communication Conventions Manual allows a selection to be returned in formats other than strings, e.g. as an array of atoms or integers. If this happens, Tk converts the selection back into a string before calling proc. If a selection is returned as an array of atoms, Tk converts it to a string containing the atom names separated by white space. For any other format besides string, Tk converts a selection to a string containing hexadecimal values separated by white space.

Tk_GetSelection returns to its caller when the selection has been completely retrieved and processed by proc, or when a fatal error has occurred (e.g. the selection owner didn't respond promptly). Tk_GetSelection normally returns TCL_OK; if an error occurs, it returns TCL_ERROR and leaves an error message in interp->result. Proc should also return either TCL_OK or TCL_ERROR. If proc encounters an error in dealing with the selection, it should leave an error message in interp->result and return TCL_ERROR; this will abort the selection retrieval.

KEYWORDS

format, get, selection retrieval
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_GetUid manual page

NAME

Tk_GetUid, Tk_Uid - convert from string to unique identifier

SYNOPSIS

#include <tk.h>
#typedef char *Tk_Uid
Tk_Uid
Tk_GetUid(string)

ARGUMENTS

char *string (in)
String for which the corresponding unique identifier is desired.

DESCRIPTION

Tk_GetUid returns the unique identifier corresponding to string. Unique identifiers are similar to atoms in Lisp, and are used in Tk to speed up comparisons and searches. A unique identifier (type Tk_Uid) is a string pointer and may be used anywhere that a variable of type ``char *'' could be used. However, there is guaranteed to be exactly one unique identifier for any given string value. If Tk_GetUid is called twice, once with string a and once with string b, and if a and b have the same string value (strcmp(a, b) == 0), then Tk_GetUid will return exactly the same Tk_Uid value for each call (Tk_GetUid(a) == Tk_GetUid(b)). This means that variables of type Tk_Uid may be compared directly (x == y) without having to call strcmp. In addition, the return value from Tk_GetUid will have the same string value as its argument (strcmp(Tk_GetUid(a), a) == 0).

KEYWORDS

atom, unique identifier
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetVisual manual page

NAME
Tk_GetVisual - translate from string to visual
SYNOPSIS
ARGUMENTS
DESCRIPTION
class depth
default
pathName
number
best ?depth?
CREDITS
KEYWORDS

NAME

Tk_GetVisual - translate from string to visual

SYNOPSIS

#include <tk.h>
Visual *
Tk_GetVisual(interp, tkwin, string, depthPtr, colormapPtr)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting.

Tk_Window tkwin (in)
Token for window in which the visual will be used.

char *string (in)
String that identifies the desired visual. See below for valid formats.

int *depthPtr (out)
Depth of returned visual gets stored here.

Colormap *colormapPtr (out)
If non-NULL then a suitable colormap for visual is found and its identifier is stored here.

DESCRIPTION

Tk_GetVisual takes a string description of a visual and finds a suitable X Visual for use in tkwin, if there is one. It returns a pointer to the X Visual structure for the visual and stores the number of bits per pixel for it at *depthPtr. If string is unrecognizable or if no suitable visual could be found, then NULL is returned and Tk_GetVisual leaves an error message in interp->result. If colormap is non-NULL then Tk_GetVisual also locates an appropriate colormap for use with the result visual and stores its X identifier at *colormapPtr.

The string argument specifies the desired visual in one of the following ways:

class depth
The string consists of a class name followed by an integer depth, with any amount of white space (including none) in between. class selects what sort of visual is desired and must be one of directcolor, grayscale, greyscale, pseudocolor, staticcolor, staticgray, staticgrey, or truecolor, or a unique abbreviation. depth specifies how many bits per pixel are needed for the visual. If possible, Tk_GetVisual will return a visual with this depth; if there is no visual of the desired depth then Tk_GetVisual looks first for a visual with greater depth, then one with less depth.

default
Use the default visual for tkwin's screen.

pathName
Use the visual for the window given by pathName. pathName must be the name of a window on the same screen as tkwin.

number
Use the visual whose X identifier is number.

best ?depth?
Choose the ``best possible'' visual, using the following rules, in decreasing order of priority: (a) a visual that has exactly the desired depth is best, followed by a visual with greater depth than requested (but as little extra as possible), followed by a visual with less depth than requested (but as great a depth as possible); (b) if no depth is specified, then the deepest available visual is chosen; (c) pseudocolor is better than truecolor or directcolor, which are better than staticcolor, which is better than staticgray or grayscale; (d) the default visual for the screen is better than any other visual.

CREDITS

The idea for Tk_GetVisual, and the first implementation, came from Paul Mackerras.

KEYWORDS

colormap, screen, visual
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_GetVRootGeometry manual page

NAME

Tk_GetVRootGeometry - Get location and size of virtual root for window

SYNOPSIS

#include <tk.h>
Tk_GetVRootGeometry(tkwin, xPtr, yPtr, widthPtr, heightPtr)

ARGUMENTS

Tk_Window tkwin (in)
Token for window whose virtual root is to be queried.

int xPtr (out)
Points to word in which to store x-offset of virtual root.

int yPtr (out)
Points to word in which to store y-offset of virtual root.

int widthPtr (out)
Points to word in which to store width of virtual root.

int heightPtr (out)
Points to word in which to store height of virtual root.

DESCRIPTION

TkGetVRootGeometry returns geometry information about the virtual root window associated with tkwin. The ``associated'' virtual root is the one in which tkwin's nearest top-level ancestor (or tkwin itself if it is a top-level window) has been reparented by the window manager. This window is identified by a __SWM_ROOT or __WM_ROOT property placed on the top-level window by the window manager. If tkwin is not associated with a virtual root (e.g. because the window manager doesn't use virtual roots) then *xPtr and *yPtr will be set to 0 and *widthPtr and *heightPtr will be set to the dimensions of the screen containing tkwin.

KEYWORDS

geometry, height, location, virtual root, width, window manager
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_Grab manual page

NAME

Tk_Grab, Tk_Ungrab - manipulate grab state in an application

SYNOPSIS

#include <tk.h>
int
Tk_Grab(interp, tkwin, grabGlobal)
void
Tk_Ungrab(tkwin)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for error reporting

Tk_Window tkwin (in)
Window on whose behalf the pointer is to be grabbed or released

int grabGlobal (in)
Boolean indicating whether the grab is global or application local

DESCRIPTION

These functions are used to set or release a global or application local grab. When a grab is set on a particular window in a Tk application, mouse and keyboard events can only be received by that window and its descendants. Mouse and keyboard events for windows outside the tree rooted at tkwin will be redirected to tkwin. If the grab is global, then all mouse and keyboard events for windows outside the tree rooted at tkwin (even those intended for windows in other applications) will be redirected to tkwin. If the grab is application local, only mouse and keyboard events intended for a windows within the same application (but outside the tree rooted at tkwin) will be redirected.

Tk_Grab sets a grab on a particular window. Tkwin specifies the window on whose behalf the pointer is to be grabbed. GrabGlobal indicates whether the grab should be global or application local; if it is non-zero, it means the grab should be global. Normally, Tk_Grab returns TCL_OK; if an error occurs and the grab cannot be set, TCL_ERROR is returned and an error message is left if interp's result. Once this call completes successfully, no window outside the tree rooted at tkwin will receive pointer- or keyboard-related events until the next call to Tk_Ungrab. If a previous grab was in effect within the application, then it is replaced with a new one.

Tcl_Ungrab releases a grab on the mouse pointer and keyboard, if there is one set on the window given by tkwin. Once a grab is released, pointer and keyboard events will start being delivered to other windows again.

KEYWORDS

grab, window
Copyright © 1998-2000 by Scriptics Corporation.


Library Procedures - Tk_HandleEvent manual page

NAME

Tk_HandleEvent - invoke event handlers for window system events

SYNOPSIS

#include <tk.h>
Tk_HandleEvent(eventPtr)

ARGUMENTS

XEvent *eventPtr (in)
Pointer to X event to dispatch to relevant handler(s).

DESCRIPTION

Tk_HandleEvent is a lower-level procedure that deals with window events. It is called by Tcl_ServiceEvent (and indirectly by Tk_DoOneEvent), and in a few other cases within Tk. It makes callbacks to any window event handlers (created by calls to Tk_CreateEventHandler) that match eventPtr and then returns. In some cases it may be useful for an application to bypass the Tk event queue and call Tk_HandleEvent directly instead of calling Tcl_QueueEvent followed by Tcl_ServiceEvent.

This procedure may be invoked recursively. For example, it is possible to invoke Tk_HandleEvent recursively from a handler called by Tk_HandleEvent. This sort of operation is useful in some modal situations, such as when a notifier has been popped up and an application wishes to wait for the user to click a button in the notifier before doing anything else.

KEYWORDS

callback, event, handler, window
Copyright © 1990-1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_HWNDToWindow manual page

NAME

Tk_HWNDToWindow - Find Tk's window information for a Windows window

SYNOPSIS

#include <tkPlatDecls.h>
Tk_Window
Tk_HWNDToWindow(hwnd)

ARGUMENTS

HWND hwnd (in)
Windows handle for the window.

DESCRIPTION

Given a Windows HWND window identifier, this procedure returns the corresponding Tk_Window handle. If there is no Tk_Window corresponding to hwnd then NULL is returned.

KEYWORDS

Windows window id
Copyright © 1998-2000 by Scriptics Corporation.


Tk Library Procedures - Tk_IdToWindow manual page

NAME

Tk_IdToWindow - Find Tk's window information for an X window

SYNOPSIS

#include <tk.h>
Tk_Window
Tk_IdToWindow(display, window)

ARGUMENTS

Display *display (in)
X display containing the window.

Window window (in)
X id for window.

DESCRIPTION

Given an X window identifier and the X display it corresponds to, this procedure returns the corresponding Tk_Window handle. If there is no Tk_Window corresponding to window then NULL is returned.

KEYWORDS

X window id
Copyright © 1995-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_ImageChanged manual page

NAME

Tk_ImageChanged - notify widgets that image needs to be redrawn

SYNOPSIS

#include <tk.h>
Tk_ImageChanged(imageMaster, x, y, width, height, imageWidth, imageHeight)

ARGUMENTS

Tk_ImageMaster imageMaster (in)
Token for image, which was passed to image's createProc when the image was created.

int x (in)
X-coordinate of upper-left corner of region that needs redisplay (measured from upper-left corner of image).

int y (in)
Y-coordinate of upper-left corner of region that needs redisplay (measured from upper-left corner of image).

int width (in)
Width of region that needs to be redrawn, in pixels.

int height (in)
Height of region that needs to be redrawn, in pixels.

int imageWidth (in)
Current width of image, in pixels.

int imageHeight (in)
Current height of image, in pixels.

DESCRIPTION

An image manager calls Tk_ImageChanged for an image whenever anything happens that requires the image to be redrawn. As a result of calling Tk_ImageChanged, any widgets using the image are notified so that they can redisplay themselves appropriately. The imageMaster argument identifies the image, and x, y, width, and height specify a rectangular region within the image that needs to be redrawn. imageWidth and imageHeight specify the image's (new) size.

An image manager should call Tk_ImageChanged during its createProc to specify the image's initial size and to force redisplay if there are existing instances for the image. If any of the pixel values in the image should change later on, Tk_ImageChanged should be called again with x, y, width, and height values that cover all the pixels that changed. If the size of the image should change, then Tk_ImageChanged must be called to indicate the new size, even if no pixels need to be redisplayed.

SEE ALSO

Tk_CreateImageType

KEYWORDS

images, redisplay, image size changes
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_InternAtom manual page

NAME

Tk_InternAtom, Tk_GetAtomName - manage cache of X atoms

SYNOPSIS

#include <tk.h>
Atom
Tk_InternAtom(tkwin, name)
char *
Tk_GetAtomName(tkwin, atom)

ARGUMENTS

Tk_Window tkwin (in)
Token for window. Used to map atom or name relative to a particular display.

char *name (in)
String name for which atom is desired.

Atom atom (in)
Atom for which corresponding string name is desired.

DESCRIPTION

These procedures are similar to the Xlib procedures XInternAtom and XGetAtomName. Tk_InternAtom returns the atom identifier associated with string given by name; the atom identifier is only valid for the display associated with tkwin. Tk_GetAtomName returns the string associated with atom on tkwin's display. The string returned by Tk_GetAtomName is in Tk's storage: the caller need not free this space when finished with the string, and the caller should not modify the contents of the returned string. If there is no atom atom on tkwin's display, then Tk_GetAtomName returns the string ``?bad atom?''.

Tk caches the information returned by Tk_InternAtom and Tk_GetAtomName so that future calls for the same information can be serviced from the cache without contacting the server. Thus Tk_InternAtom and Tk_GetAtomName are generally much faster than their Xlib counterparts, and they should be used in place of the Xlib procedures.

KEYWORDS

atom, cache, display
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_MainLoop manual page

NAME

Tk_MainLoop - loop for events until all windows are deleted

SYNOPSIS

#include <tk.h>
Tk_MainLoop()

DESCRIPTION

Tk_MainLoop is a procedure that loops repeatedly calling Tcl_DoOneEvent. It returns only when there are no applications left in this process (i.e. no main windows exist anymore). Most windowing applications will call Tk_MainLoop after initialization; the main execution of the application will consist entirely of callbacks invoked via Tcl_DoOneEvent.

KEYWORDS

application, event, main loop
Copyright © 1990-1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_MaintainGeometry manual page

NAME

Tk_MaintainGeometry, Tk_UnmaintainGeometry - maintain geometry of one window relative to another

SYNOPSIS

#include <tk.h>
Tk_MaintainGeometry(slave, master, x, y, width, height)
Tk_UnmaintainGeometry(slave, master)

ARGUMENTS

Tk_Window slave (in)
Window whose geometry is to be controlled.

Tk_Window master (in)
Window relative to which slave's geometry will be controlled.

int x (in)
Desired x-coordinate of slave in master, measured in pixels from the inside of master's left border to the outside of slave's left border.

int y (in)
Desired y-coordinate of slave in master, measured in pixels from the inside of master's top border to the outside of slave's top border.

int width (in)
Desired width for slave, in pixels.

int height (in)
Desired height for slave, in pixels.

DESCRIPTION

Tk_MaintainGeometry and Tk_UnmaintainGeometry make it easier for geometry managers to deal with slaves whose masters are not their parents. Three problems arise if the master for a slave is not its parent:

[1]
The x- and y-position of the slave must be translated from the coordinate system of the master to that of the parent before positioning the slave.

[2]
If the master window, or any of its ancestors up to the slave's parent, is moved, then the slave must be repositioned within its parent in order to maintain the correct position relative to the master.

[3]
If the master or one of its ancestors is mapped or unmapped, then the slave must be mapped or unmapped to correspond.

None of these problems is an issue if the parent and master are the same. For example, if the master or one of its ancestors is unmapped, the slave is automatically removed by the screen by X.

Tk_MaintainGeometry deals with these problems for slaves whose masters aren't their parents, as well as handling the simpler case of slaves whose masters are their parents. Tk_MaintainGeometry is typically called by a window manager once it has decided where a slave should be positioned relative to its master. Tk_MaintainGeometry translates the coordinates to the coordinate system of slave's parent and then moves and resizes the slave appropriately. Furthermore, it remembers the desired position and creates event handlers to monitor the master and all of its ancestors up to (but not including) the slave's parent. If any of these windows is moved, mapped, or unmapped, the slave will be adjusted so that it is mapped only when the master is mapped and its geometry relative to the master remains as specified by x, y, width, and height.

When a window manager relinquishes control over a window, or if it decides that it does not want the window to appear on the screen under any conditions, it calls Tk_UnmaintainGeometry. Tk_UnmaintainGeometry unmaps the window and cancels any previous calls to Tk_MaintainGeometry for the master-slave pair, so that the slave's geometry and mapped state are no longer maintained automatically. Tk_UnmaintainGeometry need not be called by a geometry manager if the slave, the master, or any of the master's ancestors is destroyed: Tk will call it automatically.

If Tk_MaintainGeometry is called repeatedly for the same master-slave pair, the information from the most recent call supersedes any older information. If Tk_UnmaintainGeometry is called for a master-slave pair that is isn't currently managed, the call has no effect.

KEYWORDS

geometry manager, map, master, parent, position, slave, unmap
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_MainWindow manual page

NAME

Tk_MainWindow, Tk_GetNumMainWindows - functions for querying main window information

SYNOPSIS

#include <tk.h>
Tk_Window
Tk_MainWindow(interp)
int
Tk_GetNumMainWindows()

ARGUMENTS

Tcl_Interp *interp (in/out)
Interpreter associated with the application.

DESCRIPTION

A main window is a special kind of toplevel window used as the outermost window in an application.

If interp is associated with a Tk application then Tk_MainWindow returns the application's main window. If there is no Tk application associated with interp then Tk_MainWindow returns NULL and leaves an error message in interp->result.

Tk_GetNumMainWindows returns a count of the number of main windows currently open in the process.

KEYWORDS

application, main window
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_ManageGeometry manual page

NAME

Tk_ManageGeometry - arrange to handle geometry requests for a window

SYNOPSIS

#include <tk.h>
Tk_ManageGeometry(tkwin, mgrPtr, clientData)

ARGUMENTS

Tk_Window tkwin (in)
Token for window to be managed.

Tk_GeomMgr *mgrPtr (in)
Pointer to data structure containing information about the geometry manager, or NULL to indicate that tkwin's geometry shouldn't be managed anymore. The data structure pointed to by mgrPtr must be static: Tk keeps a reference to it as long as the window is managed.

ClientData clientData (in)
Arbitrary one-word value to pass to geometry manager callbacks.

DESCRIPTION

Tk_ManageGeometry arranges for a particular geometry manager, described by the mgrPtr argument, to control the geometry of a particular slave window, given by tkwin. If tkwin was previously managed by some other geometry manager, the previous manager loses control in favor of the new one. If mgrPtr is NULL, geometry management is cancelled for tkwin.

The structure pointed to by mgrPtr contains information about the geometry manager:

typedef struct {
    char *name;
    Tk_GeomRequestProc *requestProc;
    Tk_GeomLostSlaveProc *lostSlaveProc;
} Tk_GeomMgr;
The name field is the textual name for the geometry manager, such as pack or place; this value will be returned by the command winfo manager.

requestProc is a procedure in the geometry manager that will be invoked whenever Tk_GeometryRequest is called by the slave to change its desired geometry. requestProc should have arguments and results that match the type Tk_GeomRequestProc:

typedef void Tk_GeomRequestProc(
    ClientData clientData,
    Tk_Window tkwin);
The parameters to requestProc will be identical to the corresponding parameters passed to Tk_ManageGeometry. clientData usually points to a data structure containing application-specific information about how to manage tkwin's geometry.

The lostSlaveProc field of mgrPtr points to another procedure in the geometry manager. Tk will invoke lostSlaveProc if some other manager calls Tk_ManageGeometry to claim tkwin away from the current geometry manager. lostSlaveProc is not invoked if Tk_ManageGeometry is called with a NULL value for mgrPtr (presumably the current geometry manager has made this call, so it already knows that the window is no longer managed), nor is it called if mgrPtr is the same as the window's current geometry manager. lostSlaveProc should have arguments and results that match the following prototype:

typedef void Tk_GeomLostSlaveProc(
    ClientData clientData,
    Tk_Window tkwin);
The parameters to lostSlaveProc will be identical to the corresponding parameters passed to Tk_ManageGeometry.

KEYWORDS

callback, geometry, managed, request, unmanaged
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_MapWindow manual page

NAME

Tk_MapWindow, Tk_UnmapWindow - map or unmap a window

SYNOPSIS

#include <tk.h>
Tk_Window
Tk_MapWindow(tkwin)
Tk_UnmapWindow(tkwin)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

DESCRIPTION

These procedures may be used to map and unmap windows managed by Tk. Tk_MapWindow maps the window given by tkwin, and also creates an X window corresponding to tkwin if it doesn't already exist. See the Tk_CreateWindow manual entry for information on deferred window creation. Tk_UnmapWindow unmaps tkwin's window from the screen.

If tkwin is a child window (i.e. Tk_CreateWindow was used to create a child window), then event handlers interested in map and unmap events are invoked immediately. If tkwin isn't an internal window, then the event handlers will be invoked later, after X has seen the request and returned an event for it.

These procedures should be used in place of the X procedures XMapWindow and XUnmapWindow, since they update Tk's local data structure for tkwin. Applications using Tk should not invoke XMapWindow and XUnmapWindow directly.

KEYWORDS

map, unmap, window
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tk Library Procedures - Tk_MeasureChars manual page

NAME

Tk_MeasureChars, Tk_TextWidth, Tk_DrawChars, Tk_UnderlineChars - routines to measure and display simple single-line strings.

SYNOPSIS

#include <tk.h>
int
Tk_MeasureChars(tkfont, string, numBytes, maxPixels, flags, lengthPtr)
int
Tk_TextWidth(tkfont, string, numBytes)
void
Tk_DrawChars(display, drawable, gc, tkfont, string, numBytes, x, y)
void
Tk_UnderlineChars(display, drawable, gc, tkfont, string, x, y, firstByte, lastByte)

ARGUMENTS

Tk_Font tkfont (in)
Token for font in which text is to be drawn or measured. Must have been returned by a previous call to Tk_GetFont.

const char *string (in)
Text to be measured or displayed. Need not be null terminated. Any non-printing meta-characters in the string (such as tabs, newlines, and other control characters) will be measured or displayed in a platform-dependent manner.

int numBytes (in)
The maximum number of bytes to consider when measuring or drawing string. Must be greater than or equal to 0.

int maxPixels (in)
If maxPixels is >= 0, it specifies the longest permissible line length in pixels. Characters from string are processed only until this many pixels have been covered. If maxPixels is < 0, then the line length is unbounded and the flags argument is ignored.

int flags (in)
Various flag bits OR-ed together: TK_PARTIAL_OK means include a character as long as any part of it fits in the length given by maxPixels; otherwise, a character must fit completely to be considered. TK_WHOLE_WORDS means stop on a word boundary, if possible. If TK_AT_LEAST_ONE is set, it means return at least one character even if no characters could fit in the length given by maxPixels. If TK_AT_LEAST_ONE is set and TK_WHOLE_WORDS is also set, it means that if not even one word fits on the line, return the first few letters of the word that did fit; if not even one letter of the word fit, then the first letter will still be returned.

int *lengthPtr (out)
Filled with the number of pixels occupied by the number of characters returned as the result of Tk_MeasureChars.

Display *display (in)
Display on which to draw.

Drawable drawable (in)
Window or pixmap in which to draw.

GC gc (in)
Graphics context for drawing characters. The font selected into this GC must be the same as the tkfont.

int x, y (in)
Coordinates at which to place the left edge of the baseline when displaying string.

int firstByte (in)
The index of the first byte of the first character to underline in the string. Underlining begins at the left edge of this character.

int lastByte (in)
The index of the first byte of the last character up to which the underline will be drawn. The character specified by lastByte will not itself be underlined.

DESCRIPTION

These routines are for measuring and displaying simple single-font, single-line, strings. To measure and display single-font, multi-line, justified text, refer to the documentation for Tk_ComputeTextLayout. There is no programming interface in the core of Tk that supports multi-font, multi-line text; support for that behavior must be built on top of simpler layers. Note that the interfaces described here are byte-oriented not character-oriented, so index values coming from Tcl scripts need to be converted to byte offsets using the Tcl_UtfAtIndex and related routines.

A glyph is the displayable picture of a letter, number, or some other symbol. Not all character codes in a given font have a glyph. Characters such as tabs, newlines/returns, and control characters that have no glyph are measured and displayed by these procedures in a platform-dependent manner; under X, they are replaced with backslashed escape sequences, while under Windows and Macintosh hollow or solid boxes may be substituted. Refer to the documentation for Tk_ComputeTextLayout for a programming interface that supports the platform-independent expansion of tab characters into columns and newlines/returns into multi-line text.

Tk_MeasureChars is used both to compute the length of a given string and to compute how many characters from a string fit in a given amount of space. The return value is the number of bytes from string that fit in the space specified by maxPixels subject to the conditions described by flags. If all characters fit, the return value will be numBytes. *lengthPtr is filled with the computed width, in pixels, of the portion of the string that was measured. For example, if the return value is 5, then *lengthPtr is filled with the distance between the left edge of string[0] and the right edge of string[4].

Tk_TextWidth is a wrapper function that provides a simpler interface to the Tk_MeasureChars function. The return value is how much space in pixels the given string needs.

Tk_DrawChars draws the string at the given location in the given drawable.

Tk_UnderlineChars underlines the given range of characters in the given string. It doesn't draw the characters (which are assumed to have been displayed previously by Tk_DrawChars); it just draws the underline. This procedure is used to underline a few characters without having to construct an underlined font. To produce natively underlined text, the appropriate underlined font should be constructed and used.

KEYWORDS

font
Copyright © 1996 Sun Microsystems, Inc.


Library Procedures - Tk_MoveToplevelWindow manual page

NAME

Tk_MoveToplevelWindow - Adjust the position of a top-level window

SYNOPSIS

#include <tk.h>
Tk_MoveToplevelWindow(tkwin, x, y)

ARGUMENTS

Tk_Window tkwin (in)
Token for top-level window to move.

int x (in)
New x-coordinate for the top-left pixel of tkwin's border, or the top-left pixel of the decorative border supplied for tkwin by the window manager, if there is one.

int y (in)
New y-coordinate for the top-left pixel of tkwin's border, or the top-left pixel of the decorative border supplied for tkwin by the window manager, if there is one.

DESCRIPTION

In general, a window should never set its own position; this should be done only by the geometry manger that is responsible for the window. For top-level windows the window manager is effectively the geometry manager; Tk provides interface code between the application and the window manager to convey the application's desires to the geometry manager. The desired size for a top-level window is conveyed using the usual Tk_GeometryRequest mechanism. The procedure Tk_MoveToplevelWindow may be used by an application to request a particular position for a top-level window; this procedure is similar in function to the wm geometry Tcl command except that negative offsets cannot be specified. It is invoked by widgets such as menus that want to appear at a particular place on the screen.

When Tk_MoveToplevelWindow is called it doesn't immediately pass on the new desired location to the window manager; it defers this action until all other outstanding work has been completed, using the Tk_DoWhenIdle mechanism.

KEYWORDS

position, top-level window, window manager
Copyright © 1990-1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_Name manual page

NAME

Tk_Name, Tk_PathName, Tk_NameToWindow - convert between names and window tokens

SYNOPSIS

#include <tk.h>
Tk_Uid
Tk_Name(tkwin)
char *
Tk_PathName(tkwin)
Tk_Window
Tk_NameToWindow(interp, pathName, tkwin)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

Tcl_Interp *interp (out)
Interpreter to use for error reporting.

char *pathName (in)
Character string containing path name of window.

DESCRIPTION

Each window managed by Tk has two names, a short name that identifies a window among children of the same parent, and a path name that identifies the window uniquely among all the windows belonging to the same main window. The path name is used more often in Tk than the short name; many commands, like bind, expect path names as arguments.

The Tk_Name macro returns a window's short name, which is the same as the name argument passed to Tk_CreateWindow when the window was created. The value is returned as a Tk_Uid, which may be used just like a string pointer but also has the properties of a unique identifier (see the manual entry for Tk_GetUid for details).

The Tk_PathName macro returns a hierarchical name for tkwin. Path names have a structure similar to file names in Unix but with dots between elements instead of slashes: the main window for an application has the path name ``.''; its children have names like ``.a'' and ``.b''; their children have names like ``.a.aa'' and ``.b.bb''; and so on. A window is considered to be be a child of another window for naming purposes if the second window was named as the first window's parent when the first window was created. This is not always the same as the X window hierarchy. For example, a pop-up is created as a child of the root window, but its logical parent will usually be a window within the application.

The procedure Tk_NameToWindow returns the token for a window given its path name (the pathName argument) and another window belonging to the same main window (tkwin). It normally returns a token for the named window, but if no such window exists Tk_NameToWindow leaves an error message in interp->result and returns NULL. The tkwin argument to Tk_NameToWindow is needed because path names are only unique within a single application hierarchy. If, for example, a single process has opened two main windows, each will have a separate naming hierarchy and the same path name might appear in each of the hierarchies. Normally tkwin is the main window of the desired hierarchy, but this need not be the case: any window in the desired hierarchy may be used.

KEYWORDS

name, path name, token, window
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Tk Library Procedures - Tk_NameOfImage manual page

NAME

Tk_NameOfImage - Return name of image.

SYNOPSIS

#include <tk.h>
char *
Tk_NameOfImage(typePtr)

ARGUMENTS

Tk_ImageMaster *masterPtr (in)
Token for image, which was passed to image manager's createProc when the image was created.

DESCRIPTION

This procedure is invoked by image managers to find out the name of an image. Given the token for the image, it returns the string name for the image.

KEYWORDS

image manager, image name
Copyright © 1995-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_OwnSelection manual page

NAME

Tk_OwnSelection - make a window the owner of the primary selection

SYNOPSIS

#include <tk.h>
Tk_OwnSelection(tkwin, selection, proc, clientData)

ARGUMENTS

Tk_Window tkwin (in)
Window that is to become new selection owner.

Atom selection (in)
The name of the selection to be owned, such as XA_PRIMARY.

Tk_LostSelProc *proc (in)
Procedure to invoke when tkwin loses selection ownership later.

ClientData clientData (in)
Arbitrary one-word value to pass to proc.

DESCRIPTION

Tk_OwnSelection arranges for tkwin to become the new owner of the selection specified by the atom selection. After this call completes, future requests for the selection will be directed to handlers created for tkwin using Tk_CreateSelHandler. When tkwin eventually loses the selection ownership, proc will be invoked so that the window can clean itself up (e.g. by unhighlighting the selection). Proc should have arguments and result that match the type Tk_LostSelProc:
typedef void Tk_LostSelProc(ClientData clientData);
The clientData parameter to proc is a copy of the clientData argument given to Tk_OwnSelection, and is usually a pointer to a data structure containing application-specific information about tkwin.

KEYWORDS

own, selection owner
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_ParseArgv manual page

NAME
Tk_ParseArgv - process command-line options
SYNOPSIS
ARGUMENTS
DESCRIPTION
TK_ARGV_END
TK_ARGV_CONSTANT
TK_ARGV_INT
TK_ARGV_FLOAT
TK_ARGV_STRING
TK_ARGV_UID
TK_ARGV_CONST_OPTION
TK_ARGV_OPTION_VALUE
TK_ARGV_OPTION_NAME_VALUE
TK_ARGV_HELP
TK_ARGV_REST
TK_ARGV_FUNC
TK_ARGV_GENFUNC
FLAGS
TK_ARGV_DONT_SKIP_FIRST_ARG
TK_ARGV_NO_ABBREV
TK_ARGV_NO_LEFTOVERS
TK_ARGV_NO_DEFAULTS
EXAMPLE
KEYWORDS

NAME

Tk_ParseArgv - process command-line options

SYNOPSIS

#include <tk.h>
int
Tk_ParseArgv(interp, tkwin, argcPtr, argv, argTable, flags)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter to use for returning error messages.

Tk_Window tkwin (in)
Window to use when arguments specify Tk options. If NULL, then no Tk options will be processed.

int argcPtr (in/out)
Pointer to number of arguments in argv; gets modified to hold number of unprocessed arguments that remain after the call.

char **argv (in/out)
Command line arguments passed to main program. Modified to hold unprocessed arguments that remain after the call.

Tk_ArgvInfo *argTable (in)
Array of argument descriptors, terminated by element with type TK_ARGV_END.

int flags (in)
If non-zero, then it specifies one or more flags that control the parsing of arguments. Different flags may be OR'ed together. The flags currently defined are TK_ARGV_DONT_SKIP_FIRST_ARG, TK_ARGV_NO_ABBREV, TK_ARGV_NO_LEFTOVERS, and TK_ARGV_NO_DEFAULTS.

DESCRIPTION

Tk_ParseArgv processes an array of command-line arguments according to a table describing the kinds of arguments that are expected. Each of the arguments in argv is processed in turn: if it matches one of the entries in argTable, the argument is processed according to that entry and discarded. The arguments that do not match anything in argTable are copied down to the beginning of argv (retaining their original order) and returned to the caller. At the end of the call Tk_ParseArgv sets *argcPtr to hold the number of arguments that are left in argv, and argv[*argcPtr] will hold the value NULL. Normally, Tk_ParseArgv assumes that argv[0] is a command name, so it is treated like an argument that doesn't match argTable and returned to the caller; however, if the TK_ARGV_DONT_SKIP_FIRST_ARG bit is set in flags then argv[0] will be processed just like the other elements of argv.

Tk_ParseArgv normally returns the value TCL_OK. If an error occurs while parsing the arguments, then TCL_ERROR is returned and Tk_ParseArgv will leave an error message in interp->result in the standard Tcl fashion. In the event of an error return, *argvPtr will not have been modified, but argv could have been partially modified. The possible causes of errors are explained below.

The argTable array specifies the kinds of arguments that are expected; each of its entries has the following structure:

typedef struct {
    char *key;
    int type;
    char *src;
    char *dst;
    char *help;
} Tk_ArgvInfo;
The key field is a string such as ``-display'' or ``-bg'' that is compared with the values in argv. Type indicates how to process an argument that matches key (more on this below). Src and dst are additional values used in processing the argument. Their exact usage depends on type, but typically src indicates a value and dst indicates where to store the value. The char * declarations for src and dst are placeholders: the actual types may be different. Lastly, help is a string giving a brief description of this option; this string is printed when users ask for help about command-line options.

When processing an argument in argv, Tk_ParseArgv compares the argument to each of the key's in argTable. Tk_ParseArgv selects the first specifier whose key matches the argument exactly, if such a specifier exists. Otherwise Tk_ParseArgv selects a specifier for which the argument is a unique abbreviation. If the argument is a unique abbreviation for more than one specifier, then an error is returned. If there is no matching entry in argTable, then the argument is skipped and returned to the caller.

Once a matching argument specifier is found, Tk_ParseArgv processes the argument according to the type field of the specifier. The argument that matched key is called ``the matching argument'' in the descriptions below. As part of the processing, Tk_ParseArgv may also use the next argument in argv after the matching argument, which is called ``the following argument''. The legal values for type, and the processing that they cause, are as follows:

TK_ARGV_END
Marks the end of the table. The last entry in argTable must have this type; all of its other fields are ignored and it will never match any arguments.

TK_ARGV_CONSTANT
Src is treated as an integer and dst is treated as a pointer to an integer. Src is stored at *dst. The matching argument is discarded.

TK_ARGV_INT
The following argument must contain an integer string in the format accepted by strtol (e.g. ``0'' and ``0x'' prefixes may be used to specify octal or hexadecimal numbers, respectively). Dst is treated as a pointer to an integer; the following argument is converted to an integer value and stored at *dst. Src is ignored. The matching and following arguments are discarded from argv.

TK_ARGV_FLOAT
The following argument must contain a floating-point number in the format accepted by strtol. Dst is treated as the address of an double-precision floating point value; the following argument is converted to a double-precision value and stored at *dst. The matching and following arguments are discarded from argv.

TK_ARGV_STRING
In this form, dst is treated as a pointer to a (char *); Tk_ParseArgv stores at *dst a pointer to the following argument, and discards the matching and following arguments from argv. Src is ignored.

TK_ARGV_UID
This form is similar to TK_ARGV_STRING, except that the argument is turned into a Tk_Uid by calling Tk_GetUid. Dst is treated as a pointer to a Tk_Uid; Tk_ParseArgv stores at *dst the Tk_Uid corresponding to the following argument, and discards the matching and following arguments from argv. Src is ignored.

TK_ARGV_CONST_OPTION
This form causes a Tk option to be set (as if the option command had been invoked). The src field is treated as a pointer to a string giving the value of an option, and dst is treated as a pointer to the name of the option. The matching argument is discarded. If tkwin is NULL, then argument specifiers of this type are ignored (as if they did not exist).

TK_ARGV_OPTION_VALUE
This form is similar to TK_ARGV_CONST_OPTION, except that the value of the option is taken from the following argument instead of from src. Dst is used as the name of the option. Src is ignored. The matching and following arguments are discarded. If tkwin is NULL, then argument specifiers of this type are ignored (as if they did not exist).

TK_ARGV_OPTION_NAME_VALUE
In this case the following argument is taken as the name of a Tk option and the argument after that is taken as the value for that option. Both src and dst are ignored. All three arguments are discarded from argv. If tkwin is NULL, then argument specifiers of this type are ignored (as if they did not exist).

TK_ARGV_HELP
When this kind of option is encountered, Tk_ParseArgv uses the help fields of argTable to format a message describing all the valid arguments. The message is placed in interp->result and Tk_ParseArgv returns TCL_ERROR. When this happens, the caller normally prints the help message and aborts. If the key field of a TK_ARGV_HELP specifier is NULL, then the specifier will never match any arguments; in this case the specifier simply provides extra documentation, which will be included when some other TK_ARGV_HELP entry causes help information to be returned.

TK_ARGV_REST
This option is used by programs or commands that allow the last several of their options to be the name and/or options for some other program. If a TK_ARGV_REST argument is found, then Tk_ParseArgv doesn't process any of the remaining arguments; it returns them all at the beginning of argv (along with any other unprocessed arguments). In addition, Tk_ParseArgv treats dst as the address of an integer value, and stores at *dst the index of the first of the TK_ARGV_REST options in the returned argv. This allows the program to distinguish the TK_ARGV_REST options from other unprocessed options that preceded the TK_ARGV_REST.

TK_ARGV_FUNC
For this kind of argument, src is treated as the address of a procedure, which is invoked to process the following argument. The procedure should have the following structure:
int
func(dst, key, nextArg)
    char *dst;
    char *key;
    char *nextArg;
{
}
The dst and key parameters will contain the corresponding fields from the argTable entry, and nextArg will point to the following argument from argv (or NULL if there aren't any more arguments left in argv). If func uses nextArg (so that Tk_ParseArgv should discard it), then it should return 1. Otherwise it should return 0 and TkParseArgv will process the following argument in the normal fashion. In either event the matching argument is discarded.

TK_ARGV_GENFUNC
This form provides a more general procedural escape. It treats src as the address of a procedure, and passes that procedure all of the remaining arguments. The procedure should have the following form:
int
genfunc(dst, interp, key, argc, argv)
    char *dst;
    Tcl_Interp *interp;
    char *key;
    int argc;
    char **argv;
{
}
The dst and key parameters will contain the corresponding fields from the argTable entry. Interp will be the same as the interp argument to Tcl_ParseArgv. Argc and argv refer to all of the options after the matching one. Genfunc should behave in a fashion similar to Tk_ParseArgv: parse as many of the remaining arguments as it can, then return any that are left by compacting them to the beginning of argv (starting at argv[0]). Genfunc should return a count of how many arguments are left in argv; Tk_ParseArgv will process them. If genfunc encounters an error then it should leave an error message in interp->result, in the usual Tcl fashion, and return -1; when this happens Tk_ParseArgv will abort its processing and return TCL_ERROR.

FLAGS

TK_ARGV_DONT_SKIP_FIRST_ARG
Tk_ParseArgv normally treats argv[0] as a program or command name, and returns it to the caller just as if it hadn't matched argTable. If this flag is given, then argv[0] is not given special treatment.

TK_ARGV_NO_ABBREV
Normally, Tk_ParseArgv accepts unique abbreviations for key values in argTable. If this flag is given then only exact matches will be acceptable.

TK_ARGV_NO_LEFTOVERS
Normally, Tk_ParseArgv returns unrecognized arguments to the caller. If this bit is set in flags then Tk_ParseArgv will return an error if it encounters any argument that doesn't match argTable. The only exception to this rule is argv[0], which will be returned to the caller with no errors as long as TK_ARGV_DONT_SKIP_FIRST_ARG isn't specified.

TK_ARGV_NO_DEFAULTS
Normally, Tk_ParseArgv searches an internal table of standard argument specifiers in addition to argTable. If this bit is set in flags, then Tk_ParseArgv will use only argTable and not its default table.

EXAMPLE

Here is an example definition of an argTable and some sample command lines that use the options. Note the effect on argc and argv; arguments processed by Tk_ParseArgv are eliminated from argv, and argc is updated to reflect reduced number of arguments.
/*
 * Define and set default values for globals.
 */
int debugFlag = 0;
int numReps = 100;
char defaultFileName[] = "out";
char *fileName = defaultFileName;
Boolean exec = FALSE;

/*
 * Define option descriptions.
 */
Tk_ArgvInfo argTable[] = {
    {"-X", TK_ARGV_CONSTANT, (char *) 1, (char *) &debugFlag,
        "Turn on debugging printfs"},
    {"-N", TK_ARGV_INT, (char *) NULL, (char *) &numReps,
        "Number of repetitions"},
    {"-of", TK_ARGV_STRING, (char *) NULL, (char *) &fileName,
        "Name of file for output"},
    {"x", TK_ARGV_REST, (char *) NULL, (char *) &exec,
        "File to exec, followed by any arguments (must be last argument)."},
    {(char *) NULL, TK_ARGV_END, (char *) NULL, (char *) NULL,
        (char *) NULL}
};

main(argc, argv)
    int argc;
    char *argv[];
{
        ...

    if (Tk_ParseArgv(interp, tkwin, &argc, argv, argTable, 0) != TCL_OK) {
        fprintf(stderr, "%s\n", interp->result);
        exit(1);
    }

    /*
     * Remainder of the program.
     */
}

Note that default values can be assigned to variables named in argTable: the variables will only be overwritten if the particular arguments are present in argv. Here are some example command lines and their effects.

prog -N 200 infile		# just sets the numReps variable to 200
prog -of out200 infile 	# sets fileName to reference "out200"
prog -XN 10 infile		# sets the debug flag, also sets numReps
In all of the above examples, argc will be set by Tk_ParseArgv to 2, argv[0] will be ``prog'', argv[1] will be ``infile'', and argv[2] will be NULL.

KEYWORDS

arguments, command line, options
Copyright © 1990-1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_QueueWindowEvent manual page

NAME

Tk_QueueWindowEvent - Add a window event to the Tcl event queue

SYNOPSIS

#include <tk.h>
Tk_QueueWindowEvent(eventPtr, position)

ARGUMENTS

XEvent *eventPtr (in)
An event to add to the event queue.

Tcl_QueuePosition position (in)
Where to add the new event in the queue: TCL_QUEUE_TAIL, TCL_QUEUE_HEAD, or TCL_QUEUE_MARK.

DESCRIPTION

This procedure places a window event on Tcl's internal event queue for eventual servicing. It creates a Tcl_Event structure, copies the event into that structure, and calls Tcl_QueueEvent to add the event to the queue. When the event is eventually removed from the queue it is processed just like all window events.

The position argument to Tk_QueueWindowEvent has the same significance as for Tcl_QueueEvent; see the documentation for Tcl_QueueEvent for details.

KEYWORDS

callback, clock, handler, modal timeout
Copyright © 1995-1996 Sun Microsystems, Inc.


Library Procedures - Tk_RestackWindow manual page

NAME

Tk_RestackWindow - Change a window's position in the stacking order

SYNOPSIS

#include <tk.h>
int
Tk_RestackWindow(tkwin, aboveBelow, other)

ARGUMENTS

Tk_Window tkwin (in)
Token for window to restack.

int aboveBelow (in)
Indicates new position of tkwin relative to other; must be Above or Below.

Tk_Window other (in)
Tkwin will be repositioned just above or below this window. Must be a sibling of tkwin or a descendant of a sibling. If NULL then tkwin is restacked above or below all siblings.

DESCRIPTION

Tk_RestackWindow changes the stacking order of window relative to its siblings. If other is specified as NULL then window is repositioned at the top or bottom of its stacking order, depending on whether aboveBelow is Above or Below. If other has a non-NULL value then window is repositioned just above or below other.

The aboveBelow argument must have one of the symbolic values Above or Below. Both of these values are defined by the include file <X11/Xlib.h>.

KEYWORDS

above, below, obscure, stacking order
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Library Procedures - Tk_RestrictEvents manual page

NAME

Tk_RestrictEvents - filter and selectively delay X events

SYNOPSIS

#include <tk.h>
Tk_RestrictProc *
Tk_RestrictEvents(proc, clientData, prevClientDataPtr)

ARGUMENTS

Tk_RestrictProc *proc (in)
Predicate procedure to call to filter incoming X events. NULL means do not restrict events at all.

ClientData clientData (in)
Arbitrary argument to pass to proc.

ClientData *prevClientDataPtr (out)
Pointer to place to save argument to previous restrict procedure.

DESCRIPTION

This procedure is useful in certain situations where applications are only prepared to receive certain X events. After Tk_RestrictEvents is called, Tk_DoOneEvent (and hence Tk_MainLoop) will filter X input events through proc. Proc indicates whether a given event is to be processed immediately, deferred until some later time (e.g. when the event restriction is lifted), or discarded. Proc is a procedure with arguments and result that match the type Tk_RestrictProc:
typedef Tk_RestrictAction Tk_RestrictProc(
    ClientData clientData,
    XEvent *eventPtr);
The clientData argument is a copy of the clientData passed to Tk_RestrictEvents; it may be used to provide proc with information it needs to filter events. The eventPtr points to an event under consideration. Proc returns a restrict action (enumerated type Tk_RestrictAction) that indicates what Tk_DoOneEvent should do with the event. If the return value is TK_PROCESS_EVENT, then the event will be handled immediately. If the return value is TK_DEFER_EVENT, then the event will be left on the event queue for later processing. If the return value is TK_DISCARD_EVENT, then the event will be removed from the event queue and discarded without being processed.

Tk_RestrictEvents uses its return value and prevClientDataPtr to return information about the current event restriction procedure (a NULL return value means there are currently no restrictions). These values may be used to restore the previous restriction state when there is no longer any need for the current restriction.

There are very few places where Tk_RestrictEvents is needed. In most cases, the best way to restrict events is by changing the bindings with the bind Tcl command or by calling Tk_CreateEventHandler and Tk_DeleteEventHandler from C. The main place where Tk_RestrictEvents must be used is when performing synchronous actions (for example, if you need to wait for a particular event to occur on a particular window but you don't want to invoke any handlers for any other events). The ``obvious'' solution in these situations is to call XNextEvent or XWindowEvent, but these procedures cannot be used because Tk keeps its own event queue that is separate from the X event queue. Instead, call Tk_RestrictEvents to set up a filter, then call Tk_DoOneEvent to retrieve the desired event(s).

KEYWORDS

delay, event, filter, restriction
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_SetAppName manual page

NAME

Tk_SetAppName - Set the name of an application for ``send'' commands

SYNOPSIS

#include <tk.h>
char *
Tk_SetAppName(tkwin, name)

ARGUMENTS

Tk_Window tkwin (in)
Token for window in application. Used only to select a particular application.

char *name (in)
Name under which to register the application.

DESCRIPTION

Tk_SetAppName associates a name with a given application and records that association on the display containing with the application's main window. After this procedure has been invoked, other applications on the display will be able to use the send command to invoke operations in the application. If name is already in use by some other application on the display, then a new name will be generated by appending `` #2'' to name; if this name is also in use, the number will be incremented until an unused name is found. The return value from the procedure is a pointer to the name actually used.

If the application already has a name when Tk_SetAppName is called, then the new name replaces the old name.

Tk_SetAppName also adds a send command to the application's interpreter, which can be used to send commands from this application to others on any of the displays where the application has windows.

The application's name registration persists until the interpreter is deleted or the send command is deleted from interp, at which point the name is automatically unregistered and the application becomes inaccessible via send. The application can be made accessible again by calling Tk_SetAppName.

Tk_SetAppName is called automatically by Tk_Init, so applications don't normally need to call it explicitly.

The command tk appname provides Tcl-level access to the functionality of Tk_SetAppName.

KEYWORDS

application, name, register, send command
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Library Procedures - Tk_SetClass manual page

NAME

Tk_SetClass, Tk_Class - set or retrieve a window's class

SYNOPSIS

#include <tk.h>
Tk_SetClass(tkwin, class)
Tk_Uid
Tk_Class(tkwin)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

char *class (in)
New class name for window.

DESCRIPTION

Tk_SetClass is called to associate a class with a particular window. The class string identifies the type of the window; all windows with the same general class of behavior (button, menu, etc.) should have the same class. By convention all class names start with a capital letter, and there exists a Tcl command with the same name as each class (except all in lower-case) which can be used to create and manipulate windows of that class. A window's class string is initialized to NULL when the window is created.

For main windows, Tk automatically propagates the name and class to the WM_CLASS property used by window managers. This happens either when a main window is actually created (e.g. in Tk_MakeWindowExist), or when Tk_SetClass is called, whichever occurs later. If a main window has not been assigned a class then Tk will not set the WM_CLASS property for the window.

Tk_Class is a macro that returns the current value of tkwin's class. The value is returned as a Tk_Uid, which may be used just like a string pointer but also has the properties of a unique identifier (see the manual entry for Tk_GetUid for details). If tkwin has not yet been given a class, then Tk_Class will return NULL.

KEYWORDS

class, unique identifier, window, window manager
Copyright © 1990 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_SetGrid manual page

NAME

Tk_SetGrid, Tk_UnsetGrid - control the grid for interactive resizing

SYNOPSIS

#include <tk.h>
Tk_SetGrid(tkwin, reqWidth, reqHeight, widthInc, heightInc)
Tk_UnsetGrid(tkwin)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

int reqWidth (in)
Width in grid units that corresponds to the pixel dimension tkwin has requested via Tk_GeometryRequest.

int reqHeight (in)
Height in grid units that corresponds to the pixel dimension tkwin has requested via Tk_GeometryRequest.

int widthInc (in)
Width of one grid unit, in pixels.

int heightInc (in)
Height of one grid unit, in pixels.

DESCRIPTION

Tk_SetGrid turns on gridded geometry management for tkwin's toplevel window and specifies the geometry of the grid. Tk_SetGrid is typically invoked by a widget when its setGrid option is true. It restricts interactive resizing of tkwin's toplevel window so that the space allocated to the toplevel is equal to its requested size plus or minus even multiples of widthInc and heightInc. Furthermore, the reqWidth and reqHeight values are passed to the window manager so that it can report the window's size in grid units during interactive resizes. If tkwin's configuration changes (e.g., the size of a grid unit changes) then the widget should invoke Tk_SetGrid again with the new information.

Tk_UnsetGrid cancels gridded geometry management for tkwin's toplevel window.

For each toplevel window there can be at most one internal window with gridding enabled. If Tk_SetGrid or Tk_UnsetGrid is invoked when some other window is already controlling gridding for tkwin's toplevel, the calls for the new window have no effect.

See the wm manual entry for additional information on gridded geometry management.

KEYWORDS

grid, window, window manager
Copyright © 1990-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_SetOptions manual page

NAME
Tk_CreateOptionTable, Tk_DeleteOptionTable, Tk_InitOptions, Tk_SetOptions, Tk_FreeSavedOptions, Tk_RestoreSavedOptions, Tk_GetOptionValue, Tk_GetOptionInfo, Tk_FreeConfigOptions, Tk_Offset - process configuration options
SYNOPSIS
ARGUMENTS
DESCRIPTION
TEMPLATES
TK_OPTION_ANCHOR
TK_OPTION_BITMAP
TK_OPTION_BOOLEAN
TK_OPTION_BORDER
TK_OPTION_COLOR
TK_OPTION_CURSOR
TK_OPTION_DOUBLE
TK_OPTION_END
TK_OPTION_FONT
TK_OPTION_INT
TK_OPTION_JUSTIFY
TK_OPTION_PIXELS
TK_OPTION_RELIEF
TK_OPTION_STRING
TK_OPTION_STRING_TABLE
TK_OPTION_SYNONYM
TK_OPTION_WINDOW
STORAGE MANAGEMENT ISSUES
OBJOFFSET VS. INTERNALOFFSET
KEYWORDS

NAME

Tk_CreateOptionTable, Tk_DeleteOptionTable, Tk_InitOptions, Tk_SetOptions, Tk_FreeSavedOptions, Tk_RestoreSavedOptions, Tk_GetOptionValue, Tk_GetOptionInfo, Tk_FreeConfigOptions, Tk_Offset - process configuration options

SYNOPSIS

#include <tk.h>
Tk_OptionTable
Tk_CreateOptionTable(interp, templatePtr)
Tk_DeleteOptionTable(optionTable)
int
Tk_InitOptions(interp, recordPtr, optionTable, tkwin)
int
Tk_SetOptions(interp, recordPtr, optionTable, objc, objv, tkwin, savePtr, maskPtr)
Tk_FreeSavedOptions(savedPtr)
Tk_RestoreSavedOptions(savedPtr)
Tcl_Obj *
Tk_GetOptionValue(interp, recordPtr, optionTable, namePtr, tkwin)
Tcl_Obj *
Tk_GetOptionInfo(interp, recordPtr, optionTable, namePtr, tkwin)
Tk_FreeConfigOptions(recordPtr, optionTable, tkwin)
int
Tk_Offset(type, field)

ARGUMENTS

Tcl_Interp *interp (in)
A Tcl interpreter. Most procedures use this only for returning error messages; if it is NULL then no error messages are returned. For Tk_CreateOptionTable the value cannot be NULL; it gives the interpreter in which the option table will be used.

Tk_OptionSpec *templatePtr (in)
Points to an array of static information that describes the configuration options that are supported. Used to build a Tk_OptionTable. The information pointed to by this argument must exist for the lifetime of the Tk_OptionTable.

Tk_OptionTable optionTable (in)
Token for an option table. Must have been returned by a previous call to Tk_CreateOptionTable.

char *recordPtr (in/out)
Points to structure in which values of configuration options are stored; fields of this record are modified by procedures such as Tk_SetOptions and read by procedures such as Tk_GetOptionValue.

Tk_Window tkwin (in)
For options such as TK_OPTION_COLOR, this argument indicates the window in which the option will be used. If optionTable uses no window-dependent options, then a NULL value may be supplied for this argument.

int objc (in)
Number of values in objv.

Tcl_Obj *CONST objv[] (in)
Command-line arguments for setting configuring options.

Tk_SavedOptions *savePtr (out)
If not NULL, the structure pointed to by this argument is filled in with the old values of any options that were modified and old values are restored automatically if an error occurs in Tk_SetOptions.

int *maskPtr (out)
If not NULL, the word pointed to by maskPtr is filled in with the bit-wise OR of the typeMask fields for the options that were modified.

Tk_SavedOptions *savedPtr (in/out)
Points to a structure previously filled in by Tk_SetOptions with old values of modified options.

Tcl_Obj *namePtr (in)
The value of this object is the name of a particular option. If NULL is passed to Tk_GetOptionInfo then information is returned for all options. Must not be NULL when Tk_GetOptionValue is called.

type name type (in)
The name of the type of a record.

field name field (in)
The name of a field in records of type type.

DESCRIPTION

These procedures handle most of the details of parsing configuration options such as those for Tk widgets. Given a description of what options are supported, these procedures handle all the details of parsing options and storing their values into a C structure associated with the widget or object. The procedures were designed primarily for widgets in Tk, but they can also be used for other kinds of objects that have configuration options. In the rest of this manual page ``widget'' will be used to refer to the object whose options are being managed; in practice the object may not actually be a widget. The term ``widget record'' is used to refer to the C-level structure in which information about a particular widget or object is stored.

Note: the easiest way to learn how to use these procedures is to look at a working example. In Tk, the simplest example is the code that implements the button family of widgets, which is an tkButton.c. Other examples are in tkSquare.c and tkMenu.c.

In order to use these procedures, the code that implements the widget must contain a static array of Tk_OptionSpec structures. This is a template that describes the various options supported by that class of widget; there is a separate template for each kind of widget. The template contains information such as the name of each option, its type, its default value, and where the value of the option is stored in the widget record. See TEMPLATES below for more detail.

In order to process configuration options efficiently, the static template must be augmented with additional information that is available only at runtime. The procedure Tk_CreateOptionTable creates this dynamic information from the template and returns a Tk_OptionTable token that describes both the static and dynamic information. All of the other procedures, such as Tk_SetOptions, take a Tk_OptionTable token as argument. Typically, Tk_CreateOptionTable is called the first time that a widget of a particular class is created and the resulting Tk_OptionTable is used in the future for all widgets of that class. A Tk_OptionTable may be used only in a single interpreter, given by the interp argument to Tk_CreateOptionTable. When an option table is no longer needed Tk_DeleteOptionTable should be called to free all of its resources. All of the option tables for a Tcl interpreter are freed automatically if the interpreter is deleted.

Tk_InitOptions is invoked when a new widget is created to set the default values for all of the widget's configuration options. Tk_InitOptions is passed a token for an option table (optionTable) and a pointer to a widget record (recordPtr), which is the C structure that holds information about this widget. Tk_InitOptions uses the information in the option table to choose an appropriate default for each option, then it stores the default value directly into the widget record, overwriting any information that was already present in the widget record. Tk_InitOptions normally returns TCL_OK. If an error occurred while setting the default values (e.g., because a default value was erroneous) then TCL_ERROR is returned and an error message is left in interp's result if interp isn't NULL.

Tk_SetOptions is invoked to modify configuration options based on information specified in a Tcl command. The command might be one that creates a new widget, or a command that modifies options on an existing widget. The objc and objv arguments describe the values of the arguments from the Tcl command. Objv must contain an even number of objects: the first object of each pair gives the name of an option and the second object gives the new value for that option. Tk_SetOptions looks up each name in optionTable, checks that the new value of the option conforms to the type in optionTable, and stores the value of the option into the widget record given by recordPtr. Tk_SetOptions normally returns TCL_OK. If an error occurred (such as an unknown option name or an illegal option value) then TCL_ERROR is returned and an error message is left in interp's result if interp isn't NULL.

Tk_SetOptions has two additional features. First, if the maskPtr argument isn't NULL then it points to an integer value that is filled in with information about the options that were modified. For each option in the template passed to Tk_CreateOptionTable there is a typeMask field. The bits of this field are defined by the code that implements the widget; for example, each bit might correspond to a particular configuration option. Alternatively, bits might be used functionally. For example, one bit might be used for redisplay: all options that affect the widget's display, such that changing the option requires the widget to be redisplayed, might have that bit set. Another bit might indicate that the geometry of the widget must be recomputed, and so on. Tk_SetOptions OR's together the typeMask fields from all the options that were modified and returns this value at *maskPtr; the caller can then use this information to optimize itself so that, for example, it doesn't redisplay the widget if the modified options don't affect the widget's appearance.

The second additional feature of Tk_SetOptions has to do with error recovery. If an error occurs while processing configuration options, this feature makes it possible to restore all the configuration options to their previous values. Errors can occur either while processing options in Tk_SetOptions or later in the caller. In many cases the caller does additional processing after Tk_SetOptions returns; for example, it might use an option value to set a trace on a variable and may detect an error if the variable is an array instead of a scalar. Error recovery is enabled by passing in a non-NULL value for the savePtr argument to Tk_SetOptions; this should be a pointer to an uninitialized Tk_SavedOptions structure on the caller's stack. Tk_SetOptions overwrites the structure pointed to by savePtr with information about the old values of any options modified by the procedure. If Tk_SetOptions returns successfully, the caller uses the structure in one of two ways. If the caller completes its processing of the new options without any errors, then it must pass the structure to Tk_FreeSavedOptions so that the old values can be freed. If the caller detects an error in its processing of the new options, then it should pass the structure to Tk_RestoreSavedOptions, which will copy the old values back into the widget record and free the new values. If Tk_SetOptions detects an error then it automatically restores any options that had already been modified and leaves *savePtr in an empty state: the caller need not call either Tk_FreeSavedOptions or Tk_RestoreSavedOptions. If the savePtr argument to Tk_SetOptions is NULL then Tk_SetOptions frees each old option value immediately when it sets a new value for the option. In this case, if an error occurs in the third option, the old values for the first two options cannot be restored.

Tk_GetOptionValue returns the current value of a configuration option for a particular widget. The namePtr argument contains the name of an option; Tk_GetOptionValue uses optionTable to lookup the option and extract its value from the widget record pointed to by recordPtr, then it returns an object containing that value. If an error occurs (e.g., because namePtr contains an unknown option name) then NULL is returned and an error message is left in interp's result unless interp is NULL.

Tk_GetOptionInfo returns information about configuration options in a form suitable for configure widget commands. If the namePtr argument is not NULL, it points to an object that gives the name of a configuration option; Tk_GetOptionInfo returns an object containing a list with five elements, which are the name of the option, the name and class used for the option in the option database, the default value for the option, and the current value for the option. If the namePtr argument is NULL, then Tk_GetOptionInfo returns information about all options in the form of a list of lists; each sublist describes one option. Synonym options are handled differently depending on whether namePtr is NULL: if namePtr is NULL then the sublist for each synonym option has only two elements, which are the name of the option and the name of the other option that it refers to; if namePtr is non-NULL and names a synonym option then the object returned is the five-element list for the other option that the synonym refers to. If an error occurs (e.g., because namePtr contains an unknown option name) then NULL is returned and an error message is left in interp's result unless interp is NULL.

Tk_FreeConfigOptions must be invoked when a widget is deleted. It frees all of the resources associated with any of the configuration options defined in recordPtr by optionTable.

The Tk_Offset macro is provided as a safe way of generating the objOffset and internalOffset values for entries in Tk_OptionSpec structures. It takes two arguments: the name of a type of record, and the name of a field in that record. It returns the byte offset of the named field in records of the given type.

TEMPLATES

The array of Tk_OptionSpec structures passed to Tk_CreateOptionTable via its templatePtr argument describes the configuration options supported by a particular class of widgets. Each structure specifies one configuration option and has the following fields:
typedef struct {
    Tk_OptionType type;
    char *optionName;
    char *dbName;
    char *dbClass;
    char *defValue;
    int objOffset;
    int internalOffset;
    int flags;
    ClientData clientData;
    int typeMask;
} Tk_OptionSpec;
The type field indicates what kind of configuration option this is (e.g. TK_OPTION_COLOR for a color value, or TK_OPTION_INT for an integer value). Type determines how the value of the option is parsed (more on this below). The optionName field is a string such as -font or -bg; it is the name used for the option in Tcl commands and passed to procedures via the objc or namePtr arguments. The dbName and dbClass fields are used by Tk_InitOptions to look up a default value for this option in the option database; if dbName is NULL then the option database is not used by Tk_InitOptions for this option. The defValue field specifies a default value for this configuration option if no value is specified in the option database. The objOffset and internalOffset fields indicate where to store the value of this option in widget records (more on this below); values for the objOffset and internalOffset fields should always be generated with the Tk_Offset macro. The flags field contains additional information to control the processing of this configuration option (see below for details). ClientData provides additional type-specific data needed by certain types. For instance, for TK_OPTION_COLOR types, clientData is a string giving the default value to use on monochrome displays. See the descriptions of the different types below for details. The last field, typeMask, is used by Tk_SetOptions to return information about which options were modified; see the description of Tk_SetOptions above for details.

When Tk_InitOptions and Tk_SetOptions store the value of an option into the widget record, they can do it in either of two ways. If the objOffset field of the Tk_OptionSpec is greater than or equal to zero, then the value of the option is stored as a (Tcl_Obj *) at the location in the widget record given by objOffset. If the internalOffset field of the Tk_OptionSpec is greater than or equal to zero, then the value of the option is stored in a type-specific internal form at the location in the widget record given by internalOffset. For example, if the option's type is TK_OPTION_INT then the internal form is an integer. If the objOffset or internalOffset field is negative then the value is not stored in that form. At least one of the offsets must be greater than or equal to zero.

The flags field consists of one or more bits ORed together. At present only a single flag is supported: TK_OPTION_NULL_OK. If this bit is set for an option then an empty string will be accepted as the value for the option and the resulting internal form will be a NULL pointer or None, depending on the type of the option. If the flag is not set then empty strings will result in errors. TK_OPTION_NULL_OK is typically used to allow a feature to be turned off entirely, e.g. set a cursor value to None so that a window simply inherits its parent's cursor. Not all option types support the TK_OPTION_NULL_OK flag; for those that do, there is an explicit indication of that fact in the descriptions below.

The type field of each Tk_OptionSpec structure determines how to parse the value of that configuration option. The legal value for type, and the corresponding actions, are described below. If the type requires a tkwin value to be passed into procedures like Tk_SetOptions, or if it uses the clientData field of the Tk_OptionSpec, then it is indicated explicitly; if not mentioned, the type requires neither tkwin nor clientData.

TK_OPTION_ANCHOR
The value must be a standard anchor position such as ne or center. The internal form is a Tk_Anchor value like the ones returned by Tk_GetAnchorFromObj.

TK_OPTION_BITMAP
The value must be a standard Tk bitmap name. The internal form is a Pixmap token like the ones returned by Tk_AllocBitmapFromObj. This option type requires tkwin to be supplied to procedures such as Tk_SetOptions, and it supports the TK_OPTION_NULL_OK flag.

TK_OPTION_BOOLEAN
The value must be a standard boolean value such as true or no. The internal form is an integer with value 0 or 1.

TK_OPTION_BORDER
The value must be a standard color name such as red or #ff8080. The internal form is a Tk_3DBorder token like the ones returned by Tk_Alloc3DBorderFromObj. This option type requires tkwin to be supplied to procedures such as Tk_SetOptions, and it supports the TK_OPTION_NULL_OK flag.

TK_OPTION_COLOR
The value must be a standard color name such as red or #ff8080. The internal form is an (XColor *) token like the ones returned by Tk_AllocColorFromObj. This option type requires tkwin to be supplied to procedures such as Tk_SetOptions, and it supports the TK_OPTION_NULL_OK flag.

TK_OPTION_CURSOR
The value must be a standard cursor name such as cross or @foo. The internal form is a Tk_Cursor token like the ones returned by Tk_AllocCursorFromObj. This option type requires tkwin to be supplied to procedures such as Tk_SetOptions, and when the option is set the cursor for the window is changed by calling XDefineCursor. This option type also supports the TK_OPTION_NULL_OK flag.

TK_OPTION_DOUBLE
The string value must be a floating-point number in the format accepted by strtol. The internal form is a C double value.

TK_OPTION_END
Marks the end of the template. There must be a Tk_OptionSpec structure with type TK_OPTION_END at the end of each template. If the clientData field of this structure isn't NULL, then it points to an additional array of Tk_OptionSpec's, which is itself terminated by another TK_OPTION_END entry. Templates may be chained arbitrarily deeply. This feature allows common options to be shared by several widget classes.

TK_OPTION_FONT
The value must be a standard font name such as Times 16. The internal form is a Tk_Font handle like the ones returned by Tk_AllocFontFromObj. This option type requires tkwin to be supplied to procedures such as Tk_SetOptions, and it supports the TK_OPTION_NULL_OK flag.

TK_OPTION_INT
The string value must be an integer in the format accepted by strtol (e.g. 0 and 0x prefixes may be used to specify octal or hexadecimal numbers, respectively). The internal form is a C int value.

TK_OPTION_JUSTIFY
The value must be a standard justification value such as left. The internal form is a Tk_Justify like the values returned by Tk_GetJustifyFromObj.

TK_OPTION_PIXELS
The value must specify a screen distance such as 2i or 6.4. The internal form is an integer value giving a distance in pixels, like the values returned by Tk_GetPixelsFromObj. Note: if the objOffset field isn't used then information about the original value of this option will be lost. See OBJOFFSET VS. INTERNALOFFSET below for details.

TK_OPTION_RELIEF
The value must be standard relief such as raised. The internal form is an integer relief value such as TK_RELIEF_RAISED.

TK_OPTION_STRING
The value may be any string. The internal form is a (char *) pointer that points to a dynamically allocated copy of the value. This option type supports the TK_OPTION_NULL_OK flag.

TK_OPTION_STRING_TABLE
For this type, clientData is a pointer to an array of strings suitable for passing to Tcl_GetIndexFromObj. The value must be one of the strings in the table, or a unique abbreviation of one of the strings. The internal form is an integer giving the index into the table of the matching string, like the return value from Tcl_GetStringFromObj.

TK_OPTION_SYNONYM
This type is used to provide alternative names for an option (for example, -bg is often used as a synonym for -background). The clientData field is a (char *) pointer that gives the name of another option in the same table. Whenever the synonym option is used, the information from the other option will be used instead.

TK_OPTION_WINDOW
The value must be a window path name. The internal form is a Tk_Window token for the window. This option type requires tkwin to be supplied to procedures such as Tk_SetOptions (in order to identify the application), and it supports the TK_OPTION_NULL_OK flag.

STORAGE MANAGEMENT ISSUES

If a field of a widget record has its offset stored in the objOffset or internalOffset field of a Tk_OptionSpec structure then the procedures described here will handle all of the storage allocation and resource management issues associated with the field. When the value of an option is changed, Tk_SetOptions (or Tk_FreeSavedOptions will automatically free any resources associated with the old value, such as Tk_Fonts for TK_OPTION_FONT options or dynamically allocated memory for TK_OPTION_STRING options. For an option stored as an object using the objOffset field of a Tk_OptionSpec, the widget record shares the object pointed to by the objv value from the call to Tk_SetOptions. The reference count for this object is incremented when a pointer to it is stored in the widget record and decremented when the option is modified. When the widget is deleted Tk_FreeConfigOptions should be invoked; it will free the resources associated with all options and decrement reference counts for any objects.

However, the widget code is responsible for storing NULL or None in all pointer and token fields before invoking Tk_InitOptions. This is needed to allow proper cleanup in the rare case where an error occurs in Tk_InitOptions.

OBJOFFSET VS. INTERNALOFFSET

In most cases it is simplest to use the internalOffset field of a Tk_OptionSpec structure and not the objOffset field. This makes the internal form of the value immediately available to the widget code so the value doesn't have to be extracted from an object each time it is used. However, there are two cases where the objOffset field is useful. The first case is for TK_OPTION_PIXELS options. In this case, the internal form is an integer pixel value that is valid only for a particular screen. If the value of the option is retrieved, it will be returned as a simple number. For example, after the command .b configure -borderwidth 2m, the command .b configure -borderwidth might return 7, which is the integer pixel value corresponding to 2m. Unfortunately, this loses the original screen-independent value. Thus for TK_OPTION_PIXELS options it is better to use the objOffset field. In this case the original value of the option is retained in the object and can be returned when the option is retrieved. In most cases it is convenient to use the internalOffset field field as well, so that the integer value is immediately available for use in the widget code (alternatively, Tk_GetPixelsFromObj can be used to extract the integer value from the object whenever it is needed). Note: the problem of losing information on retrievals exists only for TK_OPTION_PIXELS options.

The second reason to use the objOffset field is in order to implement new types of options not supported by these procedures. To implement a new type of option, use TK_OPTION_STRING as the type in the Tk_OptionSpec structure and set the objOffset field but not the internalOffset field. Then, after calling Tk_SetOptions, convert the object to internal form yourself.

KEYWORDS

anchor, bitmap, boolean, border, color, configuration option, cursor, double, font, integer, justify, pixels, relief, screen distance, synonym
Copyright © 1998 Sun Microsystems, Inc.


Tk Library Procedures - Tk_SetWindowVisual manual page

NAME

Tk_SetWindowVisual - change visual characteristics of window

SYNOPSIS

#include <tk.h>
int
Tk_SetWindowVisual(tkwin, visual, depth, colormap)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

Visual *visual (in)
New visual type to use for tkwin.

int depth (in)
Number of bits per pixel desired for tkwin.

Colormap colormap (in)
New colormap for tkwin, which must be compatible with visual and depth.

DESCRIPTION

When Tk creates a new window it assigns it the default visual characteristics (visual, depth, and colormap) for its screen. Tk_SetWindowVisual may be called to change them. Tk_SetWindowVisual must be called before the window has actually been created in X (e.g. before Tk_MapWindow or Tk_MakeWindowExist has been invoked for the window). The safest thing is to call Tk_SetWindowVisual immediately after calling Tk_CreateWindow. If tkwin has already been created before Tk_SetWindowVisual is called then it returns 0 and doesn't make any changes; otherwise it returns 1 to signify that the operation completed successfully.

Note: Tk_SetWindowVisual should not be called if you just want to change a window's colormap without changing its visual or depth; call Tk_SetWindowColormap instead.

KEYWORDS

colormap, depth, visual
Copyright © 1992 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_StrictMotif manual page

NAME

Tk_StrictMotif - Return value of tk_strictMotif variable

SYNOPSIS

#include <tk.h>
int
Tk_StrictMotif(tkwin)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

DESCRIPTION

This procedure returns the current value of the tk_strictMotif variable in the interpreter associated with tkwin's application. The value is returned as an integer that is either 0 or 1. 1 means that strict Motif compliance has been requested, so anything that is not part of the Motif specification should be avoided. 0 means that ``Motif-like'' is good enough, and extra features are welcome.

This procedure uses a link to the Tcl variable to provide much faster access to the variable's value than could be had by calling Tcl_GetVar.

KEYWORDS

Motif compliance, tk_strictMotif variable
Copyright © 1995-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_ComputeTextLayout manual page

NAME

Tk_ComputeTextLayout, Tk_FreeTextLayout, Tk_DrawTextLayout, Tk_UnderlineTextLayout, Tk_PointToChar, Tk_CharBbox, Tk_DistanceToTextLayout, Tk_IntersectTextLayout, Tk_TextLayoutToPostscript - routines to measure and display single-font, multi-line, justified text.

SYNOPSIS

#include <tk.h>
Tk_TextLayout
Tk_ComputeTextLayout(tkfont, string, numChars, wrapLength, justify, flags, widthPtr, heightPtr)
void
Tk_FreeTextLayout(layout)
void
Tk_DrawTextLayout(display, drawable, gc, layout, x, y, firstChar, lastChar)
void
Tk_UnderlineTextLayout(display, drawable, gc, layout, x, y, underline)
int
Tk_PointToChar(layout, x, y)
int
Tk_CharBbox(layout, index, xPtr, yPtr, widthPtr, heightPtr)
int
Tk_DistanceToTextLayout(layout, x, y)
int
Tk_IntersectTextLayout(layout, x, y, width, height)
void
Tk_TextLayoutToPostscript(interp, layout)

ARGUMENTS

Tk_Font tkfont (in)
Font to use when constructing and displaying a text layout. The tkfont must remain valid for the lifetime of the text layout. Must have been returned by a previous call to Tk_GetFont.

const char *string (in)
Potentially multi-line string whose dimensions are to be computed and stored in the text layout. The string must remain valid for the lifetime of the text layout.

int numChars (in)
The number of characters to consider from string. If numChars is less than 0, then assumes string is null terminated and uses Tcl_NumUtfChars to determine the length of string.

int wrapLength (in)
Longest permissible line length, in pixels. Lines in string will automatically be broken at word boundaries and wrapped when they reach this length. If wrapLength is too small for even a single character to fit on a line, it will be expanded to allow one character to fit on each line. If wrapLength is <= 0, there is no automatic wrapping; lines will get as long as they need to be and only wrap if a newline/return character is encountered.

Tk_Justify justify (in)
How to justify the lines in a multi-line text layout. Possible values are TK_JUSTIFY_LEFT, TK_JUSTIFY_CENTER, or TK_JUSTIFY_RIGHT. If the text layout only occupies a single line, then justify is irrelevant.

int flags (in)
Various flag bits OR-ed together. TK_IGNORE_TABS means that tab characters should not be expanded to the next tab stop. TK_IGNORE_NEWLINES means that newline/return characters should not cause a line break. If either tabs or newlines/returns are ignored, then they will be treated as regular characters, being measured and displayed in a platform-dependent manner as described in Tk_MeasureChars, and will not have any special behaviors.

int *widthPtr (out)
If non-NULL, filled with either the width, in pixels, of the widest line in the text layout, or the width, in pixels, of the bounding box for the character specified by index.

int *heightPtr (out)
If non-NULL, filled with either the total height, in pixels, of all the lines in the text layout, or the height, in pixels, of the bounding box for the character specified by index.

Tk_TextLayout layout (in)
A token that represents the cached layout information about the single-font, multi-line, justified piece of text. This token is returned by Tk_ComputeTextLayout.

Display *display (in)
Display on which to draw.

Drawable drawable (in)
Window or pixmap in which to draw.

GC gc (in)
Graphics context to use for drawing text layout. The font selected in this GC must correspond to the tkfont used when constructing the text layout.

int x, y (in)
Point, in pixels, at which to place the upper-left hand corner of the text layout when it is being drawn, or the coordinates of a point (with respect to the upper-left hand corner of the text layout) to check against the text layout.

int firstChar (in)
The index of the first character to draw from the given text layout. The number 0 means to draw from the beginning.

int lastChar (in)
The index of the last character up to which to draw. The character specified by lastChar itself will not be drawn. A number less than 0 means to draw all characters in the text layout.

int underline (in)
Index of the single character to underline in the text layout, or a number less than 0 for no underline.

int index (in)
The index of the character whose bounding box is desired. The bounding box is computed with respect to the upper-left hand corner of the text layout.

int *xPtr, *yPtr (out)
Filled with the upper-left hand corner, in pixels, of the bounding box for the character specified by index. Either or both xPtr and yPtr may be NULL, in which case the corresponding value is not calculated.

int width, height (in)
Specifies the width and height, in pixels, of the rectangular area to compare for intersection against the text layout.

Tcl_Interp *interp (out)
Postscript code that will print the text layout is appended to interp->result.

DESCRIPTION

These routines are for measuring and displaying single-font, multi-line, justified text. To measure and display simple single-font, single-line strings, refer to the documentation for Tk_MeasureChars. There is no programming interface in the core of Tk that supports multi-font, multi-line text; support for that behavior must be built on top of simpler layers. Note that unlike the lower level text display routines, the functions described here all operate on character-oriented lengths and indices rather than byte-oriented values. See the description of Tcl_UtfAtIndex for more details on converting between character and byte offsets.

The routines described here are built on top of the programming interface described in the Tk_MeasureChars documentation. Tab characters and newline/return characters may be treated specially by these procedures, but all other characters are passed through to the lower level.

Tk_ComputeTextLayout computes the layout information needed to display a single-font, multi-line, justified string of text and returns a Tk_TextLayout token that holds this information. This token is used in subsequent calls to procedures such as Tk_DrawTextLayout, Tk_DistanceToTextLayout, and Tk_FreeTextLayout. The string and tkfont used when computing the layout must remain valid for the lifetime of this token.

Tk_FreeTextLayout is called to release the storage associated with layout when it is no longer needed. A layout should not be used in any other text layout procedures once it has been released.

Tk_DrawTextLayout uses the information in layout to display a single-font, multi-line, justified string of text at the specified location.

Tk_UnderlineTextLayout uses the information in layout to display an underline below an individual character. This procedure does not draw the text, just the underline. To produce natively underlined text, an underlined font should be constructed and used. All characters, including tabs, newline/return characters, and spaces at the ends of lines, can be underlined using this method. However, the underline will never be drawn outside of the computed width of layout; the underline will stop at the edge for any character that would extend partially outside of layout, and the underline will not be visible at all for any character that would be located completely outside of the layout.

Tk_PointToChar uses the information in layout to determine the character closest to the given point. The point is specified with respect to the upper-left hand corner of the layout, which is considered to be located at (0, 0). Any point whose y-value is less that 0 will be considered closest to the first character in the text layout; any point whose y-value is greater than the height of the text layout will be considered closest to the last character in the text layout. Any point whose x-value is less than 0 will be considered closest to the first character on that line; any point whose x-value is greater than the width of the text layout will be considered closest to the last character on that line. The return value is the index of the character that was closest to the point. Given a layout with no characters, the value 0 will always be returned, referring to a hypothetical zero-width placeholder character.

Tk_CharBbox uses the information in layout to return the bounding box for the character specified by index. The width of the bounding box is the advance width of the character, and does not include any left or right bearing. Any character that extends partially outside of layout is considered to be truncated at the edge. Any character that would be located completely outside of layout is considered to be zero-width and pegged against the edge. The height of the bounding box is the line height for this font, extending from the top of the ascent to the bottom of the descent; information about the actual height of individual letters is not available. For measurement purposes, a layout that contains no characters is considered to contain a single zero-width placeholder character at index 0. If index was not a valid character index, the return value is 0 and *xPtr, *yPtr, *widthPtr, and *heightPtr are unmodified. Otherwise, if index did specify a valid, the return value is non-zero, and *xPtr, *yPtr, *widthPtr, and *heightPtr are filled with the bounding box information for the character. If any of xPtr, yPtr, widthPtr, or heightPtr are NULL, the corresponding value is not calculated or stored.

Tk_DistanceToTextLayout computes the shortest distance in pixels from the given point (x, y) to the characters in layout. Newline/return characters and non-displaying space characters that occur at the end of individual lines in the text layout are ignored for hit detection purposes, but tab characters are not. The return value is 0 if the point actually hits the layout. If the point didn't hit the layout then the return value is the distance in pixels from the point to the layout.

Tk_IntersectTextLayout determines whether a layout lies entirely inside, entirely outside, or overlaps a given rectangle. Newline/return characters and non-displaying space characters that occur at the end of individual lines in the layout are ignored for intersection calculations. The return value is -1 if the layout is entirely outside of the rectangle, 0 if it overlaps, and 1 if it is entirely inside of the rectangle.

Tk_TextLayoutToPostscript outputs code consisting of a Postscript array of strings that represent the individual lines in layout. It is the responsibility of the caller to take the Postscript array of strings and add some Postscript function operate on the array to render each of the lines. The code that represents the Postscript array of strings is appended to interp->result.

DISPLAY MODEL

When measuring a text layout, space characters that occur at the end of a line are ignored. The space characters still exist and the insertion point can be positioned amongst them, but their additional width is ignored when justifying lines or returning the total width of a text layout. All end-of-line space characters are considered to be attached to the right edge of the line; this behavior is logical for left-justified text and reasonable for center-justified text, but not very useful when editing right-justified text. Spaces are considered variable width characters; the first space that extends past the edge of the text layout is clipped to the edge, and any subsequent spaces on the line are considered zero width and pegged against the edge. Space characters that occur in the middle of a line of text are not suppressed and occupy their normal space width.

Tab characters are not ignored for measurement calculations. If wrapping is turned on and there are enough tabs on a line, the next tab will wrap to the beginning of the next line. There are some possible strange interactions between tabs and justification; tab positions are calculated and the line length computed in a left-justified world, and then the whole resulting line is shifted so it is centered or right-justified, causing the tab columns not to align any more.

When wrapping is turned on, lines may wrap at word breaks (space or tab characters) or newline/returns. A dash or hyphen character in the middle of a word is not considered a word break. Tk_ComputeTextLayout always attempts to place at least one word on each line. If it cannot because the wrapLength is too small, the word will be broken and as much as fits placed on the line and the rest on subsequent line(s). If wrapLength is so small that not even one character can fit on a given line, the wrapLength is ignored for that line and one character will be placed on the line anyhow. When wrapping is turned off, only newline/return characters may cause a line break.

When a text layout has been created using an underlined tkfont, then any space characters that occur at the end of individual lines, newlines/returns, and tabs will not be displayed underlined when Tk_DrawTextLayout is called, because those characters are never actually drawn - they are merely placeholders maintained in the layout.

KEYWORDS

font
Copyright © 1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_Init manual page

NAME
Tk_Init, Tk_SafeInit - add Tk to an interpreter and make a new Tk application.
SYNOPSIS
ARGUMENTS
DESCRIPTION
bell
clipboard
grab
menu
selection
send
tk
tkwait
toplevel
wm
KEYWORDS

NAME

Tk_Init, Tk_SafeInit - add Tk to an interpreter and make a new Tk application.

SYNOPSIS

#include <tk.h>
int
Tk_Init(interp)
int
Tk_SafeInit(interp)

ARGUMENTS

Tcl_Interp *interp (in)
Interpreter in which to load Tk. Tk should not already be loaded in this interpreter.

DESCRIPTION

Tk_Init is the package initialization procedure for Tk. It is normally invoked by the Tcl_AppInit procedure for an application or by the load command. Tk_Init adds all of Tk's commands to interp and creates a new Tk application, including its main window. If the initialization is successful Tk_Init returns TCL_OK; if there is an error it returns TCL_ERROR. Tk_Init also leaves a result or error message in interp->result.

If there is a variable argv in interp, Tk_Init treats the contents of this variable as a list of options for the new Tk application. The options may have any of the forms documented for the wish application (in fact, wish uses Tk_Init to process its command-line arguments).

Tk_SafeInit is identical to Tk_Init except that it removes all Tk commands that are considered unsafe. Those commands and the reasons for their exclusion are:

bell
Continuous ringing of the bell is a nuisance.

clipboard
A malicious script could replace the contents of the clipboard with the string "rm -r *" and lead to surprises when the contents of the clipboard are pasted.

grab
Grab can be used to block the user from using any other applications.

menu
Menus can be used to cover the entire screen and to steal input from the user.

selection
See clipboard.

send
Send can be used to cause unsafe interpreters to execute commands.

tk
The tk command recreates the send command, which is unsafe.

tkwait
Tkwait can block the containing process forever

toplevel
Toplevels can be used to cover the entire screen and to steal input from the user.

wm
If toplevels are ever allowed, wm can be used to remove decorations, move windows around, etc.

KEYWORDS

safe, application, initialization, load, main window
Copyright © 1995-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_Main manual page

NAME

Tk_Main - main program for Tk-based applications

SYNOPSIS

#include <tk.h>
Tk_Main(argc, argv, appInitProc)

ARGUMENTS

int argc (in)
Number of elements in argv.

char *argv[] (in)
Array of strings containing command-line arguments.

Tcl_AppInitProc *appInitProc (in)
Address of an application-specific initialization procedure. The value for this argument is usually Tcl_AppInit.

DESCRIPTION

Tk_Main acts as the main program for most Tk-based applications. Starting with Tk 4.0 it is not called main anymore because it is part of the Tk library and having a function main in a library (particularly a shared library) causes problems on many systems. Having main in the Tk library would also make it hard to use Tk in C++ programs, since C++ programs must have special C++ main functions.

Normally each application contains a small main function that does nothing but invoke Tk_Main. Tk_Main then does all the work of creating and running a wish-like application.

When it is has finished its own initialization, but before it processes commands, Tk_Main calls the procedure given by the appInitProc argument. This procedure provides a ``hook'' for the application to perform its own initialization, such as defining application-specific commands. The procedure must have an interface that matches the type Tcl_AppInitProc:

typedef int Tcl_AppInitProc(Tcl_Interp *interp);
AppInitProc is almost always a pointer to Tcl_AppInit; for more details on this procedure, see the documentation for Tcl_AppInit.

KEYWORDS

application-specific initialization, command-line arguments, main program
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Library Procedures - Tk_InitStubs manual page

NAME
Tk_InitStubs - initialize the Tk stubs mechanism
SYNOPSIS
ARGUMENTS
INTRODUCTION
1)
2)
2)
3)
DESCRIPTION
SEE ALSO
KEYWORDS

NAME

Tk_InitStubs - initialize the Tk stubs mechanism

SYNOPSIS

#include <tk.h>
char *
Tk_InitStubs(interp, version, exact)

ARGUMENTS

Tcl_Interp *interp (in)
Tcl interpreter handle.

char *version (in)
A version string consisting of one or more decimal numbers separated by dots.

int exact (in)
Non-zero means that only the particular Tk version specified by version is acceptable. Zero means that versions newer than version are also acceptable as long as they have the same major version number as version.

INTRODUCTION

The Tcl stubs mechanism defines a way to dynamically bind extensions to a particular Tcl implementation at run time. the stubs mechanism requires no changes to applications incoporating Tcl/Tk interpreters. Only developers creating C-based Tcl/Tk extensions need to take steps to use the stubs mechanism with their extensions. See the Tcl_InitStubs page for more information.

Enabling the stubs mechanism for a Tcl/Tk extension requires the following steps:

1)
Call Tcl_InitStubs in the extension before calling any other Tcl functions.

2)
Call Tk_InitStubs if the extension before calling any other Tk functions.

2)
Define the USE_TCL_STUBS symbol. Typically, you would include the -DUSE_TCL_STUBS flag when compiling the extension.

3)
Link the extension with the Tcl and Tk stubs libraries instead of the standard Tcl and Tk libraries. On Unix platforms, the library names are libtclstub8.1.a and libtkstub8.1.a; on Windows platforms, the library names are tclstub81.lib and tkstub81.lib.

DESCRIPTION

Tk_InitStubs attempts to initialize the Tk stub table pointers and ensure that the correct version of Tk is loaded. In addition to an interpreter handle, it accepts as arguments a version number and a Boolean flag indicating whether the extension requires an exact version match or not. If exact is 0, then the extension is indicating that newer versions of Tk are acceptable as long as they have the same major version number as version; non-zero means that only the specified version is acceptable. Tcl_InitStubs returns a string containing the actual version of Tk satisfying the request, or NULL if the Tk version is not acceptable, does not support the stubs mechansim, or any other error condition occurred.

SEE ALSO

Tcl_InitStubs

KEYWORDS

stubs
Copyright © 1999 Scriptics Corportation
Copyright © 1995-1997 Roger E. Critchlow Jr.


Library Procedures - Tk_WindowId manual page

NAME

Tk_WindowId, Tk_Parent, Tk_Display, Tk_DisplayName, Tk_ScreenNumber, Tk_Screen, Tk_X, Tk_Y, Tk_Width, Tk_Height, Tk_Changes, Tk_Attributes, Tk_IsContainer, Tk_IsEmbedded, Tk_IsMapped, Tk_IsTopLevel, Tk_ReqWidth, Tk_ReqHeight, Tk_InternalBorderWidth, Tk_Visual, Tk_Depth, Tk_Colormap - retrieve information from Tk's local data structure

SYNOPSIS

#include <tk.h>
Window
Tk_WindowId(tkwin)
Tk_Window
Tk_Parent(tkwin)
Display *
Tk_Display(tkwin)
char *
Tk_DisplayName(tkwin)
int
Tk_ScreenNumber(tkwin)
Screen *
Tk_Screen(tkwin)
int
Tk_X(tkwin)
int
Tk_Y(tkwin)
int
Tk_Width(tkwin)
int
Tk_Height(tkwin)
XWindowChanges *
Tk_Changes(tkwin)
XSetWindowAttributes *
Tk_Attributes(tkwin)
int
Tk_IsContainer(tkwin)
int
Tk_IsEmbedded(tkwin)
int
Tk_IsMapped(tkwin)
int
Tk_IsTopLevel(tkwin)
int
Tk_ReqWidth(tkwin)
int
Tk_ReqHeight(tkwin)
int
Tk_InternalBorderWidth(tkwin)
Visual *
Tk_Visual(tkwin)
int
Tk_Depth(tkwin)
Colormap
Tk_Colormap(tkwin)

ARGUMENTS

Tk_Window tkwin (in)
Token for window.

DESCRIPTION

Tk_WindowId and the other names listed above are all macros that return fields from Tk's local data structure for tkwin. None of these macros requires any interaction with the server; it is safe to assume that all are fast.

Tk_WindowId returns the X identifier for tkwin, or NULL if no X window has been created for tkwin yet.

Tk_Parent returns Tk's token for the logical parent of tkwin. The parent is the token that was specified when tkwin was created, or NULL for main windows.

Tk_Display returns a pointer to the Xlib display structure corresponding to tkwin. Tk_DisplayName returns an ASCII string identifying tkwin's display. Tk_ScreenNumber returns the index of tkwin's screen among all the screens of tkwin's display. Tk_Screen returns a pointer to the Xlib structure corresponding to tkwin's screen.

Tk_X, Tk_Y, Tk_Width, and Tk_Height return information about tkwin's location within its parent and its size. The location information refers to the upper-left pixel in the window, or its border if there is one. The width and height information refers to the interior size of the window, not including any border. Tk_Changes returns a pointer to a structure containing all of the above information plus a few other fields. Tk_Attributes returns a pointer to an XSetWindowAttributes structure describing all of the attributes of the tkwin's window, such as background pixmap, event mask, and so on (Tk keeps track of all this information as it is changed by the application). Note: it is essential that applications use Tk procedures like Tk_ResizeWindow instead of X procedures like XResizeWindow, so that Tk can keep its data structures up-to-date.

Tk_IsContainer returns a non-zero value if tkwin is a container, and that some other application may be embedding itself inside tkwin.

Tk_IsEmbedded returns a non-zero value if tkwin is is not a free-standing window, but rather is embedded in some other application.

Tk_IsMapped returns a non-zero value if tkwin is mapped and zero if tkwin isn't mapped.

Tk_IsTopLevel returns a non-zero value if tkwin is a top-level window (its X parent is the root window of the screen) and zero if tkwin isn't a top-level window.

Tk_ReqWidth and Tk_ReqHeight return information about the window's requested size. These values correspond to the last call to Tk_GeometryRequest for tkwin.

Tk_InternalBorderWidth returns the width of internal border that has been requested for tkwin, or 0 if no internal border was requested. The return value is simply the last value passed to Tk_SetInternalBorder for tkwin.

Tk_Visual, Tk_Depth, and Tk_Colormap return information about the visual characteristics of a window. Tk_Visual returns the visual type for the window, Tk_Depth returns the number of bits per pixel, and Tk_Colormap returns the current colormap for the window. The visual characteristics are normally set from the defaults for the window's screen, but they may be overridden by calling Tk_SetWindowVisual.

KEYWORDS

attributes, colormap, depth, display, height, geometry manager, identifier, mapped, requested size, screen, top-level, visual, width, window, x, y
Copyright © 1990-1993 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.


Applications - tclsh manual page

NAME
tclsh - Simple shell containing Tcl interpreter
SYNOPSIS
tclsh ?fileName arg arg ...?
DESCRIPTION
SCRIPT FILES
VARIABLES
argc
argv
argv0
tcl_interactive
PROMPTS
KEYWORDS

NAME

tclsh - Simple shell containing Tcl interpreter

SYNOPSIS

tclsh ?fileName arg arg ...?

DESCRIPTION

Tclsh is a shell-like application that reads Tcl commands from its standard input or from a file and evaluates them. If invoked with no arguments then it runs interactively, reading Tcl commands from standard input and printing command results and error messages to standard output. It runs until the exit command is invoked or until it reaches end-of-file on its standard input. If there exists a file .tclshrc (or tclshrc.tcl on the Windows platforms) in the home directory of the user, tclsh evaluates the file as a Tcl script just before reading the first command from standard input.

SCRIPT FILES

If tclsh is invoked with arguments then the first argument is the name of a script file and any additional arguments are made available to the script as variables (see below). Instead of reading commands from standard input tclsh will read Tcl commands from the named file; tclsh will exit when it reaches the end of the file. There is no automatic evaluation of .tclshrc in this case, but the script file can always source it if desired.

If you create a Tcl script in a file whose first line is

#!/usr/local/bin/tclsh
then you can invoke the script file directly from your shell if you mark the file as executable. This assumes that tclsh has been installed in the default location in /usr/local/bin; if it's installed somewhere else then you'll have to modify the above line to match. Many UNIX systems do not allow the #! line to exceed about 30 characters in length, so be sure that the tclsh executable can be accessed with a short file name.

An even better approach is to start your script files with the following three lines:

#!/bin/sh
# the next line restarts using tclsh \
exec tclsh "$0" "$@"
This approach has three advantages over the approach in the previous paragraph. First, the location of the tclsh binary doesn't have to be hard-wired into the script: it can be anywhere in your shell search path. Second, it gets around the 30-character file name limit in the previous approach. Third, this approach will work even if tclsh is itself a shell script (this is done on some systems in order to handle multiple architectures or operating systems: the tclsh script selects one of several binaries to run). The three lines cause both sh and tclsh to process the script, but the exec is only executed by sh. sh processes the script first; it treats the second line as a comment and executes the third line. The exec statement cause the shell to stop processing and instead to start up tclsh to reprocess the entire script. When tclsh starts up, it treats all three lines as comments, since the backslash at the end of the second line causes the third line to be treated as part of the comment on the second line.

You should note that it is also common practise to install tclsh with 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.

VARIABLES

Tclsh sets the following Tcl variables:

argc
Contains a count of the number of arg arguments (0 if none), not including the name of the script file.

argv
Contains a Tcl list whose elements are the arg arguments, in order, or an empty string if there are no arg arguments.

argv0
Contains fileName if it was specified. Otherwise, contains the name by which tclsh was invoked.

tcl_interactive
Contains 1 if tclsh is running interactively (no fileName was specified and standard input is a terminal-like device), 0 otherwise.

PROMPTS

When tclsh is invoked interactively it normally prompts for each command with ``% ''. You can change the prompt by setting the variables tcl_prompt1 and tcl_prompt2. If variable tcl_prompt1 exists then it must consist of a Tcl script to output a prompt; instead of outputting a prompt tclsh will evaluate the script in tcl_prompt1. The variable tcl_prompt2 is used in a similar way when a newline is typed but the current command isn't yet complete; if tcl_prompt2 isn't set then no prompt is output for incomplete commands.

KEYWORDS

argument, interpreter, prompt, script file, shell
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


Tk Applications - wish manual page

NAME
wish - Simple windowing shell
SYNOPSIS
wish ?fileName arg arg ...?
OPTIONS
-colormap new
-display display
-geometry geometry
-name name
-sync
-use id
-visual visual
- -
DESCRIPTION
OPTIONS
APPLICATION NAME AND CLASS
VARIABLES
argc
argv
argv0
geometry
tcl_interactive
SCRIPT FILES
PROMPTS
KEYWORDS

NAME

wish - Simple windowing shell

SYNOPSIS

wish ?fileName arg arg ...?

OPTIONS

-colormap new
Specifies that the window should have a new private colormap instead of using the default colormap for the screen.

-display display
Display (and screen) on which to display window.

-geometry geometry
Initial geometry to use for window. If this option is specified, its value is stored in the geometry global variable of the application's Tcl interpreter.

-name name
Use name as the title to be displayed in the window, and as the name of the interpreter for send commands.

-sync
Execute all X server commands synchronously, so that errors are reported immediately. This will result in much slower execution, but it is useful for debugging.

-use id
Specifies that the main window for the application is to be embedded in the window whose identifier is id, instead of being created as an independent toplevel window. Id must be specified in the same way as the value for the -use option for toplevel widgets (i.e. it has a form like that returned by the winfo id command).

-visual visual
Specifies the visual to use for the window. Visual may have any of the forms supported by the Tk_GetVisual procedure.

- -
Pass all remaining arguments through to the script's argv variable without interpreting them. This provides a mechanism for passing arguments such as -name to a script instead of having wish interpret them.

DESCRIPTION

Wish is a simple program consisting of the Tcl command language, the Tk toolkit, and a main program that reads commands from standard input or from a file. It creates a main window and then processes Tcl commands. If wish is invoked with no arguments, or with a first argument that starts with ``-'', then it reads Tcl commands interactively from standard input. It will continue processing commands until all windows have been deleted or until end-of-file is reached on standard input. If there exists a file .wishrc in the home directory of the user, wish evaluates the file as a Tcl script just before reading the first command from standard input.

If wish is invoked with an initial fileName argument, then fileName is treated as the name of a script file. Wish will evaluate the script in fileName (which presumably creates a user interface), then it will respond to events until all windows have been deleted. Commands will not be read from standard input. There is no automatic evaluation of .wishrc in this case, but the script file can always source it if desired.

OPTIONS

Wish automatically processes all of the command-line options described in the OPTIONS summary above. Any other command-line arguments besides these are passed through to the application using the argc and argv variables described later.

APPLICATION NAME AND CLASS

The name of the application, which is used for purposes such as send commands, is taken from the -name option, if it is specified; otherwise it is taken from fileName, if it is specified, or from the command name by which wish was invoked. In the last two cases, if the name contains a ``/'' character, then only the characters after the last slash are used as the application name.

The class of the application, which is used for purposes such as specifying options with a RESOURCE_MANAGER property or .Xdefaults file, is the same as its name except that the first letter is capitalized.

VARIABLES

Wish sets the following Tcl variables:

argc
Contains a count of the number of arg arguments (0 if none), not including the options described above.

argv
Contains a Tcl list whose elements are the arg arguments that follow a - - option or don't match any of the options described in OPTIONS above, in order, or an empty string if there are no such arguments.

argv0
Contains fileName if it was specified. Otherwise, contains the name by which wish was invoked.

geometry
If the -geometry option is specified, wish copies its value into this variable. If the variable still exists after fileName has been evaluated, wish uses the value of the variable in a wm geometry command to set the main window's geometry.

tcl_interactive
Contains 1 if wish is reading commands interactively (fileName was not specified and standard input is a terminal-like device), 0 otherwise.

SCRIPT FILES

If you create a Tcl script in a file whose first line is
#!/usr/local/bin/wish
then you can invoke the script file directly from your shell if you mark it as executable. This assumes that wish has been installed in the default location in /usr/local/bin; if it's installed somewhere else then you'll have to modify the above line to match. Many UNIX systems do not allow the #! line to exceed about 30 characters in length, so be sure that the wish executable can be accessed with a short file name.

An even better approach is to start your script files with the following three lines:

#!/bin/sh
# the next line restarts using wish \
exec wish "$0" "$@"
This approach has three advantages over the approach in the previous paragraph. First, the location of the wish binary doesn't have to be hard-wired into the script: it can be anywhere in your shell search path. Second, it gets around the 30-character file name limit in the previous approach. Third, this approach will work even if wish is itself a shell script (this is done on some systems in order to handle multiple architectures or operating systems: the wish script selects one of several binaries to run). The three lines cause both sh and wish to process the script, but the exec is only executed by sh. sh processes the script first; it treats the second line as a comment and executes the third line. The exec statement cause the shell to stop processing and instead to start up wish to reprocess the entire script. When wish starts up, it treats all three lines as comments, since the backslash at the end of the second line causes the third line to be treated as part of the comment on the second line.

PROMPTS

When wish is invoked interactively it normally prompts for each command with ``% ''. You can change the prompt by setting the variables tcl_prompt1 and tcl_prompt2. If variable tcl_prompt1 exists then it must consist of a Tcl script to output a prompt; instead of outputting a prompt wish will evaluate the script in tcl_prompt1. The variable tcl_prompt2 is used in a similar way when a newline is typed but the current command isn't yet complete; if tcl_prompt2 isn't set then no prompt is output for incomplete commands.

KEYWORDS

shell, toolkit
Copyright © 1991-1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.


tcllib comm

 Table of Contents

Name

comm.tcl - A remote communications facility for Tcl (7.6, 8.0, and later)

Synopsis

package require comm ?3.7?

chan send ?-async? id cmd ?arg arg ...?

chan interps

chan ids

chan self

chan connect ?id?

chan config
chan config name
chan config ?name value ...?
-listen ?0|1? -local ?0|1? -port ?port?

chan new chan ?name value ...?

chan channels

chan shutdown id

chan abort

chan destroy

chan remoteid

chan hook event ?+??script?

The package initializes comm as the default chan.

Introduction

The comm command provides an inter-interpreter remote execution facility much like Tk's send(n) , except that it uses sockets rather than the X server for the communication path. As a result, comm works with multiple interpreters, works on Windows and Macintosh systems, and provides control over the remote execution path.

These commands work just like send and winfo interps: comm send ?-async? id cmd ?arg arg ...? comm interps
This is all that is really needed to know in order to use comm.

Description

comm names communication endpoints with an id unique to each machine. Before sending commands, the id of another interpreter is needed. Unlike Tk's send, comm doesn't implicitly know the id's of all the interpreters on the system.

comm send ?-async? id cmd ?arg arg ...? This invokes the given command in the interpreter named by id. The command waits for the result and remote errors are returned unless the -async option is given.

comm self
Returns the id for this channel.

comm interps
Returns a list of all the remote id's to which this channel is connected. comm learns a new remote id when a command is first issued it, or when a remote id first issues a command to this comm channel. comm ids is an alias for this method.

comm connect ?id?
Whereas comm send will automatically connect to the given id, this forces a connection to a remote id without sending a command. After this, the remote id will appear in comm interps.

These four methods make up the basic comm interface.

Eval Semantics

The evaluation semantics of comm send are intended to match Tk's send exactly. This means that comm evaluates arguments on the remote side.

If you find that comm send doesn't work for a particular command, try the same thing with Tk's send and see if the result is different. If there is a problem, please report it. For instance, there was had one report that this command produced an error. Note that the equivalent send command also produces the same error.
% comm send id llength {a b c} wrong # args: should be «llength list" % send name llength {a b c}
wrong # args: should be «llength list"

The eval hook (described below) can be used to change from send's double eval semantics to single eval semantics.

Multiple Channels

More than one comm channel (or listener) can be created in each Tcl interpeter. This allows flexibility to create full and restricted channels. For instance, hook scripts are specific to the channel they are defined against. comm new chan ?name value ...?
This creates a new channel and Tcl command with the given channel name. This new command controls the new channel and takes all the same arguments as comm. Any remaining arguments are passed to the config method.

comm channels
This lists all the channels allocated in this Tcl interpreter.

The default configuration parameters for a new channel are:
-port 0 -local 1 -listen 0
The default channel comm is created with: comm new comm -port 0 -local 1 -listen 1

Channel Configuration

The config method acts similar to fconfigure in that it sets or queries configuration variables associated with a channel.
comm config
comm config name
comm config ?name value ...?
When given no arguments, config returns a list of all variables and their value With one argument, config returns the value of just that argument. With an even number of arguments, the given variables are set to the given values.

These configuration variables can be changed (descriptions of them are elsewhere in this manual page): -listen ?0|1? -local ?0|1? -port ?port?

These configuration variables are readonly: -chan chan -serial n -socket sockn

When config changes the parameters of an existing channel, it closes and reopens the listening socket. An automatically assigned channel id will change when this happens. Recycling the socket is done by invoking comm abort, which causes all active sends to terminate.

Id/Port Assignments

comm uses a TCP port for endpoint id. The interps (or ids) method merely lists all the TCP ports to which the channel is connected. By default, each channel's id is randomly assigned by the operating system (but usually starts at a low value around 1024 and increases each time a new socket is opened). This behavior is accomplished by giving the -port config option a value of 0. Alternately, a specific TCP port number may be provided for a given channel. As a special case, comm contains code to allocate a a high-numbered TCP port (>10000) by using -port {}. Note that a channel won't be created and initialized unless the specific port can be allocated.

As a special case, if the channel is configured with -listen 0, then it will not create a listening socket and will use an id of 0 for itself. Such a channel is only good for outgoing connections (although once a connection is established, it can carry send traffic in both directions).

Remote Interpreters

By default, each channel is restricted to accepting connections from the local system. This can be overriden by using the -local 0 configuration option For such channels, the id parameter takes the form {id host} .

WARNING: The host must always be specified in the same form (e.g., as either a fully qualified domain name, plain hostname or an IP address).

Closing Connections

These methods give control over closing connections:

comm shutdown id
This closes the connection to id, aborting all outstanding commands in progress. Note that nothing prevents the connection from being immediately reopened by another incoming or outgoing command.

comm abort
This invokes shutdown on all open connections in this comm channel.

comm destroy
This aborts all connections and then destroys the this comm channel itself, including closing the listening socket. Special code allows the default comm channel to be closed such that the comm command it is not destroyed. Doing so closes the listening socket, preventing both incoming and outgoing commands on the channel. This sequence reinitializes the default channel:
comm destroy; comm new comm

When a remote connection is lost (because the remote exited or called shutdown), comm can invoke an application callback. This can be used to cleanup or restart an ancillary process, for instance. See the lost callback below.

Callbacks

This is a mechanism for setting hooks for particular events:
comm hook event ?+??script?

This uses a syntax similar to Tk's bind command. Prefixing script with a + causes the new script to be appended. Without this, a new script replaces any existing script. When invoked without a script, no change is made. In all cases, the new hook script is returned by the command.

When an event occurs, the script associated with it is evaluated with the listed variables in scope and available. The return code (not the return value) of the script is commonly used decide how to further process after the hook.

Common variables include:

chan the name of the comm channel (and command)

id
the id of the remote in question

fid the file id for the socket of the connection

These are the defined events:

connecting
Variables: chan id host port
This hook is invoked before making a connection to the remote named in id. An error return (via error) will abort the connection attempt with the error. Example:

% comm hook connecting {
if [string match {*[02468]} $id] { error «Can't connect to even ids" }
}
% comm send 10000 puts ok
Connect to remote failed: Can't connect to even ids %

connected
Variables: chan fid id host port This hook is invoked immediately after making a remote connection to id, allowing arbitrary authentication over the socket named by fid. An error return (via error) will close the connection with the error. host and port are merely extracted from the id; changing any of these will have no effect on the connection, however. It is also possible to substitute and replace fid .

incoming
Variables: chan fid addr remport Hook invoked when receiving an incoming connection, allowing arbitrary authentication over socket named by fid. An error return (via error) will close the connection with the error. Note that the peer is named by remport and addr but that the remote id is still unknown. Example:

comm hook incoming {
if [string match 127.0.0.1 $addr] { error «I don't talk to myself" }
}

eval
Variables: chan id cmd buffer This hook is invoked after collecting a complete script from a remote but before evalutating it. This allows complete control over the processing of incoming commands. cmd contains either send or async. buffer holds the script to evaluate. At the time the hook is called, $chan remoteid is identical in value to id.

By changing buffer, the hook can change the script to be evaluated. The hook can short circuit evaluation and cause a value to be immediately returned by using return result (or, from within a procedure, return -code return result). An error return (via error) will return an error result, as is if the script caused the error. Any other return will evaluate the script in buffer as normal. For compatibility with 3.2, break and return -code break result is supported, acting similarly to return {} and return -code return result.

Examples:
1. augmenting a command
% comm send [comm self] pid % comm hook eval {puts «going to execute $buffer"} % comm send [comm self] pid going to execute pid

2. short circuting a command
% comm hook eval {puts «would have executed $buffer"; return 0} % comm send [comm self] pid would have executed pid

3. Replacing double eval semantics % comm send [comm self] llength {a b c} wrong # args: should be «llength list" % comm hook eval {return [uplevel #0 $buffer]} return [uplevel #0 $buffer] % comm send [comm self] llength {a b c}

4. Using a slave interpreter
% interp create foo
% comm hook eval {return [foo eval $buffer]} % comm send [comm self] set myvar 123 % set myvar
can't read «myvar": no such variable % foo eval set myvar

5. Using a slave interpreter (double eval) % comm hook eval {return [eval foo eval $buffer]} 6. Subverting the script to execute % comm hook eval {
switch -- $buffer {
a {return A-OK} b {return B-OK} default {error «$buffer is a no-no"} }
}
% comm send [comm self] pid pid is a no-no
% comm send [comm self] a A-OK

reply
Variables: chan id buffer ret return() This hook is invoked after collecting a complete reply script from a remote but before evalutating it. This allows complete control over the processing of replies to sent commands. The reply buffer is in one of the following forms return result
return -code code result
return -code code -errorinfo info -errorcode ecode msg For safety reasons, this is decomposed. The return result is in ret, and the return switches are in the return array:
return(-code)
return(-errorinfo)
return(-errordcode)
Any of these may be the empty string. Modifying these four variables can change the return value, whereas modifying buffer has no effect.

lost
Variables: chan id reason This hook is invoked when the connection to id is lost. Return value (or thrown error) is ignored. reason is an explanatory string indicating why the connection was lost. Example:

comm hook lost {

global myvar
if {$myvar(id) == $id} {
myfunc
return
}
}

Unsupported

These interfaces may change or go away in subsequence releases.

comm remoteid
Returns the id of the sender of the last remote command executed on this channel. If used by a proc being invoked remotely, it must be called before any events are processed. Otherwise, another command may get invoked and change the value.

comm_send
Invoking this procedure will substitute the Tk send and winfo interps commands with these equivalents that use comm.

proc send {args} {
eval comm send $args
}
rename winfo tk_winfo
proc winfo {cmd args} {
if ![string match in* $cmd] {return [eval [list tk_winfo $cmd] $args]} return [comm interps]
}

Security

Something here soon.

Blocking Semantics

There is one outstanding difference between comm and send. When blocking in a synchronous remote command, send uses an internal C hook (Tk_RestrictEvents) to the event loop to look ahead for send-related events and only process those without processing any other events. In contrast, comm uses the vwait command as a semaphore to indicate the return message has arrived. The difference is that a synchornous send will block the application and prevent all events (including window related ones) from being processed, while a synchronous comm will block the application but still allow other events will still get processed. In particular, after idle handlers will fire immediately when comm blocks.

What can be done about this? First, note that this behavior will come from any code using vwait to block and wait for an event to occur. At the cost of multiple channel support, comm could be changed to do blocking I/O on the socket, givng send-like blocking semantics. However, multiple channel support is a very useful feature of comm that it is deemed too important to lose. The remaining approaches involve a new loadable module written in C (which is somewhat against the philosophy of comm) One way would be to create a modified version of the vwait command that allow the event flags passed to Tcl_DoOneEvent to be specified. For comm, just the TCL_FILE_EVENTS would be processed. Another way would be to implement a mechanism like Tk_RestrictEvents, but apply it to the Tcl event loop (since comm doesn't require Tk). One of these approaches will be available in a future comm release as an optional component.

Compatibility

Comm exports itself as a package. The package version number is in the form major.minor, where the major version will only change when a non-compatible change happens to the API or protocol. Minor bug fixes and changes will only affect the minor version. To load comm this command is usually used:
package require Comm 3
Note that requiring no version (or a specific version) can also be done.

The revision history of comm includes these releases:

3.6 A bug in the looking up of the remoteid for a executed command could be triggered when the connection was closed while several asynchronous sends were queued to be executed.

3.5 Internal change to how reply messages from a send are handled. Reply messages are now decoded into the value to pass to return; a new return statement is then cons'd up to with this value. Previously, the return code was passed in from the remote as a command to evaluate. Since the wire protocol has not changed, this is still the case. Instead, the reply handling code decodes the reply message.

3.4 Added more source commentary, as well as documenting config variables in this man page. Fixed bug were loss of connection would give error about a variable named rather than the message about the lost connection. comm ids is now an alias for comm interps (previously, it an alias for comm chans). Since the method invocation change of 3.0, break and other exceptional conditions were not being returned correctly from comm send. This has been fixed by removing the extra level of indirection into the internal procedure commSend. Also added propogation of the errorCode variable. This means that these commands return exactly as they would with send: comm send id break
catch {comm send id break}
comm send id expr 1 / 0
Added a new hook for reply messages. Reworked method invocation to avoid the use of comm:* procedures; this also cut the invocation time down by 40%. Documented comm config (as this manual page still listed the defunct comm init!)

3.3 Some minor bugs were corrected and the documentation was cleaned up. Added some examples for hooks. The return semantics of the eval hook were changed.

3.2 A new wire protocol, version 3, was added. This is backwards compatible with version 2 but adds an exchange of supported protocol versions to allow protocol negotiation in the future. Several bugs with the hook implementation were fixed. A new section of the man page on blocking semantics was added.

3.1 All the documented hooks were implemented. commLostHook was removed. A bug in comm new was fixed.

3.0 This is a new version of comm with several major changes. There is a new way of creating the methods available under the comm command. The comm init method has been retired and is replaced by comm configure which allows access to many of the welldefined internal variables. This also generalizes the options available to comm new. Finally, there is now a protocol version exchanged when a connection is established. This will allow for future on-wire protocol changes. Currently, the protocol version is set to 2.

2.3 comm ids was renamed to comm channels . General support for comm hook was fully implemented, but only the lost hook exists, and it was changed to follow the general hook API. commLostHook was unsupported (replaced by comm hook lost ) and commLost was removed.

2.2 The died hook was renamed lost, to be accessed by commLostHook and an early implementation of comm lost hook. As such, commDied is now commLost.

2.1 Unsupported method comm remoteid was added.

2.0 comm has been rewritten from scratch (but is fully compatible with Comm 1.0, without the requirement to use obTcl).

See Also

send(n)

Author

John LoVerso, John@LoVerso.Southborough.MA.US

http://www.opengroup.org/~loverso/tcl-tk/#comm

Copyright

Copyright (C) 1995-1998 The Open Group. All Rights Reserved. Please see the file comm.LICENSE that accompanied this source, or http://www.open_group.org/www/dist_client/caubweb/COPYRIGHT.free.html.

This license for comm, new as of version 3.2, allows it to be used for free, without any licensing fee or royalty.

Bugs

· If there is a failure initializing a channel created
with comm new, then the channel should be destroyed. Currently, it is left in an inconsistent state.
· There should be a way to force a channel to quiesce
when changing the configuration.

The following items can be implemented with the existing hooks and are listed here as a reminder to provide a sample hook in a future version.

· Allow easier use of a slave interp for actual command
execution (especially when operating in «not local» mode).
· Add host list (xhost-like) or «magic cookie"
(xauth-like) authentication to initial handshake.

The following are outstanding todo items.

· Add an interp discovery and name->port mapping.
This is likely to be in a separate, optional nameserver. (See also the related work, below.)
· Fix the {id host} form so as not to be dependent

upon canonical hostnames. This requires fixes to Tcl to resolve hostnames!

This man page is bigger than the source file.

on Using Old Versions of Tcl

Tcl7.5 under Windows contains a bug that causes the interpreter to hang when EOF is reached on non-blocking sockets. This can be triggered with a command such as this: comm send $other exit
Always make sure the channel is quiescent before closing/exiting or use at least Tcl7.6 under Windows.

Tcl7.6 on the Mac contains several bugs. It is recommended you use at least Tcl7.6p2.

Tcl8.0 on UNIX contains a socket bug that can crash Tcl. It is recommended you use Tcl8.0p1 (or Tcl7.6p2).

Related Work

Tcl-DP provides an RPC-based remote execution interface, but is a compiled Tcl extension. See http://www.cs.cor_nell.edu/Info/Projects/zeno/Projects/Tcl-DP.html.

Michael Doyle <miked@eolas.com> has code that implements the Tcl-DP RPC interface using standard Tcl sockets, much like comm.

Andreas Kupries <a.kupries@westend.com> uses comm and has built a simple nameserver as part of his Pool library. See http://www.westend.com/~kupries/doc/pool/index.htm.

Table of Contents

  • Name
  • Synopsis
  • Introduction
  • Description
  • Eval Semantics
  • Multiple Channels
  • Channel Configuration
  • Id/Port Assignments
  • Remote Interpreters
  • Closing Connections
  • Callbacks
  • Unsupported
  • Security
  • Blocking Semantics
  • Compatibility
  • See Also
  • Author
  • Copyright
  • Bugs
  • on Using Old Versions of Tcl
  • Related Work


tcllib control

 Table of Contents

_________________________________________________________________

Name

control - Procedures for control flow structures.

Synopsis

package require Tcl 8.2

package require control ?0.0?

control::control command option ?arg arg ...?

control::assert expr ?arg arg ...?

control::no-op ?arg arg ...?
_________________________________________________________________

Description

The control package provides a variety of commands that provide additional flow of control structures beyond the built-in ones provided by Tcl. These are commands that in many programming languages might be considered keywords, or a part of the language itself. In Tcl, control flow structures are just commands like everything else.

Commands

control::control command option ?arg arg ...? The control command is used as a configuration command for customizing the other public commands of the control package. The command argument names the command to be customized. The set of valid option and subsequent arguments are determined by the command being customized, and are documented with the command.

control::assert expr ?arg arg ...?
When disabled, the assert command behaves exactly like the no-op command.

When enabled, the assert command evaluates expr as an expression (in the same way that expr evaluates its argument). If evaluation reveals that expr is not a valid boolean expression (according to [string is boolean -strict]), an error is raised. If expr evaluates to a true boolean value (as recognized by if), then assert returns an empty string. Otherwise, the remaining arguments to assert are used to construct a message string. If there are no arguments, the message string is «assertion failed: $expr". If there are arguments, they are joined by join to form the message string. The message string is then appended as an argument to a callback command, and the completed callback command is evaluated in the global namespace.

The assert command can be customized by the control command in two ways:

[control::control assert enabled ?boolean?] queries or sets whether control::assert is enabled. When called without a boolean argument, a boolean value is returned indicating whether the control::assert command is enabled. When called with a valid boolean value as the boolean argument, the control::assert command is enabled or disabled to match the argument, and an empty string is returned.

[control::control assert callback ?command?] queries or sets the callback command that will be called by an enabled assert on assertion failure. When called without a command argument, the current callback command is returned. When called with a command argument, that argument becomes the new assertion failure callback command. Note that an assertion failure callback command is always defined, even when assert is disabled. The default callback command is [return -code error].

Note that control::assert has been written so that in combination with [namespace import], it is possible to use enabled assert commands in some namespaces and disabled assert commands in other namespaces at the same time. % package require control
% control::control assert enabled 1 % namespace eval one namespace import ::control::assert % control::control assert enabled 0 % namespace eval two namespace import ::control::assert % one::assert {1 == 0}
assertion failed: 1 == 0
% two::assert {1 == 0}
This capability is useful so that debugging efforts can be independently controlled module by module.

control::no-op ?arg arg ...?
The no-op command takes any number of arguments and does nothing. It returns an empty string.

See Also

expr, if, join, namespace, return, string

Keywords

control, flow, structure, no-op, assert

Table of Contents

  • Name
  • Synopsis
  • Description
  • Commands
  • See Also
  • Keywords


tcllib ftp

 Table of Contents

_________________________________________________________________

Name

ftp - Client-side tcl implementation of the ftp protocol

Synopsis

package require Tcl

package require ftp ?2.2.1?

ftp::Open server user passwd ?options?

ftp::Close handle

ftp::Cd handle directory

ftp::Pwd handle

ftp::Type handle ?ascii|binary|tenex?

ftp::List handle ?directory?

ftp::NList handle ?directory?

ftp::FileSize handle file

ftp::ModTime handle file

ftp::Delete handle file

ftp::Rename handle from to

ftp::Put handle (local | -data data) ?remote?

ftp::Append handle (local | -data data) ?remote?

ftp::Get handle remote ?(local | -variable varname)?

ftp::Reget handle remote ?local?

ftp::Newer handle remote ?local?

ftp::MkDir handle directory

ftp::RmDir handle directory

ftp::Quote handle arg1 arg2 ...

ftp::DisplayMsg handle msg ?state?

_________________________________________________________________

Description

The ftp library package provides the client side of the ftp protocol. The package implements both active (default) and passive ftp sessions.

A new ftp session is started with the Open command. To shutdown an existing ftp session use Close. All other commands are restricted to usage in an an open ftp session. They will generate errors if they are used out of context. The ftp package includes file and directory manipulating commands for remote sites. To perform the same operations on the local site use commands built into the core, like cd or file.

The output of the package is controlled by two state variables, ftp::VERBOSE and ftp::DEBUG. Setting ftp::VERBOSE to 1 forces the package to show all responses from a remote server. The default value is 0. Setting ftp::DEBUG to 1 enables debugging and forces the package to show all return codes, states, state changes and «real» ftp commands. The default value is 0.

The procedure DisplayMsg is used to show the different messages from the ftp session. The package itself declares this command very simple, writing the messages to stdout (if VERBOSE was set, s.a.) and throwing tcl errors for error messages. It is the responsibility of the application to overwrite it as needed. A state variable for different states assigned to different colors is recommended by the author. The log package can be useful for this.

API

ftp::Open server user passwd ?options?
This command is used to start a FTP session by establishing a control connection to the FTP server. The defaults are used for any option not specified by the caller.

The command takes a host name server, a user name user and a password password as its parameters and returns a session handle that is an integer number greater than or equal to 0, if the connection is successfully established. Otherwise it returns -1. The server parameter must be the name or internet address (in dotted decimal notation) of the ftp server to connect to. The user and passwd parameters must contain a valid user name and password to complete the login process.

The options overwrite some default values or set special abilities:

-blocksize size
The blocksize is used during data transfer. At most size bytes are transfered at once. The default value for this option is 4096.

The package will evaluate the -progress callback for the session after the transfer of each block.

-timeout seconds
If seconds is non-zero, then ftp::Open sets up a timeout which will occur after the specified number of seconds. The default value is 600.
-port number
The port number specifies an alternative remote port on the ftp server on which the ftp service resides. Most ftp services listen for connection requests on the default port 21. Sometimes, usually for security reasons, port numbers other than 21 are used for ftp connections.
-mode mode
The transfer mode option determines if a file transfer occurs in active or passive mode. In passive mode the client will ask the ftp server to listen on a data port and wait for the connection rather than to initiate the process by itself when a data transfer request comes in. Passive mode is normally a requirement when accessing sites via a firewall. The default mode is active.
-progress callback
This callback is evaluated whenever a block of data was transfered. See the option -blocksize for how to specify the size of the transfered blocks.

When evaluating the callback one argument is appended to the callback script, the current accumulated number of bytes transferred so far.

-command callback
Specifying this option places the connection into asynchronous mode. The callback is evaluated after the completion of any operation. When an operation is running no further operations must be started until a callback has been received for the currently executing operation.

When evaluating the callback several arguments are appended to the callback script, namely the keyword of the operation that has completed and any additional arguments specific to the operation. If an error occured during the execution of the operation the callback is given the keyword error.

ftp::Close handle
This command terminates the specified ftp session. If no file transfer is in progress, the server will close the control connection immediately. If a file transfer is in progress however, the control connection will remain open until the transfers completes. When that happens the server will write the result response for the transfer to it and close the conenction afterward.

ftp::Cd handle directory
This command changes the current working directory on the ftp server to a specified target directory. The command returns 1 if the current working directory was successfully changed to the specified directory or 0 if it fails. The target directory can be

*
a subdirectory of the current directory,
*
directory)
*
or a fully qualified path to a new working directory.

ftp::Pwd handle
This command returns the complete path of the current working directory on the ftp server, or an empty string in case of an error.

ftp::Type handle ?ascii|binary|tenex?
This command sets the ftp file transfer type to either ascii, binary, or tenex. The command always returns the currently set type. If called without type no change is made.

Currently only ascii and binary types are supported. There is some early (alpha) support for Tenex mode. The type ascii is normally used to convert text files into a format suitable for text editors on the platform of the destination machine. This mainly affects end-of-line markers. The type binary on the other hand allows the undisturbed transfer of non-text files, such as compressed files, images and executables.

ftp::List handle ?directory?
This commands lists the contents of the specified a directory or other group of files. If no directory is specified the current remote directory is used instead. Wildcard expressions such as *.tcl are allowed. A directory or file name must be fully qualified, otherwise the commands lists the entries in the current remote directory.

The listing includes any system-dependent information that the server chooses to include. For example most UNIX systems produce output from the command ls -l. The command returns the retrieved information as a tcl list with one item per entry. Empty lines and UNIX's «total» lines are ignored and not included in the result as reported by this command.

If the command fails an empty list is returned.

ftp::NList handle ?directory?
This command has the same behavior as the ftp::List command, except that it only retrieves an abbreviated listing. This means only file names are returned in a sorted list.

ftp::FileSize handle file
This command returns the size of the specified file on the ftp server. If the command fails an empty string is returned.

ATTENTION! It will not work properly when in ascii mode and is not supported by all ftp server implementations.

ftp::ModTime handle file
This command retrieves the time of the last modification of the file on the ftp server as a system dependent integer value in seconds or an empty string if an error occured. Use the built-in command clock to convert the retrieves value into other formats.

ftp::Delete handle file
This command deletes the specified file on the ftp server. The command returns 1 if the specified file was successfully deleted or 0 if it failed.

ftp::Rename handle from to
This command renames the file from in the current directory of the ftp server to the specified new file name to. This new file name must not be the same as any existing subdirectory or file name. The command returns 1 if the specified file was successfully renamed or 0 if it failed.

ftp::Put handle (local | -data data) ?remote? This command transfers a local file local to a remote file remote on the ftp server. If the file parameters passed to the command do not fully qualified path names the command will use the current directory on local and remote host. If the remote file name is unspecified, the server will use the name of the local file as the name of the remote file. The command returns 1 to indicate a sucessful transfer and 0 in the case of a failure.

If -data data is specified instead of a local file, the system will not transfer a file, but the data passed into it. In this case the name of the remote file has to be specified.

ftp::Append handle (local | -data data) ?remote? This command behaves like ftp::Puts, but appends the transfered information to the remote file. If the file did not exist on the server it will be created.

ftp::Get handle remote ?(local | -variable varname)? This command retrieves a remote file remote on the ftp server and stores its contents into the local file local. If the file parameters passed to the command do not fully qualified path names the command will use the current directory on local and remote host. If the local file name is unspecified, the server will use the name of the remote file as the name of the local file. The command returns 1 to indicate a sucessful transfer and 0 in the case of a failure.

If -variable varname is specified, the system will store the retrieved data into the variable varname instead of a file.

ftp::Reget handle remote ?local?
This command behaves like ftp::Get, except that if local file local exists and is smaller than remote file remote, the local file is presumed to be a partially transferred copy of the remote file and the transfer is continued from the apparent point of failure. This command is useful when transferring very large files over networks that tend to drop connections.

ftp::Newer handle remote ?local?
This command behaves like ftp::Get, except that it retrives the remote file only if the modification time of the remote file is more recent than the file on the local system. If the file does not exist on the local system, the remote file is considered newer.

ftp::MkDir handle directory
This command creates the specified directory on the ftp server. If the specified path is relative the new directory will be created as a subdirectory of the current working directory. Else the created directory will have the specified path name. The command returns 1 to indicate a sucessful creation of the directory and 0 in the case of a failure.

ftp::RmDir handle directory
This command removes the specified directory on the ftp server. The remote directory has to be empty or the command will fail. The command returns 1 to indicate a sucessful removal of the directory and 0 in the case of a failure.

ftp::Quote handle arg1 arg2 ...
This command is used to send an arbitrary ftp command to the server. It cannot be used to obtain a directory listing or for transferring files. It is included to allow an application to execute commands on the ftp server which are not provided by this package. The arguments are sent verbatim, i.e. as is, with no changes.

In constrast to the other commands in this package this command will not parse the response it got from the ftp server but return it verbatim to the caller.

ftp::DisplayMsg handle msg ?state?
This command is used by the package itself to show the different messages from the ftp sessions. The package itself declares this command very simple, writing the messages to stdout (if VERBOSE was set, see below) and throwing tcl errors for error messages. It is the responsibility of the application to overwrite it as needed. A state variable for different states assigned to different colors is recommended by the author. The log package can be useful for this.

ftp::VERBOSE
A state variable controlling the output of the package. Setting ftp::VERBOSE to 1 forces the package to show all responses from a remote server. The default value is 0.

ftp::DEBUG
A state variable controlling the output of ftp. Setting ftp::DEBUG to 1 enables debugging and forces the package to show all return codes, states, state changes and «real» ftp commands. The default value is 0.

Bugs

The correct execution of many commands depends upon the proper behavior by the remote server, network and router configuration.

An update command placed in the procedure DisplayMsg may run into persistent errors or infinite loops. The solution to this problem is to use update idletasks instead of update.

See Also

ftpd, smtp, pop3, mime

Keywords

ftp, rfc959, internet, net

Table of Contents

  • Name
  • Synopsis
  • Description
  • API
  • Bugs
  • See Also
  • Keywords


tcllib mime

 Table of Contents

_________________________________________________________________

Name

mime - Manipulation of MIME body parts

Synopsis

package require Tcl

package require mime ?1.2?

mime::initialize ?-canonical type/subtype ?-param {key value}...? ?-encoding value? ?-header {key value}...?? (-file name | -string value | -parse {token1 ... tokenN} )

mime::finalize token ?-subordinates all | dynamic | none?

mime::getproperty token ?property | -names?

mime::getheader token ?key | -names?

mime::setheader token key value ?-mode write | append delete?

mime::getbody token ?-command callback ?-blocksize octets??

mime::copymessage token channel

mime::buildmessage token

mime::parseaddress string

mime::parsedatetime (string | -now) property

mime::mapencoding encoding_name

mime::reversemapencoding charset_type

_________________________________________________________________

Description

The mime library package provides the commands to create and manipulate MIME body parts.

mime::initialize ?-canonical type/subtype ?-param {key

value}...?
?-encoding value? ?-header {key value}...?? (-file name | -string value | -parse {token1 ... tokenN} ) This command creates a MIME part and returns a token representing it.
* If the -canonical option is present, then
the body is in canonical (raw) form and is found by consulting either the -file, -string, or -part option.

In addition, both the -param and -header options may occur zero or more times to specify Content-Type parameters (e.g., charset) and header keyword/values (e.g., Content-Disposition), respectively.

Also, -encoding, if present, specifies the Content-Transfer-Encoding when copying the body.

* If the -canonical option is not present,
then the MIME part contained in either the -file or the -string option is parsed, dynamically generating subordinates as appropriate.

mime::finalize token ?-subordinates all | dynamic | none? This command destroys the MIME part represented by token. It returns an empty string.

If the -subordinates option is present, it specifies which subordinates should also be destroyed. The default value is dynamic, destroying all subordinates which were created by mime::initialize together with the containing body part.

mime::getproperty token ?property | -names? This command returns a string or a list of strings containing the properties of a MIME part. If the command is invoked with the name of a specific property, then the corresponding value is returned; instead, if -names is specified, a list of all properties is returned; otherwise, a serialized array of properties and values is returned. .sp The possible properties are:

content
The type/subtype describing the content

encoding
The «Content-Transfer-Encoding"

params A list of «Content-Type» parameters

parts A list of tokens for the part's subordinates. This property is present only if the MIME part has subordinates.

size The approximate size of the content (unencoded)

mime::getheader token ?key | -names?
This command returns the header of a MIME part, as a list of strings.

A header consists of zero or more key/value pairs. Each value is a list containing one or more strings.

If this command is invoked with the name of a specific key, then a list containing the corresponding value(s) is returned; instead, if -names is specified, a list of all keys is returned; otherwise, a serialized array of keys and values is returned. Note that when a key is specified (e.g., «Subject"), the list returned usually contains exactly one string; however, some keys (e.g., «Received") often occur more than once in the header, accordingly the list returned usually contains more than one string.

mime::setheader token key value ?-mode write | append delete?
This command writes, appends to, or deletes the value associated with a key in the header. It returns a list of strings containing the previous value associated with the key.

The value for -mode is one of:

write The key/value is either created or overwritten (the default).

append A new value is appended for the key (creating it as necessary).

delete All values associated with the key are removed (the value parameter is ignored).

mime::getbody token ?-command callback ?-blocksize octets??
This command returns a string containing the body of the leaf MIME part represented by token in canonical form.

If the -command option is present, then it is repeatedly invoked with a fragment of the body as this: uplevel #0 $callback [list «data» $fragment]

(The -blocksize option, if present, specifies the maximum size of each fragment passed to the callback.)

When the end of the body is reached, the callback is invoked as: uplevel #0 $callback «end"

Alternatively, if an error occurs, the callback is invoked as: uplevel #0 $callback [list «error» reason]

Regardless, the return value of the final invocation of the callback is propagated upwards by mime::getbody.

If the -command option is absent, then the return value of mime::getbody is a string containing the MIME part's entire body.

mime::copymessage token channel
This command copies the MIME represented by token part to the specified channel. The command operates synchronously, and uses fileevent to allow asynchronous operations to proceed independently. It returns an empty string.

mime::buildmessage token
This command returns the MIME part represented by token as a string. It is similar to mime::copymessage, only it returns the data as a return string instead of writing to a channel.

mime::parseaddress string
This command takes a string containing one or more 822-style address specifications and returns a list of serialized arrays, one element for each address specified in the argument.

Each serialized array contains the properties below. Note that one or more of these properties may be empty.

address
local@domain

comment
822-style comment

domain the domain part (rhs)

error non-empty on a parse error

group this address begins a group

friendly
user-friendly rendering

local the local part (lhs)

memberP
this address belongs to a group

phrase the phrase part

proper 822-style address specification route 822-style route specification (obsolete)

mime::parsedatetime (string | -now) property This command takes a string containing an 822-style date-time specification and returns the specified property as a serialized array.

The list of properties and their ranges are:

hour
0 .. 23

lmonth January, February, ..., December

lweekday
Sunday, Monday, ... Saturday

mday
1 .. 31
min
0 .. 59
mon
1 .. 12

month Jan, Feb, ..., Dec

proper 822-style date-time specification

rclock elapsed seconds between then and now

sec
0 .. 59
wday
0 .. 6 (Sun .. Mon)

weekday
Sun, Mon, ..., Sat

yday
1 .. 366
year
1900 ...
zone
-720 .. 720 (minutes east of GMT)

mime::mapencoding encoding_name
This commansd maps tcl encodings onto the proper names for their MIME charset type. This is only done for encodings whose charset types were known. The remaining encodings return «» for now.

mime::reversemapencoding charset_type
This command maps MIME charset types onto tcl encoding names. Those that are unknown return «".

See Also

smtp, pop3, ftp, http

Keywords

mail, email, smtp, mime, rfc821, rfc822, internet, net

Table of Contents

  • Name
  • Synopsis
  • Description
  • See Also
  • Keywords


tcllib smtp

 Table of Contents

_________________________________________________________________

Name

smtp - Client-side tcl implementation of the smtp protocol

Synopsis

package require Tcl

package require mime ?1.0?

package require smtp ?1.3?

smtp::sendmessage token options

_________________________________________________________________

Description

The smtp library package provides the client side of the smtp protocol.

smtp::sendmessage token options
This command sends the MIME part represented by token to an SMTP server. options is a list of options and their associated values. The recognized options are:

-servers
A list of SMTP servers. The default is localhost.
-ports A list of SMTP ports. The default is 25.
-queue Indicates
that the SMTP server should be asked to queue the message for later processing. A boolean value.
-atleastone
Indicates that the SMTP server must find at least one recipient acceptable for the message to be sent. A boolean value.
-originator
A string containing an 822-style address specification. If present the header isn't examined for an originator address.
-recipients
A string containing one or more 822-style address specifications. If present the header isn't examined for recipient addresses).
-header
A list of keywords and their values (may occur zero or more times).

If the -originator option is not present, the originator address is taken from From (or Resent-From); similarly, if the -recipients option is not present, recipient addresses are taken from To, cc, and Bcc (or Resent-To, and so on). Note that the header key/values supplied by the -header option (not those present in the MIME part) are consulted. Regardless, header key/values are added to the outgoing message as necessary to ensure that a valid 822-style message is sent.

The command returns a list indicating which recipients were unacceptable to the SMTP server. Each element of the list is another list, containing the address, an SMTP error code, and a textual diagnostic. Depending on the -atleastone option and the intended recipients, a nonempty list may still indicate that the message was accepted by the server.

See Also

mime, pop3, ftp, http

Keywords

mail, email, smtp, mime, rfc821, rfc822, internet, net

Table of Contents

  • Name
  • Synopsis
  • Description
  • See Also
  • Keywords


Examples

SourceForge Logo

Tcl DOM Packages

 TclSOAP Logo
Project
Project Page
File Releases
WebPage
Documentation
Forums
Browse CVS
Related Links
SOAP::Lite
4s4c
Userland SOAP
Support
Bugs
Support Requests
Patches
Feature Requests

TclSOAP depends heavily upon the underlying DOM implementation. Currently the only DOM implementation supported is the TclDOM package from the tclxml project. This code can be obtained by checking out the tcldom module from the tclxml project CVS server. For those who do not wish to, or cannot obtain the source I am providing pre-compiled TclDOM 2.0 dom::c modules for linux and win32. In each case the code is compatible with ActiveTcl 8.3.3.3 for the relevant platform. Please note that these binary releases are not official tclxml project releases although they have been built from unmodified tcldom source code from a recent HEAD revision. They are however the versions currently in use by me for TclSOAP development.

  • TclDOM_C-2.0.tar.gz - the Linux version statically linked to expat.
    md5sum: db35fef853f230589b0171a91bf487cc TclDOM_C-2.0.tar.gz
  • TclDOM_C-2.0.zip - windows version compiled using MSVC 6.0.
    md5sum: 536b3575cb32e812b32df1a8081b3c2c TclDOM_C-2.0.zip

The packages should be installed somewhere in your Tcl auto_path. The simplest method is to unpack the archive in the Tcl lib subdirectory. Under Windows, that is probably \Program Files\Tcl\lib. To ensure that you are using this version of the DOM package you should execute the following commands in your tclsh shell checking that the output matches this example.

% package require dom
2.0
% info loaded
{/opt/tcl/lib/tcldom2.0/tcldom2.0.so Tcldom}              ;# Linux
{{c:\\Program Files\Tcl\lib\tcldom2.0\tcldom.dll} Tcldom} ;# Windows

Frink for Windows

Not everyone is able to get hold of a windows Frink executable so here is one

  • frink.exe - mimgw32 compiled windows console executable of Frink 2.1.5
    md5sum: 4273292d0ce6ba80d98e72f5d7a32e82 frink.exe

$Id: dom-packages.html,v 1.5 2001/10/17 21:49:21 patthoyts Exp $


TclSOAP CGI Server Package

 TclSOAP Logo
Sections
Introduction
Installation
Implementation
Type Info
Further Info
Project
Project Page
File Releases
WebPage
Documentation
Forums
Browse CVS
Interop
Round 1 Tests
Round 2 Base
Round 2B
Round 2C
Support
Bugs
Support Requests
Patches
Feature Requests

Introduction

The SOAP::CGI package allows you to provide SOAP web services from Tcl scripts via the CGI script capabilities of your web server. This document describes the use of this package with the Apache httpd server but the package should be applicable to any other server supporting the Common Gateway Interface.

The package provides a fairly comprehensive framework to deal with hiding the details of the web service protocols. The Tcl scripts implementing the service need to know nothing of XML nor the RPC protocol in use. Errors are returned via the normal Tcl error mechanism. The only special feature needed is variable type hinting. It is not possible to distinguish between a string with whitespace and a list in Tcl, so the rpcvar package is used to provide the additional type information when required.

Installation

Installation really only requires placing a script into the http servers cgi-bin directory and writing some service implementations. A generic script is provided as cgi-bin/rpc with some example services in cgi-bin/soap/. The package has four variables to configure so that it can find the service implementations:

package require SOAP::CGI
set SOAP::CGI::soapdir "../method-scripts"
set SOAP::CGI::soapmapfile "soapmap.dat"
set SOAP::CGI::xmlrpcdir "../method-scripts"
set SOAP::CGI::xmlrpcmapfile "xmlrpcmap.dat"
set SOAP::CGI::logfile "../logs/rpc.log"
SOAP::CGI::main

The SOAP and XML-RPC implementations can be the same, as above, or placed into separate directories. The log file is optional (unset the variable to disable logs) and will need to be writable by the httpd user - this usually means it needs to be world writable. The soapmap file is used to identify the implementation script file from the SOAPAction header. There is more information in the sample soapmap.dat file.

The script needs to be able to execute using tcl 8.3 or better and needs to be able to find the TclSOAP package. Bear in mind that the httpd process will not run with your environment (unless you are working on Windows). The supplied script shows how you can set the location of the package, should you need to. If you are using the Windows Apache server then you can't set the environment before execing tclsh so you need to manipulate the auto_path variable from within the CGI script instead.

Writing Service Implementations

Upon receipt of an HTTP POST the CGI framework examines the data and decides which RPC protocol should handle the request. The handlers then retrieve the method name from the request and look for a file with this name in the configured directory. This is sourced and then evaluated with the arguments obtained from the POST data. For example, the implementation for the square service will be the file ../method-scripts/square with the following code:

proc square {num} {
    return [expr $num * $num]
}

Given the configuration shown above, this implementation will be used for both SOAP and XML-RPC requests to the square service. It is necessary to identify the commands that are webservices to prevent clients from running arbitrary Tcl commands. This is done by the use of the SOAP::export or the corresponding XMLRPC::export commands. This means that the actual implementation for the square webservice would be:

package require SOAP
package require XMLRPC

SOAP::export square
XMLRPC export square

proc square {num} {
    return [expr $num * $num]
}

For more complex types such as structs, the reply will need to be an rpcvar so that the RPC handler can package the result correctly. So the implementation of the platform service which returns a struct containing the ::tcl_platform variable information is as follows

package require rpcvar
package require SOAP
SOAP::export platform

proc platform {} {
    return [rpcvar::rpcvar struct ::tcl_platform]
}

Structs are passed to the implementing procedure as a list of name value pairs suitable for use with array set ..., arrays are passed in as Tcl lists and everything else is passed in as a string. If the result type cannot be guessed then you should return a typed variable otherwise it will be assumed to be a string. The only types that can be guessed are integer, double and boolean (if expressed with true or false).

Providing Type Information

rpcvar to be done

Further Information

Look in the cgi-bin/soap subdirectory in the TclSOAP distribution for some examples of service implementations. There is an implementation of the UserLand SOAP interoperability suite that is used to ensure the package conforms to this standard. These illustrate the use of arrays and structs fairly comprehensively.

The client code for the validator suite is in samples/validator.tcl. To test a server implementation, source this script and run validate_soap url. This will run the test suite against the server implementation at the provided URL.

A similar client implementation of the XMethods Interoperability Lab test suite is in soapinterop.tcl. To use, source this file and execute soapinterop::validate url.

$Id: SOAP-CGI.html,v 1.5 2001/10/11 22:40:37 patthoyts Exp $


SOAP URL Domain Package for TclHTTPD

SourceForge Logo

Tcl SOAP Server Utility Package

 TclSOAP Logo
Project
Project Page
File Releases
WebPage
Documentation
Forums
Browse CVS
Interop
Round 1 Tests
Round 2 Base
Round 2B
Round 2C
Support
Bugs
Support Requests
Patches
Feature Requests

This code has been superceeded as of version 1.6

The SOAP::Domain package provides a wrapper enabling the simple use of Tcl procedures as SOAP methods. The package is designed to operate with the tclhttpd web server but in principal could be converted to another server fairly easily.

As an example of its use enter the following code and save as soap1.tcl in the custom subdirectory of the tclhttp server. (Alternatively source this script into a running server).

package require SOAP::Domain
SOAP::Domain::register -prefix /soap -namespace zsplat::Test

proc zsplat::Test::/square {num} {
    if { [catch {expr $num + 0}] } {
        error "parameter num must be a number"
    }
    return [expr $num * $num]
}

This block of code loads the SOAP server utilities (the SOAP::Domain package) and registers a handler for the /soap URL namespace with the http server. The effect of this is that any URL under /soap will be handled by SOAP::Domain::domain_handler. This procedure examines incoming SOAP requests and attempts to evaluate corresponding procedures in the specified namespace. By specifying a namespace we can isolate the soap procedures from any other procedures defined in the server. If we require an additional level of security we can specify a named slave interpreter rather than a namespace and then define our soap methods within the slave interpreter.

We can test the above server by entering the following script to get a SOAP command in Tcl to use this service.

% package require SOAP
1.4
% SOAP::create square \
           -uri urn:zsplat-Test \
           -proxy http://localhost:8015/soap/square \
           -params {num integer}
::square
% square 8
64

Errors returned by the Tcl procedure are converted into SOAP Fault reply packets. According to the SOAP 1.1 specification the presence of a detail element under the Fault element is indicative of a failure in evaluating the body of the SOAP request. For errors thrown by the evaluated procedure this package generates a Fault packet and places the contents of the global errorInfo variable into the detail element.

To illustrate this, if we evaluate the following in the server

% catch {square Hello} msg
1
% puts "$msg"
SOAP-ENV:Client {parameter num must be a number}
% SOAP::dump square
<?xml version='1.0'?>
<SOAP-ENV:Envelope
  xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsd="http://www.w3.org/1999/XMLSchema">
  <SOAP-ENV:Body>
    <SOAP-ENV:Fault>
      <faultcode>SOAP-ENV:Client</faultcode>
      <faultstring>parameter num must be a number</faultstring>
      <detail>
        <e:errorInfo xmlns:e="urn:TclSOAP-ErrorInfo">
          <errorCode>NONE</errorCode>
          <stackTrace>parameter num must be a number
    while executing
"error "parameter num must be a number""
    (procedure "::zsplat::Test::/square" line 3)
    invoked from within
"::zsplat::Test::/square Hello"
    invoked from within
"interp eval $xmlinterp [list $xmlns] $argValues"</stackTrace>
        </e:errorInfo>
      </detail>
    </SOAP-ENV:Fault>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

As can be seen from the XML data, if an error is raised by the Tcl implementation of the SOAP method then the SOAP::Domain package includes the stack trace (from the global variable errorLevel) as one of the detail elements. This is very useful for debugging such procedures.

$Id: SOAPURLDomain.html,v 1.7 2001/10/11 22:40:37 patthoyts Exp $


XML-RPC URL Domain Package for TclHTTPD

SourceForge Logo

Tcl XML-RPC Server Utility Package

 TclSOAP Logo
Project
Project Page
File Releases
WebPage
Documentation
Forums
Browse CVS
Interop
Round 1 Tests
Round 2 Base
Round 2B
Round 2C
Support
Bugs
Support Requests
Patches
Feature Requests

This code has been superceeded as of version 1.6

The XMLRPC::Domain package provides a wrapper enabling the simple use of Tcl procedures as XML-RPC methods. This package is almost identical to the SOAP::Domain package as can be seen by the following example of the square method, here implemented over XML-RPC instead of SOAP:

package require XMLRPC::Domain
XMLRPC::Domain::register -prefix /rpc -namespace zsplat::RPC

proc zsplat::RPC::/square {num} {
    if { [catch {expr $num + 0}] } {
        error "parameter num must be a number"
    }
    return [expr $num * $num]
}

The only significant difference between the XMLRPC and the SOAP Domain packages is that the XML-RPC version supports a method for providing hints to the framework about the type of the result of the users procedure. Here is an example of a procedure that returns an XML-RPC dateTime.iso8601 result:

package require XMLRPC::TypedVariable

proc zsplat::RPC::/time {} {
    set result [clock format [clock seconds] -format {%Y%m%dT%H:%M:%S}]
    set result [XMLRPC::TypedVariable::create dateTime.iso8601 $result]
    return $result
}
The result here is initially a string formatted in the iso8601 point in time format. As there is no real way for Tcl to distinguish between this string and a non-date string we have to provide a hint so that the XML-RPC reply has the correct type information.

For simple types: int, double, string the framework can guess the correct type. For other types, you will need to return a TypedVariable as the result.

A more significant example of this is a method returning an array:

proc zsplat::RPC::/sort {args} {
    eval set n $args
    set result [lsort $n]
    set result [XMLRPC::TypedVariable::create array $result]
    return $result
}
Here, we are returning an array of sorted elements. The type of each element will have to be guessed by the framework as the elements themselves are not TypedVariables.

XML-RPC supports struct results as well as arrays. This is supported from Tcl as Tcl arrays. The struct element name is set from the array element name.

For more details about writing services look at the SOAP::Domain documentation.

$Id: XMLRPCDomain.html,v 1.3 2001/10/11 22:40:37 patthoyts Exp $


TclX Memory

 Table of Contents

Name

ckalloc, memory, ckfree, Tcl_DisplayMemory, Tcl_InitMemory, Tcl_ValidateAllMemory - Validated memory allocation interface.

Synopsis

memory info

memory trace [on|off]

memory validate [on|off]

memory trace_on_at_malloc nnn

memory break_on_malloc nnn

memory display file

#include <tcl.h>

char *
ckalloc (unsigned size)

void
ckfree (char *ptr)

int
Tcl_DumpActiveMemory (char *fileName);

void
Tcl_ValidateAllMemory (char *file,
int line)

void
Tcl_InitMemory (interp)

Arguments

A pointer to the Tcl interpreter. The filename of the caller of Tcl_ValidateAllMemory. The line number of the caller of Tcl_ValidateAllMemory. File to display list of active memory.

Description

ckalloc
Thi macro allocates memory, in the same manner as malloc, with the following differences: One, ckalloc checks the value returned from malloc (it calls malloc for you) and panics if the allocation request fails. Two, if enabled at compile time, a version of ckalloc with special memory debugging capabilities replaces the normal version of ckalloc, which aids in detecting memory overwrites and leaks (repeated allocations not matched by corresponding frees).

Parameters:
o size - The size of the memory block to be allocated.

Returns:
A pointer to the allocated memory block.

ckfree
This macro frees memory allocated by ckalloc. Like ckalloc, when memory debugging is enabled, ckfree has enhanced capabilities for detecting memory overwrites and leaks.

It is very important that you use ckalloc when you need to allocate memory, and that you use ckfree to free it. Should you use malloc to allocate and ckfree to free, spurious memory validation errors will occur when memory debugging is enabled. Should you use free to free memory allocated by ckalloc, memory corruption will occur when memory debugging is enabled. Any memory that is to be become the property of the Tcl interpreter, such as result space, must be allocated with ckalloc. If it is absolutely necessary for an application to pass back malloced memory to Tcl, it will work only if Tcl is complied with the TCL_MEM_DEBUG flag turned off. If you convert your application to use this facility, it will help you find memory over runs and lost memory. Note that memory allocated by a C library routine requiring freeing should still be freed with free, since it calls malloc rather than ckalloc to do the allocation.

Parmeters:
o ptr - The address of a block to free, as returned by ckalloc.

Tcl_DumpActiveMemory
This function will output a list of all currently allocated memory to the specified file. The following information is outputted for each allocated block of memory: starting and ending addresses (excluding guard zone), size, source file where ckalloc was called to allocate the block and line number in that file. It is especially useful to call Tcl_DumpActiveMemory after the Tcl interpreter has been deleted.

Parameters:
o fileName - The name of the file to output the memory list to.

Tcl_ValidateAllMemory
Forces a validation of the guard zones of all currently allocated blocks of memory. Normally validation of a block occurs when its freed, unless full validation is enabled, in which case validation of all blocks occurs when ckalloc and ckfree are called. This function forces the validation to occur at any point.

Parameters:
o file - The file that this routine is being called from, normally __FILE__.
o line - The line that this routine is being called from, normally __LINE__.

Enabling Memory Debugging

To enable memory debugging, Tcl should be recompiled from scratch with TCL_MEM_DEBUG defined. This will also compile in a non-stub version of Tcl_InitMemory to add the memory command to Tcl.

TCL_MEM_DEBUG must be either left defined for all modules or undefined for all modules that are going to be linked together. If they are not, link errors will occur, with either TclDbCkfree and Tcl_DbCkalloc or Tcl_Ckalloc and Tcl_Ckfree being undefined.

Guard Zones

When memory debugging is enabled, whenever a call to ckalloc is made, slightly more memory than requested is allocated so the memory debugging code can keep track of the allocated memory, and also eight-byte ``guard zones'' are placed in front of and behind the space that will be returned to the caller. (The size of the guard zone is defined by the C #define GUARD_SIZE in base_line/src/ckalloc.c -- it can be extended if you suspect large overwrite problems, at some cost in performance.) A known pattern is written into the guard zones and, on a call to ckfree, the guard zones of the space being freed are checked to see if either zone has been modified in any way. If one has been, the guard bytes and their new contents are identified, and a ``low guard failed'' or ``high guard failed'' message is issued. The ``guard failed'' message includes the address of the memory packet and the file name and line number of the code that called ckfree. This allows you to detect the common sorts of one-off problems, where not enough space was allocated to contain the data written, for example.

the Memory Command

memory options
The Tcl memory command gives the Tcl developer control of Tcl's memory debugging capabilities. The memory command has several suboptions, which are described below. It is only available when Tcl has been compiled with memory debugging enabled.

memory info
Produces a report containing the total allocations and frees since Tcl began, the current packets allocated (the current number of calls to ckalloc not met by a corresponding call to ckfree), the current bytes allocated, and the maximum number of packets and bytes allocated.

memory trace [on|off]
Turns memory tracing on or off. When memory tracing is on, every call to ckalloc causes a line of trace information to be written to stderr, consisting of the word ckalloc, followed by the address returned, the amount of memory allocated, and the C filename and line number of the code performing the allocation, for example...

ckalloc 40e478 98 tclProc.c 1406

Calls to ckfree are traced in the same manner, except that the word ckalloc is replaced by the word ckfree.

memory validate [on|off]
Turns memory validation on or off. When memory validation is enabled, on every call to ckalloc or ckfree, the guard zones are checked for every piece of memory currently in existence that was allocated by ckalloc. This has a large performance impact and should only be used when overwrite problems are strongly suspected. The advantage of enabling memory validation is that a guard zone overwrite can be detected on the first call to ckalloc or ckfree after the overwrite occurred, rather than when the specific memory with the overwritten guard zone(s) is freed, which may occur long after the overwrite occurred.

memory trace_on_at_malloc nnn
Enable memory tracing after nnn ckallocs have been performed. For example, if you enter memory trace_on_at_malloc 100, after the 100th call to ckalloc, memory trace information will begin being displayed for all allocations and frees. Since there can be a lot of memory activity before a problem occurs, judicious use of this option can reduce the slowdown caused by tracing (and the amount of trace information produced), if you can identify a number of allocations that occur before the problem sets in. The current number of memory allocations that have occurred since Tcl started is printed on a guard zone failure.

memory break_on_malloc nnn
After the nnn allocations have been performed, ckallocs output a message to this effect and that it is now attempting to enter the C debugger. Tcl will then issue a SIGINT signal against itself. If you are running Tcl under a C debugger, it should then enter the debugger command mode.

memory display file
Write a list of all currently allocated memory to the specified file.

Debugging Difficult Memory Corruption Problems

Normally, Tcl compiled with memory debugging enabled will make it easy to isolate a corruption problem. Turning on memory validation with the memory command can help isolate difficult problems. If you suspect (or know) that corruption is occurring before the Tcl interpreter comes up far enough for you to issue commands, you can set MEM_VALIDATE define, recompile tclCkalloc.c and rebuild Tcl. This will enable memory validation from the first call to ckalloc, again, at a large performance impact.

If you are desperate and validating memory on every call to ckalloc and ckfree isn't enough, you can explicitly call Tcl_ValidateAllMemory directly at any point. It takes a char * and an int which are normally the filename and line number of the caller, but they can actually be anything you want. Remember to remove the calls after you find the problem.

Keywords

ckalloc, ckfree, free, memory, malloc

Table of Contents

  • Name
  • Synopsis
  • Arguments
  • Description
  • Enabling Memory Debugging
  • Guard Zones
  • the Memory Command
  • Debugging Difficult Memory Corruption Problems
  • Keywords


TclXML

Contents

  • Synopsis
  • Description
  • Commands
    • ::xml::parserclass
      • Command Options
    • ::xml::parser
      • Configuration Options
      • Parser Command
  • Callback Return Codes
  • Application Examples
  • Parser Classes
    • Tcl Parser Class
    • Expat Parser Class
    • Xerces Parser Class
  • Keywords

Name

::xml::parserclass, ::xml::parser — XML parser support for Tcl

Synopsis

package require xml
package require parserclass

package require xml ?2.0?
::xml::parserclass option ?arg arg...?
::xml::parser ?name? ?-option value...?
parser option arg

Tcl Namespace Usage

::xml
::sgml
::xml::tclparser

Description

TclXML provides event-based parsing of XML documents. The application may register callback scripts for certain document features, and when the parser encounters those features while parsing the document the callback is evaluated.

The parser may also perform other functions, such as normalisation, validation and/or entity expansion. Generally, these functions are under the control of configuration options. Whether these functions can be performed at all depends on the parser implementation.

The TclXML package provides a generic interface for use by a Tcl application, along with a low-level interface for use by a parser implementation. Each implementation provides a class of XML parser, and these register themselves using the ::xml::parserclass create command. One of the registered parser classes will be the default parser class.

Loading the package with the generic package require xml command allows the package to automatically determine the default parser class. In order to select a particular parser class as the default, that class' package may be loaded directly, eg. package require expat. In all cases, all available parser classes are registered with the TclXML package, the difference is simply in which one becomes the default.

Commands

::xml::parserclass

The ::xml::parserclass command is used to manage XML parser classes.

Command Options

The following command options may be used:

::xml::parserclass create name ?-createcommand script? ?-createentityparsercommand script? ?-parsecommand script? ?-configurecommand script? ?-getcommand script? ?-deletecommand script?
Creates an XML parser class with the given name.

::xml::parserclass destroy name
Destroys an XML parser class.

::xml::parserclass info names
Returns information about registered XML parser classes.

::xml::parser

The ::xml::parser command creates an XML parser object. The return value of the command is the name of the newly created parser.

The parser scans an XML document's syntactical structure, evaluating callback scripts for each feature found. At the very least the parser will normalise the document and check the document for well-formedness. If the document is not well-formed then the -errorcommand option will be evaluated. Some parser classes may perform additional functions, such as validation. Additional features provided by the various parser classes are described in the section Parser Classes

Parsing is performed synchronously. The command blocks until the entire document has been parsed. Parsing may be terminated by an application callback, see the section Callback Return Codes. Incremental parsing is also supported by using the -final configuration option.

Configuration Options

The ::xml::parser command accepts the following configuration options:

-attlistdeclcommand script

Specifies the prefix of a Tcl command to be evaluated whenever an attribute list declaration is encountered in the DTD subset of an XML document. The command evaluated is:
script name attrname type default value
where:
name | Element type name
attrname | Attribute name being declared
type | Attribute type
default | Attribute default, such as #IMPLIED
value | Default attribute value. Empty string if none given.

-baseurl URI

Specifies the base URI for resolving relative URIs that may be used in the XML document to refer to external entities.

-characterdatacommand script

Specifies the prefix of a Tcl command to be evaluated whenever character data is encountered in the XML document being parsed. The command evaluated is:
script data
where:
data Character data in the document

-commentcommand script

Specifies the prefix of a Tcl command to be evaluated whenever a comment is encountered in the XML document being parsed. The command evaluated is:
script data
where:
data Comment data

-defaultcommand script

Specifies the prefix of a Tcl command to be evaluated when no other callback has been defined for a document feature which has been encountered. The command evaluated is:
script data
where:
data Document data

-defaultexpandinternalentities boolean

Specifies whether entities declared in the internal DTD subset are expanded with their replacement text. If entities are not expanded then the entity references will be reported with no expansion.

-doctypecommand script

Specifies the prefix of a Tcl command to be evaluated when the document type declaration is encountered. The command evaluated is:
script name public system dtd
where:
name | The name of the document element
public | Public identifier for the external DTD subset
system | System identifier for the external DTD subset. Usually a URI.
dtd | The internal DTD subset
See also -startdoctypedeclcommand and -enddoctypedeclcommand.

-elementdeclcommand script

Specifies the prefix of a Tcl command to be evaluated when an element markup declaration is encountered. The command evaluated is:
script name model
where:
name | The element type name
model | Content model specification

-elementendcommand script

Specifies the prefix of a Tcl command to be evaluated when an element end tag is encountered. The command evaluated is:
script name args
where:
name | The element type name that has ended
args | Additional information about this element
Additional information about the element takes the form of configuration options. Possible options are:
-empty boolean | The empty element syntax was used for this element
-namespace uri | The element is in the XML namespace associated with the given URI

-elementstartcommand script

Specifies the prefix of a Tcl command to be evaluated when an element start tag is encountered. The command evaluated is:
script name attlist args
where:
name | The element type name that has started
attlist | A Tcl list containing the attributes for this element. The list of attributes is formatted as pairs of attribute names and their values.
args | Additional information about this element
Additional information about the element takes the form of configuration options. Possible options are:
-empty boolean | The empty element syntax was used for this element
-namespace uri | The element is in the XML namespace associated with the given URI
-namespacedecls list | The start tag included one or more XML Namespace declarations. list is a Tcl list giving the namespaces declared. The list is formatted as pairs of values, the first value is the namespace URI and the second value is the prefix used for the namespace in this document. A default XML namespace declaration will have an empty string for the prefix.

-endcdatasectioncommand script

Specifies the prefix of a Tcl command to be evaluated when end of a CDATA section is encountered. The command is evaluated with no further arguments.

-enddoctypedeclcommand script

Specifies the prefix of a Tcl command to be evaluated when end of the document type declaration is encountered. The command is evaluated with no further arguments.

-entitydeclcommand script

Specifies the prefix of a Tcl command to be evaluated when an entity declaration is encountered. The command evaluated is:
script name args
where:
name | The name of the entity being declared
args | Additional information about the entity declaration. An internal entity shall have a single argument, the replacement text. An external parsed entity shall have two additional arguments, the public and system indentifiers of the external resource. An external unparsed entity shall have three additional arguments, the public and system identifiers followed by the notation name.

-entityreferencecommand script

Specifies the prefix of a Tcl command to be evaluated when an entity reference is encountered. The command evaluated is:
script name
where:
name The name of the entity being referenced

-errorcommand script

Specifies the prefix of a Tcl command to be evaluated when a fatal error is detected. The error may be due to the XML document not being well-formed. In the case of a validating parser class, the error may also be due to the XML document not obeying validity constraints. By default, a callback script is provided which causes an error return code, but an application may supply a script which attempts to continue parsing. The command evaluated is:
script errorcode errormsg
where:
errorcode | A single word description of the error, intended for use by an application
errormsg | A human-readable description of the error

-externalentitycommand script

Specifies the prefix of a Tcl command to be evaluated to resolve an external entity reference. If the parser has been configured to validate the XML document, a default script is supplied that resolves the URI given as the system identifier of the external entity and recursively parses the entity's data. If the parser has been configured as a non-validating parser, then by default external entities are not resolved. This option can be used to override the default behaviour. The command evaluated is:
script name baseuri uri id
where:
name | The Tcl command name of the current parser
baseuri | An absolute URI for the current entity which is to be used to resolve relative URIs
uri | The system identifier of the external entity, usually a URI
id | The public identifier of the external entity. If no public identifier was given in the entity declaration then id will be an empty string.

-final boolean

Specifies whether the XML document being parsed is complete. If the document is to be incrementally parsed then this option will be set to false, and when the last fragment of document is parsed it is set to true. For example,

set parser [::xml::parser -final 0]
$parser parse $data1
.
.
.
$parser parse $data2
.
.
.
$parser configure -final 1
$parser parse $finaldata

-ignorewhitespace boolean

If this option is set to true then spans of character data in the XML document which are composed only of white-space (CR, LF, space, tab) will not be reported to the application. In other words, the data passed to every invocation of the -characterdatacommand script will contain at least one non-white-space character.

-notationdeclcommand script

Specifies the prefix of a Tcl command to be evaluated when a notation declaration is encountered. The command evaluated is:
script name uri
where:
name | The name of the notation
uri | An external identifier for the notation, usually a URI.

-notstandalonecommand script

Specifies the prefix of a Tcl command to be evaluated when the parser determines that the XML document being parsed is not a standalone document.

-paramentityparsing boolean

Controls whether external parameter entities are parsed.

-parameterentitydeclcommand script

Specifies the prefix of a Tcl command to be evaluated when a parameter entity declaration is encountered. The command evaluated is:
script name args
where:
name | The name of the parameter entity
args | For an internal parameter entity there is only one additional argument, the replacement text. For external parameter entities there are two additional arguments, the system and public identifiers respectively.

-parser name

The name of the parser class to instantiate for this parser object. This option may only be specified when the parser instance is created.

-processinginstructioncommand script

Specifies the prefix of a Tcl command to be evaluated when a processing instruction is encountered. The command evaluated is:
script target data
where:
target | The name of the processing instruction target
data | Remaining data from the processing instruction

-reportempty boolean

If this option is enabled then when an element is encountered that uses the special empty element syntax, additional arguments are appended to the -elementstartcommand and -elementendcommand callbacks. The arguments [-empty 1] are appended. For example:
script -empty 1

-startcdatasectioncommand script

Specifies the prefix of a Tcl command to be evaluated when the start of a CDATA section section is encountered. No arguments are appended to the script.

-startdoctypedeclcommand script

Specifies the prefix of a Tcl command to be evaluated at the start of a document type declaration. No arguments are appended to the script.

-unknownencodingcommand script

Specifies the prefix of a Tcl command to be evaluated when a character is encountered with an unknown encoding. This option has not been implemented.

-unparsedentitydeclcommand script

Specifies the prefix of a Tcl command to be evaluated when a declaration is encountered for an unparsed entity. The command evaluated is:
script system public notation
where:
system | The system identifier of the external entity, usually a URI
public | The public identifier of the external entity
notation | The name of the notation for the external entity

-validate boolean

Enables validation of the XML document to be parsed. Any changes to this option are ignored after an XML document has started to be parsed, but the option may be changed after a reset.

-warningcommand script

Specifies the prefix of a Tcl command to be evaluated when a warning condition is detected. A warning condition is where the XML document has not been authored correctly, but is still well-formed and may be valid. For example, the special empty element syntax may be used for an element which has not been declared to have empty content. By default, a callback script is provided which silently ignores the warning. The command evaluated is:
script warningcode warningmsg
where:
warningcode | A single word description of the warning, intended for use by an application
wanringmsg | A human-readable description of the warning

-xmldeclcommand script

Specifies the prefix of a Tcl command to be evaluated when the XML declaration is encountered. The command evaluated is:
script version encoding standalone
where:
version | The version number of the XML specification to which this document purports to conform
encoding | The character encoding of the document
standalone | A boolean declaring whether the document is standalone

Parser Command

The ::xml::parser command creates a new Tcl command with the same name as the parser. This command may be used to invoke various operations on the parser object. It has the following general form:

name option arg

option and the [arg...] determine the exact behaviour of the command. The following commands are possible for parser objects:

name cget -option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the parser object.

name configure -option value...
Modify the configuration options of the parser object. Option may have any of the values accepted by the parser object.

name entityparser option value...
Creates a new parser object. The new object inherits the same configuration options as the parent parser object, but is able to parse XML data in a parsed entity. The option -dtdsubset allows markup declarations to be treated as being in the internal or external DTD subset.

name free name
Frees all resources associated with the parser object. The object is not usable after this command has been invoked.

name get name args
Returns information about the XML document being parsed. Each parser class provides different information, see the documentation for the parser class.

name parse xml args
Parses the XML document. The usual desired effect is for various application callbacks to be evaluated. Other functions will also be performed by the parser class, at the very least this includes checking the XML document for well-formedness.

name reset
Initialises the parser object in preparation for parsing a new XML document.

Callback Return Codes

Every callback script evaluated by a parser may return a return code other than [TCL_OK]. Return codes are interpreted as follows:

break | Suppresses invocation of all further callback scripts. The parse method returns the TCL_OK return code.
continue | Suppresses invocation of further callback scripts until the current element has finished.
error | Suppresses invocation of all further callback scripts. The parse method also returns the TCL_ERROR return code.
default | Any other return code suppresses invocation of all further callback scripts. The parse method returns the same return code.

Application Examples

This script outputs the character data of an XML document read from stdin.

package require xml

proc cdata {data args} {
    puts -nonewline $data
}

set parser [::xml::parser -characterdatacommand cdata]
$parser parse [read stdin]

This script counts the number of elements in an XML document read from stdin.

package require xml

proc EStart {varName name attlist args} {
    upvar #0 $varName var
    incr var
}

set count 0
set parser [::xml::parser -elementstartcommand [list EStart count]]
$parser parse [read stdin]
puts "The XML document contains $count elements"

Parser Classes

This section will discuss how a parser class is implemented

Tcl Parser Class

This section will discuss the pure-Tcl parser class

Expat Parser Class

This section will discuss the Expat parser class

Xerces Parser Class

This section will discuss the Xerces-C parser class

Keywords


tkcon: Limitations

tkcon: Limitations SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages

Limitations:

TkCon requires Tk8.0+. Since TkCon is meant to behave like the original Tk console, it does not separate itself from the environment (it does not use send to function, except when attached to foreign Tk interpreters). This means that it can be can be altered or destroyed by any sourced applications, and it will respond to an application's 'exit' call by exiting (by default, slave consoles will only close themselves instead of exiting the entire TkCon environment). However, the widget tree of TkCon is hidden from the user environment.

Since TkCon is built for cross-platform capability, in Unix/Windows environments it does not have tty/shell behavior. This means programs like vi and less (those that rely on tty/shell settings) will not function appropriately (currently they may hang TkCon). Programs like ls and more will just spit output to the TkCon screen without any special control or formatting (note that ls has been rewritten for TkCon). You also do not get any job (process) control outside of what tcl normally can provide. Currently there is no way to handle stdin input.

When connecting to non-Tcl Tk interpreters (ie - PerlTk, SchemeTk, ...), you must use the syntax of the target environment. See my notes on using other Tk-embedded languages for more info.

© Jeffrey Hobbs


tkcon for Non-Tcl Users

tkcon: Non-Tcl Usage SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages
This document is for those users who are trying to use TkCon with a non-Tcl based Tk language (ie - SchemeTk, PerlTk, PythonTk...).

TkCon requires Tcl/Tk 8.0+ to run. However, it can attach to any language with Tk4+ embedded into it with the use of the Tk 'send' command. I have been able to succesfully talk to SchemeTk-3.0 and Perl/Tk. When using TkCon attached to these interpreters, you must remember to talk to the connected interpreter in its language.

I welcome further comments from users of Tk-embedded languages on their experiences or ideas. Of course, you can always try to port TkCon in full to your language. I'd like to see the results from any such efforts.

Special Language Notes:

Perl Tk

Read the man page on Perl/Tk's send command. You have to define Tk::Receive before it will work. Stephen Lidie (lusol@Turkey.CC.Lehigh.EDU) contributed a companion Perl/Tk program that does the trick with some extras.
© Jeffrey Hobbs


#!/usr/local/bin/perl -w

# tkcon.pl - a Perl/Tk	"shell" companion for tkcon.tcl.
#
# Variable $MW is an object reference to the main window, from which you can
# create and manipulate child widgets.	Variable names beginning with an
# underscore are reserved for this application.
#
# Stephen O. Lidie, 96/08/25

require 5.002;
use English;
use Tk;
use Tk::Pretty qw(Pretty);
use Tk::Dialog;
use strict;
use subs qw(doit tkcon);
my($MW, $_TKCON, $_VERSION, $_HELP, $_SHELL, $_TAB, $_PARA, @_ERRORS, $_MES);

tkcon;				# main

sub doit {

    # Eval some code without use strict constraints.

    my($code) = @ARG;

    {
    no strict;
    if ($_MES) {
        $_MES->packForget;
        $_MES->destroy;
        $_MES = 0;
    }
    @_ERRORS = ();
    $SIG{'__WARN__'} = sub {push @_ERRORS, @ARG};
    my $_res = eval $code;
    push @_ERRORS, $EVAL_ERROR if $EVAL_ERROR;
    push @_ERRORS, $_res;
    }

} # end doit

sub tkcon {

    # Nothing fancy here, just create the main window and the help dialog
    # object, and display a pointer to the help.

    $_TKCON = 'tkcon.pl';
    $_VERSION = '0.2';
    $_SHELL = '/bin/sh';
    $_SHELL = $ENV{'SHELL'} if $ENV{'SHELL'};
    $_TAB = 0;
    $_PARA = '';

    $MW = MainWindow->new;
    $MW->title($_TKCON);
    $MW->iconname($_TKCON);
    $_HELP = $MW->Dialog(
    -title	    => "$_TKCON Help",
    -font	    => 'fixed',
    -wraplength => '6i',
    -justify    => 'left',
    -text	    =>
        "?	  - this text.\n" .
        "|	  - pass arguments to your shell (default /bin/sh).\n" .
        "p	  - use Tk::Pretty to \"pretty-print\" arguments.\n" .
        "+	  - a tab starts/stops multiline input mode.\n" .
        "exit - quit $_TKCON.\n" .
        "\nOther input is assumed to be a Perl/Tk command.\n" .
        "\n\$MW is the MainWindow.\n",
             );
    $_HELP->configure(-foreground => 'blue');
    $_MES = $MW->Label(-text => "\nEnter ? for help.\n")->pack;
    MainLoop;

} # end tkcon

sub Tk::Receive {

    shift();
    $ARG = shift();
    if (/^\?(.*)/) {		# help
    $_HELP->Show;
    } elsif (/^\|(.*)/) {	# bang
    @_ERRORS = ();
    push @_ERRORS, `$_SHELL -c $1 2>&1`;
    } elsif (/^\+$/) {
    $_TAB++;
    if ($_TAB % 2) {
        @_ERRORS = ();
        $_PARA = '';
        push @_ERRORS, '+';
    } else {
        doit $_PARA;
    }
    } else {			# Perl/Tk command
    $ARG = "Pretty($1)" if (/^p\s(.*)$/);
    if ($_TAB % 2) {
        $_PARA .= $ARG;
        push @_ERRORS, '+';
    } else {
        doit $ARG;
    }
    } # ifend

    return @_ERRORS;

} # end Tk::Receive


tkcon: Tcl Plugin Stripped Demo

tkcon Documentation (May 2001) SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages

This is the full tkcon script when run inside the plugin. It feels like a stripped down version of tkcon, but the only limitations are those established by the plugin. You can test the basic console features and get a feel for the mutli-color output. Below the demo are some ideas to try out. v2 of the plugin is distributed with a megawidget version of tkcon for debugging tclets. The demo below uses rev 1.28 of tkcon in CVS (this correlates to v2.1 of tkcon).

Have a look at some of the features: (culled from the tkcon documentation)
  • Variable / Path / Procedure Name Expansion. Type in set tc at the prompt. Hit <Control-Shift-V>. set tcl_ should now be visible. Hit <Control-Shift-V> again. You should see the rest of the completions printed out for you. Works the same for procedures and files paths (file access restricted from plugin). Works properly when spaces or other funny characters are including in the name.
  • Command Highlighting. Note that set should be in green, denoting it is a recognized command in that interpreter.
  • Electric Character Matching. Watch while you type the following: proc foo { a b } { puts [list $a $b] }. Did you notice the blink matching of the braces? Yes, it's smart.
  • Command History. Use the Up/Down arrows or <Control-p>/<Control-n> to peruse the command history. <Control-r>/<Control-s> Actually does command history matching (like tcsh or other advanced Unix shells).
  • Useful Colorization. Having defined foo above, type in foo hey. Note that the error comes back in red. Go up one in the command history and add you and see that regular stdout output comes through in blue (the colors are configurable).
  • Cut/Copy/Paste. You should be able to do that between outside windows and TkCon. The default keys are <Control-x>/<Control-c>/<Control-v>.
© Jeffrey Hobbs


tkcon: Purpose & Features

tkcon: Purpose & Features SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages

Purpose:

tkcon is a replacement for the standard console that comes with Tk (on Windows/Mac, but also works on Unix). The console itself provides many more features than the standard console. tkcon works on all platforms where Tcl/Tk is available. It is meant primarily to aid one when working with the little details inside tcl and tk, giving Unix users the GUI console provided by default in the Mac and Windows Tk. It's also not a bad replacement for the default MS-DOS shell (although it needs lots of fine tuning).

See Limitations for a good idea of what tkcon can't do for you.

Features:

Just in case you don't run across them while playing, here are some of the extras in tkcon:
  • Command history
  • Path (Unix style) / Proc / Variable name expansion
  • Multiple consoles, each with its own state (via multiple interpreters)
  • Captures stdout and stderr to console window
  • Electric character matching (a la emacs)
  • Electric proc highlighting
  • Enhanced history searching
  • Configurable
  • Cut / Copy / Paste between windows
  • Communication between consoles and other Tk interpreters (including non-tcl ones)
  • Hot Errors (click on error result to see stack trace)
  • Works on all Tk platforms
Read the documentation for how to take advantage of these features.
© Jeffrey Hobbs


tkcon: To Do Ideas

tkcon: To Do Ideas SourceForge Logo
Documentation | Purpose & Features | Limitations | To Do | License
Online Demo (requires Tk plugin) |  | Using TkCon with other Tk Languages

Future Ideas

  • Add encoding auto-conversion to exec commands
  • keep history file, also keep history of sourced files
  • set mimetype(extension,au) "audio/u-law"
set mimetype(extension,wav) "audio/wave"
set mimetype(extension,mid) "audio/midi"
/etc/magic
proc run {file} {
    global mimetype

    if {[file executable $file]} {
        exec $file
        return
    }

    catch {set mimetype $mimetype(extension,[file extension $file])}

    if {![info exists mimetype]} {
        set mimetype $mimetype(magic,[exec /bin/file $file])
    }

    exec $mimetype(application,$mimetype) $file
}
  • Add socket level communication model
  • Enhance the true debugging capabilities - I'm looking at tcl-debug and into what I can adopt from the tkInspect philosophy.
  • I'm taking ideas...

Known Bugs/Quirks

  • Command highlighting isn't perfect because I try to make it too efficient.
  • All interpreters have the same current working directory. This is a limitation of tcl.
  • You can't 'attach' on machines where send does not exist. John Loverso has a comm.tcl replacement. In any case, you can still attach to internal interpreters and namespaces.
  • Need to clean up checkpointed states when the associated interp dies. Works with slaves, but not foreign interps.
  • Can't identify non-Tcl or pre-Tk4 interpreters automagically...
  • You tell me...
© Jeffrey Hobbs


Interface Specification For The HTML Widget

This is a draft interface specification for the Tk HTML widget currently under development. Since it is still a draft, it is subject to change. Eventually, the interface will stabilize and this interface specification will morph into a manual page.

Configuration Options

-appletcommand

This option specifies the name of the Tcl procedure to invoke when the <applet>...</applet> tag sequence is seen. The html widget will append two arguments to the procedure before calling it. The first argument is the name of a widget that the callback should create to hold the applet. The second argument is a list of name/value pairs which are the arguments to the <applet> tag.

The text between <applet> and </applet> is normally suppressed. However, if the -appletcommand option is set to the empty string, the <applet> tag is ignored and all text between <applet> and </applet> is displayed normally.

"<embed>" is treated as an alias for "<applet></applet>".

-background

The background color for the widget.

Note that the <body bgcolor=...> HTML tag does not automatically cause the widget to change its background color. If you want the background color to change in response to this HTML tag, then your Tcl script should intercept the <body> tag using the ``token handler'' widget command (described below) and change the background color manually.

-base

The base URI for the current document. This should be set to the URI that was used to retrieve the document before parsing begins.

-bd | An alias for -borderwidth
-bg | An alias for -background
-borderwidth

The width of the 3-D border drawn around the parameter of the widget, in pixels.

-cursor

The cursor displayed when the pointer is positioned over the HTML widget. If {}, the cursor reverts to its default shape.

-exportselection
-fontcommand

The name of a TCL procedure that is used to convert HTML font names into TCL font names. A default built-in procedure is used if the value of this option is {}.

When the HTML widget needs a new font, it calls this procedure with two arguments. This first argument is the font size expressed as an integer between 1 and 7. The standard size is 4. The second argument is a set of between 0 and 3 keywords drawn from the following set: "bold", "italic", and "fixed". If the "bold" keyword is present in the second argument, the font returned should be bold. If the "italic" keyword is present, the font should be italic. If the "fixed" keyword is present, the font should be fixed-width. The TCL procedure should return the name of the TCL font that the HTML widget will use to render the given HTML font. If the TCL procedure returns an empty string, then the built-in default procedure is used to determine the font.

Examples: This is {4 {}}. This is {4 fixed}. This is {3 {}}. This is {5 {fixed bold}}

-fg | An alias for -foreground.
-foreground | The default foreground color in which HTML text is rendered. The HTML can override this using the color=... attribute on various HTML tags.
-formcommand string Declares a handler for everything to do with forms within a document. Arguments will be appended to string and the result evaluated during parsing (for form creation) and when the widget is cleared (for form cleanup). The first argument is a token for identifying a form. The second argument selects the action to perform. The remaining arguments depend on the action, as follows.
string token form URL method attrs
The handler should begin taking notes for form token, especially the (resolved) URL of the action and the method to be applied. The raw attributes of the FORM element are in the pairlist attrs.
string token flush
When the document is cleared, the widget will destroy all the windows it requested. This handler should clean up anything else it created for that form.
string token input path attrs
The handler should create a window named path appropriate for the element described by the attrs. The widget will map the window into its rendering appropriately.

It is not an error for the handler to return without creating such a window (it's natural in the case of type=hidden); the widget simply ignores the element in that case. The attributes are the raw values in the HTML, with one exception; a src will be resolved before the handler is called.

string token textarea path attrs initial
The handler should create a window (a single Text, or a Frame with Text and Scrollbars, or whatever) appropriate for a <textarea> and initialise it to the initial string.
string token select path attrs choices initial
<select> is quite a complicated case... The handler should create a window appropriate for a <select> of the given attributes and present the list of choices. Each choice is a pair, the value and its label. initial is a list of values initially selected. This approach is somewhat questionable but should do most of the time.
Caution: Be very careful to avoid confusing HTML variables with TCL variables. It may be tempting to use the name attribute fairly directly to link together related widgets, but it will likely cause incorrect behaviours. Also be careful to observe the order in which the elements are created; this determines the order in which they must be submitted. A default form handler with the correct bahaviour written in TCL will be bundled with the widget.

The attribute names will be downcased within attrs.

-framecommand | The script specified by this option is invoked when the HTML parser encounters a <frameset>...</frameset> tag sequence. The arguments to the script are TBD. If the value of the option is the empty string, then the text within the <noframe>...</noframe> tag sequence is displayed.
-height | Specifies the height of the area into which HTML is rendered. This value plus twice the -padx, -borderwidth and -highlightthickness values is the total height of the widget.
-highlightbackground
-highlightcolor
-highlightthickness
-hyperlinkcommand | The script specified by this option is invoked whenever the user clicks on a hyperlink on the HTML page. Before invoking this script, the URI for the hyperlink is appended.
-imagecommand When a ``<img src=...>'' tag is encountered, the HTML widget invokes the script specified by this option in order to get the name of a Tk image object to display the HTML image. Before invoking the script, the following arguments are appended:
  1. The value of the src=... parameter after have been processed by the resolver.
  2. The value of the width=... parameter.
  3. The value of the height=... parameter.
  4. A list containing the names and values of all parameters.
If the name returned by this script is the empty string, or if the script is an empty string, then the HTML widget displays the alt=... text of the <img> tag instead of an image.
-bgimagecommand When a ``<table background=...>'' tag is encountered, the HTML widget invokes the script specified by this option in order to get the name of a Tk image object to display as the background for the table. Similarly for TD, TH, and TR. Before invoking the script, the following arguments are appended:
  1. The value of the background=... parameter after have been processed by the resolver.
  2. The token id (TID) of the table, row or col markup tag.
The image name to use for the background can may be returned. Or if the return value is empty. the user can set the background image when available via the bgimage command with the tokenid.
-isvisitedcommand | When the HTML widget encounters a hyperlink (``<a href=...>'') it invokes the script specified by this option in order to determine whether or not the hyperlink has been visited. This information is needed to determine what color to use to display the hyperlink.
-padx | The amount of extra space to insert between the 3-D border and the left and right sides of the document text.
-pady | The amount of extra space to insert between the 3-D border and the top and bottom of the document text.
-relief | The relief used to draw the 3-D border.
-resolvercommand

The name of a TCL command used to resolve URIs. If blank, a built-in resolver is used. If a TCL command is specified but it returns an empty string, the built-in resolver is used then too. The build-in resolver is based on the algorithm in section 5.2 of RFC 2396.

Multiple URIs are appended to the TCL command before it is executed. The first URI is the BASE URI of the document (the URL that specified by the -base configuration option and updated according to any prior <BASE> markup). Zero or more additional URIs are appended to this base. The result of the script should be the resolution of the whole series or URIs.

-rulerelief

Determines the appearance of the Horizontal Rule (<HR>) markup. The default is "sunken". This can also be "raised" or "flat". If "flat", then the <HR> is drawn using a solid line in the current foreground color. "groove" and "ridge" are the same as "flat".

-scriptcommand

Whenever <SCRIPT>...</SCRIPT> markup is encountered in the input HTML, the line number, the attributes of the <SCRIPT> markup and the body of the script are appended to this string and the result is executed as a TCL command. If this options is the empty string, then the script is ignored.

-selectioncolor | The background color used when drawing the selection. The foreground color for the selection is the same as the regular foreground color.
-tablerelief

Determines the appearance of the borders around tables. The default is "raised". This can also be "sunken" or "flat". If "flat", then the borders is drawn using solid lines in the current foreground color. "groove" and "ridge" are the same as "flat".

-takefocus
-unvisitedcolor | The foreground color used to draw hyperlinks that have not been visited.
-underlinehyperlinks | Set to TRUE to cause hyperlinks to be drawn using an underlined font.
-visitedcolor | The foreground color used to draw hyperlinks that have been visited.
-width | The width of the document text. This value does not include space allocated for -highlightthickness, -borderwiddth or -padx.
-xscrollcommand
-yscrollcommand

Indices

Internally, the HTML widget stores the HTML document as a list of tokens. Each token is either
  • a contiguous sequence of non-space characters (Text),
  • a contiguous sequence of spaces, tabs or newlines (Space),
  • or an HTML markup tag (such as ``<em>''.)
Tokens are identified by number. The first token is ``1'', the second is ``2'' and so forth. So in its simplest form, an index is just an integer greater than 0.

Within a single Text or Space token, individual characters are also identified by number, though the counting starts with 0 instead of 1. The character number is connected to the token number by a period. So, for example, the 4th character in the 9th token would be ``9.3''.

Two integers separated by a dot is called the connonical form of an index. Other index forms are available, including:
end | The keyword ``end'' means one character past the last character of the last token.
last | The keyword ``last'' means the last character of the last token.
@X,Y | The character located at screen coordinates X,Y.
&DOM | The element matching the given DOM address. eg. ``tables(1).rows(3)''.
*.last | The second integer can be replaced by the keyword ``last'' to mean the last character in the token.
sel.first | This is the first character that is part of the selection.
sel.last | This is the last character that is part of the selection.
insert | The character immediately following the insertion cursor.

Commands

html window ?options ...?

Create a new HTML widget instance named windows

html reformat from to text

Convert text from one encoding to another. The text is given in the text argument. The current encoding of the text is specified by the from argument. This command returns the same text in the to encoding.

From and to may be any of the following values:

plain | Ordinary text with no characters escaped.
http | The text is encoded in a form suitable for use with the HTTP protocol. Spaces are converted to "+". Special characters and escaped as "%aa" where "a" is a hexadecimal digit. A special character is anything other than an alphanumeric or one of these: ".", "$", "-", or "_".
url | The text is encoded in a form suitable for use as a URI. Spaces are converted to "+". Special characters and escaped as "%aa" where "a" is a hexadecimal digit. A special character is anything other than an alphanumeric or one of these: ".", "$", "-", "_", or "/".
html | The text is encoded in a form suitable for use within HTML. "&" is encoded as "&amp;", "<" is encoded as "&lt;" and so forth.

This command is intended to be useful to the TCL procedures that implement callbacks for the HTML widget.

html uri join scheme authority path query fragment

This command takes the five main components of a URI and joins them together into a complete URI. Special characters in any component are escaped.

html uri split uri

This command takes a single URI and splits it into its five major components: scheme, authorithy, path, query and fragement. The command returns a list where each component is an element of the list. Components missing from the URI are represented as empty elements in the list.

Widget Commands

WIDGET bgimage IMAGE ?TID?

Set IMAGE to be the background image. TID, if supplied, is the token id of a TABLE, TD, TH or TR. If TID is ommitted, it is the background image for the whole page.

WIDGET cget config-option

Return the value of a configuration option. Works just like any other Tk widget.

WIDGET clear

Remove all tokens and text from the HTML widget. The parser is reset to its initial state. This routine should be called to changes pages.

WIDGET configure ?args...?

The standard Tk configuration command.

WIDGET coords ?INDEX ?percent??

Return the screen coordinates of INDEX.

WIDGET forminfo INDEX

Return forminfo for given INDEX.

WIDGET href X Y

If the coordinates X Y define a point above a hyperlink, then this command will return the target URL for that hyperlink. The URL will be resolved using the -resolvercommand before it is returned.

WIDGET imageadd ID IMAGE

Add a single image onto animated image list.

WIDGET imageat X Y

If the coordinates X Y define a point above an image, then this command will return the Token Id for that image.

WIDGET images

Return the list of animated images.

WIDGET imageset ID NUM

For animated gifs, set image number NUM to be the current image. This is only used for buffered animations.

WIDGET imageupdate ID IMAGES

When an Animated gif comes in, this allows changing the current image into multiple images.

WIDGET index INDEX ?COUNT UNITS?

Translates INDEX into its connonical form. The connonical form of an index is two integers separated by a period.

The optional 3rd and 4th arguments specify a displacement from INDEX to the value of the index returned. COUNT can be any integer value, including a negative number. UNITS must be either ``char'' or ``line''.

WIDGET insert INDEX

Causes the insertion cursor (a flashing vertical bar) to be positioned immediately before the character specified by INDEX.

WIDGET names

This command causes the widget to scan the entire text of the document looking for tags of the form ``<a name=...>''. It returns a list of values of the name=... fields.

The vertical position of the document can be moved to any of these names using the ``WIDGET yview NAME'' command described below.

WIDGET onscreen ID X Y

Return 1 if ID is onscreen (visible).

WIDGET over X Y ?-muponly?

Return a list of TIDS where the coordinates X Y define a point above objects. If -muponly, give only markup elements.

WIDGET overattr X Y ATTRS

Like over but returns markup containing one or more of the attributes in the list ATTRS. ATTRS.

WIDGET parse HTML-TEXT

Adds the given HTML text to the end of any text previously received through the parse command and parses as much of the text as possible into tokens. Afterwards, the display is updated to show the new tokens, if they are visible.

WIDGET resolver ?uri ...?

The resolver specified by the -resolvercommand option is called with the base URI of the document followed by the remaining arguments to this commant. The result of this command is the result of the -resolvercommand script.

WIDGET selection subcommand args...

The selection widget command is used to control the selection.

WIDGET selection clear

Clear the current selection. No text will be selected after this command executes.

WIDGET selection set START END

Change the selection to be all text contained within the given indices.

WIDGET refresh options

Cause a relayout and redraw. Useful after a token insert or update. Valid options are zero or more of: images, resize, focus, text, border, extend, clipwin,, styler, animate, vscroll, hscroll, gotfocus, layout. The default is layout. You may abreviate options with the first letter.

WIDGET source

Return the html source for the current page.

WIDGET text subcommand args...

There are several token commands. They all have the common property that they directly manipulate the text that is displayed. These commands can be used to build an WYSIWYG editor for HTML.

WIDGET text ascii INDEX-1 INDEX-2

Returns plain ASCII text that represents all characters between INDEX-1 and INDEX-2. Formatting tags are omitted. The INDEX-1 character is included by INDEX-2 is omitted.

WIDGET text delete INDEX-1 INDEX-2

All text from INDEX-1 up to, but not including INDEX-2 is removed and the display is updated accordingly.

WIDGET text html INDEX-1 INDEX-2

Returns HTML text that represents all characters and formatting tags between INDEX-1 and INDEX-2. The INDEX-1 character is included by INDEX-2 is omitted.

WIDGET text insert INDEX TEXT

Inserts one or more characters immediately before the character whose index is given. The insertion cursor is updated.

WIDGET text break INDEX

Break the text token at index into two text tokens.

WIDGET text find TEXT ?nocase? ?before|after INDEX?

Find text. If index is given, start search from there. If before, search backwards. nocase will ignore case.

WIDGET token subcommand args...

There are several token commands. They all have the common property that they involve the list of tokens into which the HTML is parsed.

Some of the following subcommands make use of indices. The character number of these indices is ignored since these commands deal only with whole tokens.

WIDGET token append TAG ARGUMENTS

The command causes a token to be appended to the current list of tokens in the HTML widget. This command is typically used within a token handler.

WIDGET token delete INDEX ?INDEX-2?

Deletes the single token indentified by the index. If a second index is given, the range of tokens from the first to the second index inclusive is deleted.

WIDGET token find TAG ?before|after|near INDEX?

Locates all tokens with the given TAG and returns them all as a list. Each element of the returned list is a sublist containing the index for the token and the arguments for the token.

WIDGET token get INDEX ?INDEX-2?

Returns a list of tokens in the range of INDEX through INDEX-2. Each element of the list consists of the token tag followed by the token arguments.

WIDGET token list INDEX INDEX-2?

The same as token get, but has the token id as the first item in each list element.

WIDGET token markup INDEX INDEX-2?

The same as token list, but ignores space and text.

WIDGET token domtokens INDEX INDEX-2?

The same as token domtokens, but ignores all non-DOM tokens.

WIDGET token getend INDEX

Given a start token, find the matching end token.

WIDGET token offset START NUM1 NUM2

Hard to describe, but used as follows: when you extract text, and do a regex on it, with -indices, you need to convert these offsets back into INDEXES. This returns those begin and end anchor.

WIDGET token attr INDEX ?NAME ?VALUE??

Allow get or set a tokens attribute(s). Getting non-existent attr returns an empty string.

WIDGET token handler TAG ?SCRIPT?

This command allows special processing to occur for selected tokens in the HTML input stream. The TAG argument is either ``Text'' or ``Space'' or the name of an HTML tag (ex: ``H3'' or ``/A''). If a non-empty script is specified for a particular tag, then when instances of that tag are encountered by the parser, the parser calls the corresponding script instead of appending the token to the end of the token list. Before calling the script, three arguments are appended:
  1. The token number.
  2. The tag. (ex: H3)
  3. A list of name/value pairs describing all arguments to the tag.
An empty handler script causes the default processing to occur for the tag. If the script argument is omitted all together, then the current value of the token handler for the given tag is returned.

Only one handler may be defined for each token type. If a new handler is specified for a token type that previously had a different handler defined, then the old handler is overwritten by the new.

WIDGET token insert INDEX TAG ARGUMENTS

Inserts a single token given by TAG and ARGUMENTS into the token list immediately before INDEX. if index is after end of a text token, inserts after token. The insertion cursor is updated.

WIDGET token attrs ATTRLIST ?INDEX ?INDEX? ?

Find all tags that contain an attr named in input list. Return TIDs.

WIDGET token onEvents ?INDEX ?INDEX? ?

Look for all the onSubmit, onMouseover, etc attributes. returns list of: Event TID Event TID...

WIDGET token unique TAG ?INDEX ?INDEX? ?

For the given tag, return all known unique attribute names for the tag.

WIDGET dom subcommand args...

There are several dom commands. In all the following, DOMSPEC is a DOM style address. eg. TABLE(1).ROW(2). The Token Id is returned for that element in the page.
WIDGET dom nameidx TAG NAME

Convert a named markup to it's array position. ie. TABLE foo might translate to TABLE[2] returning the integer index 2.

WIDGET dom radioidx TAG NAME

Translate a radio input items array index to a form item index.

WIDGET dom id DOMSPEC

Given a DOMSPEC, return the TID. Obsolete, use ``index &DOMSPEC''.

WIDGET dom ids DOMSPEC

Like above, but returns both begin and end TID.

WIDGET dom value DOMSPEC

Like dom id, but returns the attributes rather than the TID. Obsolete. Should now use: token attr &DOMSPEC.

WIDGET dom addr INDEX

Given an index, return the best guess of the DOM address. eg. TABLES(2).ROWS(1)

WIDGET dom formel NNAME

For the forms(N), return the form element with name NAME.

WIDGET dom tree INDEX VALUE

Return the HTML Doc as one big DOM tree list. Not fully implemented.

WIDGET xview args...

Used to control horizontal scrolling.

WIDGET xview

Returns a list containing two elements. The elements are a fractions between 0.0 and 1.0 that define the position of the left and right edges of the visible part of the document as a fraction of the whole.

WIDGET xview moveto FRACTION

Adjusts the horizontal position of the document so that FRACTION of the horizontal span of the document is off-screen to the left.

WIDGET xview scroll  NUMBER  WHAT

Shifts the view in the window left or right according to NUMBER and WHAT.   NUMBER is an integer and WHAT is either units or pages.

WIDGET  yview  args...

Used to control the vertical position of the document.

WIDGET  yview

Returns a list containing two elements. The elements are a fractions between 0.0 and 1.0 that define the position of the top and bottom edges of the visible part of the document as a fraction of the whole.

WIDGET  yview  NAME

Adjusts the vertical position of the document so that the tag ``<a name=NAME>'' is on screen, and preferably near the top of the screen.

WIDGET  yview moveto  FRACTION

Adjusts the horizontal position of the document so that FRACTION of the vertical span of the document is off-screen above the visible region.

WIDGET  xview scroll  NUMBER  WHAT

Shifts the view in the window up or down according to NUMBER and WHAT.   NUMBER is an integer and WHAT is either units or pages.