#!/bin/sh
# This is a Tcl/Tk script to be interpreted by wish (Tk4.0 or better): \
exec wish "$0" "$@"

##########################################################################
# Version of TkInfo:
set tki_version 1.3
#
# Authors:	Kennard White <kennard@ohm.eecs.berkeley.edu> (up to 0.7)
# 		Axel Boldt <boldt@math.ucsb.edu> (beginning with 0.8)
# Copyright:	see below
# RCS:		$Id: tkinfo,v 1.18 1997/03/08 23:43:26 axel Exp $
#
# Tk script to read GNU "info" files and display them.  tkInfo can be
# used stand alone (via WISH), embedded within an application to provide
# integrated, on-line help, or used as a server tool for on-line application
# help.
#
# Please see the "About" and "Info" file sections below.  (search for
# "README" to find these sections quickly).  These explain much more
# about what tkInfo is and what info files are, and gives references to
# other programs and sources of info.  For information on the internals
# of tkInfo, see the roadmap below.
#
# The program provides on-line help about itself: start it and type 'h'.
#
# This release should work with tcl7.4/tk4.0 or later.  tkInfo no
# longer works with older versions (sorry).  tkInfo has gone through
# several releases, but it is by no means complete.  Feel free to make
# suggestions, or better yet, send me patch files.
#
# See below for copyright.  Basically you can re-distribute this any
# way you like, just don't sue me and don't pretend you wrote tkInfo.
#
# Contributions and/or good ideas (some minor, some major) by Larry
# Virden <lvirden@cas.org>, Bob Bagwill <bagwill@swe.ncsl.nist.gov>,
# ??? <tlukka@snakemail.hut.fi>, Kurt Hornik
# <hornik@neuro.tuwien.ac.at>, Hume Smith <850347s@dragon.acadiau.ca>,
# Stephen Gildea <gildea@x.org>, Warren Jones <wjones@tc.fluke.COM>,
# Robert Wilensky <wilensky@CS.Berkeley.EDU>, Frank Joachim Leitner
# <ldvhp47.ldv.e-technik.tu-muenchen.de>.
# Tom Phelps <phelps@CS.Berkeley.EDU> contributed the searching code, as
# well as many other good ideas.

set tki_help_usage \
{
TkInfo: Stand-alone usage
-------------------------

    (requires the wish shell (Tk version 4.0 or better))

When invoked with no arguments, tkInfo looks for an "info tree" (a
collection of info files installed on your system) and displays the
top level node.  On a well maintained system, you can get to every
info file starting from this top level node.  Alternatively, you can
specify the file and node you want to see on the command line.

Usage: tkinfo [--help] [-headers | +headers] [-buttons | +buttons] 
              [-nodelook looktype] 
              [-geometry geom] [-display display] [-iconic]
              [-dir dir1] [-dir dir2] ... [node]

Options:
   --help     Produces this help message.
   -/+headers Turns on/off display of the raw info node headers.
   -/+buttons Turns on/off display of the lower button row.
   -nodelook  Specifies how to highlight xrefs and menu entries.  Must
	      be one of "color", "font", or "underline".
   -geometry  Geometry of the window, size in characters and
              location in pixels, format: XxY+A+B or XxY or +A+B.
   -display   X display to use for the tkInfo window.
   -iconic    Start the first window in iconic state.
   -dir       Specifies directories to search for info files, in addition 
              to those contained in the INFOPATH environment variable.
              The directories specified with -dir will be searched first,
              in the order given.
   node	      Specifies the node to visit initially. Possible formats:
                 "(filename)nodename"  most general
                 "(filename)"          equivalent to (filename)Top
                 "filename"            equivalent to (filename).
              If filename is not absolute, the info directories (from 
              INFOPATH and -dir) will be searched. If filename cannot be 
              found, its lower case version will be tried.
              An alternative way to specify the node "(FILE)NODE" is 
	      with "-file FILE -node NODE".
	      If no node is given, the default "(dir)Top" is used.

Environment variables:
   INFOPATH	A colon (``:'') separated list of directories to search
		for info files. More directories can be given with -dir 
                option, above. If not set, TkInfo will try various
                standard directories that should be ok for most systems.
   INFOSUFFIX	A colon separated list of file suffixes to try when searching
		for an info file. If not set, tkinfo will try the suffixes
                "", ".info", and "-info". In addition, tkinfo will
                always automatically try the suffixes .Z, .z, and .gz
                and deal with the compressed file if necessary.
}; set tki_custom \
{
How to customize tkInfo
-----------------------

The colors, fonts, and geometry of tkInfo can be customized using the
usual X options database. A random example follows. You can either put
(parts of) this in your .Xdefaults or .Xresources file or you can
create a global file /usr/lib/X11/app-defaults/tkinfo that will apply
to all users of your site. To have the new options take effect,
restart your X server or use the program xrdb. More information about
the X options mechanism is available from the X man page.

Windows and Mac users can't do this, but they can change the "option" 
lines in the procedure tkiInit in the script itself.


=========== snip ==================================================
! These tkInfo settings are annoying on purpose, just to demonstrate 
! what harm an evil mind can do.
!
! Specify the size in characters, the position in dots. You can also
! leave the position out.
tkinfo.geometry:                80x40+10+10
! How the links are highlighted. Can be one of "color" (default),
! "underline" (default on b&w terminals), or "font".
tkinfo*nodelook:                font
! The following is only used if linkstyle is set to "color"
tkinfo*linkcolor:               red
! The following is only used if linkstyle is set to "font".
tkinfo*linkfont:                  -*-courier-bold-o-normal-*-16-*-*-*-*-*-*-*
! To switch off the lower row of buttons. (The default is "1" which means 
! display the buttons.)
tkinfo*showbuttons:             0
! To switch off display of the full info file headers. (The default is "1" 
! which means show the info headers).
tkinfo*showheaders:             0
! You can specify colors either as names (on my system, they are defined in 
! /usr/lib/X11/rgb.txt), or in the format #C0F1DD as a sequence of three 
! hex numbers giving the red-green-blue components.
tkinfo*background:              yellow
tkinfo*Text.background:         orange
! The "trough" is the area where the scrollbar moves.
tkinfo*troughColor:             blue
! This is for disabled menuentries and buttons.
tkinfo*disabledForeground:      #F00909
tkinfo*activeBackground:        blue
tkinfo*foreground:              black
! Font for the buttons and messages. You can find nice fonts with the program
! xfontsel.
tkinfo*font:                    -*-helvetica-bold-r-normal-*-16-*-*-*-*-*-*-*
tkinfo*Text.font:               -*-courier-medium-r-normal-*-16-*-*-*-*-*-*-*
! If you don't like the window owning the focus being highlighted:
tkinfo*highlightThickness:      0
! Change the different mouse pointers here; the available cursornames
! are contained in the file /usr/include/X11/cursorfont.h on my system.
tkinfo*linkcursor:              "double_arrow"
tkinfo*normcursor:              "fleur"
tkinfo*waitcursor:              "heart"
=========== snip ==================================================


You can disable the X default mechanism altogether by setting the variable 
Priority to "interactive" in the procedure tkiInit.

}; set tki_roadmap \
{
Roadmap through the tkInfo source
---------------------------------

This is for people familiar with Tcl/Tk who want to hack on tkInfo.
You should read the tkinfo source along with this roadmap.

We keep a global array of variables tki() to store things such as the
current status of the user-toggable options, the current window, list
of all windows, the mouse position at button-press events, and the
extracted information of already parsed info files (including their
full node text, see below). We also have a global array of variables
for every toplevel window; the array has the same name as the window
and is usually called wvars() through a call to upvar. We use wvars() to
store displayed status messages, the name of the displayed node, the
list of previously visited nodes, the string being searched for etc.

The widget tree looks like this: the toplevel windows are called
.tki1, .tki2, etc. .tki1.bar is the menubar with buttons .file, .node,
.view, .options, and .help. The associated menus are called
.tki1.bar.file.m and so on. The main text window is called
.tki1.main.text and its scrollbar is .tki1.main.vsb. Then there is the
the button row .tki1.buts with buttons .next, .prev, .up, and .last
and the status line .tki1.s with status message .tki1.s.status and 
user prompt area .tki1.s.goto (which is only displayed if needed).

tkInfo requires the following global variables:
 tki		This is a huge array where all the loaded info-files
		are stored.  It also contains some configuration state.
		The contents of this is described below.
 .tki##		Each toplevel info window has a global variable associated
		with it.  The name of the variable is the same as the
		toplevel window name, which is ".tki" followed by some number.
 tkiEmbed	tkInfo can operate stand-alone (like the "info" program) or
		embedded (part of your application).  Embedded mode is
		used iff this variable exists.  When this file is
		sourced in the stand-alone case, the argv options will be
		parsed (see tkiBoot() below) and a new toplevel window
	 	will be opened.


tkInfo may be used in one of three modes: stand alone, embedded or
as a server tool.  These modes are described below:

Stand-alone
	In this mode, the user directly invokes tkinfo, and directly
	manipulates it to display the nodes of interest.  This mode
	requires that the shell script "tkinfo" be proper configured,
	and that the info path be properly configured, either 
	by editing the default info path in "tkinfo.tcl"/tkiInit(),
	or by the user's INFOPATH environment variable.  The file
	"tkinfo.tcl", as well as the built-in help contains additional
	information (command line arguments) for this mode.

Embedded
	In this mode, your application will include tkinfo as part of
	its distribution, and tkinfo will run within the same process
	and the the same TCL interpreter as your application.  tkInfo
	is written with this in mind, and avoids name space pollution.
	In this mode, tkInfo doesn't do anything until the application
	explicitly request an action by calling tkiWinShow(); normally
	the application will do this in response to the user selecting
	a "Help" button or pressing a "Help" key.

	To use this mode, your application must set the global variable
	``tkiEmbed'' to any value and then source "tkinfo.tcl" (the
	auto-load facility may replace explicitly source'ing
	"tkinfo.tcl", but ``tkiEmbed'' must be set before this
	happens).  tkInfo attempts to minimize start up time and will
	not explicitly source all of its files; for this reason, the
	tclIndex must be valid and the auto-load facility active.
	tkiAddInfoPaths() should be called by the application to let
	tkInfo know where the application's info files are installed.
	The application should call tkiWinShow() to display a window.
	Also, the application may find tkiWinContextHelp() useful
	for processing "Help" key bindings.

Server Tool
	From the user's perspective, this is very similar to the
	Embedded mode, but the implementation is different.  In this
	mode, tkInfo runs as in the stand-alone mode, but responds to
	requests from other applications via Tk's "send" mechanism.
	The application must rendezvous with tkInfo (locating the
	existing server or starting a new server running) and makes
	calls to tkiAddInfoPaths() and tkiWinShow() as in the embedded
	case (but via "send").  The application may wish tkInfo to
	dedicate a single window to the application, the "window tag"
	feature of tkiWinShow() may be useful for this.


The core structure of an info file is a {node}.  Each info file consists
of a set of nodes separated by a magic character.  Each nodes consists of
of a header, body, and menu.  There are also special nodes that contain
control information used to reference "split" files and speed up access.
A node may be specified in one of several ways (called a {nodeSpec}):
	(filename)nodename      Explicit.
	nodename		The given node within the current file.
	(filename)		The "Top" node of the file.
If a filename can't be found, we try the lower case version; if a nodename 
can't be found we try case insensitive match.

In the implementation below, the info format consists of {nodes} stored 
in files.  A given info file has three identifiers associated with it:
 -	The {filename}, which is the name used either by the user to
	reference a file, or by one info file to reference another.
	Such a reference could be complete UNIX path name (either
	absolute or relative), or may be a partial specification (see below).
 -	The {filepath}, which is a valid UNIX path name to access the
	file.  The filepath is derived from the filename.  If the filename
	is already a valid path, no work needs be done.  Otherwise,
	the filepath is formed by prepending a path prefix and appending
	a file suffix.  These are defined by the INFOPATH and INFOSUFFIX
	variables.
 -	The {filekey}, which is an internal, auto-generated token associated
	with each file.


The global array "tki" contains the following elements about the
already parsed files:
  file-$fileName	The fileKey for $fileName.
  fileinfo-$fileKey	The fileinfo struct for $fileKey. Each fileinfo is
			{ fileKey fileName filePath pntKey wholeB }
  incore-$fileKey	Boolean 0/1; true if file has been loaded into core.
  nodesinfo-$fileKey	A list of nodeinfo for every node in $fileKey.
			Each nodeinfo is a list { idx node file up prev next }.
  nodesbody-$fileKey	A list of the textual body for every node in $fileKey.
  indirf-$fileKey	List of indirect-file-info for $fileKey.  Each
			info is a list { indirFileKey byteOfs }.
  indirn-$fileKey	List of indirect-node-info for $fileKey.  Each
			info is a list { nodeName byteOfs fileKey }.
  xrefinfo-$fileKey-$nodeIdx
			Contains information on all cross reference
			pointers within the node's body text.
  menuinfo-$fileKey-$nodeIdx
			Contains information on all menu entries
			within the node's menu text.  Consists of list of:
			 { linecnt menucnt toNode nBeg nEnd menutxt }

Notes (some important, some not).
1.	Because of the graphical system, there may be several parallel
	info windows active.  These windows must operate independently.
	Because of this, there can be no concept of the "current file"
	or "current node" within the tkinfo core.  Rather, this information
	must be maintained by the window.
2.	Because of #1, we must maintain multiple files in core.  Currently
	we never flush.
3.	The background color used in tkiInit() is BISQUE1, from tk/defaults.h
4.	The byte offsets in the indirect tables are not used as such;
	this is because we parse the file when loaded.  However, they are
	used to identify which indirect file the node is in.
5.	The function tkiLoadFile() attempts to deal with compressed files.
	Currently it uses "zcat" for .Z files and "gunzip -c" for .z and .gz
	files.
	If you have better suggestions, please let me know.


Here are descriptions of the more important procedures:

tkiInit 
   Initializes the default INFOPATH and other global variables such as
   the default geometry, link color, cursor etc.  It also sets the
   regular expression used for parsing info files by calling
   _tkiNodeParseInit and sets up the builtin info pages by calling
   _tkiBuiltinFile (which does its job by setting up the relevant
   tki() variables so that it looks like tkInfo has actually parsed
   the builtin info "files").

tkiTimeStatus
   takes a script as argument, executes it, and prints the time it
   took on stdout. This can be used to profile tkinfo if the option
   "Time Status" is enabled from the option menu. Several crucial
   calls are wrapped in a tkiTimeStatus.

tkiInfoWindow
   Accepts the same arguments as tkinfo. It first parses the options
   using topgetopt, processes them, and then calls tkiWinShow to
   actually create the new window and display the node.

tkiWinShow
   The main entry point: takes the specification of an info node,
   creates a new window, and displays the node. This is also suitable
   for being called from other tcl programs via send.

_tkiWinShowIdle 
   is now nothing but a synonym for tkiWinShow.

tkiWinCreate
   creates a toplevel window with all its subwindows. Also initializes
   the winfo() variables for that window. Creates all bindings except
   those for the main text window which are handled by _tkiWinBind.

_tkiWinBind
   Creates all the bindings for the text window and search entry
   boxes. Many of these bindings are created automatically via
   _tkiBindAccels from the accelerators of the various menu
   entries. If you have bindings to add, here's the place.

_tkiWinAction
   The central manager of all actions that can be performed by the user
   on a window, such as quitting, scrolling, searching, and moving to
   other nodes. The actions themselves are actually handled by other
   procedures.  This function is designed to be bound to various
   events.

_tkiWinDpyNode
   Inserts a node into the current text window, complete with tags. The
   actual parsing is done in tkiNodeParseBody. Stores the parse results
   in tki() for later reuse. Also updates the Next/Previous/Last button
   bindings.

tkiWindDpy
   wrapper around _tkiWinDpyNode for public use.

tkiWinContextHelp
   helper function for the case where tkinfo is embedded in a larger
   application. The app can associate an infonode spec to every major
   window, and this function will display the associated node in a new
   tkinfo window.

tkiFileGet
   loads a file into memory and returns the filekey using tkiFileFind
   and tkiFileLoad.

tkiFileFind
   returns the full filename of a partially specified info file using
   the list of info directories and info suffixes and compression
   suffixes.

tkiFileLoad
   loads an info file and parses its nodes using tkiFileParseNode in
   order to fill up the respective entries in tki(). tkiFileParseNode
   has to deal with tag tables (which describe where in a file a node
   is located) and indirect tables which point to other info files.

tkiGetNodeRef
   locates an info node wherever it is; loads the info file if
   necessary. Info files can be split; for example, emacs.info is only
   a short table containing pointers to the info files emacs-1 to
   emacs-29. This is called an "Indirect" table, and emacs.info is
   called the parent of the other emacs info files. tkiGetNodeRef
   deals with this mess transparently, calling itself recursively on a
   child if necessary.

tkiNodeParseBody
   parses the body of a node to locate all crossreferences, and
   returns a list of them to be stored in tki().

tkiNodeParseMenu
   parses the body of a node to locate all menu entries, and returns a
   list of them to be stored in tki().

_tkiWinManPage
   displays a man page in a tkman window. Either starts a new tkman or
   contacts an existing one. Communication is via the tcl send
   mechanism. This does not work if you X server is insecure; use xdm
   to get a secure session.

_tkiBindAccels
   a nice utility function to support accelerator keys in menus.

searchboxSearch and searchboxNext
   support for searching, regexp or normal, ready to be bound to
   events.

TextSearch and regexpTextSearch
   used by the searchbox functions to locate all matching strings in a
   text window and to apply a given tag to them.

searchboxKeyNav
   not used right now, but appears to have some support for
   incremental search?

}

#
# README: You might want to customize "defInfoPath" below for your site,
#	  just put your paths there and remove the others for faster 
#         startup. 
#	  If you feel there is a "standard" location not listed below,
#	  please send me mail.
#
proc tkiInit { } {
    global tki env auto_path tkiEmbed geometry

    set defInfoPath [list . \
      /usr/info /usr/local/info /usr/local/gnu/info \
      /usr/local/emacs/info /usr/local/lib/emacs/info \
      /usr/lib/xemacs/info /usr/local/lib/xemacs/info \
      /usr/tools/gnu/info /usr/sww/info /usr/sww/lib/emacs/info \
      /usr/gnu/info \
      ]

    set Priority startupFile
    # If you want to disallow overriding the following options 
    # from .Xdefaults:
    #set Priority interactive

    option add *geometry                80x30    $Priority
    option add *background		#d9d9d9  $Priority
    option add *foreground		Black    $Priority
    option add *linkcolor               blue     $Priority
    option add *Text.background		#d9d9d9  $Priority
    option add *Text.foreground		Black    $Priority
    option add *font			"-*-helvetica-bold-r-normal-*-12-*-*-*-*-*-*-*" $Priority
    option add *Text.font		"-*-courier-medium-r-normal-*-12-*-*-*-*-*-*-*" $Priority
    option add *linkfont                "-*-courier-bold-o-normal-*-12-*-*-*-*-*-*-*" $Priority
    option add *nodelook                "color" $Priority
    if { "[info commands winfo]"!="" } {
	if { [winfo depth .] == 1 } {
	    option add *nodelook "underline" $Priority
	}
    }
    option add *showbuttons             "1" $Priority
    option add *showheaders             "1" $Priority
    option add *linkcursor		"hand2" $Priority
    option add *normcursor		"left_ptr" $Priority
    option add *waitcursor		"watch" $Priority
    

    set defInfoSuffix [list "" .info -info]

    if { [info exist tki(sn)] } return

    set tki(sn)			0
    set tki(self)		[info script]
    set tki(detailstatusB)	0
    set tki(timestatusB)	0
    set tki(iconic)             0
    set tki(compresscat-Z)	"zcat"
    set tki(compresscat-z)	"gunzip -c"
    set tki(compresscat-gz)	"gunzip -c"
    set tki(rawHeadersB)	[option get . showheaders Showheaders]
    set tki(showButtonsB)	[option get . showbuttons Showbuttons]
    set tki(nodeSep)		"\037"
    set tki(nodeByteSep)	"\177"
    set tki(topLevelFile)	"dir"
    set tki(topLevelNode)	"Top"
    set tki(lastDir)            "(dir)"

    # The global $geometry is set by wish if -geometry was given on
    # the command line. The command line option is eaten by wish and
    # we will never see it.
    set tki(geometry)           [option get . geometry Geometry]
    if { [info exists geometry] } {
        if { [string match "+*" $geometry] } {
            regexp "\[^\\+\]*" $tki(geometry) dummy
            set tki(geometry) $dummy$geometry
        } else {
            set tki(geometry) $geometry
        }
    }

    set tki(nodelook)		[option get . nodelook Nodelook]
    set tki(nodelookColor)	[option get . linkcolor Linkcolor]
    set tki(nodelookFont)	[option get . linkfont Linkfont]
    set tki(linkCursor)		[option get . linkcursor Linkcursor]
    set tki(normCursor)		[option get . normcursor Normcursor]
    set tki(waitCursor)		[option get . waitcursor Waitcursor]
    set tki(windows)		""
    set tki(curWindow)		""
    if [info exist env(INFOPATH)] {
      tkiAddInfoPaths [split $env(INFOPATH) ":"]
    } else {
      tkiAddInfoPaths $defInfoPath
    }

    if [info exist env(INFOSUFFIX)] {
	set tki(infoSuffix) [split $env(INFOSUFFIX) ":"]
    } else {
	set tki(infoSuffix) $defInfoSuffix
    }

    _tkiNodeParseInit
    rename _tkiNodeParseInit ""

    _tkiBuiltinFile
    rename _tkiBuiltinFile ""

    trace var tki(rawHeadersB) w "_tkiTraceOptionsCB"
    trace var tki(showButtonsB) w "_tkiTraceOptionsCB"
    trace var tki(nodelook) w "_tkiTraceOptionsCB"
}

proc _tkiTraceOptionsCB { n1 n2 op } {
    tkiWinRefreshAll
}

proc tkiUninit { } {
    global tki
    # Must destroy all existing windows so that there is no trace
    # on anything in $tki.  Note that the "Options" menu does direct
    # traces on stuff in tki.
    catch {eval destroy $tki(windows)}
    catch {unset tki}
}

proc tkiReset { } {
    tkiUninit
    tkiInit
}

proc tkiStatus { msg } {
    global tki
    if { "$tki(curWindow)"=="" } {
        puts stdout "tkInfo: $msg"
    } else {
	$tki(curWindow).s.status conf -text "$msg"
	# idletasks should be sufficient, but the geometry management
	# apparently needs some X-events to make the redisplay occur
	update
    }
}

proc tkiDetailStatus { msg } {
    global tki
    if { $tki(detailstatusB) } {
	tkiStatus $msg
    }
}

proc tkiWarning { msg } {
    # Warnings always go to stderr
    puts stderr "tkInfo Warning: $msg"
}

proc tkiFileWarning { fileSpec msg } {
    global tki
    if [info exist tki(fileinfo-$fileSpec)] {
	set fileSpec [lindex $tki(fileinfo-$fileSpec) 2]
    }
    tkiWarning "$fileSpec: $msg"
}

proc tkiError { msg } {
    global tki
    if [info exist tki(error-active)] {
	puts stderr "tkInfo Warning: Re-entrant error message!"
        return
    }
    set tki(error-active) 1
    if { "$tki(curWindow)"=="" } {
        puts stdout "tkInfo Error: $msg"
    } else {
	set infowin $tki(curWindow)
	upvar #0 $infowin wvars
        $infowin conf -cursor  $tki(normCursor)
        $infowin.main.text conf -cursor $tki(normCursor)
#        set wvars(status) [$infowin.s.status cget -text]
        $infowin.s.status conf -text "Error!"
	set w .tkierr[tkiGetSN]
	if ![winfo ismapped $infowin] {
	    tkwait vis $infowin
	}
	toplevel $w
	wm geom $w +[winfo rootx $infowin]+[winfo rooty $infowin]
	wm title $w "tkInfo Error"
	wm iconname $w "tkInfo Error"
        grab $w
	pack append $w [label $w.title -text "tkInfo Error"] \
	  {top fillx}
	pack append $w [message $w.msg -text $msg \
	  -width [winfo width $infowin]] {top fill expand}
	pack append $w [button $w.dismiss -text "Dismiss" \
	  -com "tkiErrorDone $w $infowin"] {top fillx}
        bind $w <Key-Return> "tkiErrorDone $w $infowin"
        focus -force $w.dismiss
	tkwait window $w
        $infowin.s.status conf -text $wvars(status)
        focus -force $infowin.main.text
    }
    unset tki(error-active)
}

proc tkiErrorDone { errwin infowin } {
    catch {destroy $errwin}
}

#
# This is complicated by the fact that "time" doesn't provide access to
# the return value.  Thus "cnt" is used as follows:
#	0 ==> Do once for timing, and repeat for return value (no side-affects)
#	1 ==> Do once for timing&side-affects, empty return value
#
proc tkiTimeStatus { msg cnt args } {
    global tki
    if { $tki(detailstatusB) } {
	tkiStatus $msg
    }
    if { $tki(timestatusB) } {
	puts stdout "tkInfo time: $msg [lindex [time $args] 0] microseconds"
	if { $cnt == 0 } {
	    return [eval $args]
	} else {
	    return ""
	}
    } else {
	return [eval $args]
    }
}

#
# This proc is called once during initialization, and then destroyed.
# (It is destroyed to save memory).
# Currently we fake all the appropriate table entires to create a "builtin"
# file.  It might be easier, however, to just pass one large text string
# into the parser and have it be dealt with like any other file.
#
proc _tkiBuiltinFile { } {
    global tki tki_help_usage tki_roadmap tki_version tki_custom

    set fileKey			builtin
    set tki(file-$fileKey)	$fileKey
    set tki(fileinfo-$fileKey)	[list $fileKey $fileKey $fileKey "" 0]
    set tki(incore-$fileKey)	1
    set tki(nodesinfo-$fileKey) ""
    set tki(nodesbody-$fileKey) ""


    tkiFileParseNode $fileKey "
File: builtin, Node: Top, Up: (dir)Top, Next: About

TkInfo
------

This is the builtin info on tkInfo itself.  If you need help on using
tkInfo, try selecting \"Quick Help\" or \"Plain Info\" below. Select
an item by moving the mouse over the highlighted text and pressing the
left or middle mouse button.

* Menu:
* About::		About tkInfo.
* Info::		Info files.
* Quick Help::		Quick summary of how to use tkInfo.
* Plain Info::		Tutorial on using the plain info.
* Command Line::	TkInfo's command line options.
* Customization::	Customizing tkInfo's colors, fonts, etc.
* Source::		Roadmap through the source, for tcl hackers.
* To Do::		Projects for YOU to work on.
* Copyright::		TkInfo's copyright.
"

#VERSION README
    tkiFileParseNode $fileKey "
File: builtin, Node: About, Up: Top, Next: Info, Prev: Top

About tkInfo
------------

This is tkInfo version $tki_version, built at \$Date: 1997/03/08 23:43:26 $.

tkInfo displays ``info'' files.  Info files provide a hyper-text
capability that is ideal for on-line help.  The format is suitable for
both text-based systems and graphical systems.  In addition, the same
document source can produce both a nice hardcopy manual and Info
files.  For more information, *note Info::.

The versions of tkInfo up to 0.7-beta were written by Kennard White
(kennard@ohm.eecs.Berkeley.EDU).  You can obtain the tkInfo
distribution up to version 0.7-beta by anonymous ftp from:

	ftp://ptolemy.eecs.berkeley.edu/pub/misc

Axel Boldt (boldt@math.ucsb.edu) adapted tkInfo for newer tcl/tk
versions and added some features. The versions 0.8 and later are at
        
        http://www.math.ucsb.edu/~boldt/tkinfo/



RCS: \$Id: tkinfo,v 1.18 1997/03/08 23:43:26 axel Exp $
    "

    tkiFileParseNode $fileKey {
File: builtin, Node: Info, Up: Top, Prev: About, Next: Quick Help

Info Files
----------

tkInfo displays "info" files, a file format that supports a robust
hypertext system which is ideal for on-line help.  Each info file
contains several "nodes", units of information that can contain
crossreferences to other nodes.  Some nodes also contain menus
pointing to subnodes, thus creating a tree like structure. These
subnodes specify their parent as their "up node". Furthermore, most
nodes specify a "next node" and a "previous node" on the same level,
and this yields a convenient way to traverse the tree.

In order to visit all the nodes in an info file, you can use the
following method: if the current node contains a menu, go to the first
entry you haven't seen already; if it doesn't contain a menu but
specifies a "next node", go there; finally, if neither a menu nor a
"next node" is present, go to the "up node" and continue from there.

The top-level info file is called "dir", is usually contained in a
directory called "info", and (hopefully) lists all the other info
files on your system (typically about GNU software, since most GNU
software is documented using texinfo). This is where tkinfo starts out
by default.

Info files are usually created automatically using the GNU "makeinfo"
program from sources in the texinfo format. These sources can also
easily be used to create high-quality printed hard copies, and texinfo
is therefore an ideal format for software documentation. Texinfo files
are most easily created using the texinfo mode of the editor Emacs.
LaTeXinfo is similar to texinfo but it provides some enhancements and
uses LaTeX syntax.

Portions of the GNU "makeinfo" program are GNU copylefted, but only
the author of the document needs "makeinfo": the author can freely
redistribute the info files produced by "makeinfo" (the ones read by
this program).  I think latexinfo is similar.

Besides tkInfo, there are several other info file browsers or viewers:
  
  emacs info mode:   info files originated with this editor.
  info:              a text-based info reader, commands similar to emacs.
  Xemacs info mode:  better than emacs, but huge.
  xinfo:	     an X11 athena-based program (old and unsupported).
  info2www:          converts info files on the fly to HTML for the WWW.
  texi2html:         converts texinfo files to HTML (results look better 
                     than info2www's, but need to be stored permanently).

See the texinfo package for the info viewer, makeinfo program,
emacs info mode and general information about info files.

All these info packages may be obtained from:

texinfo:     ftp://prep.ai.mit.edu/pub/gnu/
latexinfo:   ftp://ftp.duke.edu/tex-archive/macros/latex209/contrib/latexinfo
emacs:       ftp://prep.ai.mit.edu/pub/gnu/
xinfo:	     ftp://wuarchive.wustl.edu/systems/gnu/
info2html:   http://www.ericsson.se/info2www/info2www.html
texi2html:   http://wwwcn.cern.ch/dci/texi2html/
    }

    tkiFileParseNode $fileKey {
File: builtin, Node: Quick Help, Up: Top, Prev: Info, Next: Plain Info

tkInfo Commands
---------------

Use scroll bar or drag with middle mouse button to scroll through the
node text.  Cross references and menu entries are shown highlighted.
Press left mouse button over highlighted text to view that node in the
current window, or press middle mouse button to view it in a new window.
Access menus by holding down ALT and pressing the underlined letter.

Accelerator keys:
n       Move to the "next" node of this node.
p       Move to the "previous" node of this node.
u       Move "up" from this node.
d       Move to the "directory" node of the first tree.
l       Move back to the "last" node you were at, stack based.
t       "Toggle" to last node you were at, toggle based.
?       Show this quick help message.
h       Show builtin info file describing tkinfo.
c       Close current info window.
q       Quit tkInfo.

Advanced commands:
1-9     Pick first, second, etc, item in node's menu and show in current
        window. Use Ctrl-1 - Ctrl-9 to show node in a new window.
Ctrl-m  Jump to the start of current node's menu.
m,f     prompts for beginning of a menu entry (resp. crossreference) in 
        the current node, and then jumps there. If several links match, 
        then the first currently visible one wins. Case does not matter.
        Ctrl-g aborts. 
s,/     Search for text in current node literally (resp. by regular 
        expression). Use the special characters .*+?^$[]()|\ for grep-style 
        regexps. Ctrl-g aborts and Ctrl-u erases the line.
Ctrl-s  Continue previous search.
g,(     Goto given node. Ctrl-g aborts.
        Syntax: NODENAME or (FILENAME)NODENAME or FILENAME.
M       Show manual page using tkman.  Uses selection or prompts.
A       Show unix apropos using tkman. Uses selection or prompts.
!       Issue tcl command, results printed on stdout.

Scrolling commands:
b, HOME, <			 Scroll to the beginning of the node.
e, END,  >			 Scroll to the end of the node.
SPACE, Ctrl-f, Ctrl-v, PgDn	 Scroll forwards one page.
BCKSPC, DEL, Ctrl-b, Alt-v, PgUp Scroll backwards one page.
Crsr DOWN, j, Ctrl-n		 Scroll forwards one line.
Crsr UP, k, Ctrl-p		 Scroll backwards one line.
Ctrl-m				 Jump to beginning of current node's menu.

You can go "up" from this node to obtain more information on tkInfo
and the info system in general, or you can go back to the "last" node 
you visited before coming here.
    }


    tkiFileParseNode $fileKey {
File: builtin, Node: Plain Info, Up: Top, Prev: Quick Help, Next: Command Line

Plain Info
----------

There is a GNU program called "info" that is similar to tkInfo, but
non-graphical and text based.  There is a tutorial info file written
for this program that is available on most systems.  This tutorial
might be useful for some people learning how to use tkInfo.  However,
some of the commands and functionality is different, so don't assume
everything it says applies to tkInfo.  To see this tutorial, select
the menu entry below.

* Menu:
* Plain Info Tutorial: (info)Help.
    }

    tkiFileParseNode $fileKey "
File: builtin, Node: Command Line, Up: Top, Next: Customization, Prev: Plain Info
$tki_help_usage"

    tkiFileParseNode $fileKey "
File: builtin, Node: Customization, Up: Top, Next: Source, Prev: Command Line
$tki_custom"

    tkiFileParseNode $fileKey "
File: builtin, Node: Source, Up: Top, Next: To Do, Prev: Customization
$tki_roadmap"

    tkiFileParseNode $fileKey {
File: builtin, Node: To Do, Up: Top, Prev: Source, Next: Copyright

Todo list
---------

tkInfo is still incomplete.  The following is a list of things to do.
Feel free to send in patches.

-  Add option to allow all the "*note:" to not be drawn on the screen,
   or change them to "see also".
-  Implement stat'ing of the source files with auto-reload.
-  Profile the whole mess: speed up file loading and node formating.
-  Figure out some heuristic for un-loading files to save memory.
-  Extend searching to whole-file search. Incremental search. Glimpse?
-  History of all visited nodes, accessible from a menu.
-  Customizable list of favorites.
-  In short, implement everything from tkman, the mother of all tk 
   scripts.
    }

#README
    tkiFileParseNode $fileKey {
File: builtin, Node: Copyright, Up: Top, Prev: To Do

Copyright for tkInfo
--------------------

This copyright applies to the tkInfo system only.  If tkInfo is
embedded within a larger system, that system will most likely have
a different copyright.

Sorry this is so long.  Basically, do whatever you want with this
software, just don't sue me and don't pretend you wrote it -- kennard.

What little I have added is Copyright (c) 1997 Axel Boldt and is 
covered by the same license below -- Axel.

Copyright (c) 1993 The Regents of the University of California.
All rights reserved.

Permission is hereby granted, without written agreement and without
license or royalty fees, to use, copy, modify, and distribute this
software and its documentation for any purpose, provided that the above
copyright notice and the following two paragraphs appear in all copies
of this software.

IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY 
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES 
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF 
THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF 
SUCH DAMAGE.

THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
ENHANCEMENTS, OR MODIFICATIONS.
    }

# Does this save memory? Who knows, it can't hurt.
set tki_custom ""
set tki_roadmap ""

}


#
# Do stand-alone help window
# The -node option is for compatibility to the info program only.
#
proc tkiInfoWindow { args } {
    global  tki_help_usage tki

    if { ! [info exist tki] } { tkiInit }

    set w ""
    set nodeSpec ""
    set fileSpec ""
    set fileSpec2 ""
    set dirList ""
    set nodelook ""
    set headersB -1
    set buttonsB -1
    set help -1
    set initialIconic -1
    set opt_list { 
        { "window" w } 
        { "dir" dirList append } 
        { "file" fileSpec }
        { "headers" headersB bool }
        { "buttons" buttonsB bool }
        { "help" help bool }
        { "h" help bool }
        { "-help" help bool }
        { "iconic" initialIconic bool }
        { "nodelook" nodelook }
        { "infofile" fileSpec2 }
        { "node" nodeSpec append }
    }

    set args [topgetopt $opt_list $args]

    if { $help != -1 } {puts $tki_help_usage; exit}
    if { "$dirList"!="" } {
	set infoPaths ""
	foreach dir $dirList {
	    eval lappend infoPaths [split $dir ":"]
	}
	tkiAddInfoPaths $infoPaths
    }
    if { "$nodelook" != "" }	{ set tki(nodelook) $nodelook }
    if { $initialIconic != -1 } { set tki(iconic) $initialIconic }
    if { $headersB != -1 }	{ set tki(rawHeadersB) $headersB }
    if { $buttonsB != -1 }	{ set tki(showButtonsB) $buttonsB }
    if { "$fileSpec"=="" }	{ set fileSpec $fileSpec2 }

    if { "$args"!="" } {
	eval lappend nodeSpec $args
    }
    if { [llength $nodeSpec] > 1 } {
	error "tkiInfoWindow: Only one node may be specified"
    }
    set nodeSpec [lindex $nodeSpec 0]
    if { "$fileSpec"=="" && "$nodeSpec"!="" && ![string match "(*" $nodeSpec] } {
        set fileSpec $nodeSpec
        set nodeSpec ""
    }
    if { "$fileSpec"!="" }	{ tkiAddInfoPaths [file dirname $fileSpec] }

    tkiWinShow $nodeSpec $fileSpec $w
    return ""
}

#
# We are operating in one of two modes:
#   1)  Stand-alone.  Popup an initial window, filling it according to argv.
#	Kill the stupid "." window.
#   2)	Embedded within a larger application.  Don't do anything automatically;
#	instead, let that application's startup script handle things.
#
# We are operating in embedded mode iff the global tkiEmbed exists.
#
proc tkiBoot { } {
    global argv tki tkiEmbed tk_version

    if { [info exists tkiEmbed] } return

    # We need the following 'if' only for the -help command line option;
    # apparently, Tk is not loaded if -help is given to wish...
    if { [info exists tk_version]} {
        wm withdraw .
    }
#    if { "[lindex $argv 0]"!="" && [file isfile [lindex $argv 0]] } {
#	# Some wishs pass the filename as argv[0].  Kill it off.
#	set argv [lreplace $argv 0 0]
#    }
     
    eval tkiInfoWindow $argv
}

##########################################################################
# The following material was formerly contained in the file tkiwin.tcl
#
#  In the function names below, I use the abbreviations:
#  	Show	Display a node specified by a nodeSpec and optional fileSpec.
#  		This provides the external interface, and requires
#  		processing by the tkicore functions to retrieve the
#  		actual data for display.
#  	Dpy	Display a node specified by a fileKey and an internal
#  		representation of the node.  This is an internal interface.
#


##############################################################################
#
#		Binding callbacks and binding creation
#
##############################################################################


#
# There are some rather bizzare interactions with the timing of certain
# events.  In particular, changing the text of a text widget while a
# scan or other mouse-driven functions are active causes problems.  These
# functions provide the ability to defer activity.
#
# (I'm not sure what this is about, maybe it was a pre-4.0 issue, I'll take
# it out for now --A.B.)
#

#  proc _tkiWinShowIdle_Do { nodeSpec fileSpec w } {
#      global tki
#  #puts stdout "tkiWinShowIdle_Do: $nodeSpec"
#      update
#      set tw $w.main.text
#      tkiWinShow $nodeSpec $fileSpec $w
#      $tw conf -cursor $tki(normCursor)
#  }

# proc _tkiWinShowIdle { nodeSpec {fileSpec ""} {w ""} } {
#     global tki
#     if { "$w"!="" } {
# 	set tw $w.main.text
# 	if { "[lindex [$tw conf -cursor] 4]"=="$tki(waitCursor)" } return
# 	$tw conf -cursor $tki(waitCursor)
#     }
# #puts stdout "_tkiWinShowIdle: $nodeSpec"
#     after 1 [list _tkiWinShowIdle_Do $nodeSpec $fileSpec $w]
# }

proc _tkiWinShowIdle { nodeSpec {fileSpec ""} {w ""} } {
    tkiWinShow $nodeSpec $fileSpec $w
}

#
# Support calling a running tkman (or starting one up). Adapted from
# remote.tcl that comes with tkman. This supports both regular man pages
# and apropos searches (if $apropos == 1).
#

proc _tkiWinManPage { w manpage {apropos 0}} {
   global tki
 
   if {[set found [lsearch [winfo interps] tkman*]]==-1} {
      # if TkMan doesn't already exist, start one up
      if {[catch {exec tkman &}]} {tkiError "Tkman cannot be started"; return}

      # wait for it to be registered
      for {set found -1} {$found==-1} {after 200} {
         set found [lsearch [winfo interps] tkman*]
      }
      
      # check whether server is secure
      catch {send tkman set manx(init)} error
      if {[string match "*insecure*" $error]} {
          tkiError \
"Cannot communicate with tkman:
X server is insecure.
Use xauth or xdm."
          return
      }
      
      # wait for it to initialize
      for {set ready 0} {!$ready} {after 200} {
         catch {if {[send tkman set manx(init)]=="1"} {set ready 1}}
      }
   }
   set tkman [lindex [winfo interps] $found]

   # .man is the main window, guaranteed to exist
   send $tkman raise .man
   if { $apropos } {
       send $tkman manApropos $manpage
   } else {
       send $tkman manShowMan $manpage
   }

   return
}

#
# Various functions for manipulating the "prompting" window.  This
# is the entry widget at the bottom of the info window used for entering
# node names and search text.
#

proc _tkiWinPromptMap { w mode {extra ""} } {
    upvar #0 $w wvars
    set wvars(promptmode) $mode
    set dd $w.s
    $dd.goto delete 0 end
    $dd.goto insert end $extra
    pack after $dd.status $dd.goto { left expand fill }
    switch $mode {
        search {
            pack after $dd.goto $dd.regexp { left filly }
            pack after $dd.regexp $dd.case { left filly }
        }
        manual {
            pack after $dd.goto $dd.man { left filly }
            pack after $dd.man $dd.apropos {left filly }
        }
    }
    focus $dd.goto
}

proc _tkiWinPromptUnmap { w } {
    upvar #0 $w wvars
    set wvars(promptmode) ""
    set dd $w.s
    focus $w.main.text
    pack unpack $dd.goto
    pack unpack $dd.regexp
    pack unpack $dd.case
    pack unpack $dd.apropos
    pack unpack $dd.man
    $dd.status conf -text $wvars(status)
}

#
# This is called when <Return> is pressed in the "goto" text window.
# We could either be in a goto-node command, or a search, or an 
# exec-tcl, or a manual command.
# We take the appropriate action and cleanup.
#
proc _tkiWinPromptOk { w } {
    global tki
    upvar #0 $w wvars
    set dd $w.s
    set node [string trim [$dd.goto get]]
    if {"$node"==""} {
        _tkiWinPromptUnmap $w
	return
    }
    set tw $w.main.text
    $tw conf -cursor $tki(waitCursor)
    $w conf -cursor $tki(waitCursor)
    switch $wvars(promptmode) {
      search {
	set tki(curWindow) $w
        _tkiWinPromptUnmap $w
	set cnt [searchboxSearch $node $wvars(searchRegexpB) \
	  $wvars(searchCaseB) searchkey $w.main.text]
	if {$cnt==0} {
            $w.bar.view.m entryconf "Search next" -state disabled
            set wvars(searchStr) $node
        } else {
            $w.bar.view.m entryconf "Search next" -state normal
            set wvars(searchStr) ""
        }
	set tki(curWindow) ""
      }
      goto {
	set wvars(gotoStr) $node
        _tkiWinPromptUnmap $w
	_tkiWinShowIdle $node $wvars(fileKey) $w
      }
      tclcmd {
	set wvars(tclcmdStr) $node
        if [catch {uplevel #0 $node} error] {
            puts stdout "Error: $error"
        } else {
            puts stdout [expr { "$error"=="" ? "Ok" : "$error" }]
        }
        set node ""
        _tkiWinPromptUnmap $w
      }
      manual {
          set tki(curWindow) $w
          _tkiWinPromptUnmap $w
          if { $wvars(manB) } {
              _tkiWinManPage $w $node
          } else {
              _tkiWinManPage $w $node 1
          }
          set tki(curWindow) ""
      }
      menu {
          set toNode [_tkiFindRef $w $node 0]
          _tkiWinPromptUnmap $w
          if {"$toNode"==""} {
              set wvars(menuStr) $node
              $w.s.status conf -text "No such menu entry!"
          } else {
              set wvars(menuStr) ""
              _tkiWinShowIdle $toNode $wvars(fileKey) $w
          }
      }
      xref {
          set toNode [_tkiFindRef $w $node 1]
          _tkiWinPromptUnmap $w
          if {"$toNode"==""} {
              set wvars(xrefStr) $node
              $w.s.status conf -text "No such crossreference!"
          } else {
              set wvars(xrefStr) ""
              _tkiWinShowIdle $toNode $wvars(fileKey) $w
          }
      }
    }
    $tw conf -cursor $tki(normCursor)
    $w conf -cursor $tki(normCursor)
}

proc _tkiWinPromptAbort { w } {
    upvar #0 $w wvars
    _tkiWinPromptUnmap $w
}

#
# This updates the global $tki(geometry) variable to the size of the
# specified window.
#

proc _tkiWinGetGeom { w } {
  global tki
  set geom [wm geometry [winfo toplevel $w]]
  scan "$geom" "%dx%d+%s"  x y leftover
  set tki(geometry) "${x}x$y"
}

#
# Return the node in the current node's menu whose label starts with 
# $labelstart. We assume that the current node has a menu resp. 
# crossreferences. If there are more than one matching node, the first 
# currently visible one wins. Case does not matter.
# If xref is 1, look for crossreferences instead.
# Returns "" if nothing can be found.
#
proc _tkiFindRef { w labelstart xref } {
    upvar #0 $w wvars
    if {$xref == 1} {
        set nodeIdx 1
        set labelIdx 4
        set listvar "xrefinfo"
    } else {
        set nodeIdx 2
        set labelIdx 5
        set listvar "menuinfo"
    }
    set labelstart [string tolower $labelstart]
    set found ""
    foreach mi $wvars($listvar) {
        set label [lindex $mi $labelIdx]
        set label [string tolower $label]
        if { [string first $labelstart $label] == 0 } {
            lappend found $mi
        }
    }
    if { "$found"!="" } {
        scan "[wm geometry [winfo toplevel $w]]" "%dx%d+%s" x lines leftover
        scan "[$w.main.text index @0,0]" "%d.%d" top leftover
        set bottom [expr $top + $lines - 1]
        foreach mi $found {
            # Now determine whether this element is currently visible.
            if {$xref == 0} {
                set currentindex [$w.main.text index "menu.first + [lindex $mi 0] lines - 2 lines"]
            } else {
                set currentindex [$w.main.text index "1.0 + [lindex $mi 2] c"]
            }
            scan "$currentindex" "%d.%d" currentline leftover
            if { $currentline > $bottom } {
                break
            } else {
                if { $currentline >= $top } {
                    return [lindex $mi $nodeIdx]
                }
            }   
        }
        # none is visible; return first one.
        return [lindex [lindex $found 0] $nodeIdx]
    }
    return ""
}

#
# Perform various actions on the info window.  
# Note that if the action requires prompting (searching or goto-node)
# then we have to play with the focus.  This can badly interact with
# the focus games played when unmapping popup menus, so the "idle"
# option should be used when called from a menu.
# (I don't know what this is about --A.B.)
#
proc _tkiWinAction { w args } {
    upvar #0 $w wvars
    global tki

    set toNode ""
    set toFile $wvars(fileKey) 
    
    set arg1 [lindex $args 1]
    case [lindex $args 0] {
        idle {
            after 1 _tkiWinAction $w [lrange $args 1 end]
            return
        }
        quit {
            catch {unset wvars}
            catch {destroy $w}
            # XXX: !!This is a major hack!!
            global tkiEmbed
            if { ![info exist tkiEmbed] && "[winfo children .]"=="" } {
                destroy .
            }
            return
        }
        goto {
            set dd $w.s
            set wvars(status) [$dd.status cget -text]
            $dd.status conf -text "Node (^g cancels): "
            _tkiWinPromptMap $w goto $arg1
            return
        }
        tclcmd {
            set dd $w.s
            set wvars(status) [$dd.status cget -text]
            $dd.status conf -text "Tcl cmd (^g cancels): "
            if { "$arg1"=="" } { set arg1 $wvars(tclcmdStr) }
            _tkiWinPromptMap $w tclcmd $arg1
            return
        }
        search {
            if { "$arg1"=="incr" } {
                set tki(curWindow) $w
                searchboxNext searchkey $w.main.text $w.main.vsb
                set tki(curWindow) ""
                #$w.s.status conf -text $wvars(status)
            } else {
                set wvars(searchRegexpB) [expr {"$arg1"=="regexp"}]
                #set wvars(searchCaseB) 0
                set wvars(status) [$w.s.status cget -text]
                $w.s.status conf -text "Search (^g cancels): "
                _tkiWinPromptMap $w search $wvars(searchStr)
            }
            return
        }
        manual {
            set tki(curWindow) $w
            if {[catch {selection get} manpage] || "$manpage"=="" } {
                set wvars(status) [$w.s.status cget -text]
                set wvars(manB) [expr {"$arg1"!="apropos"}]
                $w.s.status conf -text "Unix manual (^g cancels): "
                _tkiWinPromptMap $w manual ""
            } else {
                $w conf -cursor $tki(waitCursor)
                $w.main.text conf -cursor $tki(waitCursor)
                _tkiWinManPage $w $manpage [expr {"$arg1"=="apropos"}]
                $w conf -cursor  $tki(normCursor)
                $w.main.text conf -cursor $tki(normCursor)
            }
            set tki(curWindow) ""
            return
        }
        last {
            set idx [expr { [llength $wvars(lastNodes)] - 2 } ]
            if { $idx >= 0 } {
                set lastinfo [lindex $wvars(lastNodes) $idx]
                set wvars(lastNodes) [lreplace $wvars(lastNodes) $idx end]
                set toFile [lindex $lastinfo 0]
                set toNode [lindex $lastinfo 1]
            }
        }
        toggle {
            if { [info exist wvars(toggle)] } {
                set toFile [lindex $wvars(toggle) 0]
                set toNode [lindex $wvars(toggle) 1]
            }
        }
        
        up   { set toNode [lindex $wvars(nodeinfo) 3] }
        prev { set toNode [lindex $wvars(nodeinfo) 4] }
        next { set toNode [lindex $wvars(nodeinfo) 5] }
        dir  { 
            if { "$arg1"=="" } {
                set toNode $wvars(lastDir)
            } else {
                set toNode $arg1
                set wvars(lastDir) $arg1
            }
        }
        othermenu {
            if { [info exist wvars(menuinfo)] } {
                set menuitem [lindex $wvars(menuinfo) $arg1]
                set toNode [lindex $menuitem 2]
                if { "$toNode" != "" } {
                    set tki(lastDir) $wvars(lastDir)
                    _tkiWinAction $w newwin [list -node $toNode -file $toFile]
                    return
                }
            }
        }
        newwin {
            set tw $w.main.text
            $tw conf -cursor $tki(waitCursor)
            $w conf -cursor $tki(waitCursor)
            _tkiWinGetGeom $tw
            set tki(lastDir) $wvars(lastDir)
            if {"$arg1"==""} {
                tkiInfoWindow $wvars(lastDir)
            } else {
                eval tkiInfoWindow $arg1
            }
            $tw conf -cursor $tki(normCursor)
            $w conf -cursor $tki(normCursor)
            return
        }
        menu {
            if { [info exist wvars(menuinfo)] } {
                if { "$arg1"=="" } {
                    set tki(curWindow) $w
                    set wvars(status) [$w.s.status cget -text]
                    $w.s.status conf -text "Beginning of Menu entry (^g cancels): "
                    _tkiWinPromptMap $w menu $wvars(menuStr)
                    set tki(curWindow) ""
                    return
                } else {
                    set menuitem [lindex $wvars(menuinfo) $arg1]
                    set toNode [lindex $menuitem 2]
                }
            }
        }
        xref {
            if { "$wvars(xrefinfo)"!="" } {
                set tki(curWindow) $w
                set wvars(status) [$w.s.status cget -text]
                $w.s.status conf -text "Beginning of Xref label (^g cancels): "
                _tkiWinPromptMap $w xref $wvars(xrefStr)
                set tki(curWindow) ""
                return
            }
        }
        scroll {
            case $arg1 {
                forw     { $w.main.text yview scroll 1 pages; return }
                back     { $w.main.text yview scroll -1 pages; return }
                top      { $w.main.text yview moveto 0; return }
                bottom   { $w.main.text yview moveto 1; return }
                lineup   { $w.main.text yview scroll 1 units; return }
                linedown { $w.main.text yview scroll -1 units; return }
                menu     {
                    if [info exist wvars(menuinfo)] {
                        $w.main.text yview [$w.main.text index "menu.first - 1 lines"] 
                    }
                }
            }
        }
    }
    if { "$toNode"=="" } {
        bell
    } else {
        _tkiWinShowIdle $toNode $toFile $w
    }
}
    
#
# Utility function for turning the "-acc" options from
# menus into actual bindings.
# Traverse {menu}, and install accelerators onto {winSpec}.
# {winSpec} may be a list of windows.  {menu} may be a menu, a
# menu button, or a frame containing menu buttons.
# Accelerator sequences may be any sequence of "normal" characters,
# or a normal char prefixed by "^" for Control.
# This code is cut&pasted from "tkgraph/lib/topwin.tcl topWin.BindAccels()".
#
proc _tkiBindAccels { winSpec menu } {
    switch [winfo class $menu] {
      Frame {
	foreach submenu [winfo children $menu] {
	    _tkiBindAccels $winSpec $submenu
	}
      }
      Menubutton {
	_tkiBindAccels $winSpec [lindex [$menu conf -menu] 4]
      }
      Menu {
	set lastIdx [$menu index last]
	for {set idx 0} {$idx <= $lastIdx} {incr idx} {
	    if [catch {$menu entryconf $idx -acc} acc] continue
	    set acc [lindex $acc 4]
	    if { "$acc"!="" && "$acc"!="==>" } {
		regsub -all "\\^(.)" $acc "<Control-\\1>" acc
		regsub -all "<(.)>" $acc "<Key-\\1>" acc
		foreach win $winSpec {
		    bind $win $acc "$menu invoke $idx; break"
		}
	    }
	    if { ! [catch {$menu entryconf $idx -menu} submenu] } {
		set submenu [lindex $submenu 4]
		if { "$submenu"!="" } {
		    _tkiBindAccels $winSpec $submenu
		}
	    }
	}
      }
    }
}

proc _tkiWinBind { w } {
    set tw $w.main.text
    _tkiBindAccels "$w.main.text $w.s.status" $w.bar
    foreach win "$w.main.text $w.s.status" {
	bind $win (		"_tkiWinAction $w goto ("
#	bind $win <Key-Help>	"tkiContextHelp %W"
        bind $win <Key-Help>    "[list _tkiWinShowIdle {(builtin)Quick Help} {} $w]
                                 break"
        bind $win <Key-F1>      "[list _tkiWinShowIdle {(builtin)Quick Help} {} $w]
                                 break"
	bind $win <Key-1>	"_tkiWinAction $w menu 0"
	bind $win <Key-2>	"_tkiWinAction $w menu 1"
	bind $win <Key-3>	"_tkiWinAction $w menu 2"
	bind $win <Key-4>	"_tkiWinAction $w menu 3"
	bind $win <Key-5>	"_tkiWinAction $w menu 4"
	bind $win <Key-6>	"_tkiWinAction $w menu 5"
	bind $win <Key-7>	"_tkiWinAction $w menu 6"
	bind $win <Key-8>	"_tkiWinAction $w menu 7"
	bind $win <Key-9>	"_tkiWinAction $w menu 8"
	bind $win <Control-Key-1>	"_tkiWinAction $w othermenu 0;break"
	bind $win <Control-Key-2>	"_tkiWinAction $w othermenu 1;break"
	bind $win <Control-Key-3>	"_tkiWinAction $w othermenu 2;break"
	bind $win <Control-Key-4>	"_tkiWinAction $w othermenu 3;break"
	bind $win <Control-Key-5>	"_tkiWinAction $w othermenu 4;break"
	bind $win <Control-Key-6>	"_tkiWinAction $w othermenu 5;break"
	bind $win <Control-Key-7>	"_tkiWinAction $w othermenu 6;break"
	bind $win <Control-Key-8>	"_tkiWinAction $w othermenu 7;break"
	bind $win <Control-Key-9>	"_tkiWinAction $w othermenu 8;break"
	bind $win <Key-space>		"_tkiWinAction $w scroll forw"
	bind $win <Control-Key-f>	"_tkiWinAction $w scroll forw"
	bind $win <Control-Key-d>	"return"
	bind $win <Control-Key-v>	"_tkiWinAction $w scroll forw
                                         break"
	bind $win <Key-F35>		"_tkiWinAction $w scroll forw"
	bind $win <Key-Delete>		"_tkiWinAction $w scroll back
                                         break"
	bind $win <Key-BackSpace>	"_tkiWinAction $w scroll back
                                         break"
	bind $win <Control-Key-b>	"_tkiWinAction $w scroll back"
	bind $win <Alt-Key-v>		"_tkiWinAction $w scroll back"
	bind $win <Meta-Key-v>		"_tkiWinAction $w scroll back"
        bind $win "<Key-Escape> v"      "_tkiWinAction $w scroll back"
	bind $win <Key-F29>		"_tkiWinAction $w scroll back"
        bind $win <Key-less>            "_tkiWinAction $w scroll top"
        bind $win <Key-Home>            "_tkiWinAction $w scroll top
                                         break"
        bind $win <Key-End>             "_tkiWinAction $w scroll bottom 
                                         break"
        bind $win <Key-greater>         "_tkiWinAction $w scroll bottom"
        bind $win <Key-G>               "_tkiWinAction $w scroll bottom"
        bind $win <Key-j>               "_tkiWinAction $w scroll lineup"
        bind $win <Key-Return>          "_tkiWinAction $w scroll lineup
                                         break"
        bind $win <Key-Down>            "_tkiWinAction $w scroll lineup
                                         break"
        bind $win <Control-Key-n>       "_tkiWinAction $w scroll lineup
                                         break"
        bind $win <Key-k>               "_tkiWinAction $w scroll linedown"
        bind $win <Control-Key-p>       "_tkiWinAction $w scroll linedown
                                         break"
        bind $win <Key-Up>              "_tkiWinAction $w scroll linedown
                                         break"
        bind $win <Key-C>               "_tkiWinAction $w quit"
        bind $win <Key-Q>               "exit"
        # This is really ugly but I don't know how else to prohibit the 
        # key "Alt-f" from executing the script associated with "f"
        # -- A.B.
        bind $win <Control-Key-l>       "return"
        bind $win <Alt-F1>              "return"
        bind $win <Meta-F1>             "return"
        bind $win <Alt-f>               "return"
        bind $win <Meta-f>              "return"
        bind $win <Alt-d>               "return"
        bind $win <Meta-d>              "return"
        bind $win <Alt-n>               "return"
        bind $win <Meta-n>              "return"
        bind $win <Alt-w>               "return"
        bind $win <Meta-w>              "return"
        bind $win <Alt-o>               "return"
        bind $win <Meta-o>              "return"
        bind $win <Alt-h>               "return"
        bind $win <Meta-h>              "return"
    }
    focus $w.main.text
}


#
# Make a new toplevel info window (with class ``TkInfo''),
# filled with buttons and bindings.
#
# If the argument {w} is non-empty, it specifies either the path name
# of the info window to create (if {w} doesn't already exist),
# or the parent of the info window to create (if {w} does already exist).
# It is an error for both {w} and {w}'s parent to not exist.
# If {w} is empty, the info window will be created as a child of the
# root window.
#
# If given, {tag} is some text that will appear in the window title and
# icon title.
#
# The path name of the new info window will be returned.
#
proc tkiWinCreate { {w ""} {tag ""} } {
    global tki

    if { "$w"=="" || [winfo exist $w] } {
	if { "$w"!="" && "[winfo class $w]"=="TkInfo" } {
	    # This check isn't strictly required, but it helps catch
	    # problems with Tk's multi-phase window destruction process.
	    error "Can't nest TkInfo windows."
	}
	set parent $w
	while 1 {
	    # I think (but I dont really remember) that I use [winfo parent]
	    # here instead of [winfo exist] b/c multi-phase destroy.
	    set w $parent.tki[tkiGetSN]
	    if { [catch {winfo parent $w}] } break
	}
    }
    lappend tki(windows) $w
    upvar #0 $w wvars
    set wvars(nodeinfo) ""
    set wvars(fileKey) ""
    set wvars(infonodename) "(builtin)Top"
    set wvars(lastDir) $tki(lastDir)
    set wvars(gotoStr) ""
    set wvars(tclcmdStr) ""
    set wvars(promptmode) ""
    set wvars(searchStr) ""
    set wvars(searchbottom) 0
    set wvars(xrefStr) ""
    set wvars(menuStr) ""
    set wvars(title) [expr {("$tag"=="") ? "tkInfo" : "tkInfo:$tag"}]

    toplevel $w -class TkInfo
    wm title $w $wvars(title)
    wm iconname $w $wvars(title)
#   wm minsize $w 20 20
    wm protocol $w WM_DELETE_WINDOW "_tkiWinAction $w quit"
    set dd $w.bar; pack [frame $dd -borderwidth 2 -relief raised] \
      -side top -fill x

    set ddm $dd.file.m
    pack [menubutton $dd.file -text "File" -und 0 -menu $ddm] -side left
    menu $ddm
    $ddm add com -lab "Directory" -und 0 -acc d -com "_tkiWinAction $w dir"
    $ddm add com -lab "New Window " -und 0 -acc N -com "_tkiWinAction $w newwin"
    $ddm add com -lab "Man Page..." -und 0 -acc M -com "_tkiWinAction $w manual"
    $ddm add com -lab "Apropos..." -und 0 -acc A -com "_tkiWinAction $w manual apropos"
    $ddm add com -lab "Tcl Cmd..." -und 0 -acc ! -com "_tkiWinAction $w idle tclcmd"
    $ddm add sep
    $ddm add com -lab "Close" -und 0 -acc c -com "_tkiWinAction $w quit"
    
    $ddm add com -lab "Quit" -und 0 -acc q -com "exit"
        set tki(dirnodes) ""
    foreach pp $tki(infoPath) {
	set dirpath [tkiFileFind $pp/$tki(topLevelFile)]
	if { "$dirpath" != "" } {
	    lappend tki(dirnodes) $dirpath
	}
    }
    if { [llength $tki(dirnodes)] > 1 } {
        set ddd $dd.dirs.m
        pack [menubutton $dd.dirs -text "Directories" -und 0 -menu $ddd] -side left
        menu $ddd
        foreach pp $tki(dirnodes) {
            $ddd add com -lab [file dirname $pp] -com \
                    "_tkiWinAction $w dir \{($pp)\}"
        }
    }
    set ddm $dd.node.m
    pack [menubutton $dd.node -text "Node" -und 0 -menu $ddm] -side left
    menu $ddm
    $ddm add com -lab "Up" -und 0 -acc u -com "_tkiWinAction $w up"
    $ddm add com -lab "Next" -und 0 -acc n -com "_tkiWinAction $w next"
    $ddm add com -lab "Prev" -und 0 -acc p -com "_tkiWinAction $w prev"
    $ddm add com -lab "Goto..." -und 0 -acc g -com "_tkiWinAction $w idle goto"
    $ddm add com -lab "Menu..." -und 0 -acc m -com "_tkiWinAction $w idle menu"
    $ddm add com -lab "Xref..." -und 0 -acc f -com "_tkiWinAction $w idle xref"
    $ddm add com -lab "Toggle" -und 0 -acc t -com "_tkiWinAction $w toggle"
    $ddm add com -lab "Last" -und 0 -acc l -com "_tkiWinAction $w last"

    set ddm $dd.view.m
    pack [menubutton $dd.view -text "View" -und 3 -menu $ddm] -side left
    menu $ddm
    $ddm add com -lab "Top" -und 0 -acc b -com "_tkiWinAction $w scroll top"
    $ddm add com -lab "Bottom" -und 0 -acc e -com "_tkiWinAction $w scroll bottom"
    $ddm add com -lab "Menu" -und 0 -acc ^m -com "_tkiWinAction $w scroll menu"
    $ddm add com -lab "Search (exact)..." -und 0 -acc s \
      -com "_tkiWinAction $w idle search exact"
    $ddm add com -lab "Search (regexp)... " -und 8 -acc / \
      -com "_tkiWinAction $w idle search regexp"
    $ddm add com -lab "Search next" -und 7 -acc ^s \
      -com "_tkiWinAction $w search incr"

    set ddm $dd.options.m
    pack [menubutton $dd.options -text "Options" -und 0 -menu $ddm] -side left
    menu $ddm -disabledforeground [ $dd.view.m cget -foreground ]
    $ddm add check -lab "Show Headers" -und 5 -var tki(rawHeadersB)
    $ddm add check -lab "Show Buttons" -und 5 -var tki(showButtonsB)
    $ddm add check -lab "Detailed Status" -und 0 -var tki(detailstatusB)
    $ddm add check -lab "Time Status" -und 0 -var tki(timestatusB)
    $ddm add sep
    $ddm add com -lab "Link Look:" -state disabled
    $ddm add radio -lab "Color" -und 0     -var tki(nodelook) -val color
    $ddm add radio -lab "Font" -und 0      -var tki(nodelook) -val font
    $ddm add radio -lab "Underline" -und 0 -var tki(nodelook) -val underline

    set ddm $dd.help.m
    pack [menubutton $dd.help -text "Help" -und 0 -menu $ddm] -side right
    menu $ddm
    $ddm add com -lab "Quick Help" -und 0 -acc ? \
      -com [list _tkiWinShowIdle "(builtin)Quick Help" "" $w]
    $ddm add com -lab "Documentation " -und 0 -acc h \
      -com [list _tkiWinShowIdle "(builtin)Top" "" $w]
    $ddm add sep
    $ddm add com -lab "About tkInfo" -und 0 \
      -com [list _tkiWinShowIdle "(builtin)About" "" $w]

    tk_menuBar $w.bar $w.bar.file $w.bar.view $w.bar.options $w.var.help

    set dd $w.main; pack [frame $dd] -expand 1 -fill both
    pack append $dd [scrollbar $dd.vsb -orient vert -com "$dd.text yview"] \
      { right fill }
    pack append $dd [text $dd.text -state disabled -setgrid 1 -width 80 \
                       -wrap word] \
      { left expand fill }
    $dd.text config -yscroll "$dd.vsb set"

    set dd $w.div1; pack append $w [frame $dd -bd 1 -rel sunken \
      -height 3 -width 10] { top fillx }
    # We use "-after $w.bar" here so that the status line won't disappear
    # upon resizing of the window:
    set dd $w.s; pack [frame $dd] -after $w.bar -side bottom -fill x
    pack append $dd [label $dd.status -anc w] { left fillx }
#    place [label $dd.status -anc w] -in $dd -x 0 -y 0 -anc nw
#    pack append $dd [label $dd.forhelp -anc e -text "Press ? for help."] \
#      { right filly }
    place [label $dd.forhelp -anc e -text "Press ? for help."] \
      -in $dd -relx 1 -y 0 -anc ne
    entry $dd.goto -rel sunken
    checkbutton $dd.regexp -text "Regexp" -var ${w}(searchRegexpB)
    checkbutton $dd.case -text "Case Sen" -var ${w}(searchCaseB)
    radiobutton $dd.man -text "Man page" -var ${w}(manB) -value 1
    radiobutton $dd.apropos -text "Apropos" -var ${w}(manB) -value 0
    bind $dd.goto <Return> "_tkiWinPromptOk $w"
    bind $dd.goto <Escape> "_tkiWinPromptAbort $w"
    bind $dd.goto <Any-Control-g> "_tkiWinPromptAbort $w"
    bind $dd.goto <Control-u> "$dd.goto delete 0 end"

    set dd $w.buts; frame $dd
    if { $tki(showButtonsB) } { pack $dd -after $w.s -side bottom -fill x }
    pack append $dd [button $dd.next -text "Next Node" \
      -com "_tkiWinAction $w next"] { left exp fill }
    pack append $dd [button $dd.prev -text "Prev Node" \
      -com "_tkiWinAction $w prev"] { left exp fill }
    pack append $dd [button $dd.up   -text "Up Node" \
      -com "_tkiWinAction $w up"] { left exp fill }
    pack append $dd [button $dd.last   -text "Last Node" \
      -com "_tkiWinAction $w last" -state disabled] { left exp fill }

#    pack append $dd [button $dd.toggle -text "Toggle Node" \
#      -com "_tkiWinAction $w back" -state disabled] { left exp fill }

    _tkiWinBind $w

    set tki(curWindow) $w
    wm geometry $w $tki(geometry)
    if { $tki(iconic) == 1 } { 
        wm iconify $w; set tki(iconic) 0
    }
    return $w
}

##############################################################################
#
#		Utility functions for updating info windows
#
##############################################################################

#
# Removes all empty lines in window $w starting at index $idx.
# This is more subtle than one might think.  Note that the text index
# "+1line" wont work on the last line of text, because the newline is
# considered part of the previous line.  Thus we use "lineend" instead.
#
proc _tkiTextTrim { w idx } {
    while 1 {
	set nidx [$w index "$idx lineend"]
	if { "[string trim [$w get $idx $nidx]]"!="" || "[$w index end]"=="1.0" } break
	$w delete $idx "$nidx +1char"
    }
}

# Modified version of ouster's version
proc _tkiTextInsertWithTags { w index text args } {
    set start [$w index $index]
    $w insert $start $text
    foreach tag $args {
    	$w tag add $tag $start insert
    }
}

proc _tkiConfChainButton { w which toNode } {
    set mode [expr { "$toNode"=="" ? "disabled" : "normal" } ]
    $w.buts.$which conf -state $mode
    $w.bar.node.m entryconf ?[string range $which 1 end] -state $mode
}

proc _tkiNodeLookTag { tw tag } {
    global tki
    case $tki(nodelook) {
      color { $tw tag conf $tag -fore $tki(nodelookColor) }
      underline { $tw tag conf $tag -underline 1 }
      font { $tw tag conf $tag -font $tki(nodelookFont) }
    }
    $tw tag bind $tag <Enter> \
        "$tw configure -cursor $tki(linkCursor)"
    $tw tag bind $tag <Leave> \
        "$tw configure -cursor $tki(normCursor)"
}

proc _tkiWinDpyNode { w fileKey info body } {
    global tki; upvar #0 $w wvars

    set wvars(fileKey) $fileKey
    set wvars(nodeinfo) $info
    set nodeIdx [lindex $info 0]
    set nodeSpec "([lindex $info 2])[lindex $info 1]"
    set nodeName [lindex $info 1]
    tkiStatus "Formating $nodeSpec"
    set tw $w.main.text
    $tw conf -cursor $tki(waitCursor)
    $w conf -cursor $tki(waitCursor)
    set menuidx -1
    if { ! [lindex $tki(fileinfo-$fileKey) 4] } {
	set menuidx [string first "\n* Menu:" $body]
	if { $menuidx > 0 } {
	    set menutext [string range $body [expr {$menuidx+1}] end]
	    set beforemenu [string range $body 0 $menuidx]
	}
    }

    $tw conf -state normal
    $tw delete 1.0 end
#    tkiTimeStatus "DpyNode body" 1 \
#      _tkiWinDpyBody $w $nodeName $nodeIdx $fileKey $body
    #
    # Insert the body text and add the crossref tags
    #
    if { $menuidx > 0 } {
       $tw insert end $beforemenu
       _tkiTextInsertWithTags $tw end $menutext menu
    } else {
       $tw insert end $body
    }
    if { [info exist tki(xrefinfo-$fileKey-$nodeIdx)] } {
	set xrefinfo $tki(xrefinfo-$fileKey-$nodeIdx)
    } else {
	tkiDetailStatus "Parsing $nodeIdx body"
        set xrefinfo [tkiTimeStatus "Parsing $nodeIdx body" 0 \
	  tkiNodeParseBody $nodeName $fileKey $body]
	set tki(xrefinfo-$fileKey-$nodeIdx) $xrefinfo
    }
    set wvars(xrefinfo) $xrefinfo
    tkiDetailStatus "Formating $nodeIdx body"
    set ms "1.0"
    $tw tag delete xrefkey
    foreach xi $xrefinfo {
	# xi = { xrefidx toNode startIdx endIdx label}
	set xrefidx [lindex $xi 0]
	set toNode [lindex $xi 1]
        $tw tag add xrefkey "$ms+[lindex $xi 2] c" "$ms +[lindex $xi 3] c"
        $tw tag add xref$xrefidx "$ms +[lindex $xi 2] c" "$ms +[lindex $xi 3] c"
        # We memorize the position where a button is pressed; if it is
        # released far away, we won't enable the associated action 
        # (chances are, that the user wanted to select or drag)
        $tw tag bind xref$xrefidx <Button-1> \
                "set tki(x) %x; set tki(y) %y"
	$tw tag bind xref$xrefidx <ButtonRelease-1> \
                " if {abs(%x - \$tki(x)) + abs(%y - \$tki(y)) < 8} {
                     [list _tkiWinShowIdle $toNode $fileKey $w ]
                  }"
        $tw tag bind xref$xrefidx <Button-2> \
                "set tki(y) %y"
        # The next one is really wild... $toNode can contain backslashes and
        # stuff. I didn't know how to do it more elegantly --A.B.
        $tw tag bind xref$xrefidx <ButtonRelease-2> \
                [concat [list if " abs(%y - \$tki(y)) < 7 " [list _tkiWinAction $w newwin [list -node $toNode -file $fileKey] ] ] ";" "break"]
        $tw tag bind xref$xrefidx <Shift-ButtonRelease-1> \
                   "[list _tkiWinAction $w newwin [list -node $toNode -file $fileKey]]
                   break"
    }
    _tkiNodeLookTag $tw xrefkey

    _tkiTextTrim $tw 1.0 
   if { ! $tki(rawHeadersB) } {
	$tw delete 1.0 "1.0 +1line"
        _tkiTextTrim $tw 1.0
    }
    
    #
    # Now add the menu tags
    #
    if { [info exist menutext] } {
#	tkiTimeStatus "DpyNode menu" 1 \
#	  _tkiWinDpyMenu $w $nodeName $nodeIdx $fileKey $menutext
        if { [info exist tki(menuinfo-$fileKey-$nodeIdx)] } {
	  set menuinfo $tki(menuinfo-$fileKey-$nodeIdx)
        } else {
          set menuinfo [tkiTimeStatus "Parsing $nodeIdx menu" 0 \
	    tkiNodeParseMenu $nodeName $fileKey $menutext]
	  set tki(menuinfo-$fileKey-$nodeIdx) $menuinfo
        }
        tkiDetailStatus "Formating $nodeIdx menu"
        $tw tag delete menukey
        foreach mi $menuinfo {
	  # mi = { lineidx menuidx toNode nBeg nEnd label }
	  set lineidx [lindex $mi 0]
	  set menuidx [lindex $mi 1]
	  set toNode [lindex $mi 2]
	  set ms "menu.first +$lineidx lines -2 lines"
	  $tw tag add menukey "$ms +[lindex $mi 3] c" "$ms +[lindex $mi 4] c +1 c"
#      	  $tw tag add menukey "$ms linestart" "$ms +[lindex $mi 4] c +1 c"
#	  $tw tag add menu$menuidx "$ms linestart" "$ms lineend"
#         $tw tag add menu$menuidx "$ms +[lindex $mi 3] c" "$ms +[lindex $mi 4] c +1 c"
          $tw tag add menu$menuidx "$ms linestart" "$ms +[lindex $mi 4] c +1 c"
          # We memorize the position where a button is pressed; if it is
          # released far away, we won't enable the associated action 
          # (chances are, that the user wanted to select or drag)
          $tw tag bind menu$menuidx <Button-1> \
                  "set tki(x) %x; set tki(y) %y"
	  $tw tag bind menu$menuidx <ButtonRelease-1> \
                  " if {abs(%x - \$tki(x)) + abs(%y - \$tki(y)) < 8} {
                       [list _tkiWinShowIdle $toNode $fileKey $w ]
                    }"
          $tw tag bind menu$menuidx <Button-2> \
                  "set tki(y) %y"
          $tw tag bind menu$menuidx <ButtonRelease-2> \
                [concat [list if " abs(%y - \$tki(y)) < 7 " [list _tkiWinAction $w newwin [list -node $toNode -file $fileKey] ] ] ";" "break"]
          $tw tag bind menu$menuidx <Shift-ButtonRelease-1> \
                    "[list _tkiWinAction $w newwin [list -node $toNode -file $fileKey ]]
                    break"
        }
        _tkiNodeLookTag $tw menukey

	set wvars(menuinfo) $tki(menuinfo-$fileKey-$nodeIdx)
	$w.bar.view.m entryconf Menu -state normal
    } else {
	catch {unset wvars(menuinfo)}
	$w.bar.view.m entryconf Menu -state disabled
    }
    tkiDetailStatus "Formating $nodeSpec (part 2)"
    $tw mark set insert 1.0
    $tw mark set anchor insert
    $tw tag remove sel 1.0 end
    $tw conf -state disabled -cursor $tki(normCursor)
    $w conf -cursor $tki(normCursor)
    wm title $w "$wvars(title)      $nodeSpec"
    wm iconname $w "$wvars(title) $nodeSpec"
    tkiStatus "$nodeSpec"

    # Do search colors
    $tw tag conf searchkey -foreground [lindex [$tw conf -background] 4] \
      -background [lindex [$tw conf -foreground] 4]

    #
    # Disable buttons and menu entries if necessary
    #
    _tkiConfChainButton $w up   [lindex $info 3]
    _tkiConfChainButton $w prev [lindex $info 4]
    _tkiConfChainButton $w next [lindex $info 5]
    $w.bar.view.m entryconf "Search next" -state disabled
    if { [llength $wvars(lastNodes)] >= 2 } {
        $w.buts.last conf -state normal
        $w.bar.node.m entryconf Last  -state normal
    } else {
        $w.buts.last conf -state disabled
        $w.bar.node.m entryconf Last  -state disabled
    }
    if { $menuidx > 0 } {
        $w.bar.node.m entryconf "Menu..." -state normal
    } else {
        $w.bar.node.m entryconf "Menu..." -state disabled
    }
    if { "$xrefinfo" == "" } {
        $w.bar.node.m entryconf "Xref..." -state disabled
    } else {
        $w.bar.node.m entryconf "Xref..." -state normal
    }
    if { ![info exist wvars(toggle)] } {
        $w.bar.node.m entryconf "Toggle" -state disabled
    } else {
        if { "[lindex $wvars(toggle) 1]" =="" } {
            $w.bar.node.m entryconf "Toggle" -state disabled
        } else {
            $w.bar.node.m entryconf "Toggle" -state normal
        }
    }
    # This is really gross
    focus $tw
    after 1 [list $tw tag remove sel 1.0 end]
}


proc tkiWinDpy { w fileKey info body } {
    global tki; upvar #0 $w wvars

    if { [info exist wvars(nodeinfo)] } {
	set wvars(toggle) [list $wvars(fileKey) [lindex $wvars(nodeinfo) 1]]
#        $w.buts.toggle conf -state normal
    }
    lappend wvars(lastNodes) [list $fileKey [lindex $info 1]]

    _tkiWinDpyNode $w $fileKey $info $body
}

##############################################################################
#
#	The public interface
#
##############################################################################


#
# The argument {w} specified an info window in one of three ways:
#   - if empty, a new top-level window will be created and returned.
#   - if a window (starts will a ``.''), the window must exist and must have
#     been previously obtained using tkiWinCreate() or some variant
#     of tkiWinShow().
#   - otherwise it is a "window tag", which is arbitrary text that
#     must not begin with a ``.''.  Each tag has a unique window associated
#     with it that will be created (and re-created) upon demand.
#     The tag will also appear in the window title&icon.
#
proc _tkiWinResolveWinName { w } {
    global tki
    if { ! [info exist tki] } { tkiInit }
    if { "$w"=="" }			{ return [tkiWinCreate] }
    if { "[string index $w 0]"=="." }	{ return $w }

    # It must be a tag: retrieve (or make) the window assoicated with the tag
    set tag $w
    if { ![info exist tki(wintag-$tag)] } { 
puts stdout "creating tag $tag"
	set tki(wintag-$tag) [tkiWinCreate "" $tag]
    }
    set w $tki(wintag-$tag)

    # Now see if it still exists: the user might have killed it.  If
    # gone, recreate it.
    if ![winfo exist $w] {
	tkiWinCreate $w $tag
    }
    return $w
}

# 
# This is the primary entry point of this module.  The argument {nodeSpec}
# give the node to show, and may contains a filespec as in (filename)nodename.
# If no filename is contained in {nodeSpec}, it will be augmented by
# the argument {fileSpec} (if non-empty).  The argument
# {w} specifies which info window the node should be displayed in,
# as described by _tkiWinResolveWinName() above.
#
# The return value is a list "nodeRef window" where {nodeRef} is
# the internal "handle" to the node given by {nodeSpec} and {fileSpec},
# and {window} is the full path of the info window.
# If the node couldn't be loaded, the {nodeRef} will be empty.
#
proc tkiWinShow { nodeSpec {fileSpec ""} {w ""} } {
    global tki
    set w [_tkiWinResolveWinName $w]
    set tki(curWindow) $w
    $w.main.text conf -cursor $tki(waitCursor)
    $w conf -cursor $tki(waitCursor)
#puts stdout "tkiWinShow: spec $nodeSpec file $fileSpec"
    set nodeRef [tkiGetNodeRef $nodeSpec $fileSpec]
    if { "$nodeRef"=="" } {
	set fmtSpec [tkiFmtNodeSpec $nodeSpec $fileSpec]
        # Maybe nodeSpec is of the form "filename" as in Xemacs
        # info files...
        if { "$nodeSpec"!="" && ![string match "(*" $nodeSpec] } {
            set nodeRef [tkiGetNodeRef $tki(topLevelNode) $nodeSpec]
            if { "$nodeRef"=="" } {
                tkiError "Can't locate info nodes ``$fmtSpec'' and ``($nodeSpec)$tki(topLevelNode)''"
                return ""
            }
        } else {
            tkiError "Can't locate the info node ``$fmtSpec''"
            return ""
        }

    }
    set nodeIdx [lindex $nodeRef 0]
    set fileKey [lindex $nodeRef 1]
    tkiWinDpy $w $fileKey [lindex $tki(nodesinfo-$fileKey) $nodeIdx] \
            [lindex $tki(nodesbody-$fileKey) $nodeIdx]
    set tki(curWindow) ""
    return [list $nodeRef $w]
}

#
# Get the current info node for {w}, and redisplay it in the window.
# This is used whenever the display mode (nodelook,etc) is changed.
#
proc tkiWinRefresh { w } {
    global tki; upvar #0 $w wvars
    if { $tki(showButtonsB) }	{ pack conf $w.buts -fill x } \
    else			{ pack forget $w.buts }
    if ![info exist wvars(nodeinfo)] return
    set nodeinfo $wvars(nodeinfo)
    return [tkiWinShow [lindex $nodeinfo 1] $wvars(fileKey) $w]
}

proc tkiWinRefreshAll { } {
    global tki

    foreach w $tki(windows) {
	if { ![winfo exist $w] } continue
	if [catch {tkiWinRefresh $w} error] {
	    global errorInfo
	    puts stderr "tkInfo: refresh $w: $error\n$errorInfo"
	}
    }
}

#
# A helper function to provide "context" help.  The idea is that the
# application, when it creates each window/widget, creates a global array
# variable corresponding to each "key" window in the application.  The
# array element "infonodename" contains the node name to display for
# context help for that window and its children.
#
# Start at window {w}, and traverse up the window tree looking for a variable
# of the form "$w(infonodename)".  If found, a window displaying that node
# will be generated.  {fileSpec} may be used to augment the infonode,
# and {infowin} may specific a pre-existing info window returned by
# tkiWinShow().
# 
proc tkiWinContextHelp { w {fileSpec ""} {infowin ""} } {
    for {} {"$w"!=""} {set w [winfo parent $w]} {
	# Line below is kludgy, b/c I can't see any other way to do it.
	if [uplevel #0 [list info exist ${w}(infonodename)]] {
	    upvar #0 $w wvars 
    	    return [tkiWinShow $wvars(infonodename) $fileSpec $infowin]
	}
    }
    if { "$fileSpec"!="" } {
    	return [tkiWinShow Top $fileSpec $infowin]
    }
    return [tkiWinShow "(builtin)Quick Help" "" $infowin]
}

##########################################################################
# The following material was formerly contained in the file tkicore.tcl:
#
# This is the core of the tkinfo package.  It handles reading, parsing,
# and storing info files.  Everything in here should be tcl-only, no
# tk stuff.  Note that this can't be used independently: it requires
# initialization and error handling stuff found in tkinfo.tcl.



# Get a globally unique serial number.
#
proc tkiGetSN { } {
    global tki
    incr tki(sn)
    return $tki(sn)
}

#
# Add tcl list of paths {newPaths} to the directory search list.
# The list is added in order at the *head* of the list.
# Duplicate paths are removed, leaving the first most path present.
#
proc tkiAddInfoPaths { newPaths } {
    global tki

    if { ! [info exist tki(infoPath) ] } {
	set tki(infoPath) ""
    }
    if { [llength $newPaths] > 0 } {
	set tki(infoPath) [eval linsert {$tki(infoPath)} 0 $newPaths]
    }
    # Kill off null paths
    while 1 {
	set idx [lsearch $tki(infoPath) ""]
	if { $idx < 0 }	break
	set tki(infoPath) [lreplace $tki(infoPath) $idx $idx]
    }
    # Kill off duplicate paths
    for {set idx 0} {$idx < [llength $tki(infoPath)]} {incr idx} {
	set path [lindex $tki(infoPath) $idx]
	while 1 {
	    set dup [lsearch [lrange $tki(infoPath) [expr {$idx+1} ] end] $path]
	    if { $dup < 0 } break
	    set tki(infoPath) [lreplace $tki(infoPath) [expr {$dup+$idx+1}] [expr {$dup+$idx+1}]]
	}
    }
}

proc _tkiFileFindSuf { fileName } {
    global tki

    foreach suf $tki(infoSuffix) {
	foreach extrasuf {"" .gz .Z .z} {
	    set filePath "$fileName$suf$extrasuf"
	    if { [file isfile $filePath] } {
		return $filePath
	    }
	}
    }
    return ""
}

#
# Given {fileName} (see intro section above), find the corresponding
# filepath.  The filepath of {pntFileKey}, if specified, is
# used as a starting point for locating {fileName}.
# Returns the file path if found, else empty string.
#
proc tkiFileFind { fileName {pntFileKey ""} } {
    global tki

    catch {unset tki(temp-search-path)}
    case [string index $fileName 0] {
      "/ . ~" {
	lappend tki(temp-search-path) [file dirname $fileName]
	# Should be valid UN*X path modulo suffix
	set filePath [_tkiFileFindSuf $fileName]
	if { "$filePath"!="" } { return $filePath }
	set filePath [_tkiFileFindSuf [string tolower $fileName]]
	if { "$filePath"!="" } { return $filePath }
      }
      default {
	# Try all the infopaths, and all suffixs
	set pp ""
	if { "$pntFileKey"!="" } {
	    set pp [file dirname [lindex $tki(fileinfo-$pntFileKey) 2]]
	}
	foreach prepath "$pp $tki(infoPath)" {
#puts stdout "Searching dir ``$prepath''"
	    lappend tki(temp-search-path) $prepath
	    if { ! [file isdir $prepath] } continue
	    set filePath [_tkiFileFindSuf $prepath/$fileName]
	    if { "$filePath"!="" } { return $filePath }
	    set filePath [_tkiFileFindSuf $prepath/[string tolower $fileName]]
	    if { "$filePath"!="" } { return $filePath }
	}
      }
    }
    return ""
}

#
# Given {fileName}, find the corresponding filepath via tkiFileFind().
# Create a {fileKey} for the file, and make the appropriate table entries.
# Note that {fileName} must be just that, and not a filekey.
#
proc tkiFileAdd { fileName {pntFileKey ""} {wholeB 0} } {
    global tki

    if { [info exist tki(file-$fileName)] } {
	return $tki(file-$fileName)
    }
    set filePath [tkiFileFind $fileName $pntFileKey]
    if { "$filePath"=="" } { return "" }
    set fileKey fk[tkiGetSN]
    set tki(file-$fileName) $fileKey
    set tki(fileinfo-$fileKey)  [list $fileKey $fileName $filePath $pntFileKey $wholeB]
    set tki(incore-$fileKey) 0
    return $fileKey
}

proc tkiFileGet { fileSpec {pntFileKey ""} {wholeB 0} } {
    global tki

    if { [info exist tki(fileinfo-$fileSpec)] } {
	set fileKey $fileSpec
    } else {
	if { [info exist tki(file-$fileSpec)] } {
	    set fileKey $tki(file-$fileSpec)
	} else {
	    set fileKey [tkiFileAdd $fileSpec $pntFileKey $wholeB]
	    if { "$fileKey"=="" } {
#  No need to print an error message here; this will be taken care of
#  in tkiWinShow.
#  		set msg "Can't locate info file ``$fileSpec''."
#  		if [info exist tki(temp-search-path)] {
#  		    set search $tki(temp-search-path)
#  		    regsub -all " " $search ", " search
#  		    append msg "\nSearch path is \{$search\}."
#  		}
#  		tkiError $msg
		return ""
	    }
	}
    }
    set fileinfo $tki(fileinfo-$fileKey)
    if { ! $tki(incore-$fileKey) } {
        tkiFileLoad $fileKey [lindex $fileinfo 1] [lindex $fileinfo 2] [lindex $fileinfo 4]
    }
    return $fileKey
}

proc _tkiFileLoadIndirectTbl { fileKey lines } {
    global tki

    set indirinfos ""
    foreach line $lines {
	if { "$line"!="" } {
	    set pair [split $line ":"]
	    if { [llength $pair] != 2 } {
		tkiFileWarning $fileKey "has bad file-indirect line ``$line''"
		continue
	    }
	    set indirKey [tkiFileAdd [lindex $pair 0] $fileKey]
	    if { "$indirKey"=="" } {
		tkiError "Can't locate indirect file ``[lindex $pair 0]''."
		continue
	    }
	    set byteOfs [string trim [lindex $pair 1]]
	    lappend indirinfos [list $indirKey $byteOfs]
	}
    }
    set tki(indirf-$fileKey) $indirinfos
#puts stdout "IndirectTbl $fileKey: $indirinfos"
}

proc _tkiFileLookupIndir { indirf byte } {
    set lastKey ""
    foreach fi $indirf {
	if { [lindex $fi 1] > $byte } break
	set lastKey [lindex $fi 0]
    }
    return $lastKey
}

proc _tkiFileLoadTagTbl { fileKey lines } {
    global tki

    set subkey [lindex $lines 0]
    if { "$subkey"!="(Indirect)" } return
    set indirf $tki(indirf-$fileKey)
    set indirinfos ""
    foreach line [lrange $lines 1 end] {
	if { "$line"=="" } continue
	set pair [split $line $tki(nodeByteSep)]
	if { [llength $pair] != 2 } {
	    tkiFileWarning $fileKey "has bad tag-indirect line ``$line''"
	    continue
	}
	set nodeName [string trim [string range [lindex $pair 0] 5 end]]
	set byteOfs [string trim [lindex $pair 1]]
	set indirFile [_tkiFileLookupIndir $indirf $byteOfs]
	lappend indirinfos [list $nodeName $byteOfs $indirFile]
# puts stdout "$fileKey: tag [list $nodeName $byteOfs $indirFile]"
    }
    set tki(indirn-$fileKey) $indirinfos
}

proc tkiFileParseNode { fileKey node } {
    global tki

    set lines [split $node "\n"]
    set keyline [string trim [lindex $lines 1]]
    case $keyline {
      { {[Ii]ndirect:} } {
	_tkiFileLoadIndirectTbl $fileKey [lrange $lines 2 end]
	return "IndirectTable"
      }
      { {[Tt]ag [Tt]able:} } {
	_tkiFileLoadTagTbl $fileKey [lrange $lines 2 end]
	return "TagTable"
      }
      { {[Ee]nd [Tt]ag [Tt]able} } {
	return "EndTagTable"
      }
    }
    # Some screwed up files omit the ``,'' for the file key.
    regsub "(File:\[^,\]*)Node:" $keyline "\\1,Node:" keyline
    set nodekey ""; set filekey ""
    set nextkey ""; set prevkey ""; set upkey ""
    foreach key [split $keyline ",\t"] {
	set key [string trim $key]
	case $key {
	  "File:*" { set filekey [string trim [string range $key 5 end]] }
	  "Node:*" { set nodekey [string trim [string range $key 5 end]] }
	  "Up:*"   { set upkey   [string trim [string range $key 3 end]] }
	  "Prev:*" { set prevkey [string trim [string range $key 5 end]] }
	  "Next:*" { set nextkey [string trim [string range $key 5 end]] }
	}
    }
    if { "$nodekey" == "" } { return "" }
    lappend tki(nodesinfo-$fileKey) [list [llength $tki(nodesinfo-$fileKey)] $nodekey $filekey $upkey $prevkey $nextkey]
    lappend tki(nodesbody-$fileKey) $node
    return $nodekey
}

proc tkiFileLoad { fileKey fileName filePath wholeB } {
    global tki

    case $filePath in {
      *.Z	{ set fp "|$tki(compresscat-Z) $filePath" }
      *.z	{ set fp "|$tki(compresscat-z) $filePath" }
      *.gz	{ set fp "|$tki(compresscat-gz) $filePath" }
      default	{ set fp $filePath }
    }
    if [catch {open $fp "r"} fid] {
	tkiError "Can't open ``$fp''."
	return ""
    }
    if { $wholeB } {
	set node_Top [list 0 Top $fileName "" "" ""]
    	set tki(nodesinfo-$fileKey) [list $node_Top]
    	set tki(nodesbody-$fileKey) [list [read $fid]]
        close $fid
        set tki(incore-$fileKey) 1
	return $fileKey
    }
    set nodelist [split [read $fid] $tki(nodeSep)]
    close $fid
    tkiStatus "Loading $fileName"
    set nodecnt 0
    set tki(nodesinfo-$fileKey) ""
    set tki(nodesbody-$fileKey) ""
    foreach node $nodelist {
	incr nodecnt
	if { $nodecnt==1 || [string length $node] < 10 } continue
	set nodeName [tkiFileParseNode $fileKey $node]
	if { "$nodeName" == "" } {
	    puts stdout "Warning: node #$nodecnt of file $filePath is bogus"
	    continue
	}
    }
    set tki(incore-$fileKey) 1
    return $fileKey
}

#
# Parse nodeSpec and fileSpec.  {nodeSpecVar} and {fileSpecVar} must
# refer to variables within the caller's context.  They will be substituted
# and replaced with canonical forms.
#
proc tkiParseNodeSpec { nodeSpecVar fileSpecVar } {
    global tki
    upvar $nodeSpecVar nodeSpec $fileSpecVar fileSpec

    if { "[string index $nodeSpec 0]"=="(" } {
	set ridx [string first ")" $nodeSpec]
	if { $ridx <= 0 } {
	    tkiError "Malformed nodespec ``$nodeSpec''."
	    return 0
	}
	set fileSpec [string range $nodeSpec 1 [expr $ridx-1]]
	set nodeSpec [string trim [string range $nodeSpec [expr $ridx+1] end]]
    }
    if { "$fileSpec"=="" } {
	set fileSpec $tki(topLevelFile)
    }
    if { "$nodeSpec"=="" } {
	set nodeSpec $tki(topLevelNode)
    }
    set nodeSpec [string trim $nodeSpec]
    return 1
}

proc tkiFmtFileSpec { fileSpec } {
    global tki
    if [info exist tki(fileinfo-$fileSpec)] {
	return [lindex $tki(fileinfo-$fileSpec) 1]
    }
    return $fileSpec
}

proc tkiFmtNodeSpec { nodeSpec {fileSpec ""} } {
    global tki
    if ![tkiParseNodeSpec nodeSpec fileSpec] {
	return "Bad file/node spec ``$nodeSpec''"
    }
    set fileSpec [tkiFmtFileSpec $fileSpec]
    return "($fileSpec)$nodeSpec"
}

#
# This is the core search function.  It attempts to locate {nodeSpec}
# where ever it is.  {fileSpec} is a default file name that is used
# only if {nodeSpec} doesn't contain a reference.
# Returns a list {nodeIdx fileKey}, where {nodeIdx} is the index of the
# node within {fileKey}.
#
# As discussed in the intro above, at this level we cannot allow any
# concept of "current file" or "current node": it is up to the caller
# to maintain that information and pass up the appropriate arguments.
#
proc tkiGetNodeRef { nodeSpec {fileSpec ""} {pntFileKey ""} {caseinsen 0} } {
    global tki

    if ![tkiParseNodeSpec nodeSpec fileSpec] {
	return ""
    }
    set wholeB 0
    if { "$nodeSpec"=="*" } {
	set wholeB 1
	set nodeSpec Top
    }
    set fileKey [tkiFileGet $fileSpec $pntFileKey $wholeB]
    if { "$fileKey"=="" } { return "" }
    set fileName [lindex $tki(fileinfo-$fileKey) 1]
    set realPntKey [lindex $tki(fileinfo-$fileKey) 3]
    if { $caseinsen } {
        set nodeSpec [string tolower $nodeSpec]
    }
    tkiStatus "Searching for ``$nodeSpec'' in $fileName"

    # Popup to our indirect-parent, if it has a tag table
    if { "$pntFileKey"=="" && "$realPntKey"!="" 
      && [info exist tki(indirn-$realPntKey)] } {
          set nodeRef [tkiGetNodeRef $nodeSpec $realPntKey $caseinsen]
          if { $caseinsen == 0 && $nodeRef == "" } {
              return [tkiGetNodeRef $nodeSpec $realPntKey 1]
          } else {
              return $nodeRef
          }
    }

    #  Use index on this file, pushdown to our children
    if { [info exist tki(indirn-$fileKey)] } {
	# Use node index (indirect)
        if { $caseinsen } {
            foreach indir $tki(indirn-$fileKey) {
                if { $nodeSpec == [string tolower [lindex $indir 0]] } {
                    set nodeRef [tkiGetNodeRef $nodeSpec [lindex $indir 2] $fileKey 1]
                    if { "$nodeRef"!="" } { return $nodeRef }
                    tkiFileWarning $fileKey "Incorrect tag table"; break
                }
	    }
	} else {
            foreach indir $tki(indirn-$fileKey) {
                if { $nodeSpec == [lindex $indir 0] } {
                    set nodeRef [tkiGetNodeRef $nodeSpec [lindex $indir 2] $fileKey 0]
                    if { "$nodeRef"!="" } { return $nodeRef }
                    tkiFileWarning $fileKey "Incorrect tag table"; break
                }
	    }
	}
    }

    # Brute force on this file
    if { [info exist tki(nodesinfo-$fileKey)] } {
        if { $caseinsen } {
            foreach nodeinfo $tki(nodesinfo-$fileKey) {
                if { $nodeSpec == [string tolower [lindex $nodeinfo 1]] } {
                    return [list [lindex $nodeinfo 0] $fileKey]
                }
	    }
	} else {
            foreach nodeinfo $tki(nodesinfo-$fileKey) {
                if { $nodeSpec == [lindex $nodeinfo 1] } {
                    return [list [lindex $nodeinfo 0] $fileKey]
                }
	    }
        }
    }
    # Look for node in all indirect files (brute force)
    if { [info exist tki(indirf-$fileKey)] } {
        foreach indir $tki(indirf-$fileKey) {
            set nodeRef [tkiGetNodeRef $nodeSpec [lindex $indir 0] $fileKey $caseinsen]
            if { "$nodeRef"!="" } { return $nodeRef }
        }
    }

    # Look for node in my parent, but only if not called from my pnt
    if { "$pntFileKey"=="" } {
	if { "$realPntKey"!="" } {
	    set nodeRef [tkiGetNodeRef $nodeSpec $realPntKey "" $caseinsen]
            if { "$nodeRef"!="" } { return $nodeRef }
	}
    }
    # Now try case insensitive search...
    if { $caseinsen } {
        return ""
    } else {
        return [tkiGetNodeRef $nodeSpec $fileSpec $pntFileKey 1]
    }
}

#
# Initialize the regexp strings that are used later in 
# tkiNodeParseBody() (for xrefs) and tkiNodeParseMenu() (for menus).
# This func is called once from tkiInit() and then destroyed.
#
proc _tkiNodeParseInit { } {
    global tki

    # For xrefs, there are two forms:
    #	*note nodeSpec::terminator			(form 1)
    #   *note label: nodeSpec terminator		(form 2)
    # Terminator is ``.'' or ``,'', forms may wrap across lines.
    set tki(re_xref1_p) "\\*(note\[ \t\n\]*)(\[^:\]+)::"
    set tki(re_xref1_s) "x\\1\037e\\2\037fxx"
    set tki(re_xref2_p) "\\*(note\[ \t\n\]*)(\[^:\]+)(:\[ \t\n\]*)(\\(\[^ \t\n)\]+\\))?(\[^.,\]*)\[.,\]"
    set tki(re_xref2_s) "x\\1\037a\\2\037b\\3\037c\\4\\5\037dx"


    # For menus, there are two forms:
    #	* nodeSpec::	comments...			(form 1)
    #   * label: nodeSpec[\t.,] comments...		(form 2)
    set tki(re_menu1_p) "(\\*\[ \t\]*)(\[^:\]+)::"
    set tki(re_menu1_s) "\\1\037A\\2\037B"
    # rp2 = "* ws label: ws", rp2a="rp2 nodename ws", rp2b="rp2 (file)node ws"
    set tki(re_menu2_p) "(\\*\[ \t\]*)(\[^:\]+)(:\[ \t\]*)(\\(\[^ \t)\]+\\))?(\[^\t.,\]*)"
    set tki(re_menu2_s) "\\1\037A\\2\037B\\3\037C\\4\\5\037D"
}

#
# Parse a nody-body and identify the cross references.
#
proc tkiNodeParseBody { nodeName fileKey bodytext } {
    global tki

    set nl "node ``($fileKey)$nodeName''"
    regsub -all -nocase $tki(re_xref1_p) $bodytext $tki(re_xref1_s) bodytext
    regsub -all -nocase $tki(re_xref2_p) $bodytext $tki(re_xref2_s) bodytext
    set xrefinfo ""
    set curIdx 1
    foreach seg [split $bodytext "\037"] {
        if { "[string index $seg 0]"=="a" || "[string index $seg 0]"=="e" } {
            regsub -all "\[ \t\n\]+" "[string range $seg 1 end]" " " label
            set stIdx $curIdx
        }
	set curIdx [expr { $curIdx + [string length $seg] - 1 }]
	if { "[string index $seg 0]"!="c" && "[string index $seg 0]"!="e" } {
            continue
        }
	set toNode [string range $seg 1 end]
	regsub -all "\[ \t\n\]+" $toNode " " toNode
#puts stdout "tkiNodeParseBody ``$toNode'', label: $label"
	lappend xrefinfo [list [llength $xrefinfo] $toNode $stIdx $curIdx $label]
    }
    return $xrefinfo
}

#
# Parse the menu and extract the keywords
#
proc tkiNodeParseMenu { nodeName fileKey menutext } {
    global tki

    # There are two forms:
    #	* nodeSpec::	comments...			(form 1)
    #   * label: nodeSpec[ \t.,] comments...		(form 2)
    set rp1 $tki(re_menu1_p)
    set sp1 $tki(re_menu1_s)
    set rp2 $tki(re_menu2_p)
    set sp2 $tki(re_menu2_s)

    set menuinfo ""
    set linecnt 0; set menucnt 0
    set nl "node ``($fileKey)$nodeName''"
    foreach line [split $menutext "\n"] {
	incr linecnt
	if { "[string index $line 0]"!="*" 
	  || "[string range $line 0 6]"=="* Menu:" } continue
	incr menucnt
#puts stdout "Try rp $line"
	if { [regsub $rp1 $line $sp1 prsline] } {
	    set nBeg [expr { [string first "\037A" $prsline] + 0 } ]
	    set nEnd [expr { [string first "\037B" $prsline] - 3 } ]
            set toNode [string range $line $nBeg $nEnd]
            regexp "\037A(.*)\037B" $prsline dummy label
	} else {
	    if { [regsub $rp2 $line $sp2 prsline] } {
	        set nBeg [expr { [string first "\037A" $prsline] - 0 } ]
	        set nEnd [expr { [string first "\037D" $prsline] - 7 } ]
                regexp "\037C(.*)\037D" $prsline dummy toNode
                regexp "\037A(.*)\037B" $prsline dummy label
	    } else {
		tkiFileWarning $fileKey "$nl has bad menu (line $linecnt)"
		continue
	    }
	}
	lappend menuinfo [list $linecnt $menucnt $toNode $nBeg $nEnd $label]
    }
    return $menuinfo
}


# These are called from searchbox.tcl further down:
#proc winstdout {w msg} { tkiStatus $msg; after 1000 }
proc winstdout {w msg} { tkiStatus $msg }
proc winerrout {w msg} { tkiError $msg }


##########################################################################
# The following material was formerly contained in searchbox.tcl:

#
# SearchBox mega widget
#   incremental and regular expression searching in a text widget
#
#   by Tom Phelps (phelps@cs.Berkeley.EDU)
#
# extracted from and then used by TkMan and NBT 6-Aug-93
#
# 19-Aug  made more robust (Kennard White)
#

# requires: proc regexpTextSearch
# name space use: prefixes searchbox, sb, sbx


#--------------------------------------------------
#
# searchboxSearch -- initiate a search
#
# params
#    str = string to search for
#    regexp = boolean - regular expression search?
#    casesen = case sensitive?
#    tag = tag to associate with matches
#       (do a `tag bind' in the text widget for this tag)
#    w = text widget
#    wmsg = (optional) window to show status messages
#    wcnt = (optional) widget to show number of matches
#
#
#--------------------------------------------------

proc searchboxSearch {str regexp casesen tag w {wmsg ""} {wcnt ""}} {
   global sbx
#puts stdout "searchboxSearch $str regexp=$regexp case=$casesen w=$w scrollbar=$wv wmsg=$wmsg $wcnt"
   if {$str==""} {
      winerrout $wmsg "Nothing to search for!"
      return -1
   }

   if {$regexp} {set type regexp} {set type ""}
   set cnt [${type}TextSearch $w $str $tag $casesen]
   if {$cnt==-1} {winerrout $wmsg "Malformed regular expression."; return -1}
   if {$cnt==0} {winstdout $wcnt "No matches for \"$str\"."; return 0}
   if {$cnt==1} {set txt "$cnt match for \"$str\"."} {set txt "$cnt matches for \"$str\". Hit ^s to see more."}

   upvar #0 $w wvars 
   set wvars(searchstatus) "$txt"
   winstdout $wcnt $txt

   # show the first one
   searchboxNext $tag $w $wmsg 0.0
   return $cnt
}



#--------------------------------------------------
#
# searchboxNext -- show the next match
#
# params
#    tag = tag to search for (see searchboxSearch)
#    w = text widget
#    wmsg = window to show status messages
#
#--------------------------------------------------

proc searchboxNext {tag w {wmsg ""} {next ""}} {
    upvar #0 $w wvars 
    global sbx

    if {"[$w tag ranges $tag]"==""} {return 0}
    scan "[wm geometry [winfo toplevel $w]]" "%dx%d+%s" x lines leftover
    set bottom "[$w index @0,0] + $lines lines"
    if {"$next"==""} {set next $bottom}
    set tmp [$w tag nextrange $tag $next]
    if {$tmp==""} {
        set other "[$w tag nextrange $tag 0.0 [$w index @0,0]]"
        if {"$other"==""} {
            winstdout $wmsg "No more matches."
        } else {
            if { $wvars(searchbottom) == 1 } {
                winstdout $wmsg "Restarting at top."
                $w yview -pickplace [lindex $other 0]
                set wvars(searchbottom) 0
            } else {
                winstdout $wmsg "No more matches. Hit ^s to wrap."
                bell
                set wvars(searchbottom) 1
            }
        }
    } else {
        $w yview -pickplace [lindex $tmp 0]
        set wvars(searchbottom) 0
        winstdout $wmsg "$wvars(searchstatus)"
        update
   }
}




# ### default key bindings
# # ""=unmodified, S=shift, A=alt, C=control, M=meta
#
# set sb(key,*) "add modifiers in this order: M, C, A, S"
# set sb(key,C-x) exchangepointandmark
# set sb(key,C-space) setmark
# set sb(key,-Delete) pageup
# set sb(key,M-v) pageup
# set sb(key,-space) pagedown
# set sb(key,C-v) pagedown
# set sb(key,MS-less) pagestart
# set sb(key,MS-greater) pageend
# set sb(key,-Escape) searchkill
# set sb(key,C-g) searchkill
# set sb(key,C-n) nextline
# set sb(key,C-p) prevline
# set sb(key,C-s) incrsearch
# set sb(key,C-r) revincrsearch
# set sb(key,MS-question) help
# set sb(key,-Help) help
#
#
#
#
#
# #--------------------------------------------------
# #
# # searchboxKeyNav -- keyboard-based navigation and searching
# #
# #   maybe separate out some commands so incrsearch doesn't have to wade through
# #
# # params:
# #   m = modifier key
# #   k = key
# #   casesen = case sensitive?
# #   w = text widget
# #   wv = associated vertical scrollbar
# #   wmsg = label in which to show incremental search string
# #   mode = 1=>match on first character of line, 0=>match anywhere
# #
# #--------------------------------------------------
#
# proc searchboxKeyNav {m k casesen w wv {wmsg ""} {firstmode 0}} {
#    global sb sbx
#
#    if {[regexp {(Shift|Control|Meta)_.} $k]} return
#    if {![info exists sbx(try$w)]} {
#       set sbx(try$w) 0
#       set sbx(vect$w) 1
#       set sbx(lastkeys$w) [set sbx(lastkeys-old$w) ""]
#    }
#
#
#    # get initial values
#    set minele 1
#    if {[winfo class $w]=="Text"} {set off 1; scan [$w index end] %d numLines} \
#    elseif {[winfo class $w]=="Listbox"} {set off 0; set numLines [$w size]; set minele 0}
#    scan [$wv get] "%d %d %d %d" total window first last
#
#
#    # some translations
#    if {$sbx(try$w) || "$sbx(lastkeys$w)"!=""} {
#       switch -exact -- $k {
#          space {set k " "}
#          Delete {
#             set k ""
#             set last [expr [string length $sbx(lastkeys$w)]-2]
#             set sbx(lastkeys$w) [string range $sbx(lastkeys$w) 0 $last]
#             set sbx(try$w) 1
#          }
#          default { if {"$m"==""||"$m"=="S"} {set k [name2char $k]} }
#       }
#    }
#
#
#    # commands
#    set mk $m-$k
#    if {[info exists sb(key,$mk)]} {set op $sb(key,$mk)} {set op default}
# #puts stdout "trying for a match on $mk"
# #puts stdout "*$sb(setmark)* *$sb(pageup)* *$sb(pagedown)*"
#    switch -exact -- $op {
#       help {$w.occ.m invoke Help; return}
#       exchangepointandmark {
#          # yview w/o parameter should return current value
#          set tmp [expr [lindex [$wv get] 2]+1].0
#          $w yview xmark
#          update
#          $w mark set xmark $tmp
#       }
#       setmark {$w mark set xmark [expr [lindex [$wv get] 2]+1].0}
#       pageup {$w yview [max [expr $first-$window+1] 0]}
#       pagedown {$w yview [min [expr $first+$window-1] [expr $numLines-$window]]}
#       pagestart {$w yview 0}
#       pageend {$w yview [max [expr $numLines-$window] 0]}
#       searchkill {
#          if {"$sbx(lastkeys$w)"!=""} {set sbx(lastkeys-old$w) $sbx(lastkeys$w)}
#          set sbx(lastkeys$w) ""; set sbx(try$w) 0; winstdout $wmsg ""
#       }
#       C-l {$w yview [max [expr $first-$window/2] 0]}
#       nextline {$w yview [min [expr $first+1] [expr $numLines-$window]]}
#       prevline {$w yview [max [expr $first-1] 0]}
#       default {
#          # incremental search
#          if {$op=="incrsearch"} {
#             # C-s C-s retrieves last search pattern
#             if {$sbx(try$w)&&"$sbx(lastkeys$w)"==""} {set sbx(lastkeys$w) $sbx(lastkeys-old$w)}
#             incr off; set sbx(vect$w) 1; set sbx(try$w) 1
#          } elseif {$op=="revincrsearch"} {
#             if {$sbx(try$w)&&"$sbx(lastkeys$w)"==""} {set sbx(lastkeys$w) $sbx(lastkeys-old$w)}
#             incr off -1; set sbx(vect$w) -1; set sbx(try$w) 1
#          } elseif {$firstmode} {
#             set sbx(lastkeys$w) $k
#          } elseif {$sbx(try$w)} {
# 	    append sbx(lastkeys$w) $k
#          } else return
#
#          if {$firstmode} {
#             set curline 0
#          } else {
#             set curline [lindex [$wv get] 2]
#             winstdout $wmsg "Searching for \"$sbx(lastkeys$w)\" ..."; update idletasks
#          }
#          if {"[set keys $sbx(lastkeys$w)]"==""} return
#
#          set klen [string length $keys]
#          set found -1
#          for {set i [expr $curline+$off]} {$minele<=$i && $i<=$numLines} {incr i $sbx(vect$w)} {
#             if {$firstmode} {
#                if {"$keys"=="[$w get $i.0 $i.$klen]"} {set found 0; break}
#             } elseif {!$casesen} {
#                if {[set found [string first [string tolower $keys] \
#                   [string tolower [$w get $i.0 "$i.0 lineend"]]]]!=-1} \
#                   break;
#             } elseif {[set found [string first $keys [$w get $i.0 "$i.0 lineend"]]]!=-1} {
#                break
#             }
#          }
#
#          # show results
#          if {$found!=-1} {
#             $w yview [expr $i-1]; update idletasks
#             if {!$firstmode} {winstdout $wmsg "\"$keys\" found on line $i"}
#          } elseif {$op=="incrsearch"} {
#             $w yview 0
#             winstdout $wmsg "No more matches found; restarting search at top."
#          } elseif {$op=="revincrsearch"} {
#              $w yview $total
# 	    winstdout $wmsg "No more match found; restarting search at bottom."
#          } else {
#             winstdout $wmsg "\"$keys\" not found"
#             # turn off searching once can't match what you have
#             set sbx(try$w) 0
#          }
#       }
#    }
# }
#
#
#
# #--------------------------------------------------
# #
# # searchboxSaveConfig -- dump persistent variables into passed file id
# #
# #--------------------------------------------------
#
# proc searchboxSaveConfig {fid} {
#    global sb sbx
#
#    puts $fid "#\n# SearchBox\n#\n"
#    foreach i [lsort [array names sb]] {
#       puts $fid "set sb($i) [list $sb($i)]"
#    }
#    puts $fid "\n"
# }



# swiped from mkTextSearch w
#
# The utility procedure below searches for all instances of a
# given string in a text widget and applies a given tag to each
# instance found.
# Arguments:
#
# w -		The window in which to search.  Must be a text widget.
# string -	The string to search for.  The search is done using
#		exact matching only;  no special characters.
# tag -		Tag to apply to each instance of a matching string.
# case -        (optional) case sensitive?

proc TextSearch {w string tag {case 1}} {
   set cnt 0

    $w tag remove $tag 0.0 end
    scan [$w index end] %d numLines
    set l [string length $string]
    if {!$case} {set string [string tolower $string]}
    for {set i 1} {$i <= $numLines} {incr i} {
	set match [$w get $i.0 $i.end]
	if {!$case} {set match [string tolower $match]}
	if {[string first $string $match] == -1} {
	    continue
	}
	set line $match
	set offset 0
	while 1 {
	    set index [string first $string $line]
	    if {$index < 0} {
		break
	    }
	    incr offset $index
	    $w tag add $tag $i.[expr $offset] $i.[expr $offset+$l]
            incr cnt
	    incr offset $l
	    # below bug fix from mkSearch.tcl
	    set line [string range $line [expr $index+$l] end]
	}
    }
   return $cnt
}


# modified to handle regexp's and return # of matches -TAP

proc regexpTextSearch {w string tag {case 1}} {
   set cnt 0
   if {$case} {set case ""} {set case "-nocase"}
   if {[catch {regexp $string bozomaniac}]} {return -1}

    $w tag remove $tag 0.0 end
    scan [$w index end] %d numLines

    for {set i 1} {$i <= $numLines} {incr i} {
      set line [$w get $i.0 $i.end]
      set offset 0
      while 1 {
         if {![eval regexp $case -indices {$string} {$line} match]} break
         scan $match "%d %d" index iend
         $w tag add $tag $i.[expr $offset+$index] $i.[expr $offset+$iend+1]
         set line [string range $line [expr $iend+1] end]
         incr offset [expr $iend+1]
         incr cnt
      }
   }
   return $cnt
}


##########################################################################
# The following material was formerly contained in topgetopt.tcl:

#
# The function has "top" prefix b/c it is conceptually part of my "top" library.
#
# Authors: Kennard White (kennard@ohm.eecs.berkeley.edu)
#	   Phil Lapsley (phil@ohm.eecs.berkeley.edu)
#
# Based on "@(#)getopt.tcl 1.5 12/7/91" by Phil Lapsley
#

# Simple "getopt" for TCL.
#
# topgetopt ?-any? ?-all? opt_list arg_list
# The proc will process the arguments in {arg_list} according to the
# information in {opt_list}.  Processed arguments are passed back
# to the caller by setting variables in the caller's proc-environment
# (i.e., using upvar).
#
# option_list is a list of option specs.  Each spec is a 3-tuple:
#	{ optname varname mode }
# optname is the name of the option to be parsed (without the leading dash).
# varname is the name of a tcl variable in the caller's environment.
#	If ommitted, the varname defaults to the optname.
# mode describes the type of option. If ommitted, it defaults to "single".
#	The modes:
# 	  single:	sets the variable to the next argument.
# 	  append:	lappends the next argument to the variable.
#			this allows multiple instances of the same option.
#	  boolean:	sets the variable to 0 if the argument prefix is "+"
#			 and to 1 of the argument prefix is "-".
#
# "topgetopt" sets the variables named in the option_list that were
# specified in arg_list, and returns the remainder of arg_list after
# the first non "-" or "+" option.  If a bad option specifier is
# encountered, scanning stops and getopt aborts using error.
#
# If -all is specified, then everything in arg_list must match an
# option in opt_list; that is, there may be no "leftover" arguments.
#
# If -any is specified, then processing will stop at the first
# unmatched option.  That is, the returned list of unprocessed
# arguments may contain unregcognized options.
#
# For example, the option_list:
#
#	{ min max { file filename } { toplevel toplevel boolean } }
#
# means that the option "-min value" or "-max value" should set the
# variables "min" or "max" to the specified value, and "-file foo.txt"
# should set the variable "filename" to foo.txt.  "toplevel"
# sets the variable "toplevel", and is a boolean:  the option "-toplevel"
# would set the variable "toplevel" to 1, while the option "+toplevel"
# would set the variable "toplevel" to 0.
#
# In typical usage, the caller will first initialize all the option
# variables to default values, and then call topgetopt.
#

proc topgetopt { args } {
    set do_all 0
    set do_any 0
    if { "[lindex $args 0]"=="-all" } {
	set do_all 1
	set args [lreplace $args 0 0]
    }
    if { "[lindex $args 0]"=="-any" } {
	set do_any 1
	set args [lreplace $args 0 0]
    }
    if { [llength $args]!=2 } {
	error "topgetopt: programming error: wrong number arguments\n$args"
    }
    set opt_list [lindex $args 0]
    set arg_list [lindex $args 1]

    set n [llength $arg_list]
    for { set i 0 } { $i < $n } { incr i } {
	set arg [lindex $arg_list $i]
	set argkey [string index $arg 0]
	if { "$argkey"!="-" && "$argkey"!="+" } {
	    if { $do_all } {
		error "Extra arguments after options not allowed: ``$arg''"
	    }
	    break
	}
	set argname [string range $arg 1 end]
	set matched 0
	foreach opt $opt_list {
	    if { "[lindex $opt 0]"=="$argname" } {
		set optlen [llength $opt]
		set pntVar pntVar$i
		upvar 1 [lindex $opt [expr { ($optlen > 1) ? 1 : 0 }]] $pntVar
		# lindex returns empty string for out-of-range
		case [lindex $opt 2] {
		  b* {
		    set $pntVar [expr {"$argkey"=="-" ? 1 : 0}]
		  }
		  a* {
		    lappend $pntVar [lindex $arg_list [incr i 1] ]
		  }
	          default {
		    set $pntVar [lindex $arg_list [incr i 1] ]
		  }
		}
# puts stdout "got [lindex $opt 0] -- [lindex $opt 1] -- [set $pntVar]"
		set matched 1
		break
	    }
	}
	if { $matched == 0 } {
	    if { $do_any } {
		break
	    } else {
	        error "No match for argument ``$arg''"
	    }
	}
    }
    return [lrange $arg_list $i end]
}



##########################################################################
##########################################################################
# Now start the main routines:


tkiReset
tkiBoot


##########################################################################
##########################################################################
# For emacs:

# Local Variables:
# mode: tcl
# mode: outline-minor
# outline-regexp: "proc \\|#!/bin/sh"
# End:
