From: lvirden@cas.org (Larry W. Virden)
Subject: comp.lang.tcl Frequently Asked Questions (2/3)
	 (Last updated: January 12, 1993)
Followup-To: comp.lang.tcl
Summary: A regular posting of the comp.lang.tcl Frequently Asked Questions 
	(FAQ) and their answers.  This is the second of three parts.
Originator: lwv26@lwv26aws
Keywords: tcl, expect, extended tcl, wish, tk
Supersedes: <tcl.p2_724079551@cas.org>
Reply-To: lvirden@cas.org (Larry W. Virden)
Organization: Chemical Abstracts Service
Date: Tue, 12 Jan 1993 14:02:45 GMT
Expires: Thu, 25 Feb 1993 14:02:27 GMT

Archive-name: tcl-faq/part2
Version: 2.7
Last-modified: January 12, 1993

Please do not be offended if I neglect to acknowledge your contribution
to this FAQ!  I sometimes forget to put an attribution in.  I especially
try to add them if it appears that there is further experimentation or
debugging being done though.

Index of questions:

7. Questions on building Tcl and friends on your system
	Q7a. Is there anywhere I can find help with the details of getting 
		Tcl to work on my machine?
	Q7b. When I am trying to build Tcl, the link step says that some 
		of the functions Tcl needs are missing.
	Q7c. Has anyone built Tcl 6.2 on an RS/6000 AIX 3.1? 
	Q7d. Has anyone gotten Tcl to compile under HP-UX?
	Q7e. Has anyone gotten Tcl to compile under VMS?
	Q7f. What does it take to get Tcl to compile under SCO Unix?
	Q7g. When I try to run the tclTest I get format and scan errors 
		(NeXT, AIX, etc.)
	Q7h. When I try to run tcl v6.2 tclTest under Irix 4.0.1 I get
		lots of errors.
	Q7i. Does anyone else have problems with Tcl on a Cray?
	Q7j. Does anyone know how to get Tk to run on a SparcBook or other
		laptop with a limited number of colors?
	Q7k. What does it take to get Tcl/Tk to compile on 386bsd/Linux 
		or other Posix/ANSI C systems not already supported?

8.  How, in Tcl, can I XXX:
	Q8a. get association lists or property lists?
	Q8b. call one proc with the multi parameter value returned by 
		another proc?
	Q8c. pass an array into a proc?
	Q8d. pipe output of a command back into a tcl parsing procedure?
	Q8e. merge extended Tcl into other programs such as wish or expect?
	Q8f. delete a procedure from within a script?
	Q8g. get parray to recognize an array variable I have created
		via upvar?
	Q8h. get more than 7 digits of double precision?
	Q8i. grab the command line whenever a non-built-in call is made?

9.  How, in Tk, can I XXX:
	Q9a. get my wish application to execute - I just get a wish prompt!
	Q9b. get an application to also use libXt?
	Q9c. ,using a machine with less than 8 bit color, run?
	Q9d. set X11 resources for a wish application in an app-defaults file?
	Q9e. change the X11 cursor?
	Q9f. raise or lower a window?
	Q9g. re-map a withdrawn window id?
	Q9h. specify bitmap patterns on the command line instead of 
		as a file name?
	Q9i. change the default class bindings?
	Q9j. delete a binding?
	Q9k. change a binding while it is being executed?
	Q9l. bind the arrow key on my Sun keyboard?
	Q9m. resize a listbox?
	Q9n. select two items that are not adjacent in the listbox at 
		one time?
	Q9o. select items in more than one tk listbox at a time?
	Q9p. fill a canvas which is bounded by lines as opposed to a
		shape like a polygon, oval, etc.?
	Q9q. create a scrollable window of buttons?

End of FAQ Index

------------------------------
Subject: -7- Questions on building Tcl and friends on your system

Subject: -Q7a- Is there anywhere I can find help with the details of 
		getting Tcl to work on my machine?

A7a. Glad you asked!  Look in the Tcl distribution for the file called
"porting.notes".  This will contain a collection of notes that various people
have provided about porting Tcl to various machines and operating systems.
There are also a file called "README" which should be read FIRST - before
doing anything else with the code (this should always be one's first
step with any package).  Finally, there is a "changes" file which details
what has changed since the last release - be sure to read this to see
what might need to change in your programs.

Subject: -Q7b- When I am trying to build Tcl, the link step says that
		some of the functions Tcl needs (such as strtoul and
		strerror) are missing.

A7b. Did you run the "config" program first, by doing a "csh ./config" or
equivalent?

Tcl includes equivalents for the following functions and include files
which may not be found on some systems:

dirent.h       limits.h	      stdlib.h	     string.h

opendir.c      strerror.c     strstr.c	     strtol.c	    strtoul.c

strtod.c

Subject: -Q7c- Has anyone built Tcl 6.x on an RS/6000 AIX 3.1? 

A7c.  See porting notes - especially the note about strtoul.

One user got Tcl to compile with a few minor source modifications
(for example, duplicate case statements for errno and signal symbols in 
tclUnixStr.c). 

A few other problems arose in the tests.  One is caused by AIX printf
not formatting %#x and %#o correctly when the value to be printed is
zero:  they print "0x0" and "00" instead of "0" and "0" respectively.
This was reported as not a problem in earlier releases.  No fixes have
been posted.

Finally, a problem occurs in open.test.  test 13.6 hangs because "cat"
on the RS6000 is unbuffered.  A workaround is to change the execution
of "cat" in open.test to do a "cat -u".

Dov Grobgeld <dov@menora.weizmann.ac.il> provided info on creating tcl
and tk shared libraries under AIX 3.1.5:

For tcl:

cc -o tkshar.o *.o -bE:tclshar.exp -bM:SRE -berok -lX11 -lm
ar r libtclshr tclshar.o

For tk:

cc -o tkshar.o *.o -bE:tkshar.exp -bM:SRE -berok -Ltcl -lX11 -lm -ltclshr
ar r libtkshr tkshar.o

where tckshar.exp and tkshar.exp had lists of the external functions.

Subject: -Q7d- Has anyone gotten Tcl to compile under HP-UX?

A7d. See the porting notes.

Subject: -Q7e- Has anyone gotten Tcl to compile under VMS?

A7e. Information from: derge@visacrd.ge.com (Gillmer J. Derge)

Date: 8 Jan 92 13:44:18 GMT
Reply-To: derge@crd.ge.com
Organization: GE Corporate R&D Center, Schenectady, NY

Here's a rough approximation of what I needed to do (pretty minor changes).

1. As discussed in the Makefile, do not compile the files that make
UNIX_OBJS (panic.c, tclEnv.c, tclGlob.c, tclUnixAZ.c, tclUnixStr.c and
tclUnixUtil.c).  Furthermore, define the constant TCL_GENERIC_ONLY at
compile-time.

2. Don't believe everything you read in Makefiles :-) --
TCL_GENERIC_ONLY doesn't really work.  You need to add an ifndef in
tclCkalloc.c before the "#include tclUnix.h".  Also, in tclExpr.c,
there's a reference to TCL_NO_UNIX that should be changed to
TCL_GENERIC_ONLY.

3. Finally, in order to run the test program (the test suite won't
work, see below), you'll need to change the definition of initCmd in
tclTest.c.  I chose the following, which should be more or less
compatible with non-VAX systems:

#ifdef TCL_LIBRARY
char *initCmd =
    "if [file exists [info library]/init.tcl] {source [info
library]/init.tcl}";
#else
char *initCmd =
    "format {There is no Tcl library at this installation.  Continuing
anyway.\n
}";
#endif

	There are a number of caveats to all this.  First of all, I did
not port tk or Extended Tcl.  Furthermore, I think there may have been
a release that I missed since I did it (6.1 vs 6.0).  Here's the RCS ID
from my tclExpr.c, in case you want to compare yours.

static char rcsid[] = "$Header: /sprite/src/lib/tcl/RCS/tclExpr.c,v 1.29\
91/09/04 15:08:28 ouster Exp $ SPRITE (Berkeley)";

	And perhaps most importantly of all, as you may have gleaned
from the compilation instructions, I did not do anything to port the
Unix-related functions.  As a result, the standard test suite will not
work.  You have to just try commands on your own.  I recently got mail
from jkimball@src.honeywell.com (John Kimball) indicating that he may
be working on just that problem.

	I've assumed a certain amount of C knowledge in the above.  If
that's an invalid assumption, or your confused for any other reason,
let me know, and I'll try to clear things up.  I'm guessing since you
asked about porting tk and Extended Tcl that I probably haven't taken
this as you would have liked, but maybe I've saved you at least a
little effort.  I hope so.

Subject: -Q7f- What does it take to get Tcl to compile under SCO Unix?

A7f.	Add a "#undef select" to tkEvent.c, and remove the reference to 
TK_EXCEPTION around line 460 of main.c.

Tk uses its own scheme for allocating the border colors for its 3D
widgets, which causes problems when running TK on a system with
"PseudoColor" display class, and a 16-cell colormap.

If you can't go to eight bitplanes, you can instead start the server
with a "-static" (Xsco) or "-analog" (Xsight) option, making the
display class become "StaticColor".  This makes the entire colormap
read-only, and it will return the color that most closely maps to the
desired color as possible.

This information is from Keith Amann <Keith_Amann@stortek.com>

Subject: -Q7g- When I try to run the tclTest I get format and scan errors 
		(NeXT, AIX, etc.)

A7g.  That's a problem (scanf/printf) many systems seem to have.  Don't
worry too much about it - just don't use these 'advanced' features.  If
you're hacking C, you'll have the same problems.

Subject: -Q7h- When I try to run tcl v6.2 tclTest under Irix 4.0.1 I get 
		lots of errors.

A7h. There's a bug in the 4.0.1 optimizer that's fixed in 4.0.2.
Compile tclVar.c using -O0 (no optimization).

Subject: -Q7i- Does anyone else have problems with Tcl on a Cray?

A7i. See the porting notes for a set of changes mentioned.  Also,
Booker C. Bense <benseb@grumpy.sdsc.edu> reports that version 3.0.1.6
has some real problems with char pointers, causing Tcl to crash.  Using
version 3.0.2.1, things are much better, except for a minor formatting
problem and serious problems with scan.

Subject: -Q7j- Does anyone know how to get Tk to run on a SparcBook or other
laptop with a limited number of colors?

A7j.  On a SparcBook, if you start openwin (the OpenWindows server starting
command) as:

openwin -dev "/dev/fb staticvis"

you get a static visual color model that Tk copes with better than the
default.  Some things are ugly, but not as ugly as monochrome.

Subject: -Q7k- What does it take to get Tcl/Tk to compile on 386bsd/Linux 
		or other Posix/ANSI C systems not already supported?

A7k. Patches for 386BSD were posted to comp.lang.tcl back in Nov. 1992 to
alt.sources.  See one of the ftp archive sites for this group for them.
Basically, there were some setting of defines and a few places where 
const char * had to be used in place of char *.  

------------------------------
Subject: -8-  How, in Tcl, can I XXX:

Subject: -Q8a-	association lists or property lists?

A8a. Use Extended Tcl arrays or keyed lists.

For example, if you did a:

keylset ttyFields ttyName tty1a
keylset ttyFields baudRate 57600
keylset ttyFields parity strip

And then an "echo $ttyFields", you'd get:

    {ttyName tty1a} {baudRate 57600} {parity strip}


Subject: -Q8b-	call one proc with the multi parameter value returned by 
		another proc?

A8b. Assuming y requires multiple args and x returns multiple words, use 
	Tcl's eval command "eval y [x]"

Subject: -Q8c-	pass an array into a proc?

A8c. With upvar.

set argc 2
set argv(0) zero
set argv(1) one
# print elements of an array
proc a {
  foreach element of a
  echo the element
}

proc a {arrayName} {
    upvar $arrayName myArray

    foreach element [array names myArray] {
       echo $element $myArray($element)
    }
}

Extended Tcl introduces a concept called keyed lists which are arrays
made out of lists of key-value pairs and can be passed by value to routines,
over networks, etc.

Subject: -Q8d-	pipe output of a command back into a tcl parsing 
		procedure?

A8d.  For example, to grep a pattern out of a range of files, one might
do:

karl@NeoSoft.com (Karl Lehenbauer) writes:

set files [glob /home/cole/stats/*]

proc parseInfo { site } {
   global files

#
# site is chosen from a listbox earlier
#
   set in [open [concat "|/usr/bin/grep $site $files"] r]

   while {[gets $in line]>-1} {
      puts stderr $line
   }
   catch {close $in}
}

One thing:  the matching strings are _not_ returned in directory order.

But what if I want to check the return code AND use the output of 
the command?  kennykb@dssv01.crd.ge.com (Kevin B. Kenny) writes:

if [catch {exec ls} data] {
        # The exec got an error, and $errorCode has its termination status
} else {
        # The exec succeeded
}
# In any case, `data' contains all the output from the child process.

Note that Karl Lehenbauer adds that errorCode will be a list containing
three elements, the string "CHILDSTATUS", the process ID of the child,
and the exit status of the child.

Subject: -Q8e-	merge extended Tcl into other programs such as wish or expect?

A8e. The latest version of extended TCL, tclX 6.2B, has been enhanced to
make it easier to incorporate into applications.

Subject: -Q8f-	delete a procedure from within a script?

A8f. rename procedureName ""

Subject: -Q8g- get parray to recognize an array variable I have created
	via upvar?

A8g. Right now (June, 1992) upvar doesn't allow you to attach to an
individual element of an array.  This is considered a bug by 
Mr. Ousterhout and has been place on a bug list.

Subject: -Q8h- get more than 7 digits of double precision ?

A8h. Modify the tclExpr.c module to use %lf instead of %g.

Subject: -Q8i- grab the command line whenever a non-built-in call is made?

A8i. The procedure "unknown" is called automatically with arguments 
containing the command and its arguments for any command that couldn't be 
found.  In fact, Tcl and Extended Tcl use this feature to provide demand
loaded commands, and even entire libraries.

So by modifying the unknown procedure you can provide your own extended
functionality, or even remove the demand loading capability if you so
desire.

------------------------------
Subject: -9-  How, in Tk, can I XXX:

Subject: -Q9a- get my wish application to execute - I just get a
		wish prompt!  Or I just get error msgs about permission
		denied, not found, etc.

A9a. Most systems require a full pathname to the interpreter.  So you cannot
start a wish script out as 
#! wish -f

Likewise, many Unix systems have a maximum length of characters that you can
put on a #! line.  If you exceed this, you do not get the behaviour you
expect.  So do not try to put something like:

#! /projects/somethingbig/bin/sun4/wish -f

followed by your wish code.  Keep the lines short - under 30 characters is
recommended.

Subject: -Q9b- get an application to also use libXt?

A9b. Tk2.1 and Xt have different X connections, and XtAppNextEvent will
block is there is nothing coming from the X connection.  One way
of fixing this is get the connection number of Tk using

   ConnectionNumber(Tk_Display(tk_window));

and using XtAddInput to register this with the Xt event handler.  The
callback procedure for XtAddInput wrapper procedure that runs
Tk_OneEvent(1).  There might be problems with Tk file sources which
aren't registered with Xt.

Thanks to joe@astro.as.utexas.edu (Joe Wang) for this information.

Subject: -Q9c- ,using a machine with less than 8 bit color, run?

A9c. Tk doesn't behave very well with less than 8-bit color screens.  To
try to use it, find all the places in the Tk/wish source where 
DefaultDepthOfScreen is invoked to test the number of bit-planes.  Change all
of these to pretend there is just 1 bit-plane, or call a procedure which
monitors a Tcl variable so that it is configurable, and you should be okay.

Another alternative is to see if the server you are using has alternative
visual / color models, such as static visual, etc.  One of the alternatives
may allow Tk to work better.

Thanks to "Nathaniel Borenstein" <nsb@thumper.bellcore.com> for this info!

Subject: -Q9d- set X11 resources for a wish application in an app-defaults file?

A9d. Read the documentation for the option command.
Then you should consider something like the following - assume the program
name is xwf.

The following are two general purpose functions to put into a library:

# envVal envValName
#   Looks up the envValName environment variable and returns its
#   value, or {} if it does not exists
proc envVal {envValName} {
  global env
  if [info exists env($envValName)] {return $env($envValName)} {return {}}
}

# loadAppDefaults classNameList ?priority?
#   Searches for the app-default files corresponding to classNames in
#   the order specified by X Toolkit Intrinsics, and loads them with
#   the priority specified (default: startupFile).
proc loadAppDefaults {classNameList {priority startupFile}} {
  set filepath "[split [envVal XUSERFILESEARCHPATH] :] \
		[envVal XAPPLRESDIR] \
		[split [envVal XFILESEARCHPATH] :] \
		/usr/lib/X11"
  foreach i $classNameList {
    foreach j $filepath {
      if {[file exists $j/$i]} {
	option readfile $j/$i $priority; break
      }
    }
  }
}

# Now, here is what you would put into xwf:

option add Tk.BoldFont "*-lucida sans-Bold-R-Normal-*-100-*" widgetDefault
loadAppDefaults {xwf XWF} userDefault

This sets a program default, then load any defaults specified in the user's
default resources and finally any site or general app-defaults resource.  
Of course, you would want to add some xwf command line handling to allow 
the user to override things at execution time.

Subject: -Q9e- change the X11 cursor?

A9e. Here is a tip from mgc@cray.com (M. G. Christenson).

Look at /usr/include/X11/cursorfont.h for a list of available cursors.
You can use the names in there by removing the 'XC_'.  

Here's a little proc I use to make my entire application go 'busy'
while it's doing something. Just call it with the commands you want to
execute, and the watch cursor will be displayed for the time it takes
the commands to complete.  Note that any new windows will have their
normal cursor.

proc busy {cmds} {
    global errorInfo

    set busy {.app .root}
    set list [winfo children .]
    while {$list != ""} {
	set next {}
	foreach w $list {
	    set class [winfo class $w]
	    set cursor [lindex [$w config -cursor] 4]
	    if {[winfo toplevel $w] == $w || $cursor != ""} {
		lappend busy [list $w $cursor]
	    }
	    set next [concat $next [winfo children $w]]
	}
	set list $next
    }

    foreach w $busy {
	catch {[lindex $w 0] config -cursor watch}
    }

    update idletasks

    set error [catch {uplevel eval [list $cmds]} result]
    set ei $errorInfo

    foreach w $busy {
	catch {[lindex $w 0] config -cursor [lindex $w 1]}
    }

    if $error {
	error $result $ei
    } else {
	return $result
    }
}

Subject: -Q9f- raise or lower a window?

A9f. This is on the (semi-infinite) list of things to be done in the future.
If you have the time, please go ahead and add it and submit the code and all
will be grateful.

Subject: -Q9g- re-map a withdrawn window id?

A9g. Use wm deiconify <windowid>.

Subject: -Q9h- specify bitmap patterns on the command line instead of as 
a file name?

A9h. You can not, at least as of June, 1992.

Subject: -Q9i- change the default class bindings?

A9i. All default class bindings for Tk widgets are initialized in
$tk_library/tk.tcl.  Use this file as a guide to implement new
bindings.  For instance, the following code duplicates Button 1's
drag-select facility in Button 3 for all listboxes:

bind Listbox <3> {%W select from [%W nearest %y]}
bind Listbox <B3-Motion> {%W select to [%W nearest %y]}

Subject: -Q9j- delete a binding?

A9j. Give an empty-string command to the "bind" invocation.  For
example, to disable the Delete key in all entry fields:

	bind Entry <Delete> {}

Subject: -Q9k- change a binding while it is being executed?

A9k. As of June, 1992, this was not a safe thing to do in Tk.  It was
put on the bug list by John Ousterhout to be fixed in a future version.

The solution for now is not to change the bindings, but to change
something in the code they execute.  For example, keep a state variable
that indicates which binding you'd like, but always have the binding
call a given procedure.  Then that procedure checks the variable and
executes one piece of code or another.  Or, you could just make the
binding's command "eval $cmd" and then change the variable "cmd"
depending on your application's state.

Subject: -Q9l- bind the arrow key on my Sun keyboard?

A9l.  You have to call it <Left> rather than <R10>.  Under X11, keys are
referred to by their keysym.  One can use either xmodmap -pk or the xev
program to determine what the keysym a particular key on a keyboard is
currently generating.

If the keysym that is being used is not known by Tk, you may have to edit
it's ks_names.h file.  There is a note in this file that indicates that
one should not edit it - but this is where the keysym must be for it to
be recognized.

Thanks to Wayne Christopher <faustus@ygdrasil.CS.Berkeley.EDU> for this
note.

Subject: -Q9m- resize a listbox?

A9m. Use wm min/maxsize - in a uniform manner.  Here is a resizable listbox:

        #!/usr/local/bin/wish -f
        wm minsize . 20 20
        wm maxsize . 1152 900
        pack append . [listbox .l -borderwidth 2 -relief raised] {expand fill}

Doing the same with the text widget brings its resizing under control too.

Thanks to "John C Ellson" <ellson@ontap.att.com).

Subject: -Q9n- select two items that are not adjacent in the listbox at 
		one time?

A9n. You can't.  Build your own listbox using boxes and text on a canvas.
Then you will be able to select non-contiguous entries.

Subject: -Q9o- select items in more than one tk listbox at a time?

A9o. The default for tk's listbox widget exports its selection as the
X selection.  There can only be one of these at a time.

To turn of this behavior in tk, use the -exportselection false when
you create the listbox.  Or, use the

option add *Listbox.exportselection false

command in the beginning of your script.

Thanks to David Herron <david@twg.com> for this tip.

Subject: -Q9p- fill a canvas which is bounded by lines as opposed to a
shape like a polygon, oval, etc.?

A9p. No, you have to at least use a polygon if you want to fill an area
bounded by some lines.

Subject: -Q9q- create a scrollable window of buttons?

A9q.  There are at least two ways to do this.  First, there is a hypertext
widget that one can get from the Barkley User Contributed Code Archive which
provides such a facility.  And here is some sample code from 
"Michael Moore" <mdm@stegosaur.cis.ohio-state.edu> which shows a way to 
do this using just Tk.

#! /bin/wish -f
#
# This demonstrates how to create a scrollable canvas with mutliple
# buttons.
#
# Author : Michael Moore
# Date   : November 17, 1992
#

#
# This procedure obtains all the items with the tag "active"
# and prints out their ids.

proc multi_action {} {
    set list [.frame.canvas find withtag "active"]
    puts stdout "Active Item Ids : "
    foreach item $list {
	puts stdout $item
    }
}

# 
# This simulates the toggling of a command button...
# Note that it only works on a color display as is right now
# but the principle is the same for b&w screens.
# 
proc multi_activate {num id} {
    
    set tags [.frame.canvas gettags $id]
    if {[lsearch $tags "active"] != -1} {
	.frame.canvas dtag $id "active"
	.frame.canvas.button$num configure \
	    -background "#060" \
	    -activebackground "#080" 
    } else {
	.frame.canvas addtag "active" withtag $id
	.frame.canvas.button$num configure \
	    -background "#600" \
	    -activebackground "#800"
    }
} 

proc setup {} {
     frame .frame

     scrollbar .frame.scroll \
         -command ".frame.canvas yview" \
         -relief raised

     canvas .frame.canvas \
         -yscroll ".frame.scroll set" \
         -scrollregion {0 0 0 650} \
         -relief raised \
	 -confine false \
	 -scrollincrement 25

     pack append .frame \
         .frame.scroll    {left frame center filly} \
         .frame.canvas    {left frame center fillx filly}

     pack append .\
         .frame   {left frame center fillx filly}

     button .frame.canvas.action  \
         -relief raised \
         -text "Action" \
	 -command "multi_action"
     .frame.canvas create window 1 25 \
	 -anchor w \
         -window .frame.canvas.action
     for {set i 2} {$i < 26} {incr i} {
	 button .frame.canvas.button$i  \
	    -relief raised \
	    -background "#060" \
	    -foreground wheat \
	    -activebackground "#080" \
	    -activeforeground wheat \
	    -text "Button $i" 
	 set id [.frame.canvas create window 1 [expr $i*25] \
	    -anchor w \
	    -window .frame.canvas.button$i]
	 .frame.canvas.button$i configure \
	    -command "multi_activate $i $id"
    }
}

setup
-- 
Larry W. Virden                 UUCP: osu-cis!chemabs!lvirden
Same Mbox: BITNET: lvirden@cas  INET: lvirden@cas.org
Personal: 674 Falls Place,   Reynoldsburg, OH 43068-1614
-- 
Larry W. Virden                 UUCP: osu-cis!chemabs!lvirden
Same Mbox: BITNET: lvirden@cas  INET: lvirden@cas.org
Personal: 674 Falls Place,   Reynoldsburg, OH 43068-1614