NAME
tree - Create and manage tree data objects.
SYNOPSIS
DESCRIPTION
INTRODUCTION
SYNTAX
tree create ?-fixed? ?-keyhash N? ?treeName?
-fixed
-keyhash size
tree destroy treeName...
tree names ?pattern?
tree op subcmd ?subsubcmd ...? treeName ?arg arg ...?
NODE IDS AND TAGS
all
nonroot
rootchildren
root
NODE MODIFIERS
firstchild
lastchild
nextnode
nextsibling
parentnode
prevnode
prevsibling
maxnode
"label"
'label'
TREE OPERATIONS
treeName ancestor node1 node2
treeName append node key string ?string ...?
treeName appendi tagnode key string ?string ...?
treeName apply node ?switches?
-depth number
-exact string
-glob string
-invert
-isleaf
-istree
-key key
-keyglob key
-keyregexp key
-keyexact key
-nocase
-precommand command
-postcommand command
-regexp string
-tag string
-usepath
treeName children ?-labels? node ?first? ?last?
treeName copy srcNode ?destTree? parentNode ?switches?
-label string
-overwrite
-recurse
-reverse
-tags
treeName create ?switches?
-at number
-fixed
-data list
-labelstart number
-nodes list
-num number
-offset number
-parent node
-path pathList
-prefix str
-start number
-tags tagList
treeName degree node
treeName delete node...
treeName depth node
treeName dump node ?switches?
-channel chan
-file fileName
-keys list
-skipkeys list
-tag pattern
-skiptag pattern
-notags
-nopath
treeName exists node ?key?
treeName find ?switches?
-addtag string
-command command
-count
-depth number
-exact
-exec script
%#
%W
%p
%P
%R
%r
%T
%V
%D
%%
-glob
-isarray
-invert
-isfixed
-isleaf
-isnotfixed
-istree
-keycount num
-key key
-keyglob key
-keyregexp key
-keyexact key
-limit number
-maxdepth number
-mindepth number
-name string
-nocase
-nodes tagnode
-notop
-order string
breadthfirst
inorder
postorder
preorder
-usepath
-regexp
-reldepth
-return key
-top node
-var variable
-withtag string
-withouttag string
treeName findchild node label
treeName firstchild node
treeName fixed node ?isfixed?
treeName foreach var tagnode script
treeName get node ?key? ?defaultValue?
treeName incr node key ?amount?
treeName incri tagnode key ?amount?
treeName index node
treeName insert parent ?switches?
-after child
-at number
-before child
-data dataList
-fixed bool
-label string
-names nameList
-node id
-pretags tagList
-tags tagList
-values valueList
treeName is property args
ancestor node1 node2
before node1 node2
leaf node
root node
treeName ismodified ?nodeOrTag? ?isflag?
treeName keys node ?tagnode ...?
treeName label node ?newLabel?
treeName lappend node key value ?value ...?
treeName lappendi tagnode key value ?value ...?
treeName lastchild node
treeName modify tagnode key value ?key value...?
treeName move node newParent ?switches?
-after child
-at number
-before child
treeName names node ?key?
treeName next node
treeName nextsibling node
treeName nodeseq ?start?
treeName notify args
treeName oldvalue ?newvalue?
treeName parent node
treeName path node ?delim? ?prefix?
treeName position ?-sort? ?-format ftype? node ?node ...?
treeName previous node
treeName prevsibling node
treeName restore node switches
-addtags
-channel chan
-data string
-file fileName
-keys list
-skipkeys list
-tag pattern
-skiptag pattern
-notags
-overwrite
treeName root ?node?
treeName set tagnode key value ?key value...?
treeName size node
treeName sort node ?switches?
-ascii
-command string
-decreasing
-dictionary
-integer
-key string
-real
-recurse
-reorder
-usepath
treeName sqlload ?switches? dbhfile sqlstmt
-addtags taglist
-at num
-fixed
-key name
-labelcol column
-maprowid num
-max num
-nullvalue string
-parent string
-pathcol column
-skipcols columns
-tagcol column
-treecols columns
treeName sum ?switches? tagnode key ?key ...?
-diff value
-force
-int
-runtotal key
-start num
treeName supdate node key value ?key value...?
treeName tag args
treeName trace args
treeName type node key
treeName update node key value ?key value...?
treeName unset node key...
treeName values node ?key? ?withnames?
treeName vecdump vector key ?tagnode?
treeName vecload vector key ?tagnode?
treeName with ?switch? tagnode script
-array key
-break
-keys keylist
-noupdate
-unset
ARRAY SUB-FIELDS
TAG OPERATIONS
treeName tag add string ?node?...
treeName tag delete string node...
treeName tag dump tagnode ?switches?
-keys list
-skipkeys list
-tag pattern
-skiptag pattern
-notags
-nopath
treeName tag exists string ?id?
treeName tag forget string ?string ...?
treeName tag lookups ?pattern?
treeName tag names ?-glob? ?-regexp? ?-nocase? ?node? ?node ...?
treeName tag nodes string ?string ...?
TRACE OPERATIONS
treeName trace create node key ops command ?-bgerror?
r
w
c
u
e
t
m
d
treeName trace delete traceId...
treeName trace info traceId
treeName trace names
NOTIFY OPERATIONS
treeName notify create ?switches? command ?args?...
-create
-delete
-get
-insert
-move
-movepost
-sort
-relabel
-relabelpost
-allevents
-whenidle
treeName notify delete notifyId
treeName notify info notifyId
treeName notify names
TABLE EXAMPLE
TREE EXAMPLE
SQLLOAD EXAMPLE
TREE KEY STRING STORAGE
C LANGUAGE API
KEYWORDS

NAME

tree - Create and manage tree data objects.

SYNOPSIS

tree create ?-fixed? ?-keyhash N? ?treeName?
tree destroy treeName...
tree names ?pattern?
tree op subcmd ?subsubcmd ...? treeName ?arg arg ...?

DESCRIPTION

The tree command is used to create, destroy, list and access tree data objects. A tree object is an ordered tree of nodes where each node has a label and a set of key-value data pairs. Creating a tree object associates it with, a Tcl command that is subsequently used to interact with the tree. Tree objects can also be managed via the C API, eg. the treeview widget uses a tree object internally.

INTRODUCTION

Tree provides Tcl with rich support for storing and accessing complex data structures. Here is an example.
set t [tree create]
set n [$t insert 0 -data {a 1   b 2   c "X 1 Y 2"}]
$t set $n b [$t get $n a]
$t set $n c(X) 4

Note the last line demonstrates an array value. See the section below for details.

SYNTAX

tree create ?-fixed? ?-keyhash N? ?treeName?
Creates a new tree object. The name of the new tree is returned. If no treeName argument is present, then the name of the tree is automatically generated in the form "tree0", "tree1", etc relative to the current namespace. If a tree names is given, it can not start with a dash. If the substring "#auto" is found in a given treeName, it is replaced with treeN in a generated name. For example, the name foo.#auto.bar will translate to foo.tree0.bar.

A Tcl command (with the same name as the tree) is also created. Another Tcl command or tree object can not already exist named treeName. If the Tcl command is deleted, the tree will also be freed.

Newly created trees always contain a single root node with id 0 that can not be deleted.

Switches for create are listed below:

-fixed
Make insert automatically set the -fixed flag. This will disallow later setting of keys not given as -data to the insert. Also see fixed.

-keyhash size
Define the size beyond which node key storage starts using a hash (the default is 21 keys). Normally small numbers of keys are stored as a list. But once more than size keys are added to a node, key storage converts to a hash. This affects the order of key iteration (eg. for get/names/values). A list will iterate in the order in which keys were added, whereas the order of a hash is undetermined. For large numbers of ordered keys, specify a really large size (eg. 1000000). Note that array sub-keys always use a hash table.

tree destroy treeName...
Releases one of more trees. The Tcl command associated with treeName is also removed. Trees are reference counted. The internal tree data object isn't destroyed until no one else is using the tree.

tree names ?pattern?
Returns the names of all tree objects. if a pattern argument is given, then the only those trees whose name matches pattern will be listed.

tree op subcmd ?subsubcmd ...? treeName ?arg arg ...?
Provide direct calls to sub-commands, without going through the object command. Aside from self documentating, it allows wize to provide support checked tree calls.

NODE IDS AND TAGS

Nodes in a tree object may be referred in either of two ways: by id or by tag. Each node has a unique serial number or id that is assigned to that node when it's created. The id of an node never changes and id numbers are not re-used (except when all of roots nodes are delete).

A node may also have any number of tags associated with it. A tag is just a string of characters, and it may take any form but may not start with an integer. For example, "x123" is valid, but "123x" is not. The same tag may be associated with one or multiple nodes (ranges or tagnode). Ranges are commonly used to group nodes in various interesting ways.

Commands that take a tagnode can operate on ranges and will accept either a tag or a list of zero or more integer node numbers. Node-lists can contain only integers, without leading spaces. Node-lists simplify the use of iterating commands because it avoids excessive use of eval.

There are four built-in tags:

all
Applies to every node in the tree.

nonroot
Applies to every node in the tree except the root node.

rootchildren
Applies to every node in the tree whose parent is the root node.

root
Managed automatically by the tree object, root specifies the node that is currently set as the root node for the tree.

When specifying nodes in tree object commands, if the specifier is an integer then it is assumed to refer to the single node with that id. If the specifier is not an integer, then it is assumed to refer to all of the nodes in the tree that have a tag matching the specifier. The symbol node is used below to indicate that an argument specifies either an id or a tag that selects a single node. A tagnode is either a tag that selects a group of nodes, or it's a list of zero or more integer node numbers. Many tree commands only operate on a single node at a time; if node is specified in a way that names multiple items, then an error "refers to more than one node" is generated.

NODE MODIFIERS

You can also specify node in relation to another node by appending one or more modifiers to the node id or tag. A modifier refers to a node in relation to the specified node. For example, "root->firstchild" selects the first subtree of the root node.

The following modifiers are available:

firstchild
Selects the first child of the node.

lastchild
Selects the last child of the node.

nextnode
Selects the next node in preorder to the node.

nextsibling
Selects the next sibling of the node.

parentnode
Selects the parent of the node.

prevnode
Selects the previous node in preorder to the node.

prevsibling
Selects the previous sibling of the node.

maxnode
The maximum node number.

"label"

'label'
Selects the child node whose label is label. Enclosing label in quotes (double or single) indicates to search for a node by its label (for example, even if the node is labeled "parentnode"). If mulitiple child nodes have the given label, the first node is used.

It's an error if the node can't be found. For example, lastchild and firstchild will generate errors if the node has no children. The exception to this is the index operation. You can use index to test if a modifier is valid.

TREE OPERATIONS

Once you create a tree object, you can use its Tcl command to query or modify it. The general form is

treeName operation ?arg?...

Both operation and its arguments determine the exact behavior of the command. The operations available for trees are listed below.

treeName ancestor node1 node2
Returns the mutual ancestor of the two nodes node1 and node2. The ancestor can be one of the two nodes. For example, if node1 and node2 are the same nodes, their ancestor is node1.

treeName append node key string ?string ...?
Append one or more strings to node/key value.

treeName appendi tagnode key string ?string ...?
The same as append but accepts a multi-node tag and an undefined key will be initialized to {}. Returns the number of nodes updated.

treeName apply node ?switches?
Runs commands for all nodes matching the criteria given by switches for the subtree designated by node. By default all nodes match, but you can set switches to narrow the match. This operation differs from find in two ways: 1) Tcl commands can be invoked both pre- and post-traversal of a node and 2) the tree is always traversed in depth first order.

The -exact, -glob, and -regexp switches indicate both what kind of pattern matching to perform and the pattern. By default each pattern will be compared with the node label. You can set more than one of these switches. If any of the patterns match (logical or), the node matches. If the -key switch is used, it designates the data field to be matched.

The valid switches are listed below:

-depth number
Descend at most number (a non-negative integer) levels If number is 1 this means only apply the tests to the children of node.

-exact string
Matches each node using string. The node must match string exactly.

-glob string
Test each node to string using global pattern matching. Matching is done in a fashion similar to that used by string match.

-invert
Invert the results of the pattern matching of -name.

-isleaf
Only test nodes with no children.

-istree
Only test nodes with children.

-key key

-keyglob key

-keyregexp key

-keyexact key
If pattern matching is selected (using the -exact, -glob, or -regexp switches), compare the values of the data field keyed by key instead of the node's label. If no pattern matching switches are set, then any node with this data key will match. The field names may also be patterns using -keyglob, etc.

-nocase
Ignore case when matching patterns.

-precommand command
Invoke command for each matching node. Before command is invoked, the id of the node is appended. You can control processing by the return value of command. If command generates an error, processing stops and the find operation returns an error. But if command returns break, then processing stops, no error is generated. If command returns continue, then processing stops on that subtree and continues on the next.

-postcommand command
Invoke command for each matching node. Before command is invoked, the id of the node is appended. You can control processing by the return value of command. If command generates an error, processing stops and the find operation returns an error. But if command returns break, then processing stops, no error is generated. If command returns continue, then processing stops on that subtree and continues on the next.

-regexp string
Test each node using string as a regular expression pattern.

-tag string
Only test nodes that have the tag string.

-usepath
Use the node's full path when comparing nodes. The node's full path is a list of labels, starting from the root of each ancestor and the node label. The default is to compare only the node label.

treeName children ?-labels? node ?first? ?last?
Returns a list of children for node. If node is a leaf, then an empty string is returned. If first and/or last are given they are the integer index of the children to display. If the -labels option is used, labels are returned instead of the nodes.

treeName copy srcNode ?destTree? parentNode ?switches?
Copies srcNode into parentNode. Both nodes srcNode and parentNode must already exist. The id of the new node is returned. You can copy from one tree to another. If a destTree argument is present, it indicates the name of the destination tree. By default both the source and destination trees are the same. The valid switches are listed below:

-label string
Label destNode as string. By default, destNode has the same label as srcNode.

-overwrite
Overwrite nodes that already exist. Normally nodes are always created, even if there already exists a node by the same name. This switch indicates to add or overwrite the node's data fields.

-recurse
Recursively copy all the subtrees of srcNode as well. In this case, srcNode can't be an ancestor of destNode as it would result in a cyclic copy.

-reverse
Reverse the direction of the copy.

-tags
Copy tag information. Normally the following node is copied: its label and data fields. This indicates to copy tags as well.

treeName create ?switches?
Cause the creation of zero or more nodes. Exactly one of -num, -nodes or -path is required. This can create all nodes in a given -path or efficiently populate a tree with large numbers of nodes. The return values is the id of the last created node (or -path element). The valid flags for switches are described below.

-at number
Where to insert child nodes. The default is -1, meaning append.

-fixed
Set the fixed flag.

-data list
Data to set in each node.

-labelstart number
The label generated nodes is to use a sequence number starting from number. The default is to just use the node id.

-nodes list
List of nodes ids to create. The -offset option can specify a constant to add.

-num number
The number of nodes to create.

-offset number
Number to add to each element in -nodes. For example, if loading sqlite rowids you should use 1. The default is 0.

-parent node
The node to insert children into. The default is the root node.

-path pathList
Verify that a path exists and create any missing nodes. Uses labels in pathList to lookup nodes, creating them if not found. The id for the last node in the path is returned (created or not).

-prefix str
String prefix to add to each nodes label.

-start number
Node nuber to start from when using -num. The default is 1.

-tags tagList
List of tags to add to each newly created node.

treeName degree node
Returns the number of children of node.

treeName delete node...
Recursively deletes one or more nodes from the tree. The node and all its descendants are removed. The one exception is the root node. In this case, only its descendants are removed. The root node will remain. Any tags or traces on the nodes are released.

treeName depth node
Returns the depth of the node. The depth is the number of steps from the node to the root of the tree. The depth of the root node is 0.

treeName dump node ?switches?
Save tree data for node and its descendants. With the -file option, output goes to the file fileName (this is unsupported in a safe interp). With the -channel option, data is output to channel chan. If neither option is given, the dump is returned as data.

The subtree designated by node is traversed to obtain the following information for each node: 1) the node's path relative to node, 2) a sublist key value pairs representing the node's data fields, and 3) a sublist of tags. and 4) the label This list returned can be used later to copy or restore the tree with the restore operation.

The valid switches are listed below.

-channel chan
Obtain data from from the given channel chan. The channel is not closed afterwards.

-file fileName
Obtain data from from the file. fileName. This options is unsupported in a safe interp.

-keys list
A list of patterns of matching keys to be dumped.

-skipkeys list
A list of patterns of matching keys not to be dumped.

-tag pattern
A pattern match for tags to include in a node dump.

-skiptag pattern
A pattern match for tags to not include in a node dump.

-notags
Do not restore any tags

-nopath
To save space, do not dump the full path for each node. Instead output periods for all but the last path element. Full paths are used only for partial restores.

treeName exists node ?key?
Indicates if node exists in the tree. If a key argument is present then the command also indicates if the named data field exists.

treeName find ?switches?
Finds for all nodes matching the criteria given by switches for the subtree designated by node. A list of the selected nodes is returned. By default all nodes match, but you can set switches to narrow the match.

The -exact, -glob, and -regexp switches indicate what kind of pattern matching to perform for -name. By default the pattern will be compared with the node label. If the -key switch is used, it designates the data field to be matched.

The order in which the nodes are traversed is controlled by the -order switch. The possible orderings are preorder, postorder, inorder, and breadthfirst. The default is preorder.

The valid switches are listed below:

-addtag string
Add the tag string to each selected node.

-command command
Invoke command for each matching node. Before command is invoked, the id of the node is appended. You can control processing by the return value of command. If command generates an error, processing stops and the find operation returns an error. But if command returns break, then processing stops, no error is generated. If command returns continue, then processing stops on that subtree and continues on the next.

-count
Just return the number of matches.

-depth number
Include only nodes with level equal to number.

-exact
Matches each node exactly.

-exec script
Specifies a Tcl script to be evaluated for each matching node. If -var was also specified, that variable is set with the value of the node id before each evaluation. Otherwise, percent sustitutions are performed: note this is much less efficient than using either -var or -command

The result of each eval gets appended to the return list, unless the script issues a CONTINUE, in which case that node is skipped.

The available percent substitutions on string are:

%#
The id of the node.

%W
The pathname of the tree.

%p
The label of the node.

%P
The full pathname of the node.

%R
The -> delimited path from root, eg. "root->able->baker->charlie"

%r
The -> delimited path from 0, eg. "0->able->baker->charlie"

%T
The dot delimited tag path eg. ".able.baker.charlie"

%V
The value if using -key or the label otherwise.

%D
The data for the node, ie. like that returned from get.

%%
Translates to a single percent.

-glob
Test each node using global pattern matching. Matching is done in a fashion similar to that used by the string match.

-isarray
Only test nodes where the specified -key value is an array. Can not be used with -name. The -invert flag will invert the meaning of the check. Note that this will attempt to convert the key value in each traversed node into an array type.

-invert
Invert the pattern matching of -name.

-isfixed
Only test nodes that have used fixed 1.

-isleaf
Only test nodes with no children.

-isnotfixed
Only test nodes that have not used fixed 1.

-istree
Only test nodes with children.

-keycount num
Only test if number of keys is equal to num.

-key key

-keyglob key

-keyregexp key

-keyexact key
Compare the values of the data field keyed by key instead of the node's label. If no -name pattern is used then any node with this data key will match. The key names may also be patterns using -keyglob, etc.

-limit number
Stop processing after number (a positive integer) matches.

-maxdepth number
Include only nodes at level number or less.

-mindepth number
Include only nodes at level number or greater.

-name string
The name to use for pattern matching.

-nocase
Ignore case when matching patterns.

-nodes tagnode
Search only in tagnode, which is either a tag or a list of nodes ids. This makes possible nested searches. Note this option is incompatible with -top and -notop.

-notop
Exclude the -top or starting node.

-order string
Traverse the tree and process nodes according to string. String can be one of the following:

breadthfirst
Process the node and the subtrees at each successive level. Each node on a level is processed before going to the next level.

inorder
Recursively process the nodes of the first subtree, the node itself, and any the remaining subtrees.

postorder
Recursively process all subtrees before the node.

preorder
Recursively process the node first, then any subtrees (default).

-usepath
Use the node's full path when doing the comparison. The default is to compare only the node label.

-regexp
Test each node using regular expression pattern matching.

-reldepth
Change the meaning of -depth, -mindepth and -maxdepth to be relative to the -top node.

-return key
Return the value of the given key, or the empty string if none. If the given key is the empty string, the node label will be returned. If no value was found and the given key starts with a percent returns the sustitution as per -exec. Note that a percent substitution longer than 2 chars will append values as list elements.

-top node
Search is only at node and it's descendants. The default is the root node.

-var variable
A variable to set with the node id before each iteration of the -exec script.

-withtag string
Only test nodes that have the tag string.

-withouttag string
Only test nodes that don't have the tag string.

treeName findchild node label
Searches for a child node label in node. The id of the child node is returned if found. Otherwise -1 is returned. This is the same as using index node->label.

treeName firstchild node
Returns the id of the first child in the node's list of subtrees. If node is a leaf (has no children), then -1 is returned.

treeName fixed node ?isfixed?
Get or set the fixed key-fields flag for the node. New key-fields can be added to a node only if fixed is 0 (the default) Note that copied and restored nodes do not preserve the fixed state.

treeName foreach var tagnode script
Provides a foreach loop for tree. For each node in tagnode the node-id is assigned to var and then script is evaluated. The tagnode is either a tag or a list of nodes as described in the section above.

treeName get node ?key? ?defaultValue?
Returns a list of key-value pairs of data for node. If key is present, then only the value for that particular data field is returned. It's normally an error if node does not contain the data field key. But if you provide a defaultValue argument, this value is returned instead (node will still not contain key). This feature can be used to access a data field of node without first testing if it exists. This operation may trigger read data traces.

treeName incr node key ?amount?
Increment value by 1 or given amount and return the value. The incr operation normally tries to use integers, but uses doubles when one of value or amount is a double.

treeName incri tagnode key ?amount?
The same as incr but accepts a multi-node tag and an undefined key will be initialized to 0. Returns the number of nodes updated.

treeName index node
Returns the id of node. In addition to standard node id form, node can also be a path (a list of labels from the root) as returned by the path command. If node is invalid, then -1 is returned.

treeName insert parent ?switches?
Inserts a new node into parent node parent. The parent can be the keyword end to mean the root. The id of the new node is returned. The following switches are available:

-after child
Position node after child. The node child must be a child of parent.

-at number
Inserts the node into parent's list of children at position number. The default is to append.

-before child
Position node before child. The node child must be a child of parent.

-data dataList
Sets the value for each data field in dataList for the new node. DataList is a list of key-value pairs. May not be used in conjuction with -names or -values.

-fixed bool
If bool is 1, set fixed field mode after initializing the key/value pairs from -data. This disallows creation of new key fields after the node is created. If not given, uses the tree default for fixed.

-label string
Designates the labels of the node as string. By default, nodes are labeled as 0, 1, etc.

-names nameList
The names for the data fields. This must have the same length as -values, and may not be used in conjuction with -data.

-node id
Designates the id for the node. Normally new ids are automatically generated. This allows you to create a node with a specific id. It is an error if the id is already used by another node in the tree.

-pretags tagList
Adds each tag in tagList to the new node, before data is added. Unlike -tags, traces on these tags will fire on key data during the insert.

-tags tagList
Adds each tag in tagList to the new node. TagList is a list of tags, so be careful if a tag has embedded space.

-values valueList
The values for the data fields. This must have the same length as -values, and may not be used in conjuction with -data.

treeName is property args
Indicates the property of a node. Both property and args determine the property being tested. Returns 1 if true and 0 otherwise. The following property and args are valid:

ancestor node1 node2
Indicates if node1 is an ancestor of node2.

before node1 node2
Indicates if node1 is before node2 in depth first traversal.

leaf node
Indicates if node is a leaf (it has no subtrees).

root node
Indicates if node is the designated root. This can be changed by the root operation.

treeName ismodified ?nodeOrTag? ?isflag?
Get or set modified state for the tree or nodes. With no args returns modified state for tree. With one args returns modified state for a node. With two args set modified state for one or more nodes. In the last case, where ?nodeOrTag? is the tag all, the state for the tree is also set.

Newly created nodes are always considered to be modified until explicitly cleared. After clearing, subsequent updates to keys or tags will toggle the node (and tree) modified again.

treeName keys node ?tagnode ...?
Return list of unique keys for all of the given nodes in tagnode. Accepts nodes and tags or all.

treeName label node ?newLabel?
Returns the label of the node designated by node. If newLabel is present, the node is relabeled using it as the new label.

treeName lappend node key value ?value ...?
Append one or more list values to node/key value.

treeName lappendi tagnode key value ?value ...?
The same as lappend but accepts a multi-node tag and an undefined key will be initialized to {}. Returns the number of nodes updated.

treeName lastchild node
Returns the id of the last child in the node's list of subtrees. If node is a leaf (has no children), then -1 is returned.

treeName modify tagnode key value ?key value...?
Update one or more fields in one or more nodes in tagnode. As with set, node can be a tag referring to multiple nodes. This is identical to set, except an error is thrown if any of the key fields do not exist. Despite the error, all nodes that do have said fields get updated. For modifying a single node, see update.

treeName move node newParent ?switches?
Moves node into newParent. Node is appended to the list children of newParent. Node can not be an ancestor of newParent. The valid flags for switches are described below.

-after child
Position node after child. The node child must be a child of newParent.

-at number
Inserts node into parent's list of children at position number. The default is to append the node.

-before child
Position node before child. The node child must be a child of newParent.

treeName names node ?key?
Return key names for node. If a key is given, attempts to return ARRAY fields (see ARRAY SUB-FIELDS). An error is thrown if the convert to array fails (ie. list-length is odd). The type command can be used to query the type. See also values.

treeName next node
Returns the next node from node in a preorder traversal. If node is the last node in the tree, then -1 is returned.

treeName nextsibling node
Returns the node representing the next subtree from node in its parent's list of children. If node is the last child, then -1 is returned.

treeName nodeseq ?start?
Get or set the start sequence number for subsequent node insertions not using -node. The default is 0.

treeName notify args
Manages notification events that indicate that the tree structure has been changed. See the section below.

treeName oldvalue ?newvalue?
Return the value from before the last (untraced) change operation. This is used primarly by write traces wishing to restore a key to it's pre-write value (eg. read-only variables). The oldvalue is saved internally everytime a change operation occurs to a key value by deferring its deallocation. Changes made during node traces do not affect oldvalue.

If newvalue is provided, the current value of oldvalue is discarded and replaced. This is useful really only for releasing large objects.

treeName parent node
Returns the parent node of node. If node is the root of the tree, then -1 is returned.

treeName path node ?delim? ?prefix?
Returns the full path (from root) of node using the node labels. If delim is not specified, the result is a list. Otherwise, the result is a string starting with prefix and each element of the path separated by delim. This latter form is useful for building tags like: .able.baker

treeName position ?-sort? ?-format ftype? node ?node ...?
Returns the position of the node(s) in its parent's list of children. Positions are numbered from 0. The position of the root node is always 0. The value of ftype is one of: position parent-at-position id+position id+parent-at-position.

treeName previous node
Returns the previous node from node in a preorder traversal. If node is the root of the tree, then -1 is returned.

treeName prevsibling node
Returns the node representing the previous subtree from node in its parent's list of children. If node is the first child, then -1 is returned.

treeName restore node switches
Performs the inverse function of the dump operation, restoring nodes to the tree. The format of the input data is exactly what is returned by the dump operation. It's a list containing information for each node to be restored. The information consists of 1) the relative path of the node, 2) a sublist of key value pairs representing the node's data, 3) a list of tags for the node, and 4) the label. Nodes are created starting from node. Nodes can be listed in any order. If a node's path describes ancestor nodes that do not already exist, they are automatically created.

The valid switches are listed below. Exactly one of -channel, -file or -data must be specified.

-addtags
List of tags to add to each node restored node.

-channel chan
Obtain data from from the given channel chan. The channel is not closed afterwards.

-data string
Data input is from the given string.

-file fileName
Obtain data from from the file. fileName. This options is unsupported in a safe interp.

-keys list
A list of patterns of matching keys to be restored.

-skipkeys list
A list of patterns of matching keys not to be restored.

-tag pattern
A pattern match for tags to include in a node restore.

-skiptag pattern
A pattern match for tags to not include in a node restore.

-notags
Do not restore any tags

-overwrite
Overwrite nodes that already exist. Normally nodes are always created, even if there already exists a node by the same name. This switch indicates to overwrite existing node's data fields.

treeName root ?node?
Returns the id of the root node. Normally this is node 0. If a node argument is provided, it will become the new root of the tree. This lets you temporarily work within a subset of the tree. Changing root affects operations such as next, path, previous, etc.

treeName set tagnode key value ?key value...?
Sets one or more data fields in node. tagode may be a tag that represents several nodes and a count of the number of nodes updated is returned. Key is the name of the data field to be set, or an array-like reference such as field(subkey). See the section below. Value is the respective keys value. The Key will be created if it does not exists (see modify).

The set operation triggers write and create data traces.

treeName size node
Returns the number of nodes in the subtree. This includes the node and all its descendants. The size of a leaf node is 1.

treeName sort node ?switches?
Return nodes in sorted order.

-ascii
Compare strings using the ASCII collation order.

-command string
Use command string as a comparison command. To compare two elements, evaluate a Tcl script consisting of command with the five elements appended as additional arguments: the tree, node1, node1, label1, label2. The script should return an integer less than, equal to, or greater than zero if the first element is to be considered less than, equal to, or greater than the second, respectively.

-decreasing
Sort in decreasing order (largest items come first).

-dictionary
Compare strings using a dictionary-style comparison. This is the same as -ascii except (a) case is ignored except as a tie-breaker and (b) if two strings contain embedded numbers, the numbers compare as integers, not characters. For example, in -dictionary mode, bigBoy sorts between bigbang and bigboy, and x10y sorts between x9y and x11y.

-integer
Compare the nodes as integers.

-key string
Sort based upon the node's data field keyed by string. Normally nodes are sorted according to their label. label.

-real
Compare the nodes as real numbers.

-recurse
Recursively sort the entire subtree rooted at node.

-reorder
Recursively sort subtrees for each node. Warning. Unlike the normal flat sort, where a list of nodes is returned, this will reorder the tree.

-usepath
Compare the full path of each node. The default is to compare only the node label.

treeName sqlload ?switches? dbhfile sqlstmt
Load tree with the results of evaling the SQL in sqlstmt using dbhfile. The evaluated SQL creates one tree-node per row result. The returned value is the number of rows loaded. Dbhfile is either an sqlite3 database handle, or an sqlite3 file.

The sqlload command can populate a tree with 10k nodes about 7 times faster than sqlite3 eval. It also preserves NULL values and object types (eg. int or double) used internally by sqlite. This eliminates later reconversion within tree. See the below.

The following switches are available:

-addtags taglist
The tags in taglist to add to each inserted node.

-at num
Where to insert into parents list of children. Default is -1, meaning append.

-fixed
Set the fixed flag to disallow new keys after creation.

-key name
Store the entire result in the key name instead of creating one key per column. Array notation can be used to then access column results. This is more efficent as it initially stores just one object per row. Conversion to an array is at the first array access (if that occurs).

-labelcol column
The value of column is used as the label. By default the label is the node id.

-maprowid num
This option maps the node id to the rowid plus the constant num. The key for rowid will also not be created. This is applicable only if rowid is returned in the result-set of sqlstmt. If rowid is not in the result set, this option is ignored. If mapping fails (because the tree already contains a requested node) the load will abort at that point with an error. Note that num must be >= 1 since sqlite rowids start from 0, but the root node of the tree uses the node-id 0.

-max num
The maximum number of rows to return. The default is 100,000. Note that SQL queries on large tables should probably always use LIMIT.

-nullvalue string
Define value to use for null values. The default is no value, meaning do not set key if value is null. Note this is different from the sqlite Tcl extension which uses an empty string for NULL.

-parent string
The node where results are inserted as child nodes. The default is the tree root.

-pathcol column
Name of column containing the full path where node is to be created. This works like -treecols, but uses a singl columns.

-skipcols columns
The given columns are not to be added as keys. This is useful mostly in conjuction with -tagcol, -labelcol, -pathcol.

-tagcol column
The value of column is added as a tag.

-treecols columns
Columns whose values concatenated give the path of where node is to be created. This works like -pathcol, but uses multiple columns.

treeName sum ?switches? tagnode key ?key ...?
Add values in key fields for all tagnode and return the sum. Values that are not doubles (or integer) are ignored.

-diff value
Double value difference to ignore and not do update for -runtotal. This is unused when using -int.

-force
Force update -runtotal even if value was unchanged. Normally, a check is made to avoid updating unchanged values.

-int
Use and accept only integer values.

-runtotal key
Place running total in the given key field (if changed).

-start num
The start value for the sum: default is 0.

treeName supdate node key value ?key value...?
Like update, but with a string comparison to avoid a write if the value has not changed.

treeName tag args
Manages tags for the tree object. See the section below.

treeName trace args
Manages traces for data fields in the tree object. Traces cause Tcl commands to be executed whenever a data field of a node is created, read, written, or unset. Traces can be set for a specific node or a tag, representing possibly many nodes. See the section below.

treeName type node key
Return type of value. This is the introspected type from the Tcl_Obj value passed to set.

treeName update node key value ?key value...?
Like modify, except an error is generated if a tag is used that applies to more than one node.

treeName unset node key...
Removes one or more data fields from node. Node may be a tag that represents several nodes. Key is the name of the data field to be removed. It's not an error is node does not contain key. A count of the number of nodes unset is returned. This operation may trigger unset data traces.

treeName values node ?key? ?withnames?
Return values for node. The values are returned in the same order as the keys returned from names.

If a key is given, array values get returned for the key value. If withname is True, then key names are also returned with the values. This differs from get in that the result is a true Tcl list object, not an array object. If subsequently using an array value in a list context, this can be more efficient by avoiding a split on string representations.

treeName vecdump vector key ?tagnode?
Dump key field to a vector. With no tagnode, dumps every node to the 1-1 corresponding vector index. With tag dumps nodes to consequetive vector elements.

treeName vecload vector key ?tagnode?
Loads key field from a vector. With no tagnode, loads every node from the 1-1 corresponding vector index. With tag loads nodes from consequetive vector elements.

treeName with ?switch? tagnode script
For each node in tagnode, evaluate the script after assigning key values to elements of the array variable. The -keys limits which keys may be assigned. If script completes normally, and any of the key values change in the variable, then the updates are reflected back into the key values (unless -noupdate is used). Unsetting a variable key will cause that change to be ignored. Setting a new element in the variable has no effect.

Doing a return, break, or continue inside script will still cause updates to copy back, but processing will stop and (unless -break is used) the return code will become the return code to the caller. This means that a break, continue, and return will propagate up through multiple nested with statements to the to an enclosing foreach, while, etc. But -break can be used to change this and make with act like a foreach loop.

If -keys is not used, the list of key names will be stored in variable(*) and the node id stored in variable(#) (but this can be overwritten by a key of that name). By default, the array is not cleaned up before or after each execution. However, if -unset is used, the array is unset at the start of each iteration.

If -array is used, with operates on the keys of an array instead.

Upon normal completion, the number of times script was evaluated is returned.

The valid switches are listed below:

-array key
Specifies a single key that is to be treated as an array. The fields of the array for that one key are then used (instead of keys of the whole node). This changes the meaning of -keys to be the keys of the array rather than the keys of the node. If a key value can not be converted to an array, an error will occur.

-break
Treat break and continue like foreach does rather than just passing them up to the enclosing script body.

-keys keylist
Copy only the named keys and do not set (*) or (#).

-noupdate
Forget changes to array variables and do not copy back changes.

-unset
Unset the array variable at the begin of each evaluation.

ARRAY SUB-FIELDS

Individual data fields of a node support array-like subfield access. This works somewhat like Tcls new dict command, except tree uses the familiar array notation for key fields. Here is an example:
set t [tree create]
set n [$t insert 0 -data {a 1   b 2   c "x 9 y 8 z 7"}]
puts [$t get $n];          #  a 1 b 2 c {x 9 y 8 z 7}
puts [$t get $n c];        #  x 9 y 8 z 7
puts [$t get $n c(y)];     # 8
$t update $n c(y) 8.6
puts [$t get $n c];        # x 9 y 8.6 z 7
$t unset $n c(y)
puts [$t get $n c];        # x 9 z 7
$t set $n d 10
Using incr or update on a non-existant subfield generates an error. Using the type command on such a field returns array. Note that traced operations on arrays trigger on the key value and not individual array elements.

TAG OPERATIONS

Tags are a general means of selecting and marking nodes in the tree. A tag is just a string of characters, and it may take any form except that of an integer. The same tag may be associated with many different nodes.

Most tree operations use tags. And several operations let you operate on multiple nodes at once. For example, you can use the set operation with the tag all to set a data field in for all nodes in the tree.

Tags are invoked by the tag operation. The general form is

treeName tag operation ?arg?...

Both operation and its arguments determine the exact behavior of the command. The operations available for tags are listed below.

treeName tag add string ?node?...
Adds the tag string to zero or more nodes. If no nodes are given, just creates the tag. A count of the number of nodes tagged is returned.

treeName tag delete string node...
Remove the tag string from one or more nodes. A count of the number of nodes visited is returned. Calling tag delete with a builtin tag is ignore.

treeName tag dump tagnode ?switches?
Dump the nodes specified by the tag tagnode.

The valid switches are listed below.

-keys list
A list of patterns of matching keys to be dumped.

-skipkeys list
A list of patterns of matching keys not to be dumped.

-tag pattern
A pattern match for tags to include in a node dump.

-skiptag pattern
A pattern match for tags to not include in a node dump.

-notags
Do not dump the tags.

-nopath
To save space, do not dump the full path for each node. Instead output periods for all but the last path element. Full paths are used only for partial restores.

treeName tag exists string ?id?
If an id is given, return 1 (or 0) if node has (or hasn't) the tag. Otherwise, returns 1 if at least one nodes has tag string.

treeName tag forget string ?string ...?
Removes the tag definition for one or more of string. It's not an error if the tag string does not exist.

treeName tag lookups ?pattern?
Dump a lookup table (dictionary) of nodes-to-tags, or tags-to-nodes if pattern is given. With no arguments, returns a pair list of nodes/tags, for nodes that have tags. With an argument, returns a pair list of tags/nodes. lookups provides efficient bulk processing when dealing with large numbers of nodes and/or tags.

treeName tag names ?-glob? ?-regexp? ?-nocase? ?node? ?node ...?
Returns a list of tags used by the tree. If no node argument is given, returns a list of all known tags. Otherwise, returns the union of the tags used by all given node numbers. Patterns can be used via -glob or -regexp. If -nocase is used, the pattern is expected to be all lower case.

treeName tag nodes string ?string ...?
Returns a list of any nodes that have any of given string tag. If no node is tagged with any of the string, then an empty string is returned.

TRACE OPERATIONS

Data fields can be traced much like tracing Tcl variables. Data traces cause a Tcl command to be executed whenever data fields are created, read, written, or unset. A trace can apply to one or more nodes. You can trace a specific node by using its id, or a group of nodes by a their tag. Note: operations on arrays trigger only on the key value and not individual array elements.

The tree's get, set, and unset operations can trigger various traces. The get operation can cause a read trace to fire. The set operation causes a write trace to fire. And if the data field is written for the first time, you will also get a create trace. The unset operation triggers unset traces.

Data traces are invoked by the trace operation. The general form is

treeName trace operation ?arg?...

Both operation and its arguments determine the exact behavior of the command. The operations available for traces are listed below.

treeName trace create node key ops command ?-bgerror?
Create a trace on data fields (or tags for tag traces) given by the pattern in key. The node argument can be a nodeid, or a tag to refer to multiple nodes eg. all. The return value is an identifier that can be used with "trace info" or "trace delete". Traces are temporarily disabled while executing command within the trace.

Command is a command prefix, to which four arguments are appended before invocation: treeName, nodeid, key and, ops. If an error occurs in command (and -bgerror was not used) the invoking operation will also abort.

Ops indicates which operations are of interest. It consists of one or more of the following letters:

r
Invoke command whenever key is read.

w
Invoke command whenever key is written.

c
Invoke command whenever key is created.

u
Invoke command whenever key is unset, typically with the unset command. to that.

e
Invoke command whenever exists is used on an non-existant key. This can be used to populate node key data on demand.

t
Invoke command whenever tag key is added to a node.

m
Invoke command when tag key gets added to more than one node. This trace can be used to enforce tags that should be on at most one node. It can avoid later errors with tags used in get or other commands not accepting non-unique tags.

d
Invoke command whenever tag key is deleted from a node using either tag delete or tag forget. Node deletion will not trigger this trace.

treeName trace delete traceId...
Deletes one of more traces. TraceId is the trace identifier returned by the trace create operation.

treeName trace info traceId
Returns information about the trace traceId. TraceId is a trace identifier previously returned by the trace create operation. It's the same information specified for the trace create operation. It consists of the node id or tag, data field key, a string of letters indicating the operations that are traced (it's in the same form as ops) and, the command prefix.

treeName trace names
Returns a list of identifiers for all the current traces.

NOTIFY OPERATIONS

Tree objects can be shared among many clients, such as a treeview widget. Any client can create or delete nodes, sorting the tree, etc. You can request to be notified whenever these events occur. Notify events cause Tcl commands to be executed whenever the tree structure is changed.

Notifications are handled by the notify operation. The general form is

treeName notify operation ?arg?...

Both operation and its arguments determine the exact behavior of the command. The operations available for events are listed below.

treeName notify create ?switches? command ?args?...
Creates a notifier for the tree. A notify identifier in the form "notify0", "notify1", etc. is returned.

Command and args are saved and invoked whenever the tree structure is changed (according to switches). Two arguments are appended to command and args before it's invoked: the id of the node and a string representing the type of event that occured. If an error is returned by command, and not using -whenidle the invoking operation usually returns an error. One of more switches can be set to indicate the events that are of interest. The valid switches are as follows:

-create
Invoke command whenever a new node is added. This is called after the creation. Returning an error will delete the node.

-delete
Invoke command whenever a node has been deleted. This is called before the delete starts to allow aborting it with an error. Deletes resulting from failed inserts are ignored.

-get
Invoke command whenever a node with no keys is accessed (via get or with). If a node has at least one key, this will not trigger. The invocation occurs before the read, meaning it can be used to implement demand loading of data keys into empty nodes (eg. loading database row data on read).

-insert
Invoke command when an insert completes. This differs from -create in that the call occurs after the label, tags and data are added (but before -fixed gets set). This trace applies to the subcommands create, copy, restore, sqlload, and insert (both tree and treeview). It is useful for verifying key-data, tags and labels. Returning an error will delete the node and cause the originating command to generate an error.

-move
Invoke command at the start of a node move.

-movepost
Invoke command after a node has been moved.

-sort
Invoke command whenever the tree has been sorted and reordered.

-relabel
Invoke command at the start of a node relabel.

-relabelpost
Invoke command after a node has been relabeled.

-allevents
Invoke command whenever any of the above events occur.

-whenidle
When an event occurs don't invoke command immediately, but queue it to be run the next time the event loop is entered and there are no events to process. If subsequent events occur before the event loop is entered, command will still be invoked only once.

treeName notify delete notifyId
Deletes one or more notifiers from the tree. NotifyId is the notifier identifier returned by the notify create operation.

treeName notify info notifyId
Returns information about the notify event notifyId. NotifyId is a notify identifier previously returned by the notify create operation. It's the same information specified for the notify create operation. It consists of the notify id, a sublist of event flags (it's in the same form as flags) and, the command prefix.

treeName notify names
Returns a list of identifiers for all the current notifiers.

TABLE EXAMPLE

The following is a simple example.

variable Users {
     tom  { Name "Tom Brown"  Sex M Age 19  Class {4 5} Rate {A 1 B 2}}
     mary { Name "Mary Brown" Sex F Age 16  Class {5}   Rate {A 2}}
     sam  { Name "Sam Spade"  Sex M Age 19  Class {3 4} Rate {B 3}}
 }
 set t [tree create]
 foreach {i d} $Users {
    # Use name in -tags so we don't have to do "0->mary" etc.
    $t insert 0 -tags $i -data $d -label $i
 }
 
 $t update   tom       Sex F   Name "Tomi Brown"
 $t append   sam       Name " Jr"
 $t lappend  sam       Class 5
 $t incr     mary      Age
 $t update   tom       Rate(A) 2
 $t incr     0->mary   Age
 
 # Set a trace.
 proc ::Aupd {t id key op} { tclLog "AA: $t $id $key $op" }
 $t trace create all Age w ::Aupd
 $t incr     mary Age
 
 # Display it.
 pack [treeview .t -tree $t] -fill both -expand y
 eval .t column insert end [$t keys all]

TREE EXAMPLE

The following is a nested tree example with updates.

variable Info {
   system {
      sol  { OS Linux Version 3.4 }
      bing { OS Win Version 7 }
      gui  { OS Mac Version 8 }
   }
   network {
      intra { Address 192.168.1  Netmask 255.255.255.0 }
      dmz   { Address 192.168.10 Netmask 255.255.255.0 }
      wan   { Address 0.0.0.0 Netmask 0.0.0.0 Class {A 1 B 4}}
   }
   admins {
      sully { Name "Sully Van Damme" Level 3 }
      maverick { Name "Maverick Gump" Level 1 }
   }
 }
  
 set s [tree create]
 foreach {n vals} $Info {
   set ind [$s insert 0 -label $n]
   foreach {i d} $vals {
      $s insert $ind -label $i -data $d
   }
 }
  
 set old [$s get  0->system->bing]
 $s update   0->system->bing   OS Linux Version 3.4
 $s update   0->network->dmz   Address 192.168.11
 $s update   0->network->wan   Class(A) 2
 eval $s set 0->system->bing   $old
 $s insert   0->admins -label linus -data { Name "Linus Torvalds" Level 9 }
 
 
 pack [treeview .s -tree $s -width 600] -fill both -expand y
 eval .s column insert end [$s keys all]

SQLLOAD EXAMPLE

Here is an example using sqlload on table cust from a database file, and displaying it in a treeview:
set t [tree create]
  $t sqlload mydb.dat "select rowid,* from cust"
  pack [treeview .t -tree $t -width 500] -fill both -expand y
  eval .t column insert end [lsort [$t keys all]]
Although there is no corresponding sqldump command, scripting it is easy. Following is one approach.
proc sqldump {t db table {ids {}}} {
      # Dump nodes from tree t into table in open sqlite database db.
      if {$ids == {}} { set ids [$t children root] }
      set keys [$t keys $ids]
      catch { $db eval "CREATE TABLE $table ( [join $keys ,] )" }
      $t with s $ids {
          set nams {}
          set vals {}
          foreach nam $s(*) {
              lappend vals \$s($nam)
              lappend nams $nam
          }
          set vals [join $vals ,]
          set nams [join $nams ,]
          set q [format {INSERT INTO %s (%s) VALUES (%s)} $table $nams $vals]
          $db eval $q
      }
  }
  sqlite3 [set db dbhandle] mydb.dat
  sqldump $t $db cust2

TREE KEY STRING STORAGE

Key name strings are stored by default in a global hash table. However, sometimes this can be undesirable (eg. with threading), and so the behavior may be changed (at tree create time only). To enable per-interp storage of keys, set blt::treeKeysLocal to 1 before tree creation. To enable per-tree storage of keys, set blt::treeKeysLocal to 2 before tree creation. The above is unavailable in safe interps.

C LANGUAGE API

Blt_TreeApply, Blt_TreeApplyBFS, Blt_TreeApplyDFS, Blt_TreeChangeRoot, Blt_TreeCreate, Blt_TreeCreateEventHandler, Blt_TreeCreateNode, Blt_TreeCreateTrace, Blt_TreeDeleteEventHandler, Blt_TreeDeleteNode, Blt_TreeDeleteTrace, Blt_TreeExists, Blt_TreeFindChild, Blt_TreeFirstChild, Blt_TreeFirstKey, Blt_TreeGetNode, Blt_TreeGetToken, Blt_TreeGetValue, Blt_TreeIsAncestor, Blt_TreeIsBefore, Blt_TreeIsLeaf, Blt_TreeLastChild, Blt_TreeMoveNode, Blt_TreeName, Blt_TreeNextKey, Blt_TreeNextNode, Blt_TreeNextSibling, Blt_TreeNodeDegree, Blt_TreeNodeDepth, Blt_TreeNodeId, Blt_TreeNodeLabel, Blt_TreeNodeParent, Blt_TreePrevNode, Blt_TreePrevSibling, Blt_TreeRelabelNode, Blt_TreeReleaseToken, Blt_TreeRootNode, Blt_TreeSetValue, Blt_TreeSize, Blt_TreeSortNode, and Blt_TreeUnsetValue.

KEYWORDS

tree, treeview, widget
Copyright © 1995-1997 Roger E. Critchlow Jr.