tkbook

Upload: nanostallmann

Post on 10-Oct-2015

19 views

Category:

Documents


0 download

DESCRIPTION

tcl tk book

TRANSCRIPT

  • Practical Programmingin Tcl and Tk

    Brent Welch

    DRAFT, January 13, 1995

    Updated for Tcl 7.4 and Tk 4.0THIS IS NOT THE PUBLISHED TEXT

    THE INDEX IS INCOMPLETESOME SECTIONS ARE MISSING

    THE MANUSCIRPT HAS NOT BEEN EDITED

    GET THE REAL BOOK: ISBN 0-13-182007-9

  • An enhanced version of this text has been published byPrentice Hall: ISBN 0-13-182007-9

    Send comments via email to

    [email protected] the word book in the subject.

    http://www.sunlabs.com/~bwelch/book/index.html

    The book is under copyright. Print for personal use only.

    This on-line DRAFT is available curtesty the kind folks at PH.

  • Table of Contents

    Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    1. Tcl Fundamentals ............................................. 1Getting Started ............................................................1Tcl Commands .............................................................2Hello World ..................................................................3Variables ......................................................................3Command Substitution ................................................4Math Expressions ........................................................4Backslash Substitution ................................................6Double Quotes .............................................................7Procedures ...................................................................7A While Loop Example ..................................................8Grouping And Command Substitution .......................10More About Variable Substitution ..............................11Substitution And Grouping Summary ........................11Fine Points .................................................................12Comments .................................................................13Command Line Arguments .........................................13Reference ...................................................................14

    Backslash Sequences ...........................................14Arithmetic Operators ...........................................14Built-in Math Functions ......................................15Core Tcl Commands .............................................15Predefined Variables ............................................18

    2. Strings and Pattern Matching ......................... 19The string Command ..................................................19Strings And Expresssions ...........................................20The append Command ...............................................21The format Command ................................................21The scan Command ...................................................23String Matching .........................................................24Regular Expressions ..................................................25The regexp Command ................................................26The regsub Command ................................................28

  • Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    ii

    3. Tcl Data Structures .........................................29More About Variables .................................................29

    The unset command ............................................30Using info to find out about variables ...................30

    Tcl Lists .....................................................................31Constructing Lists: list, lappend, and concat ..............32Getting List Elements: llength, lindex, and lrange .......33Modifying Lists: linsert and lreplace ...........................34Searching Lists: lsearch .............................................34Sorting Lists: lsort ......................................................35The split And join Commands ....................................35Arrays ........................................................................36The array Command ..................................................37Environment Variables ...............................................38Tracing Variable Values .............................................39

    4. Control Flow Commands .................................41If Then Else ................................................................42Switch ........................................................................43Foreach ......................................................................44While .........................................................................45For .............................................................................46Break And Continue ...................................................46Catch .........................................................................46Error ..........................................................................48Return .......................................................................49

    5. Procedures and Scope .....................................51The proc Command ....................................................51Changing command names with rename ....................52Scope .........................................................................53The global Command .................................................53Use Arrays for Global State ........................................55Call By Name Using upvar ..........................................55

    Passing arrays by name .......................................56The uplevel Command ................................................57

    6. Eval ................................................................59Eval And List .............................................................59

  • iii

    Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    Eval And Concat ........................................................61Double-quotes and eval .......................................62

    Commands That Concat Their Arguments ..................62The subst Command ..................................................63

    7. Working with UNIX ......................................... 65Running Unix Programs With exec .............................65

    auto_noexec .........................................................67Looking At The File System ........................................67Input/Output ............................................................70Opening Files For I/O ................................................70Reading And Writing ..................................................72

    The puts and gets commands ..............................72The read command ..............................................73Random access I/O .............................................73Closing I/O streams .............................................74

    The Current Directory - cd And pwd ...........................74Matching File Names With glob ..................................74The exit And pid commands .......................................75

    8. Reflection and Debugging ............................... 77The info Command .....................................................77

    Variables .............................................................78Procedures ...........................................................79The call stack ......................................................79Command evaluation ...........................................80Scripts and the library .........................................80Version numbers .................................................80

    Interactive Command History .....................................81History syntax .....................................................82A comparision to /bin/csh history syntax ............82

    Debugging ..................................................................83Don Libes debugger ...................................................84

    Breakpoints by pattern matching .........................85Deleting break points ...........................................86

    The tkerror Command ................................................87The tkinspect Program ...............................................87Performance Tuning ...................................................87

  • Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    iv

    9. Script Libraries ...............................................89The unknown Command ............................................89The tclIndex File .........................................................90Using A Library: auto_path .........................................90

    Disabling the library facility: auto_noload ............91How Auto Loading Works ...........................................91Interactive Conveniences ............................................92

    Auto Execute .......................................................92History .................................................................92Abbreviations .......................................................92

    Tcl Shell Library Environment ....................................93Coding Style ...............................................................93

    A module prefix for procedure names ...................94A global array for state variables ..........................94

    10. Tk Fundamentals ..........................................95Hello World In Tk .......................................................96Naming Tk Widgets ....................................................98Configuring Tk Widgets ..............................................98About The Tk Man Pages ............................................99Summary Of The Tk Commands .................................99

    11. Tk by Example ............................................103ExecLog ...................................................................103

    Window title .......................................................105A frame for buttons, etc. ....................................105Command buttons .............................................106A label and an entry ...........................................106Key bindings and focus ......................................106A resizable text and scrollbar .............................107The Run proc .....................................................107The Log procedure .............................................108The Stop procedure ............................................108

    The Example Browser ..............................................109More about resizing windows .............................110Managing global state ........................................111Searching through files ......................................111Cascaded menus ................................................112The Browse proc ................................................112

  • vCreated: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    A Tcl Shell ................................................................113Naming issues ................................................... 114Text marks and bindings ................................... 114

    12. The Pack Geometry Manager ....................... 115Packing towards a side ............................................. 116

    Shrinking frames and pack propagate ................ 116Horizontal And Vertical Stacking .............................. 117The Cavity Model ..................................................... 118Packing Space and Display Space ............................ 119

    The -fill option ................................................... 119Internal padding with -ipadx and -ipady ............ 120External padding with -padx and -pady ............. 123

    Expand And Resizing ............................................... 123Anchoring ................................................................125Packing Order .......................................................... 126

    pack slaves and pack info .................................. 127Pack the scrollbar first ....................................... 127

    Choosing The Parent For Packing ............................. 128Unpacking a Widget ................................................. 129Packer Summary ...................................................... 129The pack Command ................................................. 130The Place Geometry Manager ................................... 130

    The place Command .......................................... 131Window Stacking Order ............................................ 132

    13. Binding Commands to X Events .................. 133The bind Command .................................................. 133All, Class, And Widget Bindings ............................... 134

    The bindtags command ...................................... 135break and continue in bindings ......................... 135A note about bindings in earlier versions of Tk ... 135

    Event Syntax ........................................................... 136Key Events ............................................................... 137Button Events .......................................................... 138Other Events ............................................................ 138Modifiers ..................................................................139

    Events in Tk 3.6 and earlier ............................... 141Event Sequences ...................................................... 141

  • Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    vi

    Event Keywords .......................................................142

    14. Buttons and Menus .....................................145Button Commands and Scope Issues .......................145Buttons Associated with Tcl Variables ......................149Button Attributes .....................................................151Button Operations ...................................................153Menus and Menubuttons .........................................153Manipulating Menus and Menu Entries ....................155A Menu by Name Package ........................................156Popup Menus and Option Menus .............................159Keyboard Traversal ..................................................159Menu Attributes .......................................................160

    15. Simple Tk Widgets .......................................163Frames and Top-Level Windows ...............................163

    Attributes for frames and toplevels .....................164The label Widget .......................................................165

    Label attributes .................................................166Label width and wrapLength ..............................166

    The message Widget .................................................167Message Attributes ............................................168

    Arranging Labels and Messages ................................169The scale Widget ......................................................169

    Scale attributes ..................................................170Programming scales ...........................................171

    The scrollbar Widget ................................................172Scrollbar attributes ............................................174Programming scrollbars .....................................175The Tk 3.6 protocol ............................................175

    The bell Command ...................................................176

    16. Entry and Listbox Widgets ...........................177The entry Widget ......................................................177

    entry attributes ..................................................180Programming entry widgets ................................181

    The listbox Widget ....................................................183Programming listboxes .......................................185

    Listbox Bindings ......................................................189Browse select mode ............................................190

  • vii

    Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    Single select mode ............................................. 190Extended select mode ........................................ 191Multiple select mode .......................................... 192Scroll bindings ................................................... 192listbox attributes ............................................... 193Geometry gridding ............................................. 194

    17. Focus, Grabs, and Dialogs .......................... 195Input Focus ............................................................. 195

    The focus command ........................................... 196Focus follows mouse .......................................... 196Click to type ...................................................... 197Hybrid models ................................................... 197

    Grabbing the Focus .................................................. 197Dialogs .....................................................................198

    The tkwait Command ......................................... 198Prompter dialog ................................................. 198Destroying widgets ............................................. 200Focusing on buttons .......................................... 200Animation with the update command ................. 200

    File Selection Dialog ................................................. 201Creating the dialog ............................................. 201Listing the directory ........................................... 204Accepting a name .............................................. 205Easy stuff .......................................................... 207File name completion ......................................... 207

    18. The text Widget ........................................... 211Text widget taxonomy ........................................ 211

    Text Indices ............................................................. 212Text Marks ............................................................... 213Text Tags .................................................................214

    Tag attributes .................................................... 215Mixing attributes from different tags .................. 216

    Line Spacing and Justification ................................. 217The Selection ........................................................... 219Tag Bindings ............................................................ 219Embedded Widgets ................................................... 220Text Bindings ........................................................... 222

  • Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    viii

    Text Operations ........................................................223Text Attributes .........................................................225

    19. The canvas Widget .......................................227Hello, World! ............................................................227The Double-Slider Example ......................................229Canvas Coordinates .................................................233Arcs .........................................................................233Bitmap Items ...........................................................235Images .....................................................................236Line Items ................................................................236Oval Items ................................................................238Polygon Items ...........................................................239Rectangle Items ........................................................240Text Items ................................................................241Window Items ..........................................................244Canvas Operations ...................................................246Generating Postscript ...............................................248Canvas Attributes ....................................................250Hints ........................................................................251

    Large coordinate spaces .....................................251Scaling and Rotation ..........................................251X Resources .......................................................252Objects with many points ...................................252

    20. Selections and the Clipboard .......................253The selection Command ...........................................254The clipboard Command ..........................................255

    Interoperation with OpenLook ............................255Selection Handlers ...................................................255

    A canvas selection handler .................................256

    21. Callbacks and Handlers ..............................259The after Command .................................................259The fileevent Command ............................................260The send Command .................................................261

    The sender script ...............................................262Using sender ......................................................264Hooking the browser to a shell ...........................266

  • ix

    Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    22. Tk Widget Attributes ................................... 269Configuring Attributes .............................................. 269Size ..........................................................................270Borders and Relief .................................................... 272The Focus Highlight ................................................. 273Padding and Anchors ............................................... 274Putting It All Together .............................................. 275

    23. Color, Images, and Cursors ......................... 277Colors ......................................................................278Colormaps and Visuals ............................................ 280Bitmaps and Images ................................................ 281

    The image Command ......................................... 281bimap images .................................................... 281The bitmap attribute .......................................... 282photo images ..................................................... 283

    The Mouse Cursor .................................................... 285The Text Insert Cursor ............................................. 287

    24. Fonts and Text Attributes ........................... 289Fonts .......................................................................289Text Layout .............................................................. 292Padding and Anchors ............................................... 293Gridding, Resizing, and Geometry ............................ 294Selection Attributes .................................................. 295A Font Selection Application ..................................... 295

    25. Window Managers and Window Information 303The wm Command ................................................... 303

    Size, placement, and decoration ......................... 304Icons .................................................................305Session state ..................................................... 306Miscellaneous .................................................... 307

    The winfo Command ................................................ 308Sending commands between applications .......... 308Family relationships .......................................... 308Size ...................................................................309Location ............................................................. 310Virtual root window ........................................... 311

  • x Chap.

    Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    Atoms and IDs ...................................................311Colormaps and visuals .......................................312

    The tk Command .....................................................313

    26. A User Interface to bind ...............................315A Binding User Interface ..........................................315A Pair of Listboxes Working Together ........................317The Editing Interface ................................................319

    27. Using X Resources ......................................323An Introduction To X Resources ...............................323

    Warning: order is important! ..............................325Loading Option Database Files .................................325Adding Individual Database Entries .........................326Accessing The Database ...........................................326User Defined Buttons ...............................................327User Defined Menus .................................................328

    28. Managing User Preferences ..........................331App-Defaults Files ....................................................331Defining Preferences .................................................333The Preferences User Interface .................................335Managing The Preferences File .................................338Tracing Changes To Preference Variables .................340

    29. C Programming and Tcl ...............................341Using the Tcl C Library ............................................342Application Structure ...............................................342Tcl_Main and Tcl_AppInit .........................................343

    The standard main in Tcl 7.3 .............................344A C Command Procedure .........................................345Managing The Results Storage .................................346Invoking Scripts From C ...........................................347

    Bypassing Tcl_Eval ............................................347Putting A Tcl Program Together ................................349An Overview of the Tcl C library ...............................349

    Application initialization ....................................350Creating and deleting interpreters ......................350Creating and deleteing commands .....................350Managing the result string .................................350

  • xi

    Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    Lists and command parsing ............................... 350Command pipelines ........................................... 351Tracing the actions of the Tcl interpreter ............ 351Evalutating Tcl commands ................................. 351Manipulating Tcl variables ................................. 352Evalutating expressions ..................................... 352Converting numbers .......................................... 352Hash tables ....................................................... 352Dynamic Strings ................................................ 353Regular expressions and string matching ........... 353Tilde Substitution .............................................. 353Working with signals ......................................... 353

    30. C Programming and Tk ............................... 355Tk_Main and Tcl_AppInit .......................................... 355A Custom Main Program .......................................... 357A Custom Event Loop ............................................... 360An Overview of the Tk C library. ............................... 361

    Parsing command line arguments ...................... 361The standard application setup .......................... 362Creating windows .............................................. 362Application name for send ................................. 362Configuring windows ......................................... 362Window coordinates ........................................... 362Window stacking order ...................................... 363Window information ........................................... 363Configuring widget attributes ............................. 363Safe handling of the widget data structure ......... 363The selection and clipboard ............................... 363Event bindings ................................................... 364Event loop interface ........................................... 364Handling X events .............................................. 364File handlers ...................................................... 364Timer events ...................................................... 365Idle callbacks ..................................................... 365Sleeping ............................................................. 365Reporting script errors ....................................... 365Handling X protocol errors ................................. 365Using the X resource database. .......................... 365

  • xii Chap.

    Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    Managing bitmaps .............................................366Creating new image types ..................................366Using an image in a widget ................................366Photo image types ..............................................366Canvas object support .......................................366Geometry managment ........................................367String identifiers (UIDS) .....................................367Colors and Colormaps ........................................3673D Borders ........................................................368Mouse cursors ...................................................368Font structures ..................................................368Graphics Contexts .............................................368Allocate a pixmap ..............................................368Screen measurements ........................................368Relief style .........................................................369Text anchor positions .........................................369Line cap styles ...................................................369Line join styles ...................................................369Text justification styles ......................................369Atoms ................................................................369X resource ID management ................................369

    31. Writing a Tk Widget in C ..............................371Implementing a New Widget .....................................371The Widget Data Structure .......................................372Specifying Widget Attributes .....................................373The Widget Class Command .....................................375Widget Instance Command .......................................376Configuring And Reconfiguring Attributes ................378Displaying The Clock ................................................380The Window Event Procedure ...................................383Final Cleanup ..........................................................384

    32. Tcl Extension Packages ...............................387Extended Tcl ............................................................388

    Adding tclX to your application ..........................388More UNIX system calls .....................................389File operations ...................................................389New loop constructs ...........................................389

  • xiii

    Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    Command line addons ....................................... 389Debugging and development support ................. 389TCP/IP access .................................................... 390File scanning (i.e., awk) ...................................... 390Math functions as commands ............................ 390List operations ................................................... 390Keyed list data structure .................................... 390String utilities .................................................... 391XPG/3 message catalog ..................................... 391Memory debugging ............................................. 391

    Expect: Controlling Interactive Programs .................. 391The core expect commandsl ............................... 392Pattern matching ............................................... 393Important variables ............................................ 393An example expect script ................................... 394Debugging expect scripts ................................... 395

    Expects Tcl debugger ............................................... 395The Dbg C interface ........................................... 396Handling SIGINT ................................................ 397

    BLT ..........................................................................398Drag and drop ................................................... 398Hypertext ........................................................... 399Graphs .............................................................. 399Table geometry manager .................................... 399Bitmap support ................................................. 399Background exec ............................................... 399Busy window ..................................................... 399Tracing Tcl commands ....................................... 399The old-fashioned cutbuffer ............................... 400

    Tcl-DP ......................................................................400Remote Procedure Call ....................................... 400Connection setup ............................................... 401Sending network data ........................................ 401Using UDP ......................................................... 401Event processing ................................................ 401Replicated objects .............................................. 402

    The [incr tcl] Object System ...................................... 402Tcl_AppInit With Extensions .................................... 404Other Extensions ..................................................... 407

  • xiv Chap.

    Created: May 9, 1994 bookTOC.docCopyright Prentice HallDRAFT: 1/13/95

    Tcl applications ..................................................407

    33. Porting to Tk 4.0 .........................................409wish .........................................................................409Obsolete Features ....................................................409The cget Operation ...................................................410Input Focus Highlight ..............................................410Bindings ..................................................................410Scrollbar Interface ....................................................411Pack info ..................................................................411Focus .......................................................................411Send ........................................................................412Internal Button Padding ...........................................412Radio Buttons ..........................................................412Entry Widget ............................................................412Menus ......................................................................413Listboxes ..................................................................413No geometry Attribute ..............................................413Text Widget ..............................................................413Canvas scrollincrement ............................................414The Selection ...........................................................414Color Attributes .......................................................414The bell Command ...................................................415

  • List of Examples 0

    10Tcl Fundamentals..........................................................................................................................................1

    1.1 The Hello, World! example. .......................................................31.2 Tcl variables. ..............................................................................31.3 Command substitution. ..............................................................41.4 Simple arithmetic........................................................................51.5 Nested commands.......................................................................51.6 Built-in math functions...............................................................51.7 Controlling precision with tcl_precision. ......................................51.8 Quoting special characters with backslash..................................61.9 Continuing long lines with backslashes.......................................61.10 Grouping with double quotes allows substitutions. .....................71.11 Defining a procedure...................................................................81.12 A loop that multiplies the numbers from 1 to 10. ........................91.13 Embedded command and variable substitution.........................101.14 Embedded variable references...................................................1120Strings and Pattern Matching ......................................................................................................................19

    2.1 Comparing strings. ...................................................................212.2 Regular expression to parse the DISPLAY environment variable. .2730Tcl Data Structures .....................................................................................................................................29

    3.1 Using set to return a variable value...........................................303.2 Using info to determine if a variable exists. ..............................303.3 Constructing a list with the list command. ..............................323.4 Using lappend to add elements to a list. ....................................323.5 Using concat to splice together lists. .........................................333.6 Double quotes compared to the list command. ........................333.7 Modifying lists with linsert and lreplace.................................343.8 Deleting a list element by value.................................................343.9 Sorting a list using a comparison function. ...............................353.10 Use split to turn input data into Tcl lists. ..................................353.11 Using arrays. ............................................................................363.12 What if the name of the array is in a variable. ...........................373.13 Converting from an array to a list..............................................383.14 printenv prints the environment variable values. ......................393.15 Tracing variables.......................................................................403.16 Creating array elements with array traces. ................................4040Control Flow Commands .............................................................................................................................41

    4.1 A conditional if-then-else command......................................424.2 Chained conditional with elseif. ..............................................424.3 Using switch for an exact match. ..............................................434.4 Using switch with substitutions in the patterns. .......................444.5 Using switch with all pattern body pairs grouped with quotes. ..444.6 Looping with foreach. ...............................................................444.7 Parsing command line arguments. ............................................454.8 Using list with foreach............................................................45

  • xvi

    Created: September 9, 1994 bookLOX.docCopyright Prentice HallDRAFT: 1/13/95

    4.9 A while loop to read standard input. .........................................464.10 A for loop. ................................................................................464.11 A standard catch phrase...........................................................474.12 A longer catch phrase. ..............................................................474.13 The results of error with no info argument. ..............................484.14 Preserving errorInfo when calling error. ..................................484.15 Specifying errorinfo with return. .............................................4950Procedures and Scope................................................................................................................................. 51

    5.1 Default parameter values. .........................................................525.2 Variable number of arguments..................................................525.3 Variable scope and Tcl procedures. ...........................................535.4 A random number generator. ....................................................545.5 Using arrays for global state. ....................................................555.6 Print by name. ..........................................................................565.7 Improved incr procedure. .........................................................565.8 Using an array to implement a stack.........................................5660Eval ............................................................................................................................................................ 59

    6.1 Using list to construct commands...........................................606.2 Using eval with $args. ..............................................................6170Working with UNIX ..................................................................................................................................... 65

    7.1 Using exec on a process pipeline...............................................667.2 A procedure to compare file modify times. .................................687.3 Creating a directory recusively. .................................................697.4 Determining if pathnames reference the same file. ....................697.5 Opening a file for writing...........................................................707.6 Opening a file using the POSIX access flags................................717.7 A more careful use of open. .......................................................717.8 Opening a process pipeline. ......................................................727.9 Prompting for input. .................................................................727.10 A read loop using gets. .............................................................737.11 A read loop using read and split. .............................................737.12 Finding a file by name...............................................................7480Reflection and Debugging ........................................................................................................................... 77

    8.1 Printing a procedure definition..................................................798.2 Getting a trace of the Tcl call stack. ..........................................808.3 Interactive history usage..........................................................828.4 Implementing special history syntax. ........................................838.5 A Debug procedure. ..................................................................8390Script Libraries........................................................................................................................................... 89

    9.1 Maintaining a tclIndex file. ......................................................909.2 Loading a tclIndex file..............................................................91100Tk Fundamentals...................................................................................................................................... 95

    10.1 Hello, World! Tk program........................................................96110Tk by Example........................................................................................................................................ 103

    11.1 Logging the output of a UNIX program. .................................... 10411.2 A browser for the code examples in the book........................... 10911.3 A Tcl shell in a text widget. .....................................................113120The Pack Geometry Manager................................................................................................................... 115

  • xvii

    Created: September 9, 1994 bookLOX.docCopyright Prentice HallDRAFT: 1/13/95

    12.1 Two frames packed inside the main frame...............................11612.2 Turning off geometry propagation............................................11612.3 A horizontal stack inside a vertical stack.................................11712.4 Even more nesting of horizontal and vertical stacks. ...............11712.5 Mixing bottom and right packing sides....................................11812.6 Filling the display into extra packing space. ...........................11912.7 Using horizontal fill in a menubar. ..........................................12012.8 The effects of internal padding (-ipady)....................................12212.9 Button padding vs. packer padding.........................................12212.10 The look of a default button. ...................................................12312.11 Resizing without the expand option.........................................12412.12 Resizing with expand turned on. .............................................12412.13 More than one expanding widget.............................................12512.14 Setup for anchor experiments. ................................................12512.15 The effects of non-center anchors............................................12612.16 Animating the packing anchors...............................................12612.17 Controlling the packing order..................................................12712.18 Packing into other relatives. ....................................................128130Binding Commands to X Events ..............................................................................................................133

    13.1 The binding hierarchy. ............................................................13413.2 Output from the UNIX xmodmap program. ...............................14013.3 Emacs-like binding convention for Meta and Escape. ..............141140Buttons and Menus .................................................................................................................................145

    14.1 A troublesome button command. ............................................14614.2 Fixing up the troublesome situation........................................14714.3 A button associated with a Tcl procedure. ...............................14814.4 Radio and Check buttons........................................................15014.5 Acommand on a radiobutton or checkbutton...........................15114.6 A menu sampler........................................................................15414.7 A simple menu-by-name package............................................15614.8 Adding menu entries...............................................................15714.9 A wrapper for cascade entries. ................................................15814.10 Using the basic menu package. ...............................................15814.11 Keeping the accelerator display up-to-date. .............................158150Simple Tk Widgets ...................................................................................................................................163

    15.1 A label that displays different strings. ....................................16515.2 The message widget formats long lines of text...........................16715.3 Controlling the text layout in a message widget. ......................16815.4 A scale widget. .......................................................................16915.5 A text widget and two scrollbars.............................................173160Entry and Listbox Widgets.......................................................................................................................177

    16.1 A command, a label and an entry. .........................................17916.2 A listbox with scrollbars. .......................................................18316.3 A listbox with scrollbars and better alignment. ......................18416.4 Choosing items from a listbox ............................ 188170Focus, Grabs, and Dialogs.......................................................................................................................195

    17.1 Setting focus-follows-mouse input focus model. ......................196

  • xviii

    Created: September 9, 1994 bookLOX.docCopyright Prentice HallDRAFT: 1/13/95

    17.2 A simple dialog. ......................................................................19917.3 A feedback procedure..............................................................20017.4 A file selection dialog. .............................................................20117.5 Listing a directory for fileselect................................................20417.6 Accepting a file name. .............................................................20617.7 Simple support routines. ........................................................20717.8 File name completion..............................................................208180The text Widget....................................................................................................................................... 211

    18.1 Tag configurations for basic character styles. .......................... 21618.2 Line spacing and justification in the text widget. .................... 21718.3 An active text button..............................................................21918.4 Delayed creation of embedded widgets. ................................... 221190The canvas Widget .................................................................................................................................. 227

    19.1 The canvas Hello, World! example. .......................................... 22719.2 A double slider canvas example. ..............................................22919.3 Moving the markers for the double-slider. ............................... 23119.4 A large scrollable canvas. ........................................................23319.5 Canvas arc items. ...................................................................23419.6 Canvas bitmap items. ..............................................................23519.7 Canvas image items. ................................................................23619.8 A canvas stroke drawing example. ........................................... 23719.9 Canvas oval items ..................................................................23819.10 Canvas polygon items. ............................................................23919.11 Dragging out a box. ................................................................24019.12 Simple edit bindings for canvas text items. ............................. 24219.13 Using a canvas to scroll a set of widgets. ................................. 24419.14 Generating postscript from a canvas. ...................................... 249200Selections and the Clipboard................................................................................................................... 253

    20.1 Paste the PRIMARY or CLIPBOARD selection. ................................ 25320.2 A selection handler for canvas widgets..................................... 256210Callbacks and Handlers .......................................................................................................................... 259

    21.1 A read event file handler. ........................................................26121.2 The sender application............................................................26221.3 Using the sender application...................................................26421.4 Hooking the browser to an eval server. ................................... 26621.5 Making the shell into an eval server. ...................................... 267220Tk Widget Attributes ............................................................................................................................... 269

    22.1 Equal-sized labels...................................................................27222.2 3D relief sampler. ...................................................................27322.3 Borders and padding. .............................................................275230Color, Images, and Cursors..................................................................................................................... 277

    23.1 Resources for reverse video. ....................................................27723.2 Computing a darker color .......................................................27923.3 Specifying an image attribute for a widget. .............................. 28123.4 Specifying a bitmap for a widget..............................................28223.5 The built-in bitmaps ...............................................................282240Fonts and Text Attributes ....................................................................................................................... 289

  • xix

    Created: September 9, 1994 bookLOX.docCopyright Prentice HallDRAFT: 1/13/95

    24.1 FindFont matches an existing font. .........................................29124.2 Handling missing font errors...................................................29124.3 FontWidget protects against font errors...................................29224.4 A gridded, resizable listbox......................................................29524.5 A font selection application. ....................................................29524.6 Menus for each font component. ............................................29624.7 Using variable traces to fix things up. .....................................29724.8 Listing available fonts. ............................................................29724.9 Determining possible font components....................................29824.10 Creating the radiobutton menu entries. ..................................29824.11 Setting up the label and message widgets. ..............................29924.12 The font selection procedures..................................................300250Window Managers and Window Information ............................................................................................303

    25.1 Gridded geometry for a canvas. ...............................................30425.2 Telling other applications what your name is...........................308260A User Interface to bind ...........................................................................................................................315

    26.1 A user interface to widget bindings..........................................31626.2 Bind_Display presents the bindings for a given widget or class.31726.3 Related listboxes are configured to select items together..........31826.4 Controlling a pair of listboxes with one scrollbar. ....................31826.5 Drag-scrolling a pair of listboxes together................................31926.6 An interface to define bindings. ...............................................32026.7 Defining and saving bindings. .................................................321270Using X Resources...................................................................................................................................323

    27.1 Reading an option database file...............................................32527.2 A file containing resource specifications. .................................32527.3 Using resources to specify user-defined buttons......................32727.4 Defining buttons from the resource database. .........................32827.5 Specifying menu entries via resources.....................................32827.6 Defining menus from resource specifications...........................330280Managing User Preferences......................................................................................................................331

    28.1 Preferences initialization. ........................................................33228.2 Adding preference items..........................................................33328.3 Setting preference variables. ...................................................33428.4 Using the preferences package. ...............................................33428.5 A user interface to the preference items...................................33528.6 Interface objects for different preference types.........................33628.7 Displaying the help text for an item.........................................33828.8 Saving preferences settings to a file.........................................33828.9 Read settings from the preferences file. ...................................33928.10 Tracing a Tcl variable in a preference item. .............................340290C Programming and Tcl ...........................................................................................................................341

    29.1 A canonical Tcl main program and Tcl_AppInit........................34329.2 The RandomCmd C command procedure. ....................................34529.3 Calling C command procedure directly. ...................................34829.4 A Makefile for a simple Tcl C program. ....................................349300C Programming and Tk............................................................................................................................355

  • xx

    Created: September 9, 1994 bookLOX.docCopyright Prentice HallDRAFT: 1/13/95

    30.1 A canonical Tk main program and Tcl_AppInit. ....................... 35630.2 A custom Tk main program.....................................................35730.3 Using Tk_DoOneEvent with TK_DONT_WAIT. ................................. 361310Writing a Tk Widget in C ......................................................................................................................... 371

    31.1 The Clock widget data structure..............................................37231.2 Configuration specs for the clock widget. ................................ 37331.3 The ClockCmd command procedure. ......................................... 37531.4 The ClockInstanceCmd command procedure. ........................... 37731.5 ClockConfigure allocates resources for the widget. .................. 37831.6 ComputeGeometry figures out how big the widget is................... 38031.7 The ClockDisplay procedure. ..................................................38131.8 The ClockEventProc handles window events. ........................... 38331.9 The ClockDestroy cleanup procedure. ..................................... 384320Tcl Extension Packages........................................................................................................................... 387

    32.1 A sample expect script. ...........................................................39432.2 A SIGINT handler....................................................................39732.3 Summary of [incr tcl] commands.............................................40332.4 Tcl_AppInit and extension packages........................................ 40432.5 Makefile for supertcl. ..............................................................406330Porting to Tk 4.0 ..................................................................................................................................... 409

  • List of Tables 0

    10Tcl Fundamentals..........................................................................................................................................11-1 Backslash sequences. ...............................................................141-2 Arithmetic Operators from highest to lowest precedence............141-3 Built-in Math functions.............................................................151-4 Built-in Tcl Commands .............................................................151-5 Variables defined by tclsh..........................................................1820Strings and Pattern Matching ......................................................................................................................192-1 The string command................................................................202-2 Format conversions...................................................................222-3 format flags...............................................................................222-4 Regular Expression Syntax .......................................................2530Tcl Data Structures .....................................................................................................................................293-1 List-related commands..............................................................313-2 The array command..................................................................3740Control Flow Commands .............................................................................................................................4150Procedures and Scope .................................................................................................................................5160Eval.............................................................................................................................................................5970Working with UNIX......................................................................................................................................657-1 Summary of the exec syntax for I/O redirection. .......................667-2 The Tcl file command options. ................................................677-3 Tcl commands used for file access.............................................707-4 Summary of the open access arguments. ...................................717-5 Summary of POSIX flags for the access argument.......................7180Reflection and Debugging ............................................................................................................................778-1 The info command. ..................................................................788-2 The history command. .............................................................818-3 Special history syntax..............................................................828-4 Debugger commands. ...............................................................8590Script Libraries............................................................................................................................................89100Tk Fundamentals ......................................................................................................................................9510-1 Tk widget-creation commands.................................................10010-2 Tk widget-manipulation commands.........................................100110Tk by Example.........................................................................................................................................103120The Pack Geometry Manager ...................................................................................................................11512-1 A summary of the pack command............................................13012-2 Packing options. .....................................................................13012-3 A summary of the place command. .........................................13112-4 Placement options...................................................................132130Binding Commands to X Events ..............................................................................................................13313-1 Event types. Comma-separated types are equivalent. ..............13613-2 Event modifiers.......................................................................13913-3 A summary of the event keywords. ..........................................142140Buttons and Menus .................................................................................................................................14514-1 Resource names of attributes for all button widgets. ...............15214-2 Button operations. . ................................................................15314-3 Menu entry index keywords ....................................................15514-4 Menu operations. ....................................................................15514-5 Resource names of attributes for menu widgets.........................16014-6 Attributes for menu entries. ....................................................161

  • xxii

    Created: December 15, 1994 bookLOT.docCopyright Prentice HallDRAFT: 1/13/95

    150Simple Tk Widgets .................................................................................................................................. 16315-1 Resource names of attributes for frame and toplevel widgets. 16415-2 Resource names of attributes for label widgets....................... 16615-3 Resource names for attributes for message widgets. ................. 16815-4 Default bindings for scale widgets. ......................................... 17015-5 Resource names for attributes for scale widgets. .................... 17015-6 Operations on scale widgets.. .................................................17115-7 Default bindings for scrollbar widgets. .................................. 17415-8 Resource names of attributes for scrollbar widgets. ............... 17415-9 Operations on scrollbar widgets. .............................................175160Entry and Listbox Widgets ...................................................................................................................... 17716-1 Default bindings for entry widgets. ......................................... 17816-2 Resource names for attributes of entry widgets....................... 18016-3 Indices for entry widgets.........................................................18116-4 Operations on entry widgets. ..................................................18216-5 Indices for listbox widgets .....................................................18616-6 Operations on listbox widgets................................................18616-7 The values for the selectMode of a listbox. ............................. 19016-8 Bindings for browse selection mode. ........................................ 19016-9 Bindings for a listbox in single selectMode. .......................... 19016-10 Bindings for extended selection mode...................................... 19116-11 Bindings for multiple selection mode...................................... 19216-12 Scroll bindings common to all selection modes........................ 19316-13 Resource names of attributes for listbox widgets. .................. 193170Focus, Grabs, and Dialogs ...................................................................................................................... 19517-1 The focus command. ..............................................................19617-2 The grab command. ................................................................19717-3 The tkwait command..............................................................198180The text Widget....................................................................................................................................... 21118-1 Forms for the indices in text widgets. ..................................... 21218-2 Index modifiers for text widgets..............................................21318-3 Attributes for text tags. ..........................................................21518-4 Options to the window create operation. ................................. 22118-5 Bindings for the text widget. ..................................................22218-6 Operations for the text widget. ...............................................22418-7 Resource names of attributes for text widgets. ....................... 226190The canvas Widget .................................................................................................................................. 22719-1 Attributes for arc canvas items. ..............................................23419-2 Attributes for bitmap canvas items. ......................................... 23519-3 Attributes for image canvas items............................................ 23619-4 Attributes for line canvas items. ............................................ 23819-5 Attributes for oval canvas items. ............................................ 23919-6 Attributes for polygon canvas items. ....................................... 24019-7 Attributes for rectangle canvas items. ..................................... 24119-8 Indices for canvas text items..................................................24119-9 Canvas operations that apply to text items............................. 24219-10 Attributes for text canvas items. ............................................ 24419-11 Operations on a canvas widget. ...............................................246

  • xxiii

    Created: December 15, 1994 bookLOT.docCopyright Prentice HallDRAFT: 1/13/95

    19-12 Canvas postscript options. ......................................................24819-13 Resource names of attributes for the canvas widget. ................250200Selections and the Clipboard ...................................................................................................................25320-1 The selection command.........................................................25420-2 The clipboard command.........................................................255210Callbacks and Handlers...........................................................................................................................25921-1 The after command................................................................26021-2 The fileevent command.........................................................261220Tk Widget Attributes................................................................................................................................26922-1 Size attribute resource names. ................................................27022-2 Border and relief attribute resource names. ............................27222-3 Border and relief attribute resource names. ............................27422-4 Layout attribute resource names.............................................274230Color, Images, and Cursors .....................................................................................................................27723-1 Color attribute resource names. ..............................................27823-2 Visual classes for X displays. Values for the visual attribute....28023-3 Summary of the image command.............................................28123-4 Bitmap image options .............................................................28223-5 Photo image attributes ............................................................28323-6 Photo image operations. ..........................................................28423-7 Image copy options. ................................................................28523-8 Image read options..................................................................28523-9 Image write options.................................................................28523-10 Cursor attribute resource names.............................................287240Fonts and Text Attributes ........................................................................................................................28924-1 X Font specification components.............................................29024-2 Resource names for layout attributes. .....................................29324-3 Resource names for padding and anchors. ..............................29324-4 Geometry commands affected by gridding. ..............................294250Window Managers and Window Information ............................................................................................30325-1 Size, placement and decoration window manager operations. ..30525-2 Window manager commands for icons. ...................................30625-3 Session-related window manager operations. ..........................30725-4 Miscellaneous window manager operations. ............................30725-5 Information useful with the send command. ............................30825-6 Information about the window hierarchy. ................................30925-7 Information about the window size..........................................31025-8 Information about the window location. ..................................31025-9 Information associated with virtual root windows. ...................31125-10 Information about atoms and window ids................................31225-11 Information about colormaps and visual classes. ....................312260A User Interface to bind ...........................................................................................................................315270Using X Resources...................................................................................................................................323280Managing User Preferences......................................................................................................................331290C Programming and Tcl ...........................................................................................................................341300C Programming and Tk............................................................................................................................355310Writing a Tk Widget in C..........................................................................................................................37131-1 Configuration flags and corresponding C types........................374320Tcl Extension Packages............................................................................................................................387330Porting to Tk 4.0......................................................................................................................................40933-1 Changes in color attribute names............................................414

  • xxiv

    Created: December 15, 1994 bookLOT.docCopyright Prentice HallDRAFT: 1/13/95

  • Created: January 6, 1994 Preface.fm3Copyright Prentice HallDRAFT: 1/13/95

    Preface

    I first heard about Tcl from John Ouster-hout in 1988 while I was his Ph.D. student at Berkeley. We were designing a net-work operating system, Sprite. While the students hacked on a new kernel, Johnwas writing a new editor and terminal emulator. He used Tcl as the commandlanguage for both tools so that users could define menus and otherwise custom-ize those programs. This was in the days of X10, and he had plans for an X tool-kit based on Tcl that would allow programs to cooperate by communicating withTcl commands. To me, this cooperation among tools was the essence of the ToolCommand Language (Tcl).

    That early vision imagined that applications would be large bodies of com-piled code and a small amount of Tcl used for configuration and high-level com-mands. Johns editor, mx, and the terminal emulator, tx, followed this model.While this model remains valid, it has also turned out to be possible to writeentire applications in Tcl. This is because of the Tcl/Tk shell, wish, that providesall the functionality of other shell languages, which includes running other pro-grams, plus the ability to create a graphical user interface. For better or worse, itis now common to find applications that contain thousands of lines of Tcl script.

    This book came about because, while I found it enjoyable and productive touse Tcl and Tk, there were times when I was frustrated. In addition, working atXerox PARC, with many experts in languages and systems, I was compelled tounderstand both the strengths and weaknesses of Tcl and Tk. While many of mycolleagues adopted Tcl and Tk for their projects, they were also just as quick topoint out its flaws. In response, I have built up a set of programming techniquesthat exploit the power of Tcl and Tk while avoiding troublesome areas. Thus, thisbook is meant as a practical guide that will help you get the most out of Tcl andTk while avoiding some of the frustrations that I experienced.

  • xxvi

    Created: January 6, 1994 Preface.fm3Copyright Prentice HallDRAFT: 1/13/95

    Who Should Read This BookThis books is meant to be useful to the beginner as well as the expert in Tcl.

    For the beginner and expert alike I recommend careful study of the first chapteron Tcl. The programming model of Tcl is different from many programming lan-guages. The model is based on string substitutions, and it is important that youunderstand it properly to avoid trouble later on. The remainder of the book con-sists of examples that should help you get started using Tcl and Tk productively.

    This book assumes that you have some UNIX and X background, althoughyou should be able to get by even if you are a complete novice. Expertise in UNIXshell programming will help, but it is not required. Where aspects of X are rele-vant, I will try to provide some background information.

    How To Read This BookThis book is best used in a hands-on manner, at the computer trying out the

    examples. The book tries to fill the gap between the terse Tcl and Tk manualpages, which are complete but lack context and examples, and existing Tcl pro-grams that may or may not be documented or well written.

    I recommend the on-line manual pages for the Tcl and Tk commands. Theyprovide a detailed reference guide to each command. This book summarises someof the information from the man pages, but it does not provide the completedetails, which can vary from release to release.

    I also recommend the book by Ousterhout, Tcl and the Tk Toolkit, whichprovides a broad overview of all aspects of Tcl and Tk. There is some overlap withOusterhouts book, although that book provides a more detailed treatment of Cprogramming and Tcl.

    How To Review This BookAt this point I am primarily concerned with technical issues. Dont worry

    too much about spelling and other copy edits. Concentrate on the examples andpassages that are confusing. You can mark up the manuscript with a pen andreturn it to me. Or, send me email at [email protected] with the subject tclbook. This is the last major draft I will post before getting the book ready forfinal publication. If you can return your comments by mid to late February itwould be best. Thanks, in advance!

    I would like to highlight a few key spots in the manuscripts as hot tips. Ifyou could nominate one or more such paragraphs from each chapter I will addsome sort of icon to the margin to indicate the reviewer-selected hot tips!

    Thanks

    Many thanks to the patient reviewers of early drafts: Don Libes, Dan Swinehart,Carl Hauser, Pierre David, Jim Thornton, John Maxwell, Hador Shemtov,Charles Thayer, Ken Pier. [UPDATE] (Mention email reviews, too)

  • Created: March 15, 1994 Overview.fm3Copyright Prentice HallDRAFT: 1/13/95

    Introduction 0

    This introduction gives an overview of Tcl and the organization of this book.

    Why Tcl? Is it just another shell lan-guage? How can it help you?

    Tcl stands for Tool Command Language. Tcl is really two things: a scriptinglanguage, and an interpreter for that language that is designed to be easy toembed into your application. Tcl and its associated X windows toolkit, Tk, weredesigned and crafted by Prof. John Ousterhout of U.C. Berkeley. These packagescan be picked up off the Internet (see below) and used in your application, even acommercial one. The interpreter has been ported from UNIX to DOS and Macin-tosh environments.

    As a scripting language, Tcl is similar to other UNIX shell languages suchas the Bourne Shell, the C Shell, the Korn Shell, and Perl. Shell programs letyou execute other programs. They provide enough programmability (variables,control flow, procedures) that you can build up complex scripts that assembleexisting programs into a new tool tailored for your needs. Shells are wonderfulfor automating routine chores.

    It is the ability to easily add a Tcl interpreter to your application that sets itapart from other shells. Tcl fills the role of an extension language that is used toconfigure and customize applications. There is no need to invent a command lan-guage for your new application, or struggle to provide some sort of user-program-mability for your tool. Instead, by adding a Tcl interpreter you are encouraged tostructure your application as a set of primitive operations that can be composedby a script to best suit the needs of your users. It also allows programmatic con-trol over your application by other programs, leading to suites of applicationsthat work together well.

    There are other choices for extension languages that include Scheme, Elisp,and Python. Your choice between them is partly a matter of taste. Tcl has simple

  • xxviii

    Created: March 15, 1994 Overview.fm3Copyright Prentice HallDRAFT: 1/13/95

    constructs and looks somewhat like C. It is also easy to add new Tcl primitives bywriting C procedures. By now there are a large number of Tcl commands thathave been contributed by the Tcl community. So another reason to choose Tcl isbecause of what you can access from Tcl scripts out-of-the-box. To me, this ismore important than the details of the language.

    The Tcl C library has clean interfaces and is simple to use. The libraryimplements the basic interpreter and a set of core scripting commands thatimplement variables, flow control, file I/O, and procedures (see page 15). In addi-tion, your application can define new Tcl commands. These commands are associ-ated with a C or C++ procedure that your application provides. The result is thatapplications are split into a set of primitives written in a compiled language andexported as Tcl commands. A Tcl script is used to compose the primitives into theoverall application. The script layer has access to shell-like capability to runother programs and access the file system, as well as call directly into the appli-cation by using the application-specific Tcl commands you define. In addition,from the C programming level, you can call Tcl scripts, set and query Tcl vari-ables, and even trace the execution of the Tcl interpreter.

    There are many Tcl extensions freely available on the net. Most extensionsinclude a C library that provides some new functionality, and a Tcl interface tothe library. Examples include socket access for network programming, databaseaccess, telephone control, MIDI controller access, and expect, which adds Tclcommands to control interactive programs.

    The most notable extension is Tk, a toolkit for X windows. Tk defines Tclcommands that let you create and manipulate user interface widgets. The script-based approach to UI programming has three benefits. First, development is fastbecause of the rapid turnaround - there is no waiting for long compilations. Sec-ond, the Tcl commands provide a higher-level interface to X than most standardC library toolkits. Simple interfaces require just a handful of commands to definethem. At the same time, it is possible to refine the interface in order to get everydetail just so. The fast turnaround aids the refinement process. The third advan-tage is that the user interface is clearly factored out from the rest of your appli-cation. The developer can concentrate on the implementation of the applicationcore, and then fairly painlessly work up a user interface. The core set of Tk wid-gets is often sufficient for all your UI needs. However, it is also possible to writecustom Tk widgets in C, and again there are many contributed Tk widgets avail-able on the network.

    Ftp ArchivesThe network archive site for Tcl is ftp.aud.alcatel.com. Under the /tcl

    directory there are subdirectories for the core Tcl distributions (sprite-mirror,for historical reasons), contributed extensions (extensions), contributed applica-tions (code), documentation (docs), and Tcl for non-UNIX platforms (distrib).Mirror sites for the archive include:

    ftp://syd.dit.csiro.au/pub/tk/contribftp://syd.dit.csiro.au/pub/tk/sprite

  • xxix

    Created: March 15, 1994 Overview.fm3Copyright Prentice HallDRAFT: 1/13/95

    ftp://ftp.ibp.fr/pub/tcl/distribftp://ftp.ibp.fr/pub/tcl/contribftp://ftp.ibp.fr/pub/tcl/expect

    (ftp.ibp.fr = 132.227.60.2)ftp://src.doc.ic.ac.uk/packages/tcl/tcl-archive

    (src.doc.ic.ac.uk = 146.169.2.10)ftp://ftp.luth.se/pub/languages/tcl/http://ftp.luth.se/pub/langugages/tcl/ftp://ftp.switch.ch/mirror/tcl

    (Contact address: [email protected])ftp://ftp.sterling.com/programming/languages/tclftp://fpt.sunet.se/pub/lang/tclmailto://[email protected]

    (Contact: [email protected])ftp://ftp.cs.columbia.edu/archives/tcl

    (Contact: [email protected])ftp://ftp.uni-paderborn.de/pub/unix/tcl/alcatelftp://sunsite.unc.edu/pub/languages/tcl/ftp://iskut.ucs.ubc.ca/pub/X11/tcl/ftp://ftp.funet.fi/pub/languages/tcl/ftp://coma.cs.tu-berlin.de/pub/tcl/ftp://nic.funet.fi/pub/languages/tcl/

    You can verify the location of the Tcl archive by using the archie service tolook for sites that contain the Tcl distributions. Archie is a service that indexesthe contents of anonymous FTP servers. Information about using archie can beobtained by sending mail to [email protected] that contains the messageHelp.

    World Wide WebThere are a number of Tcl pages on the world-wide-web:

    http://www.sco.com/IXI/of_interest/tcl/Tcl.htmlhttp://web.cs.ualberta.ca/~wade/Auto/Tcl.html

    Typographic ConventionsThe more important examples are set apart with a title and horizontal

    rules, while others appear in-line as shown below. The examples use courier forTcl and C code. When interesting results are returned by a Tcl command, thoseare presented below in oblique courier, as shown below. The => is not part ofthe return value.

    expr 5 + 8=> 13

  • xxx Chap.

    Created: March 15, 1994 Overview.fm3Copyright Prentice HallDRAFT: 1/13/95

    The courier font is also used when naming Tcl commands and C proce-dures within sentences.

    The usage of a Tcl command is presented as shown below. The commandname and constant keywords appear in courier. Variable values appear in cou-rier oblique. Optional arguments are surrounded with question marks.

    set varname ?value?The name of a UNIX program is in italics, e.g. xterm.

    Tcl 7.4 and Tk 4.0This book is up-to-date with Tcl version 7.4 and Tk version 4.0. There are

    occasional descriptions of Tk 3.6 features. The last chapter has some notes aboutporting scripts written in earlier versions of Tk.

    Book OrganizationThe first chapter of this book describes the fundamental mechanisms that

    characterize the Tcl language. This is an important chapter that provides thebasic grounding you will need to use Tcl effectively. Even if you have pro-grammed in Tcl already, you should review this chapter.

    Chapters 2-5 cover the basic Tcl commands in more detail, including stringhandling, regular expressions, data types, control flow, procedures and scopingissues. You can skip these chapters if you already know Tcl.

    Chapter 6 discusses eval and more advanced Tcl coding techniques. If youare running into quoting problems, check out this chapter.

    Chapter 7 describes the interface to UNIX and the shell-like capabilities torun other programs and examine the file system. The I/O commands aredescribed here.